1 (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Mapillary = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
4 var Queue = require('tinyqueue');
6 module.exports = polylabel;
7 module.exports.default = polylabel;
9 function polylabel(polygon, precision, debug) {
10 precision = precision || 1.0;
12 // find the bounding box of the outer ring
13 var minX, minY, maxX, maxY;
14 for (var i = 0; i < polygon[0].length; i++) {
15 var p = polygon[0][i];
16 if (!i || p[0] < minX) minX = p[0];
17 if (!i || p[1] < minY) minY = p[1];
18 if (!i || p[0] > maxX) maxX = p[0];
19 if (!i || p[1] > maxY) maxY = p[1];
22 var width = maxX - minX;
23 var height = maxY - minY;
24 var cellSize = Math.min(width, height);
27 // a priority queue of cells in order of their "potential" (max distance to polygon)
28 var cellQueue = new Queue(null, compareMax);
30 if (cellSize === 0) return [minX, minY];
32 // cover polygon with initial cells
33 for (var x = minX; x < maxX; x += cellSize) {
34 for (var y = minY; y < maxY; y += cellSize) {
35 cellQueue.push(new Cell(x + h, y + h, h, polygon));
39 // take centroid as the first best guess
40 var bestCell = getCentroidCell(polygon);
42 // special case for rectangular polygons
43 var bboxCell = new Cell(minX + width / 2, minY + height / 2, 0, polygon);
44 if (bboxCell.d > bestCell.d) bestCell = bboxCell;
46 var numProbes = cellQueue.length;
48 while (cellQueue.length) {
49 // pick the most promising cell from the queue
50 var cell = cellQueue.pop();
52 // update the best cell if we found a better one
53 if (cell.d > bestCell.d) {
55 if (debug) console.log('found best %d after %d probes', Math.round(1e4 * cell.d) / 1e4, numProbes);
58 // do not drill down further if there's no chance of a better solution
59 if (cell.max - bestCell.d <= precision) continue;
61 // split the cell into four cells
63 cellQueue.push(new Cell(cell.x - h, cell.y - h, h, polygon));
64 cellQueue.push(new Cell(cell.x + h, cell.y - h, h, polygon));
65 cellQueue.push(new Cell(cell.x - h, cell.y + h, h, polygon));
66 cellQueue.push(new Cell(cell.x + h, cell.y + h, h, polygon));
71 console.log('num probes: ' + numProbes);
72 console.log('best distance: ' + bestCell.d);
75 return [bestCell.x, bestCell.y];
78 function compareMax(a, b) {
82 function Cell(x, y, h, polygon) {
83 this.x = x; // cell center x
84 this.y = y; // cell center y
85 this.h = h; // half the cell size
86 this.d = pointToPolygonDist(x, y, polygon); // distance from cell center to polygon
87 this.max = this.d + this.h * Math.SQRT2; // max distance to polygon within a cell
90 // signed distance from point to polygon outline (negative if point is outside)
91 function pointToPolygonDist(x, y, polygon) {
93 var minDistSq = Infinity;
95 for (var k = 0; k < polygon.length; k++) {
96 var ring = polygon[k];
98 for (var i = 0, len = ring.length, j = len - 1; i < len; j = i++) {
102 if ((a[1] > y !== b[1] > y) &&
103 (x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0])) inside = !inside;
105 minDistSq = Math.min(minDistSq, getSegDistSq(x, y, a, b));
109 return (inside ? 1 : -1) * Math.sqrt(minDistSq);
112 // get polygon centroid
113 function getCentroidCell(polygon) {
117 var points = polygon[0];
119 for (var i = 0, len = points.length, j = len - 1; i < len; j = i++) {
122 var f = a[0] * b[1] - b[0] * a[1];
123 x += (a[0] + b[0]) * f;
124 y += (a[1] + b[1]) * f;
127 if (area === 0) return new Cell(points[0][0], points[0][1], 0, polygon);
128 return new Cell(x / area, y / area, 0, polygon);
131 // get squared distance from a point to a segment
132 function getSegDistSq(px, py, a, b) {
139 if (dx !== 0 || dy !== 0) {
141 var t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
156 return dx * dx + dy * dy;
159 },{"tinyqueue":241}],2:[function(require,module,exports){
161 * Copyright (C) 2008 Apple Inc. All Rights Reserved.
163 * Redistribution and use in source and binary forms, with or without
164 * modification, are permitted provided that the following conditions
166 * 1. Redistributions of source code must retain the above copyright
167 * notice, this list of conditions and the following disclaimer.
168 * 2. Redistributions in binary form must reproduce the above copyright
169 * notice, this list of conditions and the following disclaimer in the
170 * documentation and/or other materials provided with the distribution.
172 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
173 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
174 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
175 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
176 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
177 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
178 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
179 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
180 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
181 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
182 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
185 * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h
188 module.exports = UnitBezier;
190 function UnitBezier(p1x, p1y, p2x, p2y) {
191 // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
193 this.bx = 3.0 * (p2x - p1x) - this.cx;
194 this.ax = 1.0 - this.cx - this.bx;
197 this.by = 3.0 * (p2y - p1y) - this.cy;
198 this.ay = 1.0 - this.cy - this.by;
206 UnitBezier.prototype.sampleCurveX = function(t) {
207 // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
208 return ((this.ax * t + this.bx) * t + this.cx) * t;
211 UnitBezier.prototype.sampleCurveY = function(t) {
212 return ((this.ay * t + this.by) * t + this.cy) * t;
215 UnitBezier.prototype.sampleCurveDerivativeX = function(t) {
216 return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
219 UnitBezier.prototype.solveCurveX = function(x, epsilon) {
220 if (typeof epsilon === 'undefined') epsilon = 1e-6;
222 var t0, t1, t2, x2, i;
224 // First try a few iterations of Newton's method -- normally very fast.
225 for (t2 = x, i = 0; i < 8; i++) {
227 x2 = this.sampleCurveX(t2) - x;
228 if (Math.abs(x2) < epsilon) return t2;
230 var d2 = this.sampleCurveDerivativeX(t2);
231 if (Math.abs(d2) < 1e-6) break;
236 // Fall back to the bisection method for reliability.
241 if (t2 < t0) return t0;
242 if (t2 > t1) return t1;
246 x2 = this.sampleCurveX(t2);
247 if (Math.abs(x2 - x) < epsilon) return t2;
255 t2 = (t1 - t0) * 0.5 + t0;
262 UnitBezier.prototype.solve = function(x, epsilon) {
263 return this.sampleCurveY(this.solveCurveX(x, epsilon));
266 },{}],3:[function(require,module,exports){
269 exports.byteLength = byteLength
270 exports.toByteArray = toByteArray
271 exports.fromByteArray = fromByteArray
275 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
277 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
278 for (var i = 0, len = code.length; i < len; ++i) {
280 revLookup[code.charCodeAt(i)] = i
283 revLookup['-'.charCodeAt(0)] = 62
284 revLookup['_'.charCodeAt(0)] = 63
286 function placeHoldersCount (b64) {
289 throw new Error('Invalid string. Length must be a multiple of 4')
292 // the number of equal signs (place holders)
293 // if there are two placeholders, than the two characters before it
294 // represent one byte
295 // if there is only one, then the three characters before it represent 2 bytes
296 // this is just a cheap hack to not do indexOf twice
297 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
300 function byteLength (b64) {
301 // base64 is 4/3 + up to two characters of the original data
302 return (b64.length * 3 / 4) - placeHoldersCount(b64)
305 function toByteArray (b64) {
306 var i, l, tmp, placeHolders, arr
308 placeHolders = placeHoldersCount(b64)
310 arr = new Arr((len * 3 / 4) - placeHolders)
312 // if there are placeholders, only get up to the last complete 4 chars
313 l = placeHolders > 0 ? len - 4 : len
317 for (i = 0; i < l; i += 4) {
318 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
319 arr[L++] = (tmp >> 16) & 0xFF
320 arr[L++] = (tmp >> 8) & 0xFF
321 arr[L++] = tmp & 0xFF
324 if (placeHolders === 2) {
325 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
326 arr[L++] = tmp & 0xFF
327 } else if (placeHolders === 1) {
328 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
329 arr[L++] = (tmp >> 8) & 0xFF
330 arr[L++] = tmp & 0xFF
336 function tripletToBase64 (num) {
337 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
340 function encodeChunk (uint8, start, end) {
343 for (var i = start; i < end; i += 3) {
344 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
345 output.push(tripletToBase64(tmp))
347 return output.join('')
350 function fromByteArray (uint8) {
352 var len = uint8.length
353 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
356 var maxChunkLength = 16383 // must be multiple of 3
358 // go through the array every three bytes, we'll deal with trailing stuff later
359 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
360 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
363 // pad the end with zeros, but make sure to not forget the extra bytes
364 if (extraBytes === 1) {
366 output += lookup[tmp >> 2]
367 output += lookup[(tmp << 4) & 0x3F]
369 } else if (extraBytes === 2) {
370 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
371 output += lookup[tmp >> 10]
372 output += lookup[(tmp >> 4) & 0x3F]
373 output += lookup[(tmp << 2) & 0x3F]
379 return parts.join('')
382 },{}],4:[function(require,module,exports){
384 },{}],5:[function(require,module,exports){
386 * Cross-Browser Split 1.1.1
387 * Copyright 2007-2012 Steven Levithan <stevenlevithan.com>
388 * Available under the MIT License
389 * ECMAScript compliant, uniform cross-browser split method
393 * Splits a string into an array of strings using a regex or string separator. Matches of the
394 * separator are not included in the result array. However, if `separator` is a regex that contains
395 * capturing groups, backreferences are spliced into the result each time `separator` is matched.
396 * Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably
398 * @param {String} str String to split.
399 * @param {RegExp|String} separator Regex or string to use for separating the string.
400 * @param {Number} [limit] Maximum number of items to include in the result array.
401 * @returns {Array} Array of substrings.
405 * split('a b c d', ' ');
406 * // -> ['a', 'b', 'c', 'd']
409 * split('a b c d', ' ', 2);
412 * // Backreferences in result array
413 * split('..word1 word2..', /([a-z]+)(\d+)/i);
414 * // -> ['..', 'word', '1', ' ', 'word', '2', '..']
416 module.exports = (function split(undef) {
418 var nativeSplit = String.prototype.split,
419 compliantExecNpcg = /()??/.exec("")[1] === undef,
420 // NPCG: nonparticipating capturing group
423 self = function(str, separator, limit) {
424 // If `separator` is not a regex, use `nativeSplit`
425 if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
426 return nativeSplit.call(str, separator, limit);
429 flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6
430 (separator.sticky ? "y" : ""),
433 // Make `global` and avoid `lastIndex` issues by working with a copy
434 separator = new RegExp(separator.source, flags + "g"),
435 separator2, match, lastIndex, lastLength;
436 str += ""; // Type-convert
437 if (!compliantExecNpcg) {
438 // Doesn't need flags gy, but they don't hurt
439 separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
441 /* Values for `limit`, per the spec:
442 * If undefined: 4294967295 // Math.pow(2, 32) - 1
443 * If 0, Infinity, or NaN: 0
444 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
445 * If negative number: 4294967296 - Math.floor(Math.abs(limit))
446 * If other: Type-convert, then use the above rules
448 limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1
449 limit >>> 0; // ToUint32(limit)
450 while (match = separator.exec(str)) {
451 // `separator.lastIndex` is not reliable cross-browser
452 lastIndex = match.index + match[0].length;
453 if (lastIndex > lastLastIndex) {
454 output.push(str.slice(lastLastIndex, match.index));
455 // Fix browsers whose `exec` methods don't consistently return `undefined` for
456 // nonparticipating capturing groups
457 if (!compliantExecNpcg && match.length > 1) {
458 match[0].replace(separator2, function() {
459 for (var i = 1; i < arguments.length - 2; i++) {
460 if (arguments[i] === undef) {
466 if (match.length > 1 && match.index < str.length) {
467 Array.prototype.push.apply(output, match.slice(1));
469 lastLength = match[0].length;
470 lastLastIndex = lastIndex;
471 if (output.length >= limit) {
475 if (separator.lastIndex === match.index) {
476 separator.lastIndex++; // Avoid an infinite loop
479 if (lastLastIndex === str.length) {
480 if (lastLength || !separator.test("")) {
484 output.push(str.slice(lastLastIndex));
486 return output.length > limit ? output.slice(0, limit) : output;
492 },{}],6:[function(require,module,exports){
493 // shim for using process in browser
494 var process = module.exports = {};
496 // cached from whatever global is present so that test runners that stub it
497 // don't break things. But we need to wrap it in a try catch in case it is
498 // wrapped in strict mode code which doesn't define any globals. It's inside a
499 // function because try/catches deoptimize in certain engines.
501 var cachedSetTimeout;
502 var cachedClearTimeout;
504 function defaultSetTimout() {
505 throw new Error('setTimeout has not been defined');
507 function defaultClearTimeout () {
508 throw new Error('clearTimeout has not been defined');
512 if (typeof setTimeout === 'function') {
513 cachedSetTimeout = setTimeout;
515 cachedSetTimeout = defaultSetTimout;
518 cachedSetTimeout = defaultSetTimout;
521 if (typeof clearTimeout === 'function') {
522 cachedClearTimeout = clearTimeout;
524 cachedClearTimeout = defaultClearTimeout;
527 cachedClearTimeout = defaultClearTimeout;
530 function runTimeout(fun) {
531 if (cachedSetTimeout === setTimeout) {
532 //normal enviroments in sane situations
533 return setTimeout(fun, 0);
535 // if setTimeout wasn't available but was latter defined
536 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
537 cachedSetTimeout = setTimeout;
538 return setTimeout(fun, 0);
541 // when when somebody has screwed with setTimeout but no I.E. maddness
542 return cachedSetTimeout(fun, 0);
545 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
546 return cachedSetTimeout.call(null, fun, 0);
548 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
549 return cachedSetTimeout.call(this, fun, 0);
555 function runClearTimeout(marker) {
556 if (cachedClearTimeout === clearTimeout) {
557 //normal enviroments in sane situations
558 return clearTimeout(marker);
560 // if clearTimeout wasn't available but was latter defined
561 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
562 cachedClearTimeout = clearTimeout;
563 return clearTimeout(marker);
566 // when when somebody has screwed with setTimeout but no I.E. maddness
567 return cachedClearTimeout(marker);
570 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
571 return cachedClearTimeout.call(null, marker);
573 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
574 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
575 return cachedClearTimeout.call(this, marker);
583 var draining = false;
587 function cleanUpNextTick() {
588 if (!draining || !currentQueue) {
592 if (currentQueue.length) {
593 queue = currentQueue.concat(queue);
602 function drainQueue() {
606 var timeout = runTimeout(cleanUpNextTick);
609 var len = queue.length;
611 currentQueue = queue;
613 while (++queueIndex < len) {
615 currentQueue[queueIndex].run();
623 runClearTimeout(timeout);
626 process.nextTick = function (fun) {
627 var args = new Array(arguments.length - 1);
628 if (arguments.length > 1) {
629 for (var i = 1; i < arguments.length; i++) {
630 args[i - 1] = arguments[i];
633 queue.push(new Item(fun, args));
634 if (queue.length === 1 && !draining) {
635 runTimeout(drainQueue);
639 // v8 likes predictible objects
640 function Item(fun, array) {
644 Item.prototype.run = function () {
645 this.fun.apply(null, this.array);
647 process.title = 'browser';
648 process.browser = true;
651 process.version = ''; // empty string to avoid regexp issues
652 process.versions = {};
657 process.addListener = noop;
660 process.removeListener = noop;
661 process.removeAllListeners = noop;
663 process.prependListener = noop;
664 process.prependOnceListener = noop;
666 process.listeners = function (name) { return [] }
668 process.binding = function (name) {
669 throw new Error('process.binding is not supported');
672 process.cwd = function () { return '/' };
673 process.chdir = function (dir) {
674 throw new Error('process.chdir is not supported');
676 process.umask = function() { return 0; };
678 },{}],7:[function(require,module,exports){
680 * The buffer module from node.js, for the browser.
682 * @author Feross Aboukhadijeh <https://feross.org>
685 /* eslint-disable no-proto */
689 var base64 = require('base64-js')
690 var ieee754 = require('ieee754')
692 exports.Buffer = Buffer
693 exports.SlowBuffer = SlowBuffer
694 exports.INSPECT_MAX_BYTES = 50
696 var K_MAX_LENGTH = 0x7fffffff
697 exports.kMaxLength = K_MAX_LENGTH
700 * If `Buffer.TYPED_ARRAY_SUPPORT`:
701 * === true Use Uint8Array implementation (fastest)
702 * === false Print warning and recommend using `buffer` v4.x which has an Object
703 * implementation (most compatible, even IE6)
705 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
706 * Opera 11.6+, iOS 4.2+.
708 * We report that the browser does not support typed arrays if the are not subclassable
709 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
710 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
711 * for __proto__ and has a buggy typed array implementation.
713 Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
715 if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
716 typeof console.error === 'function') {
718 'This browser lacks typed array (Uint8Array) support which is required by ' +
719 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
723 function typedArraySupport () {
724 // Can typed array instances can be augmented?
726 var arr = new Uint8Array(1)
727 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
728 return arr.foo() === 42
734 function createBuffer (length) {
735 if (length > K_MAX_LENGTH) {
736 throw new RangeError('Invalid typed array length')
738 // Return an augmented `Uint8Array` instance
739 var buf = new Uint8Array(length)
740 buf.__proto__ = Buffer.prototype
745 * The Buffer constructor returns instances of `Uint8Array` that have their
746 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
747 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
748 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
749 * returns a single octet.
751 * The `Uint8Array` prototype remains unmodified.
754 function Buffer (arg, encodingOrOffset, length) {
756 if (typeof arg === 'number') {
757 if (typeof encodingOrOffset === 'string') {
759 'If encoding is specified then the first argument must be a string'
762 return allocUnsafe(arg)
764 return from(arg, encodingOrOffset, length)
767 // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
768 if (typeof Symbol !== 'undefined' && Symbol.species &&
769 Buffer[Symbol.species] === Buffer) {
770 Object.defineProperty(Buffer, Symbol.species, {
778 Buffer.poolSize = 8192 // not used by this implementation
780 function from (value, encodingOrOffset, length) {
781 if (typeof value === 'number') {
782 throw new TypeError('"value" argument must not be a number')
785 if (isArrayBuffer(value)) {
786 return fromArrayBuffer(value, encodingOrOffset, length)
789 if (typeof value === 'string') {
790 return fromString(value, encodingOrOffset)
793 return fromObject(value)
797 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
798 * if value is a number.
799 * Buffer.from(str[, encoding])
801 * Buffer.from(buffer)
802 * Buffer.from(arrayBuffer[, byteOffset[, length]])
804 Buffer.from = function (value, encodingOrOffset, length) {
805 return from(value, encodingOrOffset, length)
808 // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
809 // https://github.com/feross/buffer/pull/148
810 Buffer.prototype.__proto__ = Uint8Array.prototype
811 Buffer.__proto__ = Uint8Array
813 function assertSize (size) {
814 if (typeof size !== 'number') {
815 throw new TypeError('"size" argument must be a number')
816 } else if (size < 0) {
817 throw new RangeError('"size" argument must not be negative')
821 function alloc (size, fill, encoding) {
824 return createBuffer(size)
826 if (fill !== undefined) {
827 // Only pay attention to encoding if it's a string. This
828 // prevents accidentally sending in a number that would
829 // be interpretted as a start offset.
830 return typeof encoding === 'string'
831 ? createBuffer(size).fill(fill, encoding)
832 : createBuffer(size).fill(fill)
834 return createBuffer(size)
838 * Creates a new filled Buffer instance.
839 * alloc(size[, fill[, encoding]])
841 Buffer.alloc = function (size, fill, encoding) {
842 return alloc(size, fill, encoding)
845 function allocUnsafe (size) {
847 return createBuffer(size < 0 ? 0 : checked(size) | 0)
851 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
853 Buffer.allocUnsafe = function (size) {
854 return allocUnsafe(size)
857 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
859 Buffer.allocUnsafeSlow = function (size) {
860 return allocUnsafe(size)
863 function fromString (string, encoding) {
864 if (typeof encoding !== 'string' || encoding === '') {
868 if (!Buffer.isEncoding(encoding)) {
869 throw new TypeError('"encoding" must be a valid string encoding')
872 var length = byteLength(string, encoding) | 0
873 var buf = createBuffer(length)
875 var actual = buf.write(string, encoding)
877 if (actual !== length) {
878 // Writing a hex string, for example, that contains invalid characters will
879 // cause everything after the first invalid character to be ignored. (e.g.
880 // 'abxxcd' will be treated as 'ab')
881 buf = buf.slice(0, actual)
887 function fromArrayLike (array) {
888 var length = array.length < 0 ? 0 : checked(array.length) | 0
889 var buf = createBuffer(length)
890 for (var i = 0; i < length; i += 1) {
891 buf[i] = array[i] & 255
896 function fromArrayBuffer (array, byteOffset, length) {
897 if (byteOffset < 0 || array.byteLength < byteOffset) {
898 throw new RangeError('\'offset\' is out of bounds')
901 if (array.byteLength < byteOffset + (length || 0)) {
902 throw new RangeError('\'length\' is out of bounds')
906 if (byteOffset === undefined && length === undefined) {
907 buf = new Uint8Array(array)
908 } else if (length === undefined) {
909 buf = new Uint8Array(array, byteOffset)
911 buf = new Uint8Array(array, byteOffset, length)
914 // Return an augmented `Uint8Array` instance
915 buf.__proto__ = Buffer.prototype
919 function fromObject (obj) {
920 if (Buffer.isBuffer(obj)) {
921 var len = checked(obj.length) | 0
922 var buf = createBuffer(len)
924 if (buf.length === 0) {
928 obj.copy(buf, 0, 0, len)
933 if (isArrayBufferView(obj) || 'length' in obj) {
934 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
935 return createBuffer(0)
937 return fromArrayLike(obj)
940 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
941 return fromArrayLike(obj.data)
945 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
948 function checked (length) {
949 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
950 // length is NaN (which is otherwise coerced to zero.)
951 if (length >= K_MAX_LENGTH) {
952 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
953 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
958 function SlowBuffer (length) {
959 if (+length != length) { // eslint-disable-line eqeqeq
962 return Buffer.alloc(+length)
965 Buffer.isBuffer = function isBuffer (b) {
966 return b != null && b._isBuffer === true
969 Buffer.compare = function compare (a, b) {
970 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
971 throw new TypeError('Arguments must be Buffers')
974 if (a === b) return 0
979 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
992 Buffer.isEncoding = function isEncoding (encoding) {
993 switch (String(encoding).toLowerCase()) {
1011 Buffer.concat = function concat (list, length) {
1012 if (!Array.isArray(list)) {
1013 throw new TypeError('"list" argument must be an Array of Buffers')
1016 if (list.length === 0) {
1017 return Buffer.alloc(0)
1021 if (length === undefined) {
1023 for (i = 0; i < list.length; ++i) {
1024 length += list[i].length
1028 var buffer = Buffer.allocUnsafe(length)
1030 for (i = 0; i < list.length; ++i) {
1032 if (!Buffer.isBuffer(buf)) {
1033 throw new TypeError('"list" argument must be an Array of Buffers')
1035 buf.copy(buffer, pos)
1041 function byteLength (string, encoding) {
1042 if (Buffer.isBuffer(string)) {
1043 return string.length
1045 if (isArrayBufferView(string) || isArrayBuffer(string)) {
1046 return string.byteLength
1048 if (typeof string !== 'string') {
1049 string = '' + string
1052 var len = string.length
1053 if (len === 0) return 0
1055 // Use a for loop to avoid recursion
1056 var loweredCase = false
1066 return utf8ToBytes(string).length
1075 return base64ToBytes(string).length
1077 if (loweredCase) return utf8ToBytes(string).length // assume utf8
1078 encoding = ('' + encoding).toLowerCase()
1083 Buffer.byteLength = byteLength
1085 function slowToString (encoding, start, end) {
1086 var loweredCase = false
1088 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1089 // property of a typed array.
1091 // This behaves neither like String nor Uint8Array in that we set start/end
1092 // to their upper/lower bounds if the value passed is out of range.
1093 // undefined is handled specially as per ECMA-262 6th Edition,
1094 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1095 if (start === undefined || start < 0) {
1098 // Return early if start > this.length. Done here to prevent potential uint32
1099 // coercion fail below.
1100 if (start > this.length) {
1104 if (end === undefined || end > this.length) {
1112 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
1120 if (!encoding) encoding = 'utf8'
1125 return hexSlice(this, start, end)
1129 return utf8Slice(this, start, end)
1132 return asciiSlice(this, start, end)
1136 return latin1Slice(this, start, end)
1139 return base64Slice(this, start, end)
1145 return utf16leSlice(this, start, end)
1148 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1149 encoding = (encoding + '').toLowerCase()
1155 // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
1156 // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
1157 // reliably in a browserify context because there could be multiple different
1158 // copies of the 'buffer' package in use. This method works even for Buffer
1159 // instances that were created from another copy of the `buffer` package.
1160 // See: https://github.com/feross/buffer/issues/154
1161 Buffer.prototype._isBuffer = true
1163 function swap (b, n, m) {
1169 Buffer.prototype.swap16 = function swap16 () {
1170 var len = this.length
1171 if (len % 2 !== 0) {
1172 throw new RangeError('Buffer size must be a multiple of 16-bits')
1174 for (var i = 0; i < len; i += 2) {
1175 swap(this, i, i + 1)
1180 Buffer.prototype.swap32 = function swap32 () {
1181 var len = this.length
1182 if (len % 4 !== 0) {
1183 throw new RangeError('Buffer size must be a multiple of 32-bits')
1185 for (var i = 0; i < len; i += 4) {
1186 swap(this, i, i + 3)
1187 swap(this, i + 1, i + 2)
1192 Buffer.prototype.swap64 = function swap64 () {
1193 var len = this.length
1194 if (len % 8 !== 0) {
1195 throw new RangeError('Buffer size must be a multiple of 64-bits')
1197 for (var i = 0; i < len; i += 8) {
1198 swap(this, i, i + 7)
1199 swap(this, i + 1, i + 6)
1200 swap(this, i + 2, i + 5)
1201 swap(this, i + 3, i + 4)
1206 Buffer.prototype.toString = function toString () {
1207 var length = this.length
1208 if (length === 0) return ''
1209 if (arguments.length === 0) return utf8Slice(this, 0, length)
1210 return slowToString.apply(this, arguments)
1213 Buffer.prototype.equals = function equals (b) {
1214 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1215 if (this === b) return true
1216 return Buffer.compare(this, b) === 0
1219 Buffer.prototype.inspect = function inspect () {
1221 var max = exports.INSPECT_MAX_BYTES
1222 if (this.length > 0) {
1223 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
1224 if (this.length > max) str += ' ... '
1226 return '<Buffer ' + str + '>'
1229 Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
1230 if (!Buffer.isBuffer(target)) {
1231 throw new TypeError('Argument must be a Buffer')
1234 if (start === undefined) {
1237 if (end === undefined) {
1238 end = target ? target.length : 0
1240 if (thisStart === undefined) {
1243 if (thisEnd === undefined) {
1244 thisEnd = this.length
1247 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1248 throw new RangeError('out of range index')
1251 if (thisStart >= thisEnd && start >= end) {
1254 if (thisStart >= thisEnd) {
1266 if (this === target) return 0
1268 var x = thisEnd - thisStart
1270 var len = Math.min(x, y)
1272 var thisCopy = this.slice(thisStart, thisEnd)
1273 var targetCopy = target.slice(start, end)
1275 for (var i = 0; i < len; ++i) {
1276 if (thisCopy[i] !== targetCopy[i]) {
1283 if (x < y) return -1
1288 // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
1289 // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
1292 // - buffer - a Buffer to search
1293 // - val - a string, Buffer, or number
1294 // - byteOffset - an index into `buffer`; will be clamped to an int32
1295 // - encoding - an optional encoding, relevant is val is a string
1296 // - dir - true for indexOf, false for lastIndexOf
1297 function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
1298 // Empty buffer means no match
1299 if (buffer.length === 0) return -1
1301 // Normalize byteOffset
1302 if (typeof byteOffset === 'string') {
1303 encoding = byteOffset
1305 } else if (byteOffset > 0x7fffffff) {
1306 byteOffset = 0x7fffffff
1307 } else if (byteOffset < -0x80000000) {
1308 byteOffset = -0x80000000
1310 byteOffset = +byteOffset // Coerce to Number.
1311 if (numberIsNaN(byteOffset)) {
1312 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
1313 byteOffset = dir ? 0 : (buffer.length - 1)
1316 // Normalize byteOffset: negative offsets start from the end of the buffer
1317 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
1318 if (byteOffset >= buffer.length) {
1320 else byteOffset = buffer.length - 1
1321 } else if (byteOffset < 0) {
1322 if (dir) byteOffset = 0
1327 if (typeof val === 'string') {
1328 val = Buffer.from(val, encoding)
1331 // Finally, search either indexOf (if dir is true) or lastIndexOf
1332 if (Buffer.isBuffer(val)) {
1333 // Special case: looking for empty string/buffer always fails
1334 if (val.length === 0) {
1337 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
1338 } else if (typeof val === 'number') {
1339 val = val & 0xFF // Search for a byte value [0-255]
1340 if (typeof Uint8Array.prototype.indexOf === 'function') {
1342 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1344 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1347 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
1350 throw new TypeError('val must be string, number or Buffer')
1353 function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1355 var arrLength = arr.length
1356 var valLength = val.length
1358 if (encoding !== undefined) {
1359 encoding = String(encoding).toLowerCase()
1360 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1361 encoding === 'utf16le' || encoding === 'utf-16le') {
1362 if (arr.length < 2 || val.length < 2) {
1372 function read (buf, i) {
1373 if (indexSize === 1) {
1376 return buf.readUInt16BE(i * indexSize)
1383 for (i = byteOffset; i < arrLength; i++) {
1384 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1385 if (foundIndex === -1) foundIndex = i
1386 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
1388 if (foundIndex !== -1) i -= i - foundIndex
1393 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1394 for (i = byteOffset; i >= 0; i--) {
1396 for (var j = 0; j < valLength; j++) {
1397 if (read(arr, i + j) !== read(val, j)) {
1409 Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1410 return this.indexOf(val, byteOffset, encoding) !== -1
1413 Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1414 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1417 Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1418 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1421 function hexWrite (buf, string, offset, length) {
1422 offset = Number(offset) || 0
1423 var remaining = buf.length - offset
1427 length = Number(length)
1428 if (length > remaining) {
1433 // must be an even number of digits
1434 var strLen = string.length
1435 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
1437 if (length > strLen / 2) {
1440 for (var i = 0; i < length; ++i) {
1441 var parsed = parseInt(string.substr(i * 2, 2), 16)
1442 if (numberIsNaN(parsed)) return i
1443 buf[offset + i] = parsed
1448 function utf8Write (buf, string, offset, length) {
1449 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1452 function asciiWrite (buf, string, offset, length) {
1453 return blitBuffer(asciiToBytes(string), buf, offset, length)
1456 function latin1Write (buf, string, offset, length) {
1457 return asciiWrite(buf, string, offset, length)
1460 function base64Write (buf, string, offset, length) {
1461 return blitBuffer(base64ToBytes(string), buf, offset, length)
1464 function ucs2Write (buf, string, offset, length) {
1465 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1468 Buffer.prototype.write = function write (string, offset, length, encoding) {
1469 // Buffer#write(string)
1470 if (offset === undefined) {
1472 length = this.length
1474 // Buffer#write(string, encoding)
1475 } else if (length === undefined && typeof offset === 'string') {
1477 length = this.length
1479 // Buffer#write(string, offset[, length][, encoding])
1480 } else if (isFinite(offset)) {
1481 offset = offset >>> 0
1482 if (isFinite(length)) {
1483 length = length >>> 0
1484 if (encoding === undefined) encoding = 'utf8'
1491 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1495 var remaining = this.length - offset
1496 if (length === undefined || length > remaining) length = remaining
1498 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1499 throw new RangeError('Attempt to write outside buffer bounds')
1502 if (!encoding) encoding = 'utf8'
1504 var loweredCase = false
1508 return hexWrite(this, string, offset, length)
1512 return utf8Write(this, string, offset, length)
1515 return asciiWrite(this, string, offset, length)
1519 return latin1Write(this, string, offset, length)
1522 // Warning: maxLength not taken into account in base64Write
1523 return base64Write(this, string, offset, length)
1529 return ucs2Write(this, string, offset, length)
1532 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1533 encoding = ('' + encoding).toLowerCase()
1539 Buffer.prototype.toJSON = function toJSON () {
1542 data: Array.prototype.slice.call(this._arr || this, 0)
1546 function base64Slice (buf, start, end) {
1547 if (start === 0 && end === buf.length) {
1548 return base64.fromByteArray(buf)
1550 return base64.fromByteArray(buf.slice(start, end))
1554 function utf8Slice (buf, start, end) {
1555 end = Math.min(buf.length, end)
1560 var firstByte = buf[i]
1561 var codePoint = null
1562 var bytesPerSequence = (firstByte > 0xEF) ? 4
1563 : (firstByte > 0xDF) ? 3
1564 : (firstByte > 0xBF) ? 2
1567 if (i + bytesPerSequence <= end) {
1568 var secondByte, thirdByte, fourthByte, tempCodePoint
1570 switch (bytesPerSequence) {
1572 if (firstByte < 0x80) {
1573 codePoint = firstByte
1577 secondByte = buf[i + 1]
1578 if ((secondByte & 0xC0) === 0x80) {
1579 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
1580 if (tempCodePoint > 0x7F) {
1581 codePoint = tempCodePoint
1586 secondByte = buf[i + 1]
1587 thirdByte = buf[i + 2]
1588 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1589 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
1590 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1591 codePoint = tempCodePoint
1596 secondByte = buf[i + 1]
1597 thirdByte = buf[i + 2]
1598 fourthByte = buf[i + 3]
1599 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1600 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
1601 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1602 codePoint = tempCodePoint
1608 if (codePoint === null) {
1609 // we did not generate a valid codePoint so insert a
1610 // replacement char (U+FFFD) and advance only 1 byte
1612 bytesPerSequence = 1
1613 } else if (codePoint > 0xFFFF) {
1614 // encode to utf16 (surrogate pair dance)
1615 codePoint -= 0x10000
1616 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1617 codePoint = 0xDC00 | codePoint & 0x3FF
1621 i += bytesPerSequence
1624 return decodeCodePointsArray(res)
1627 // Based on http://stackoverflow.com/a/22747272/680742, the browser with
1628 // the lowest limit is Chrome, with 0x10000 args.
1629 // We go 1 magnitude less, for safety
1630 var MAX_ARGUMENTS_LENGTH = 0x1000
1632 function decodeCodePointsArray (codePoints) {
1633 var len = codePoints.length
1634 if (len <= MAX_ARGUMENTS_LENGTH) {
1635 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1638 // Decode in chunks to avoid "call stack size exceeded".
1642 res += String.fromCharCode.apply(
1644 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1650 function asciiSlice (buf, start, end) {
1652 end = Math.min(buf.length, end)
1654 for (var i = start; i < end; ++i) {
1655 ret += String.fromCharCode(buf[i] & 0x7F)
1660 function latin1Slice (buf, start, end) {
1662 end = Math.min(buf.length, end)
1664 for (var i = start; i < end; ++i) {
1665 ret += String.fromCharCode(buf[i])
1670 function hexSlice (buf, start, end) {
1671 var len = buf.length
1673 if (!start || start < 0) start = 0
1674 if (!end || end < 0 || end > len) end = len
1677 for (var i = start; i < end; ++i) {
1678 out += toHex(buf[i])
1683 function utf16leSlice (buf, start, end) {
1684 var bytes = buf.slice(start, end)
1686 for (var i = 0; i < bytes.length; i += 2) {
1687 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
1692 Buffer.prototype.slice = function slice (start, end) {
1693 var len = this.length
1695 end = end === undefined ? len : ~~end
1699 if (start < 0) start = 0
1700 } else if (start > len) {
1706 if (end < 0) end = 0
1707 } else if (end > len) {
1711 if (end < start) end = start
1713 var newBuf = this.subarray(start, end)
1714 // Return an augmented `Uint8Array` instance
1715 newBuf.__proto__ = Buffer.prototype
1720 * Need to make sure that buffer isn't trying to write out of bounds.
1722 function checkOffset (offset, ext, length) {
1723 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1724 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1727 Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1728 offset = offset >>> 0
1729 byteLength = byteLength >>> 0
1730 if (!noAssert) checkOffset(offset, byteLength, this.length)
1732 var val = this[offset]
1735 while (++i < byteLength && (mul *= 0x100)) {
1736 val += this[offset + i] * mul
1742 Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1743 offset = offset >>> 0
1744 byteLength = byteLength >>> 0
1746 checkOffset(offset, byteLength, this.length)
1749 var val = this[offset + --byteLength]
1751 while (byteLength > 0 && (mul *= 0x100)) {
1752 val += this[offset + --byteLength] * mul
1758 Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1759 offset = offset >>> 0
1760 if (!noAssert) checkOffset(offset, 1, this.length)
1764 Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1765 offset = offset >>> 0
1766 if (!noAssert) checkOffset(offset, 2, this.length)
1767 return this[offset] | (this[offset + 1] << 8)
1770 Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1771 offset = offset >>> 0
1772 if (!noAssert) checkOffset(offset, 2, this.length)
1773 return (this[offset] << 8) | this[offset + 1]
1776 Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1777 offset = offset >>> 0
1778 if (!noAssert) checkOffset(offset, 4, this.length)
1780 return ((this[offset]) |
1781 (this[offset + 1] << 8) |
1782 (this[offset + 2] << 16)) +
1783 (this[offset + 3] * 0x1000000)
1786 Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1787 offset = offset >>> 0
1788 if (!noAssert) checkOffset(offset, 4, this.length)
1790 return (this[offset] * 0x1000000) +
1791 ((this[offset + 1] << 16) |
1792 (this[offset + 2] << 8) |
1796 Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1797 offset = offset >>> 0
1798 byteLength = byteLength >>> 0
1799 if (!noAssert) checkOffset(offset, byteLength, this.length)
1801 var val = this[offset]
1804 while (++i < byteLength && (mul *= 0x100)) {
1805 val += this[offset + i] * mul
1809 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1814 Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1815 offset = offset >>> 0
1816 byteLength = byteLength >>> 0
1817 if (!noAssert) checkOffset(offset, byteLength, this.length)
1821 var val = this[offset + --i]
1822 while (i > 0 && (mul *= 0x100)) {
1823 val += this[offset + --i] * mul
1827 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1832 Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1833 offset = offset >>> 0
1834 if (!noAssert) checkOffset(offset, 1, this.length)
1835 if (!(this[offset] & 0x80)) return (this[offset])
1836 return ((0xff - this[offset] + 1) * -1)
1839 Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1840 offset = offset >>> 0
1841 if (!noAssert) checkOffset(offset, 2, this.length)
1842 var val = this[offset] | (this[offset + 1] << 8)
1843 return (val & 0x8000) ? val | 0xFFFF0000 : val
1846 Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1847 offset = offset >>> 0
1848 if (!noAssert) checkOffset(offset, 2, this.length)
1849 var val = this[offset + 1] | (this[offset] << 8)
1850 return (val & 0x8000) ? val | 0xFFFF0000 : val
1853 Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1854 offset = offset >>> 0
1855 if (!noAssert) checkOffset(offset, 4, this.length)
1857 return (this[offset]) |
1858 (this[offset + 1] << 8) |
1859 (this[offset + 2] << 16) |
1860 (this[offset + 3] << 24)
1863 Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1864 offset = offset >>> 0
1865 if (!noAssert) checkOffset(offset, 4, this.length)
1867 return (this[offset] << 24) |
1868 (this[offset + 1] << 16) |
1869 (this[offset + 2] << 8) |
1873 Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1874 offset = offset >>> 0
1875 if (!noAssert) checkOffset(offset, 4, this.length)
1876 return ieee754.read(this, offset, true, 23, 4)
1879 Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1880 offset = offset >>> 0
1881 if (!noAssert) checkOffset(offset, 4, this.length)
1882 return ieee754.read(this, offset, false, 23, 4)
1885 Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1886 offset = offset >>> 0
1887 if (!noAssert) checkOffset(offset, 8, this.length)
1888 return ieee754.read(this, offset, true, 52, 8)
1891 Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1892 offset = offset >>> 0
1893 if (!noAssert) checkOffset(offset, 8, this.length)
1894 return ieee754.read(this, offset, false, 52, 8)
1897 function checkInt (buf, value, offset, ext, max, min) {
1898 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1899 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1900 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1903 Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1905 offset = offset >>> 0
1906 byteLength = byteLength >>> 0
1908 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1909 checkInt(this, value, offset, byteLength, maxBytes, 0)
1914 this[offset] = value & 0xFF
1915 while (++i < byteLength && (mul *= 0x100)) {
1916 this[offset + i] = (value / mul) & 0xFF
1919 return offset + byteLength
1922 Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1924 offset = offset >>> 0
1925 byteLength = byteLength >>> 0
1927 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1928 checkInt(this, value, offset, byteLength, maxBytes, 0)
1931 var i = byteLength - 1
1933 this[offset + i] = value & 0xFF
1934 while (--i >= 0 && (mul *= 0x100)) {
1935 this[offset + i] = (value / mul) & 0xFF
1938 return offset + byteLength
1941 Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1943 offset = offset >>> 0
1944 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1945 this[offset] = (value & 0xff)
1949 Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1951 offset = offset >>> 0
1952 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1953 this[offset] = (value & 0xff)
1954 this[offset + 1] = (value >>> 8)
1958 Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1960 offset = offset >>> 0
1961 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1962 this[offset] = (value >>> 8)
1963 this[offset + 1] = (value & 0xff)
1967 Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1969 offset = offset >>> 0
1970 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1971 this[offset + 3] = (value >>> 24)
1972 this[offset + 2] = (value >>> 16)
1973 this[offset + 1] = (value >>> 8)
1974 this[offset] = (value & 0xff)
1978 Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1980 offset = offset >>> 0
1981 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1982 this[offset] = (value >>> 24)
1983 this[offset + 1] = (value >>> 16)
1984 this[offset + 2] = (value >>> 8)
1985 this[offset + 3] = (value & 0xff)
1989 Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1991 offset = offset >>> 0
1993 var limit = Math.pow(2, (8 * byteLength) - 1)
1995 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2001 this[offset] = value & 0xFF
2002 while (++i < byteLength && (mul *= 0x100)) {
2003 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2006 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2009 return offset + byteLength
2012 Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2014 offset = offset >>> 0
2016 var limit = Math.pow(2, (8 * byteLength) - 1)
2018 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2021 var i = byteLength - 1
2024 this[offset + i] = value & 0xFF
2025 while (--i >= 0 && (mul *= 0x100)) {
2026 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2029 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2032 return offset + byteLength
2035 Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2037 offset = offset >>> 0
2038 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
2039 if (value < 0) value = 0xff + value + 1
2040 this[offset] = (value & 0xff)
2044 Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2046 offset = offset >>> 0
2047 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2048 this[offset] = (value & 0xff)
2049 this[offset + 1] = (value >>> 8)
2053 Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2055 offset = offset >>> 0
2056 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2057 this[offset] = (value >>> 8)
2058 this[offset + 1] = (value & 0xff)
2062 Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2064 offset = offset >>> 0
2065 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2066 this[offset] = (value & 0xff)
2067 this[offset + 1] = (value >>> 8)
2068 this[offset + 2] = (value >>> 16)
2069 this[offset + 3] = (value >>> 24)
2073 Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2075 offset = offset >>> 0
2076 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2077 if (value < 0) value = 0xffffffff + value + 1
2078 this[offset] = (value >>> 24)
2079 this[offset + 1] = (value >>> 16)
2080 this[offset + 2] = (value >>> 8)
2081 this[offset + 3] = (value & 0xff)
2085 function checkIEEE754 (buf, value, offset, ext, max, min) {
2086 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2087 if (offset < 0) throw new RangeError('Index out of range')
2090 function writeFloat (buf, value, offset, littleEndian, noAssert) {
2092 offset = offset >>> 0
2094 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2096 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2100 Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2101 return writeFloat(this, value, offset, true, noAssert)
2104 Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2105 return writeFloat(this, value, offset, false, noAssert)
2108 function writeDouble (buf, value, offset, littleEndian, noAssert) {
2110 offset = offset >>> 0
2112 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2114 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2118 Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2119 return writeDouble(this, value, offset, true, noAssert)
2122 Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2123 return writeDouble(this, value, offset, false, noAssert)
2126 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2127 Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2128 if (!start) start = 0
2129 if (!end && end !== 0) end = this.length
2130 if (targetStart >= target.length) targetStart = target.length
2131 if (!targetStart) targetStart = 0
2132 if (end > 0 && end < start) end = start
2134 // Copy 0 bytes; we're done
2135 if (end === start) return 0
2136 if (target.length === 0 || this.length === 0) return 0
2138 // Fatal error conditions
2139 if (targetStart < 0) {
2140 throw new RangeError('targetStart out of bounds')
2142 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
2143 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2146 if (end > this.length) end = this.length
2147 if (target.length - targetStart < end - start) {
2148 end = target.length - targetStart + start
2151 var len = end - start
2154 if (this === target && start < targetStart && targetStart < end) {
2155 // descending copy from end
2156 for (i = len - 1; i >= 0; --i) {
2157 target[i + targetStart] = this[i + start]
2159 } else if (len < 1000) {
2160 // ascending copy from start
2161 for (i = 0; i < len; ++i) {
2162 target[i + targetStart] = this[i + start]
2165 Uint8Array.prototype.set.call(
2167 this.subarray(start, start + len),
2176 // buffer.fill(number[, offset[, end]])
2177 // buffer.fill(buffer[, offset[, end]])
2178 // buffer.fill(string[, offset[, end]][, encoding])
2179 Buffer.prototype.fill = function fill (val, start, end, encoding) {
2180 // Handle string cases:
2181 if (typeof val === 'string') {
2182 if (typeof start === 'string') {
2186 } else if (typeof end === 'string') {
2190 if (val.length === 1) {
2191 var code = val.charCodeAt(0)
2196 if (encoding !== undefined && typeof encoding !== 'string') {
2197 throw new TypeError('encoding must be a string')
2199 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2200 throw new TypeError('Unknown encoding: ' + encoding)
2202 } else if (typeof val === 'number') {
2206 // Invalid ranges are not set to a default, so can range check early.
2207 if (start < 0 || this.length < start || this.length < end) {
2208 throw new RangeError('Out of range index')
2216 end = end === undefined ? this.length : end >>> 0
2221 if (typeof val === 'number') {
2222 for (i = start; i < end; ++i) {
2226 var bytes = Buffer.isBuffer(val)
2228 : new Buffer(val, encoding)
2229 var len = bytes.length
2230 for (i = 0; i < end - start; ++i) {
2231 this[i + start] = bytes[i % len]
2241 var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
2243 function base64clean (str) {
2244 // Node strips out invalid characters like \n and \t from the string, base64-js does not
2245 str = str.trim().replace(INVALID_BASE64_RE, '')
2246 // Node converts strings with length < 2 to ''
2247 if (str.length < 2) return ''
2248 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2249 while (str.length % 4 !== 0) {
2255 function toHex (n) {
2256 if (n < 16) return '0' + n.toString(16)
2257 return n.toString(16)
2260 function utf8ToBytes (string, units) {
2261 units = units || Infinity
2263 var length = string.length
2264 var leadSurrogate = null
2267 for (var i = 0; i < length; ++i) {
2268 codePoint = string.charCodeAt(i)
2270 // is surrogate component
2271 if (codePoint > 0xD7FF && codePoint < 0xE000) {
2272 // last char was a lead
2273 if (!leadSurrogate) {
2275 if (codePoint > 0xDBFF) {
2277 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2279 } else if (i + 1 === length) {
2281 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2286 leadSurrogate = codePoint
2292 if (codePoint < 0xDC00) {
2293 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2294 leadSurrogate = codePoint
2298 // valid surrogate pair
2299 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
2300 } else if (leadSurrogate) {
2301 // valid bmp char, but last char was a lead
2302 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2305 leadSurrogate = null
2308 if (codePoint < 0x80) {
2309 if ((units -= 1) < 0) break
2310 bytes.push(codePoint)
2311 } else if (codePoint < 0x800) {
2312 if ((units -= 2) < 0) break
2314 codePoint >> 0x6 | 0xC0,
2315 codePoint & 0x3F | 0x80
2317 } else if (codePoint < 0x10000) {
2318 if ((units -= 3) < 0) break
2320 codePoint >> 0xC | 0xE0,
2321 codePoint >> 0x6 & 0x3F | 0x80,
2322 codePoint & 0x3F | 0x80
2324 } else if (codePoint < 0x110000) {
2325 if ((units -= 4) < 0) break
2327 codePoint >> 0x12 | 0xF0,
2328 codePoint >> 0xC & 0x3F | 0x80,
2329 codePoint >> 0x6 & 0x3F | 0x80,
2330 codePoint & 0x3F | 0x80
2333 throw new Error('Invalid code point')
2340 function asciiToBytes (str) {
2342 for (var i = 0; i < str.length; ++i) {
2343 // Node's code seems to be doing this and not & 0x7F..
2344 byteArray.push(str.charCodeAt(i) & 0xFF)
2349 function utf16leToBytes (str, units) {
2352 for (var i = 0; i < str.length; ++i) {
2353 if ((units -= 2) < 0) break
2355 c = str.charCodeAt(i)
2365 function base64ToBytes (str) {
2366 return base64.toByteArray(base64clean(str))
2369 function blitBuffer (src, dst, offset, length) {
2370 for (var i = 0; i < length; ++i) {
2371 if ((i + offset >= dst.length) || (i >= src.length)) break
2372 dst[i + offset] = src[i]
2377 // ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
2378 // but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
2379 function isArrayBuffer (obj) {
2380 return obj instanceof ArrayBuffer ||
2381 (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
2382 typeof obj.byteLength === 'number')
2385 // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
2386 function isArrayBufferView (obj) {
2387 return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
2390 function numberIsNaN (obj) {
2391 return obj !== obj // eslint-disable-line no-self-compare
2394 },{"base64-js":3,"ieee754":17}],8:[function(require,module,exports){
2397 module.exports = earcut;
2398 module.exports.default = earcut;
2400 function earcut(data, holeIndices, dim) {
2404 var hasHoles = holeIndices && holeIndices.length,
2405 outerLen = hasHoles ? holeIndices[0] * dim : data.length,
2406 outerNode = linkedList(data, 0, outerLen, dim, true),
2409 if (!outerNode) return triangles;
2411 var minX, minY, maxX, maxY, x, y, invSize;
2413 if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
2415 // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
2416 if (data.length > 80 * dim) {
2417 minX = maxX = data[0];
2418 minY = maxY = data[1];
2420 for (var i = dim; i < outerLen; i += dim) {
2423 if (x < minX) minX = x;
2424 if (y < minY) minY = y;
2425 if (x > maxX) maxX = x;
2426 if (y > maxY) maxY = y;
2429 // minX, minY and invSize are later used to transform coords into integers for z-order calculation
2430 invSize = Math.max(maxX - minX, maxY - minY);
2431 invSize = invSize !== 0 ? 1 / invSize : 0;
2434 earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
2439 // create a circular doubly linked list from polygon points in the specified winding order
2440 function linkedList(data, start, end, dim, clockwise) {
2443 if (clockwise === (signedArea(data, start, end, dim) > 0)) {
2444 for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
2446 for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
2449 if (last && equals(last, last.next)) {
2457 // eliminate colinear or duplicate points
2458 function filterPoints(start, end) {
2459 if (!start) return start;
2460 if (!end) end = start;
2467 if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
2470 if (p === p.next) break;
2476 } while (again || p !== end);
2481 // main ear slicing loop which triangulates a polygon (given as a linked list)
2482 function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
2485 // interlink polygon nodes in z-order
2486 if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
2491 // iterate through ears, slicing them one by one
2492 while (ear.prev !== ear.next) {
2496 if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
2497 // cut off the triangle
2498 triangles.push(prev.i / dim);
2499 triangles.push(ear.i / dim);
2500 triangles.push(next.i / dim);
2504 // skipping the next vertice leads to less sliver triangles
2513 // if we looped through the whole remaining polygon and can't find any more ears
2515 // try filtering points and slicing again
2517 earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
2519 // if this didn't work, try curing all small self-intersections locally
2520 } else if (pass === 1) {
2521 ear = cureLocalIntersections(ear, triangles, dim);
2522 earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
2524 // as a last resort, try splitting the remaining polygon into two
2525 } else if (pass === 2) {
2526 splitEarcut(ear, triangles, dim, minX, minY, invSize);
2534 // check whether a polygon node forms a valid ear with adjacent nodes
2535 function isEar(ear) {
2540 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2542 // now make sure we don't have other points inside the potential ear
2543 var p = ear.next.next;
2545 while (p !== ear.prev) {
2546 if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2547 area(p.prev, p, p.next) >= 0) return false;
2554 function isEarHashed(ear, minX, minY, invSize) {
2559 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2561 // triangle bbox; min & max are calculated like this for speed
2562 var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
2563 minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
2564 maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
2565 maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
2567 // z-order range for the current triangle bbox;
2568 var minZ = zOrder(minTX, minTY, minX, minY, invSize),
2569 maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
2571 // first look for points inside the triangle in increasing z-order
2574 while (p && p.z <= maxZ) {
2575 if (p !== ear.prev && p !== ear.next &&
2576 pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2577 area(p.prev, p, p.next) >= 0) return false;
2581 // then look for points in decreasing z-order
2584 while (p && p.z >= minZ) {
2585 if (p !== ear.prev && p !== ear.next &&
2586 pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2587 area(p.prev, p, p.next) >= 0) return false;
2594 // go through all polygon nodes and cure small local self-intersections
2595 function cureLocalIntersections(start, triangles, dim) {
2601 if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
2603 triangles.push(a.i / dim);
2604 triangles.push(p.i / dim);
2605 triangles.push(b.i / dim);
2607 // remove two nodes involved
2614 } while (p !== start);
2619 // try splitting polygon into two and triangulate them independently
2620 function splitEarcut(start, triangles, dim, minX, minY, invSize) {
2621 // look for a valid diagonal that divides the polygon into two
2624 var b = a.next.next;
2625 while (b !== a.prev) {
2626 if (a.i !== b.i && isValidDiagonal(a, b)) {
2627 // split the polygon in two by the diagonal
2628 var c = splitPolygon(a, b);
2630 // filter colinear points around the cuts
2631 a = filterPoints(a, a.next);
2632 c = filterPoints(c, c.next);
2634 // run earcut on each half
2635 earcutLinked(a, triangles, dim, minX, minY, invSize);
2636 earcutLinked(c, triangles, dim, minX, minY, invSize);
2642 } while (a !== start);
2645 // link every hole into the outer loop, producing a single-ring polygon without holes
2646 function eliminateHoles(data, holeIndices, outerNode, dim) {
2648 i, len, start, end, list;
2650 for (i = 0, len = holeIndices.length; i < len; i++) {
2651 start = holeIndices[i] * dim;
2652 end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2653 list = linkedList(data, start, end, dim, false);
2654 if (list === list.next) list.steiner = true;
2655 queue.push(getLeftmost(list));
2658 queue.sort(compareX);
2660 // process holes from left to right
2661 for (i = 0; i < queue.length; i++) {
2662 eliminateHole(queue[i], outerNode);
2663 outerNode = filterPoints(outerNode, outerNode.next);
2669 function compareX(a, b) {
2673 // find a bridge between vertices that connects hole with an outer ring and and link it
2674 function eliminateHole(hole, outerNode) {
2675 outerNode = findHoleBridge(hole, outerNode);
2677 var b = splitPolygon(outerNode, hole);
2678 filterPoints(b, b.next);
2682 // David Eberly's algorithm for finding a bridge between hole and outer polygon
2683 function findHoleBridge(hole, outerNode) {
2690 // find a segment intersected by a ray from the hole's leftmost point to the left;
2691 // segment's endpoint with lesser x will be potential connection point
2693 if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
2694 var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
2695 if (x <= hx && x > qx) {
2698 if (hy === p.y) return p;
2699 if (hy === p.next.y) return p.next;
2701 m = p.x < p.next.x ? p : p.next;
2705 } while (p !== outerNode);
2707 if (!m) return null;
2709 if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
2711 // look for points inside the triangle of hole point, segment intersection and endpoint;
2712 // if there are no points found, we have a valid connection;
2713 // otherwise choose the point of the minimum angle with the ray as connection point
2723 while (p !== stop) {
2724 if (hx >= p.x && p.x >= mx && hx !== p.x &&
2725 pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
2727 tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
2729 if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
2741 // interlink polygon nodes in z-order
2742 function indexCurve(start, minX, minY, invSize) {
2745 if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
2749 } while (p !== start);
2751 p.prevZ.nextZ = null;
2757 // Simon Tatham's linked list merge sort algorithm
2758 // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
2759 function sortLinked(list) {
2760 var i, p, q, e, tail, numMerges, pSize, qSize,
2773 for (i = 0; i < inSize; i++) {
2780 while (pSize > 0 || (qSize > 0 && q)) {
2782 if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
2792 if (tail) tail.nextZ = e;
2805 } while (numMerges > 1);
2810 // z-order of a point given coords and inverse of the longer side of data bbox
2811 function zOrder(x, y, minX, minY, invSize) {
2812 // coords are transformed into non-negative 15-bit integer range
2813 x = 32767 * (x - minX) * invSize;
2814 y = 32767 * (y - minY) * invSize;
2816 x = (x | (x << 8)) & 0x00FF00FF;
2817 x = (x | (x << 4)) & 0x0F0F0F0F;
2818 x = (x | (x << 2)) & 0x33333333;
2819 x = (x | (x << 1)) & 0x55555555;
2821 y = (y | (y << 8)) & 0x00FF00FF;
2822 y = (y | (y << 4)) & 0x0F0F0F0F;
2823 y = (y | (y << 2)) & 0x33333333;
2824 y = (y | (y << 1)) & 0x55555555;
2826 return x | (y << 1);
2829 // find the leftmost node of a polygon ring
2830 function getLeftmost(start) {
2834 if (p.x < leftmost.x) leftmost = p;
2836 } while (p !== start);
2841 // check if a point lies within a convex triangle
2842 function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
2843 return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
2844 (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
2845 (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
2848 // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
2849 function isValidDiagonal(a, b) {
2850 return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
2851 locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
2854 // signed area of a triangle
2855 function area(p, q, r) {
2856 return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
2859 // check if two points are equal
2860 function equals(p1, p2) {
2861 return p1.x === p2.x && p1.y === p2.y;
2864 // check if two segments intersect
2865 function intersects(p1, q1, p2, q2) {
2866 if ((equals(p1, q1) && equals(p2, q2)) ||
2867 (equals(p1, q2) && equals(p2, q1))) return true;
2868 return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
2869 area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
2872 // check if a polygon diagonal intersects any polygon segments
2873 function intersectsPolygon(a, b) {
2876 if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
2877 intersects(p, p.next, a, b)) return true;
2884 // check if a polygon diagonal is locally inside the polygon
2885 function locallyInside(a, b) {
2886 return area(a.prev, a, a.next) < 0 ?
2887 area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
2888 area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
2891 // check if the middle point of a polygon diagonal is inside the polygon
2892 function middleInside(a, b) {
2895 px = (a.x + b.x) / 2,
2896 py = (a.y + b.y) / 2;
2898 if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
2899 (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
2907 // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
2908 // if one belongs to the outer ring and another to a hole, it merges it into a single ring
2909 function splitPolygon(a, b) {
2910 var a2 = new Node(a.i, a.x, a.y),
2911 b2 = new Node(b.i, b.x, b.y),
2930 // create a node and optionally link it with previous one (in a circular doubly linked list)
2931 function insertNode(i, x, y, last) {
2932 var p = new Node(i, x, y);
2947 function removeNode(p) {
2948 p.next.prev = p.prev;
2949 p.prev.next = p.next;
2951 if (p.prevZ) p.prevZ.nextZ = p.nextZ;
2952 if (p.nextZ) p.nextZ.prevZ = p.prevZ;
2955 function Node(i, x, y) {
2956 // vertice index in coordinates array
2959 // vertex coordinates
2963 // previous and next vertice nodes in a polygon ring
2967 // z-order curve value
2970 // previous and next nodes in z-order
2974 // indicates whether this is a steiner point
2975 this.steiner = false;
2978 // return a percentage difference between the polygon area and its triangulation area;
2979 // used to verify correctness of triangulation
2980 earcut.deviation = function (data, holeIndices, dim, triangles) {
2981 var hasHoles = holeIndices && holeIndices.length;
2982 var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
2984 var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
2986 for (var i = 0, len = holeIndices.length; i < len; i++) {
2987 var start = holeIndices[i] * dim;
2988 var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2989 polygonArea -= Math.abs(signedArea(data, start, end, dim));
2993 var trianglesArea = 0;
2994 for (i = 0; i < triangles.length; i += 3) {
2995 var a = triangles[i] * dim;
2996 var b = triangles[i + 1] * dim;
2997 var c = triangles[i + 2] * dim;
2998 trianglesArea += Math.abs(
2999 (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
3000 (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
3003 return polygonArea === 0 && trianglesArea === 0 ? 0 :
3004 Math.abs((trianglesArea - polygonArea) / polygonArea);
3007 function signedArea(data, start, end, dim) {
3009 for (var i = start, j = end - dim; i < end; i += dim) {
3010 sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
3016 // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
3017 earcut.flatten = function (data) {
3018 var dim = data[0][0].length,
3019 result = {vertices: [], holes: [], dimensions: dim},
3022 for (var i = 0; i < data.length; i++) {
3023 for (var j = 0; j < data[i].length; j++) {
3024 for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
3027 holeIndex += data[i - 1].length;
3028 result.holes.push(holeIndex);
3034 },{}],9:[function(require,module,exports){
3037 var OneVersionConstraint = require('individual/one-version');
3039 var MY_VERSION = '7';
3040 OneVersionConstraint('ev-store', MY_VERSION);
3042 var hashKey = '__EV_STORE_KEY@' + MY_VERSION;
3044 module.exports = EvStore;
3046 function EvStore(elem) {
3047 var hash = elem[hashKey];
3050 hash = elem[hashKey] = {};
3056 },{"individual/one-version":19}],10:[function(require,module,exports){
3058 var request = require('./request');
3059 var buildQueryObject = require('./buildQueryObject');
3060 var isArray = Array.isArray;
3062 function simpleExtend(obj, obj2) {
3064 for (prop in obj2) {
3065 obj[prop] = obj2[prop];
3070 function XMLHttpSource(jsongUrl, config) {
3071 this._jsongUrl = jsongUrl;
3072 if (typeof config === 'number') {
3078 this._config = simpleExtend({
3084 XMLHttpSource.prototype = {
3085 // because javascript
3086 constructor: XMLHttpSource,
3088 * buildQueryObject helper
3090 buildQueryObject: buildQueryObject,
3093 * @inheritDoc DataSource#get
3095 get: function httpSourceGet(pathSet) {
3097 var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3101 var config = simpleExtend(queryObject, this._config);
3102 // pass context for onBeforeRequest callback
3104 return request(method, config, context);
3108 * @inheritDoc DataSource#set
3110 set: function httpSourceSet(jsongEnv) {
3111 var method = 'POST';
3112 var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3113 jsonGraph: jsongEnv,
3116 var config = simpleExtend(queryObject, this._config);
3117 config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3119 // pass context for onBeforeRequest callback
3121 return request(method, config, context);
3126 * @inheritDoc DataSource#call
3128 call: function httpSourceCall(callPath, args, pathSuffix, paths) {
3129 // arguments defaults
3131 pathSuffix = pathSuffix || [];
3132 paths = paths || [];
3134 var method = 'POST';
3136 queryData.push('method=call');
3137 queryData.push('callPath=' + encodeURIComponent(JSON.stringify(callPath)));
3138 queryData.push('arguments=' + encodeURIComponent(JSON.stringify(args)));
3139 queryData.push('pathSuffixes=' + encodeURIComponent(JSON.stringify(pathSuffix)));
3140 queryData.push('paths=' + encodeURIComponent(JSON.stringify(paths)));
3142 var queryObject = this.buildQueryObject(this._jsongUrl, method, queryData.join('&'));
3143 var config = simpleExtend(queryObject, this._config);
3144 config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3146 // pass context for onBeforeRequest callback
3148 return request(method, config, context);
3152 XMLHttpSource.XMLHttpSource = XMLHttpSource;
3153 XMLHttpSource['default'] = XMLHttpSource;
3155 module.exports = XMLHttpSource;
3157 },{"./buildQueryObject":11,"./request":14}],11:[function(require,module,exports){
3159 module.exports = function buildQueryObject(url, method, queryData) {
3162 var data = {url: url};
3163 var isQueryParamUrl = url.indexOf('?') !== -1;
3164 var startUrl = (isQueryParamUrl) ? '&' : '?';
3166 if (typeof queryData === 'string') {
3167 qData.push(queryData);
3170 keys = Object.keys(queryData);
3171 keys.forEach(function (k) {
3172 var value = (typeof queryData[k] === 'object') ? JSON.stringify(queryData[k]) : queryData[k];
3173 qData.push(k + '=' + encodeURIComponent(value));
3177 if (method === 'GET') {
3178 data.url += startUrl + qData.join('&');
3180 data.data = qData.join('&');
3186 },{}],12:[function(require,module,exports){
3189 // Get CORS support even for older IE
3190 module.exports = function getCORSRequest() {
3191 var xhr = new global.XMLHttpRequest();
3192 if ('withCredentials' in xhr) {
3194 } else if (!!global.XDomainRequest) {
3195 return new XDomainRequest();
3197 throw new Error('CORS is not supported by your browser');
3201 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3203 },{}],13:[function(require,module,exports){
3206 module.exports = function getXMLHttpRequest() {
3210 if (global.XMLHttpRequest) {
3211 return new global.XMLHttpRequest();
3214 progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
3215 for (i = 0; i < 3; i++) {
3217 progId = progIds[i];
3218 if (new global.ActiveXObject(progId)) {
3223 return new global.ActiveXObject(progId);
3225 throw new Error('XMLHttpRequest is not supported by your browser');
3230 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3232 },{}],14:[function(require,module,exports){
3234 var getXMLHttpRequest = require('./getXMLHttpRequest');
3235 var getCORSRequest = require('./getCORSRequest');
3236 var hasOwnProp = Object.prototype.hasOwnProperty;
3238 var noop = function() {};
3240 function Observable() {}
3242 Observable.create = function(subscribe) {
3243 var o = new Observable();
3245 o.subscribe = function(onNext, onError, onCompleted) {
3250 if (typeof onNext === 'function') {
3253 onError: (onError || noop),
3254 onCompleted: (onCompleted || noop)
3260 disposable = subscribe(observer);
3262 if (typeof disposable === 'function') {
3274 function request(method, options, context) {
3275 return Observable.create(function requestObserver(observer) {
3278 method: method || 'GET',
3282 responseType: 'json'
3291 for (prop in options) {
3292 if (hasOwnProp.call(options, prop)) {
3293 config[prop] = options[prop];
3297 // Add request with Headers
3298 if (!config.crossDomain && !config.headers['X-Requested-With']) {
3299 config.headers['X-Requested-With'] = 'XMLHttpRequest';
3302 // allow the user to mutate the config open
3303 if (context.onBeforeRequest != null) {
3304 context.onBeforeRequest(config);
3309 xhr = config.crossDomain ? getCORSRequest() : getXMLHttpRequest();
3311 observer.onError(err);
3314 // Takes the url and opens the connection
3316 xhr.open(config.method, config.url, config.async, config.user, config.password);
3318 xhr.open(config.method, config.url, config.async);
3321 // Sets timeout information
3322 xhr.timeout = config.timeout;
3324 // Anything but explicit false results in true.
3325 xhr.withCredentials = config.withCredentials !== false;
3327 // Fills the request headers
3328 headers = config.headers;
3329 for (header in headers) {
3330 if (hasOwnProp.call(headers, header)) {
3331 xhr.setRequestHeader(header, headers[header]);
3335 if (config.responseType) {
3337 xhr.responseType = config.responseType;
3339 // WebKit added support for the json responseType value on 09/03/2013
3340 // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
3341 // known to throw when setting the value "json" as the response type. Other older
3342 // browsers implementing the responseType
3344 // The json response type can be ignored if not supported, because JSON payloads are
3345 // parsed on the client-side regardless.
3346 if (config.responseType !== 'json') {
3352 xhr.onreadystatechange = function onreadystatechange(e) {
3354 if (xhr.readyState === 4) {
3357 onXhrLoad(observer, xhr, e);
3363 xhr.ontimeout = function ontimeout(e) {
3366 onXhrError(observer, xhr, 'timeout error', e);
3371 xhr.send(config.data);
3374 observer.onError(e);
3377 return function dispose() {
3378 // Doesn't work in IE9
3379 if (!isDone && xhr.readyState !== 4) {
3388 * General handling of ultimate failure (after appropriate retries)
3390 function _handleXhrError(observer, textStatus, errorThrown) {
3391 // IE9: cross-domain request may be considered errors
3393 errorThrown = new Error(textStatus);
3396 observer.onError(errorThrown);
3399 function onXhrLoad(observer, xhr, e) {
3404 // If there's no observer, the request has been (or is being) cancelled.
3405 if (xhr && observer) {
3406 responseType = xhr.responseType;
3407 // responseText is the old-school way of retrieving response (supported by IE8 & 9)
3408 // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
3409 responseData = ('response' in xhr) ? xhr.response : xhr.responseText;
3411 // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
3412 var status = (xhr.status === 1223) ? 204 : xhr.status;
3414 if (status >= 200 && status <= 399) {
3416 if (responseType !== 'json') {
3417 responseData = JSON.parse(responseData || '');
3419 if (typeof responseData === 'string') {
3420 responseData = JSON.parse(responseData || '');
3423 _handleXhrError(observer, 'invalid json', e);
3425 observer.onNext(responseData);
3426 observer.onCompleted();
3429 } else if (status === 401 || status === 403 || status === 407) {
3431 return _handleXhrError(observer, responseData);
3433 } else if (status === 410) {
3435 return _handleXhrError(observer, responseData);
3437 } else if (status === 408 || status === 504) {
3439 return _handleXhrError(observer, responseData);
3443 return _handleXhrError(observer, responseData || ('Response code ' + status));
3449 function onXhrError(observer, xhr, status, e) {
3450 _handleXhrError(observer, status || xhr.statusText || 'request error', e);
3453 module.exports = request;
3455 },{"./getCORSRequest":12,"./getXMLHttpRequest":13}],15:[function(require,module,exports){
3457 !function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.falcor=t()}}(function(){var t;return function e(t,n,r){function o(s,u){if(!n[s]){if(!t[s]){var a="function"==typeof require&&require;if(!u&&a)return a(s,!0);if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var p=n[s]={exports:{}};t[s][0].call(p.exports,function(e){var n=t[s][1][e];return o(n?n:e)},p,p.exports,e,t,n,r)}return n[s].exports}for(var i="function"==typeof require&&require,s=0;s<r.length;s++)o(r[s]);return o}({1:[function(t,e,n){var r=t(32),o=t(130);r.atom=o.atom,r.ref=o.ref,r.error=o.error,r.pathValue=o.pathValue,r.HttpDataSource=t(125),e.exports=r},{125:125,130:130,32:32}],2:[function(t,e,n){function r(t){var e=t||{};this._root=e._root||new o(e),this._path=e.path||e._path||[],this._scheduler=e.scheduler||e._scheduler||new l,this._source=e.source||e._source,this._request=e.request||e._request||new s(this,this._scheduler),this._ID=N++,"number"==typeof e.maxSize?this._maxSize=e.maxSize:this._maxSize=e._maxSize||r.prototype._maxSize,"number"==typeof e.collectRatio?this._collectRatio=e.collectRatio:this._collectRatio=e._collectRatio||r.prototype._collectRatio,(e.boxed||e.hasOwnProperty("_boxed"))&&(this._boxed=e.boxed||e._boxed),(e.materialized||e.hasOwnProperty("_materialized"))&&(this._materialized=e.materialized||e._materialized),"boolean"==typeof e.treatErrorsAsValues?this._treatErrorsAsValues=e.treatErrorsAsValues:e.hasOwnProperty("_treatErrorsAsValues")&&(this._treatErrorsAsValues=e._treatErrorsAsValues),e.cache&&this.setCache(e.cache)}var o=t(4),i=t(3),s=t(55),u=t(64),a=t(65),c=t(61),p=t(63),h=t(73),f=t(75),l=t(74),d=t(81),v=t(84),y=t(49),b=t(134),m=t(88),g=t(100),w=t(96),x=t(102),_=t(98),S=t(99),E=t(77),C=t(76),A=t(130),N=0,k=t(116),O=function(){},P=t(14),j=t(19),D={pathValue:!0,pathSyntax:!0,json:!0,jsonGraph:!0},q=t(72);e.exports=r,r.ref=A.ref,r.atom=A.atom,r.error=A.error,r.pathValue=A.pathValue,r.prototype.constructor=r,r.prototype._materialized=!1,r.prototype._boxed=!1,r.prototype._progressive=!1,r.prototype._treatErrorsAsValues=!1,r.prototype._maxSize=Math.pow(2,53)-1,r.prototype._collectRatio=.75,r.prototype.get=t(71),r.prototype._getWithPaths=t(70),r.prototype.set=function(){var t=k(arguments,D,"set");return t!==!0?new u(function(e){e.onError(t)}):this._set.apply(this,arguments)},r.prototype.preload=function(){var t=k(arguments,q,"preload");if(t!==!0)return new u(function(e){e.onError(t)});var e=Array.prototype.slice.call(arguments),n=this;return new u(function(t){return n.get.apply(n,e).subscribe(function(){},function(e){t.onError(e)},function(){t.onCompleted()})})},r.prototype._set=function(){var t,e=-1,n=arguments.length,r=arguments[n-1];for(w(r)?n-=1:r=void 0,t=new Array(n);++e<n;)t[e]=arguments[e];return a.create(this,t,r)},r.prototype.call=function(){var t,e=-1,n=arguments.length;for(t=new Array(n);++e<n;){var r=arguments[e];t[e]=r;var o=typeof r;if(e>1&&!Array.isArray(r)||0===e&&!Array.isArray(r)&&"string"!==o||1===e&&!Array.isArray(r)&&!x(r))return new u(function(t){t.onError(new Error("Invalid argument"))})}return c.create(this,t)},r.prototype.invalidate=function(){var t,e=-1,n=arguments.length,r=arguments[n-1];for(t=new Array(n);++e<n;)if(t[e]=b.fromPath(arguments[e]),"object"!=typeof t[e])throw new Error("Invalid argument");p.create(this,t,r).subscribe(O,function(t){throw t})},r.prototype.deref=t(5),r.prototype.getValue=t(16),r.prototype.setValue=t(79),r.prototype._getValueSync=t(24),r.prototype._setValueSync=t(80),r.prototype._derefSync=t(6),r.prototype.setCache=function(t){var e=this._root.cache;if(t!==e){var n=this._root,r=this._path;this._path=[],this._root.cache={},"undefined"!=typeof e&&y(n,n.expired,m(e),0),S(t)?C(this,[t]):_(t)?E(this,[t]):g(t)&&E(this,[{json:t}]),this._path=r}else"undefined"==typeof e&&(this._root.cache={});return this},r.prototype.getCache=function(){var t=v(arguments);if(0===t.length)return P(this._root.cache);var e=[{}],n=this._path;return j.getWithPathsAsJSONGraph(this,t,e),this._path=n,e[0].jsonGraph},r.prototype.getVersion=function(t){var e=t&&b.fromPath(t)||[];if(Array.isArray(e)===!1)throw new Error("Model#getVersion must be called with an Array path.");return this._path.length&&(e=this._path.concat(e)),this._getVersion(this,e)},r.prototype._syncCheck=function(t){if(Boolean(this._source)&&this._root.syncRefCount<=0&&this._root.unsafeMode===!1)throw new Error("Model#"+t+" may only be called within the context of a request selector.");return!0},r.prototype._clone=function(t){var e=new r(this);for(var n in t){var o=t[n];"delete"===o?delete e[n]:e[n]=o}return e.setCache=void 0,e},r.prototype.batch=function(t){var e=t;"number"==typeof e?e=new f(Math.round(Math.abs(e))):e&&e.schedule||(e=new h);var n=this._clone();return n._request=new s(n,e),n},r.prototype.unbatch=function(){var t=this._clone();return t._request=new s(t,new l),t},r.prototype.treatErrorsAsValues=function(){return this._clone({_treatErrorsAsValues:!0})},r.prototype.asDataSource=function(){return new i(this)},r.prototype._materialize=function(){return this._clone({_materialized:!0})},r.prototype._dematerialize=function(){return this._clone({_materialized:"delete"})},r.prototype.boxValues=function(){return this._clone({_boxed:!0})},r.prototype.unboxValues=function(){return this._clone({_boxed:"delete"})},r.prototype.withoutDataSource=function(){return this._clone({_source:"delete"})},r.prototype.toJSON=function(){return{$type:"ref",value:this._path}},r.prototype.getPath=function(){return d(this._path)},r.prototype._getBoundValue=t(13),r.prototype._getVersion=t(18),r.prototype._getValueSync=t(17),r.prototype._getPathValuesAsPathMap=j.getWithPathsAsPathMap,r.prototype._getPathValuesAsJSONG=j.getWithPathsAsJSONGraph,r.prototype._setPathValuesAsJSON=t(78),r.prototype._setPathValuesAsJSONG=t(78),r.prototype._setPathValuesAsPathMap=t(78),r.prototype._setPathValuesAsValues=t(78),r.prototype._setPathMapsAsJSON=t(77),r.prototype._setPathMapsAsJSONG=t(77),r.prototype._setPathMapsAsPathMap=t(77),r.prototype._setPathMapsAsValues=t(77),r.prototype._setJSONGsAsJSON=t(76),r.prototype._setJSONGsAsJSONG=t(76),r.prototype._setJSONGsAsPathMap=t(76),r.prototype._setJSONGsAsValues=t(76),r.prototype._setCache=t(77),r.prototype._invalidatePathValuesAsJSON=t(48),r.prototype._invalidatePathMapsAsJSON=t(47)},{100:100,102:102,116:116,13:13,130:130,134:134,14:14,16:16,17:17,18:18,19:19,24:24,3:3,4:4,47:47,48:48,49:49,5:5,55:55,6:6,61:61,63:63,64:64,65:65,70:70,71:71,72:72,73:73,74:74,75:75,76:76,77:77,78:78,79:79,80:80,81:81,84:84,88:88,96:96,98:98,99:99}],3:[function(t,e,n){function r(t){this._model=t._materialize().treatErrorsAsValues()}r.prototype.get=function(t){return this._model.get.apply(this._model,t)._toJSONG()},r.prototype.set=function(t){return this._model.set(t)._toJSONG()},r.prototype.call=function(t,e,n,r){var o=[t,e,n].concat(r);return this._model.call.apply(this._model,o)._toJSONG()},e.exports=r},{}],4:[function(t,e,n){function r(t){var e=t||{};this.syncRefCount=0,this.expired=e.expired||[],this.unsafeMode=e.unsafeMode||!1,this.collectionScheduler=e.collectionScheduler||new s,this.cache={},o(e.comparator)&&(this.comparator=e.comparator),o(e.errorSelector)&&(this.errorSelector=e.errorSelector),o(e.onChange)&&(this.onChange=e.onChange)}var o=t(96),i=t(91),s=t(74);r.prototype.errorSelector=function(t,e){return e},r.prototype.comparator=function(t,e){return i(t,"value")&&i(e,"value")?t.value===e.value&&t.$type===e.$type&&t.$expires===e.$expires:t===e},e.exports=r},{74:74,91:91,96:96}],5:[function(t,e,n){function r(t,e){var n,r=!1;try{++t._root.syncRefCount,n=t._derefSync(e)}catch(i){n=i,r=!0}finally{--t._root.syncRefCount}return r?o.Observable["throw"](n):o.Observable["return"](n)}var o=t(159),i=t(134);e.exports=function(t){for(var e=this,n=-1,s=arguments.length-1,u=new Array(s),a=i.fromPath(t);++n<s;)u[n]=i.fromPath(arguments[n+1]);if(0===s)throw new Error("Model#deref requires at least one value path.");return o.Observable.defer(function(){return r(e,a)}).flatMap(function(t){if(Boolean(t)){if(s>0){var n=o.Observable.of(t);return t.get.apply(t,u)["catch"](o.Observable.empty()).concat(n).last().flatMap(function(){return r(e,a)}).filter(function(t){return t})}return o.Observable["return"](t)}if(s>0){var i=u.map(function(t){return a.concat(t)});return e.get.apply(e,i).concat(o.Observable.defer(function(){return r(e,a)})).last().filter(function(t){return t})}return o.Observable.empty()})}},{134:134,159:159}],6:[function(t,e,n){var r=t(134),o=t(13),i=t(8),s=t(118);e.exports=function(t){var e=r.fromPath(t);if(!Array.isArray(e))throw new Error("Model#derefSync must be called with an Array path.");var n=o(this,this._path.concat(e),!1),u=n.path,a=n.value,c=n.found;if(c&&void 0!==a&&(a.$type!==s||void 0!==a.value)){if(a.$type)throw new i;return this._clone({_path:u})}}},{118:118,13:13,134:134,8:8}],7:[function(t,e,n){function r(){this.message=r.message,this.stack=(new Error).stack}r.prototype=new Error,r.prototype.name="BoundJSONGraphModelError",r.message="It is not legal to use the JSON Graph format from a bound Model. JSON Graph format can only be used from a root model.",e.exports=r},{}],8:[function(t,e,n){function r(t,e){this.message=i,this.stack=(new Error).stack,this.boundPath=t,this.shortedPath=e}var o="InvalidModelError",i="The boundPath of the model is not valid since a value or error was found before the path end.";r.prototype=new Error,r.prototype.name=o,r.message=i,e.exports=r},{}],9:[function(t,e,n){function r(t){this.message="An exception was thrown when making a request.",this.stack=(new Error).stack,this.innerError=t}var o="InvalidSourceError";r.prototype=new Error,r.prototype.name=o,r.is=function(t){return t&&t.name===o},e.exports=r},{}],10:[function(t,e,n){function r(){this.message="The allowed number of retries have been exceeded.",this.stack=(new Error).stack}var o="MaxRetryExceededError";r.prototype=new Error,r.prototype.name=o,r.is=function(t){return t&&t.name===o},e.exports=r},{}],11:[function(t,e,n){function r(t,e,n,r,o,h,f){for(var l,d,v=n,y=o,b=r,m=0;;){if(0===m&&b[c]?(m=y.length,d=b[c]):(l=y[m++],d=v[l]),d){var g=d.$type,w=g&&d.value||d;if(m<y.length){if(g){v=d;break}v=d;continue}if(v=d,g&&u(d))break;if(b[c]||i(b,d),g===a){f?s(t,d,h,null,null,null,y,y.length,f):p(t,d),m=0,y=w,b=d,v=e;continue}break}v=void 0;break}if(m<y.length&&void 0!==v){for(var x=[],_=0;m>_;_++)x[_]=y[_];y=x}return[v,y]}var o=t(26),i=o.create,s=t(22),u=t(27),a=t(120),c=t(33),p=t(29).promote;e.exports=r},{120:120,22:22,26:26,27:27,29:29,33:33}],12:[function(t,e,n){var r=t(15),o=t(8),i=t(7);e.exports=function(t,e){return function(n,s,u){var a,c,p,h=u[0],f={values:u,optimizedPaths:[]},l=n._root.cache,d=n._path,v=l,y=d.length,b=[];if(y){if(e)return{criticalError:new i};if(v=r(n,d),v.$type)return{criticalError:new o(d,d)};for(a=[],c=0;y>c;++c)a[c]=d[c]}else a=[],y=0;for(c=0,p=s.length;p>c;c++)t(n,l,v,s[c],0,h,f,b,a,y,e);return f}}},{15:15,7:7,8:8}],13:[function(t,e,n){var r=t(17),o=t(8);e.exports=function(t,e,n){var i,s,u,a,c,p=e,h=e;for(i=t._boxed,n=t._materialized,s=t._treatErrorsAsValues,t._boxed=!0,t._materialized=void 0===n||n,t._treatErrorsAsValues=!0,u=r(t,p.concat(null),!0),t._boxed=i,t._materialized=n,t._treatErrorsAsValues=s,p=u.optimizedPath,a=u.shorted,c=u.found,u=u.value;p.length&&null===p[p.length-1];)p.pop();if(c&&a)throw new o(h,p);return{path:p,value:u,shorted:a,found:c}}},{17:17,8:8}],14:[function(t,e,n){function r(t){var e,n,r,o={},i=Object.keys(t);for(n=0,r=i.length;r>n;n++)e=i[n],s(e)||(o[e]=t[e]);return o}function o(t,e,n){Object.keys(t).filter(function(e){return!s(e)&&t[e]}).forEach(function(n){var s=t[n],u=e[n];if(u||(u=e[n]={}),s.$type){var a,c=s.value&&"object"==typeof s.value,p=!t[i];return a=c||p?r(s):s.value,void(e[n]=a)}o(s,u,n)})}var i=t(37),s=t(97);e.exports=function(t){var e={};return o(t,e),e}},{37:37,97:97}],15:[function(t,e,n){e.exports=function(t,e){for(var n=t._root.cache,r=-1,o=e.length;++r<o&&n&&!n.$type;)n=n[e[r]];return n}},{}],16:[function(t,e,n){var r=t(64),o=t(134);e.exports=function(t){for(var e=o.fromPath(t),n=0,i=e.length;++n<i;)if("object"==typeof e[n])return new r(function(t){t.onError(new Error("Paths must be simple paths"))});var s=this;return new r(function(t){return s.get(e).subscribe(function(n){for(var r=n.json,o=-1,i=e.length;r&&++o<i;)r=r[e[o]];t.onNext(r)},function(e){t.onError(e)},function(){t.onCompleted()})})}},{134:134,64:64}],17:[function(t,e,n){var r=t(11),o=t(25),i=t(27),s=t(29).promote,u=t(120),a=t(118),c=t(119);e.exports=function(t,e,n){for(var p,h,f,l,d,v=t._root.cache,y=e.length,b=[],m=!1,g=!1,w=0,x=v,_=v,S=v,E=!0,C=!1;x&&y>w;){if(p=e[w++],null!==p&&(x=_[p],b[b.length]=p),!x){S=void 0,m=!0,E=!1;break}if(f=x.$type,f===a&&void 0===x.value){S=void 0,E=!1,m=y>w;break}if(y>w){if(f===u){if(i(x)){C=!0,S=void 0,E=!1;break}if(l=r(t,v,v,x,x.value),d=l[0],!d){S=void 0,x=void 0,E=!1;break}f=d.$type,x=d,b=l[1].slice(0)}if(f)break}else S=x;_=x}if(y>w&&!C){for(h=w;y>h;++h)if(null!==e[w]){g=!0;break}for(g?(m=!0,S=void 0):S=x,h=w;y>h;++h)null!==e[h]&&(b[b.length]=e[h])}if(S&&f&&(i(S)?S=void 0:s(t,S)),S&&f===c&&!t._treatErrorsAsValues)throw{path:w===y?e:e.slice(0,w),value:S.value};return S&&t._boxed?S=Boolean(f)&&!n?o(S):S:!S&&t._materialized?S={$type:a}:S&&(S=S.value),{value:S,shorted:m,optimizedPath:b,found:E}}},{11:11,118:118,119:119,120:120,25:25,27:27,29:29}],18:[function(t,e,n){var r=t(46);e.exports=function(t,e){var n=t._getValueSync({_boxed:!0,_root:t._root,_treatErrorsAsValues:t._treatErrorsAsValues},e,!0).value,o=n&&n[r];return null==o?-1:o}},{46:46}],19:[function(t,e,n){var r=t(12),o=t(31),i=r(o,!1),s=r(o,!0);e.exports={getValueSync:t(17),getBoundValue:t(13),getWithPathsAsPathMap:i,getWithPathsAsJSONGraph:s}},{12:12,13:13,17:17,31:31}],20:[function(t,e,n){var r=t(29),o=t(25),i=r.promote;e.exports=function(t,e,n,r,s){var u=e.value;s.errors||(s.errors=[]),t._boxed&&(u=o(e)),s.errors.push({path:r.slice(0,n+1),value:u}),i(t,e)}},{25:25,29:29}],21:[function(t,e,n){function r(t,e,n,r,o,i,s){s.requestedMissingPaths.push(r.slice(0,n).concat(e)),s.optimizedMissingPaths.push(o.slice(0,i).concat(e))}var o=t(30),i=o.fastCopy;e.exports=function(t,e,n,o,s,u,a){var c;o.requestedMissingPaths||(o.requestedMissingPaths=[],o.optimizedMissingPaths=[]),c=n<e.length?i(e,n):[],r(t,c,n,s,u,a,o)}},{30:30}],22:[function(t,e,n){var r=t(29),o=t(25),i=r.promote,s=t(120),u=t(118),a=t(119),c=t(37);e.exports=function(t,e,n,r,p,h,f,l,d,v){if(n){var y,b,m,g,w,x,_,S,E=!1;if(e&&i(t,e),e&&void 0!==e.value||(E=t._materialized),E)S={$type:u};else if(t._boxed)S=o(e);else if(e.$type===s||e.$type===a)S=d?o(e):e.value;else if(d){var C=e.value&&"object"==typeof e.value,A=!e[c];S=C||A?o(e):e.value}else S=e.value;if(p&&(p.hasValue=!0),d){for(w=n.jsonGraph,w||(w=n.jsonGraph={},n.paths=[]),y=0,b=l-1;b>y;y++)g=f[y],w[g]||(w[g]={}),w=w[g];g=f[y],w[g]=E?{$type:u}:S,h&&n.paths.push(h.slice(0,r))}else if(0===r)n.json=S;else{for(w=n.json,w||(w=n.json={}),y=0;r-1>y;y++)m=h[y],w[m]||(w[m]={}),x=w,_=m,w=w[m];m=h[y],null!==m?w[m]=S:x[_]=S}}}},{118:118,119:119,120:120,25:25,29:29,37:37}],23:[function(t,e,n){var r=t(27),o=t(26),i=t(29),s=o.remove,u=i.splice,a=t(119),c=t(20),p=t(22),h=t(21),f=t(28),l=t(35);e.exports=function(t,e,n,o,i,d,v,y,b,m,g){var w=e&&e.$type,x=e&&void 0===e.value;return e&&w?void(r(e)?(e[l]||(u(t,e),s(e)),h(t,n,o,d,v,y,b)):w===a?(g&&(v[o]=null),m||t._treatErrorsAsValues?p(t,e,i,o,d,v,y,b,m,g):c(t,e,o,v,d)):(g&&(v[o]=null),(!x||x&&t._materialized)&&p(t,e,i,o,d,v,y,b,m,g))):void(f(t)?p(t,e,i,o,d,v,y,b,m,g):h(t,n,o,d,v,y,b))}},{119:119,20:20,21:21,22:22,26:26,27:27,28:28,29:29,35:35}],24:[function(t,e,n){var r=t(134);e.exports=function(t){var e=r.fromPath(t);if(Array.isArray(e)===!1)throw new Error("Model#getValueSync must be called with an Array path.");return this._path.length&&(e=this._path.concat(e)),this._syncCheck("getValueSync")&&this._getValueSync(this,e).value}},{134:134}],25:[function(t,e,n){var r=t(40);e.exports=function(t){var e,n,o,i=Object.keys(t);for(e={},n=0,o=i.length;o>n;n++){var s=i[n];s[0]!==r&&(e[s]=t[s])}return e}},{40:40}],26:[function(t,e,n){function r(t,e){var n=e[a]||0;e[i+n]=t,e[a]=n+1,t[u]=n,t[s]=e}function o(t){var e=t[s];if(e){for(var n=t[u],r=e[a];r>n;)e[i+n]=e[i+n+1],++n;e[a]=r-1,t[s]=void 0,t[u]=void 0}}var i=t(43),s=t(33),u=t(42),a=t(44);e.exports={create:r,remove:o}},{33:33,42:42,43:43,44:44}],27:[function(t,e,n){var r=t(106);e.exports=function(t){var e=void 0===t.$expires&&-1||t.$expires;return-1!==e&&1!==e&&(0===e||e<r())}},{106:106}],28:[function(t,e,n){e.exports=function(t){return t._materialized&&!t._source}},{}],29:[function(t,e,n){function r(t,e){var n=t._root,r=n[i];if(r!==e){var o=e[a],s=e[u];s&&(s[a]=o),o&&(o[u]=s),e[a]=void 0,n[i]=e,e[u]=r,r[a]=e}}function o(t,e){var n=t._root,r=e[a],o=e[u];o&&(o[a]=r),r&&(r[u]=o),e[a]=void 0,e===n[i]&&(n[i]=void 0),e===n[s]&&(n[s]=void 0),e[c]=!0,n.expired.push(e)}var i=t(34),s=t(45),u=t(38),a=t(41),c=t(35);e.exports={promote:r,splice:o}},{34:34,35:35,38:38,41:41,45:45}],30:[function(t,e,n){function r(t,e){var n,r,o,i=[];for(r=0,o=e||0,n=t.length;n>o;r++,o++)i[r]=t[o];return i}function o(t,e){var n,r,o,i=[];for(n=0,r=t.length;r>n;n++)i[n]=t[n];for(o=0,r=e.length;r>o;o++)null!==e[o]&&(i[n++]=e[o]);return i}function i(t,e){var n,r,o,i=[];for(n=0,r=t.length;r>n;n++)i[n]=t[n];for(o=0,r=e.length;r>o;o++)i[n++]=e[o];return i}e.exports={fastCat:i,fastCatSkipNulls:o,fastCopy:r}},{}],31:[function(t,e,n){var r=t(11),o=t(23),i=t(27),s=t(143).iterateKeySet,u=t(120),a=t(29).promote;e.exports=function c(t,e,n,p,h,f,l,d,v,y,b,m){var g=m,w=v;if(!n||n&&n.$type||h===p.length)return void o(t,n,p,h,f,l,d,w,y,b,g);var x,_;x=p[h];var S="object"==typeof x,E=h+1,C=!1,A=x;if(S&&(C={},A=s(x,C)),void 0!==A||!C.done){var N=y+1;do{g=!1;var k;null===A?k=n:(k=n[A],w[y]=A,d[h]=A);var O=w,P=N;if(k){var j=k.$type,D=j&&k.value||k;if(E<p.length&&j&&j===u&&!i(k)){b&&o(t,k,p,E,f,l,null,w,P,b,g),a(t,k);var q=r(t,e,e,k,D,f,b);g=!0,k=q[0];var R=q[1];for(O=[],P=R.length,_=0;P>_;++_)O[_]=R[_]}}c(t,e,k,p,E,f,l,d,O,P,b,g),C&&!C.done&&(A=s(x,C))}while(C&&!C.done)}}},{11:11,120:120,143:143,23:23,27:27,29:29}],32:[function(t,e,n){"use strict";function r(t){return new r.Model(t)}"function"==typeof Promise?r.Promise=Promise:r.Promise=t(151),e.exports=r,r.Model=t(2)},{151:151,2:2}],33:[function(t,e,n){e.exports=t(40)+"context"},{40:40}],34:[function(t,e,n){e.exports=t(40)+"head"},{40:40}],35:[function(t,e,n){e.exports=t(40)+"invalidated"},{40:40}],36:[function(t,e,n){e.exports=t(40)+"key"},{40:40}],37:[function(t,e,n){e.exports="$modelCreated"},{}],38:[function(t,e,n){e.exports=t(40)+"next"},{40:40}],39:[function(t,e,n){e.exports=t(40)+"parent"},{40:40}],40:[function(t,e,n){e.exports=String.fromCharCode(30)},{}],41:[function(t,e,n){e.exports=t(40)+"prev"},{40:40}],42:[function(t,e,n){e.exports=t(40)+"ref-index"},{40:40}],43:[function(t,e,n){e.exports=t(40)+"ref"},{40:40}],44:[function(t,e,n){e.exports=t(40)+"refs-length"},{40:40}],45:[function(t,e,n){e.exports=t(40)+"tail"},{40:40}],46:[function(t,e,n){e.exports=t(40)+"version"},{40:40}],47:[function(t,e,n){function r(t,e,n,o,s,u,c,p,h,f){if(!_(t)&&!t.$type)for(var l in t)if(l[0]!==a&&"$"!==l[0]&&m(t,l)){var d=t[l],v=g(d)&&!d.$type,y=i(n,o,s,l,d,v,!1,u,c,p,h,f),w=y[0],x=y[1];w&&(v?r(d,e+1,n,x,w,u,c,p,h,f):A(w,x,l,p)&&C(x,b(w),p,u))}}function o(t,e,n,r,o,s,a,h){if(w(n))return S(n,o,s),[void 0,e];y(s,n);var d=n,v=n.value,b=e;if(n=n[p],null!=n)b=n[c]||e;else{var m=0,g=v.length-1;b=n=e;do{var x=v[m],E=g>m,C=i(e,b,n,x,t,E,!0,r,o,s,a,h);if(n=C[0],_(n))return C;b=C[1]}while(m++<g);if(d[p]!==n){var A=n[l]||0;n[l]=A+1,n[u+A]=d,d[p]=n,d[f]=A}}return[n,b]}function i(t,e,n,r,i,u,a,c,p,h,f,l){for(var v=n.$type;v===d;){var y=o(i,t,n,c,p,h,f,l);if(n=y[0],_(n))return y;e=y[1],v=n&&n.$type}if(void 0!==v)return[n,e];if(null==r){if(u)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[s])}else e=n,n=e[r];return[n,e]}var s=t(36),u=t(43),a=t(40),c=t(39),p=t(33),h=t(46),f=t(42),l=t(44),d=t(120),v=t(13),y=t(50),b=t(88),m=t(91),g=t(100),w=t(95),x=t(96),_=t(102),S=t(86),E=t(92),C=t(115),A=t(109);e.exports=function(t,e){for(var n=t._root,o=n,i=n.expired,s=E(),u=n._comparator,a=n._errorSelector,p=t._path,f=n.cache,l=p.length?v(t,p).value:f,d=l[c]||f,y=f[h],b=-1,m=e.length;++b<m;){var g=e[b];r(g.json,0,f,d,l,s,i,o,u,a)}var w=f[h],_=n.onChange;x(_)&&y!==w&&_()}},{100:100,102:102,109:109,115:115,120:120,13:13,33:33,36:36,39:39,40:40,42:42,43:43,44:44,46:46,50:50,86:86,88:88,91:91,92:92,95:95,96:96}],48:[function(t,e,n){function r(t,e,n,o,s,u,a,c){var p={},h=e<t.length-1,f=t[e],l=x(f,p);do{var d=i(n,o,s,l,h,!1,u,a,c),v=d[0],b=d[1];v&&(h?r(t,e+1,n,b,v,u,a,c):E(v,b,l,c)&&S(b,y(v),c,u)),l=x(f,p)}while(!p.done)}function o(t,e,n,r,o){if(b(e))return w(e,r,o),[void 0,t];v(o,e);var s=e,p=e.value,l=t;if(e=e[c],null!=e)l=e[a]||t;else{var d=0,y=p.length-1;l=e=t;do{var m=p[d],x=y>d,_=i(t,l,e,m,x,!0,n,r,o);if(e=_[0],g(e))return _;l=_[1]}while(d++<y);if(s[c]!==e){var S=e[f]||0;e[f]=S+1,e[u+S]=s,s[c]=e,s[h]=S}}return[e,l]}function i(t,e,n,r,i,u,a,c,p){for(var h=n.$type;h===l;){var f=o(t,n,a,c,p);if(n=f[0],g(n))return f;e=f[1],h=n.$type}if(void 0!==h)return[n,e];if(null==r){if(i)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[s])}else e=n,n=e[r];return[n,e]}var s=t(36),u=t(43),a=t(39),c=t(33),p=t(46),h=t(42),f=t(44),l=t(120),d=t(13),v=t(50),y=t(88),b=t(95),m=t(96),g=t(102),w=t(86),x=t(143).iterateKeySet,_=t(92),S=t(115),E=t(109);e.exports=function(t,e){for(var n=t._root,o=n,i=n.expired,s=_(),u=t._path,c=n.cache,h=u.length?d(t,u).value:c,f=h[a]||c,l=c[p],v=-1,y=e.length;++v<y;){var b=e[v];r(b,0,c,f,h,s,i,o)}var g=c[p],w=n.onChange;m(w)&&l!==g&&w()}},{102:102,109:109,115:115,120:120,13:13,143:143,33:33,36:36,39:39,42:42,43:43,44:44,46:46,50:50,86:86,88:88,92:92,95:95,96:96}],49:[function(t,e,n){var r=t(36),o=t(39),i=t(34),s=t(45),u=t(38),a=t(41),c=t(108),p=t(115);e.exports=function(t,e,n,h,f,l){var d=n,v=f;"number"!=typeof v&&(v=.75);var y,b,m,g="number"==typeof l,w=h*v;for(b=e.pop();b;)m=b.$size||0,d-=m,g===!0?p(b,m,t,l):(y=b[o])&&c(b,y,b[r],t),b=e.pop();if(d>=h){var x=t[s];for(b=x;d>=w&&b;)x=x[a],m=b.$size||0,d-=m,g===!0&&p(b,m,t,l),b=x;t[s]=t[a]=b,null==b?t[i]=t[u]=void 0:b[u]=void 0}}},{108:108,115:115,34:34,36:36,38:38,39:39,41:41,45:45}],50:[function(t,e,n){var r=t(121),o=t(34),i=t(45),s=t(38),u=t(41),a=t(100);e.exports=function(t,e){if(a(e)&&e.$expires!==r){var n=t[o],c=t[i],p=e[s],h=e[u];e!==n&&(null!=p&&"object"==typeof p&&(p[u]=h),null!=h&&"object"==typeof h&&(h[s]=p),p=n,null!=n&&"object"==typeof n&&(n[u]=e),t[o]=t[s]=n=e,n[s]=p,n[u]=void 0),null!=c&&e!==c||(t[i]=t[u]=c=h||e)}return e}},{100:100,121:121,34:34,38:38,41:41,45:45}],51:[function(t,e,n){var r=t(34),o=t(45),i=t(38),s=t(41);e.exports=function(t,e){var n=t[r],u=t[o],a=e[i],c=e[s];null!=a&&"object"==typeof a&&(a[s]=c),null!=c&&"object"==typeof c&&(c[i]=a),e===n&&(t[r]=t[i]=a),e===u&&(t[o]=t[s]=c),e[i]=e[s]=void 0,n=u=a=c=void 0}},{34:34,38:38,41:41,45:45}],52:[function(t,e,n){function r(t,e){var n=!1;return function(){if(!n&&!t._disposed){n=!0,t._callbacks[e]=null,t._optimizedPaths[e]=[],t._requestedPaths[e]=[];var r=--t._count;0!==r||t.sent||(t._disposable.dispose(),t.requestQueue.removeRequest(t))}}}function o(t){for(var e=[],n=-1,r=0,o=t.length;o>r;++r)for(var i=t[r],s=0,u=i.length;u>s;++s)e[++n]=i[s];return e}var i=t(59),s=t(60),u=0,a=t(57).GetRequest,c=t(76),p=t(78),h=t(119),f=[],l=function(t,e){this.sent=!1,this.scheduled=!1,this.requestQueue=e,this.id=++u,this.type=a,this._scheduler=t,this._pathMap={},this._optimizedPaths=[],this._requestedPaths=[],this._callbacks=[],this._count=0,this._disposable=null,this._collapsed=null,this._disposed=!1};l.prototype={batch:function(t,e,n){var o=this,i=o._optimizedPaths,u=o._requestedPaths,a=o._callbacks,c=i.length;return i[c]=e,u[c]=t,a[c]=n,++o._count,o.scheduled||(o.scheduled=!0,o._disposable=o._scheduler.schedule(function(){s(o,i,function(t,e){if(o.requestQueue.removeRequest(o),o._disposed=!0,o._count){o._merge(u,t,e);for(var n=0,r=a.length;r>n;++n){var i=a[n];i&&i(t,e)}}})})),r(o,c)},add:function(t,e,n){var o,s,u=this,a=i(t,e,u._pathMap);a?(s=a[2],o=a[1]):(s=t,o=e);var c=!1,p=!1;if(o.length<e.length){c=!0;var h=u._callbacks.length;u._callbacks[h]=n,u._requestedPaths[h]=a[0],u._optimizedPaths[h]=[],++u._count,p=r(u,h)}return[c,s,o,p]},_merge:function(t,e,n){var r=this,i=r.requestQueue.model,s=i._root,u=s.errorSelector,a=s.comparator,l=i._path;i._path=f;var d=o(t);if(e){var v=e;v instanceof Error&&(v={message:v.message}),v.$type||(v={$type:h,value:v});var y=d.map(function(t){return{path:t,value:v}});p(i,y,null,u,a)}else c(i,[{paths:d,jsonGraph:n.jsonGraph}],null,u,a);i._path=l}},e.exports=l},{119:119,57:57,59:59,60:60,76:76,78:78}],53:[function(t,e,n){function r(){this.length=0,this.pending=!1,this.pathmaps=[],s.call(this,this._subscribe)}var o=t(159),i=o.Observer,s=o.Observable,u=o.Disposable,a=o.SerialDisposable,c=o.CompositeDisposable,p=t(9),h=t(143),f=h.iterateKeySet;r.create=function(t,e,n){var r=new this;return r.queue=t,r.model=e,r.index=n,r},r.prototype=Object.create(s.prototype),r.prototype.constructor=r,r.prototype.insertPath=function(t,e,n,r,o){var i=r||0,s=o||t.length-1,u=n||this.pathmaps[s+1]||(this.pathmaps[s+1]=Object.create(null));if(void 0===u||null===u)return!1;var a,c,p=t[i],h={};a=f(p,h);do{if(c=u[a],s>i){if(null==c){if(e)return!1;c=u[a]=Object.create(null)}if(this.insertPath(t,e,c,i+1,s)===!1)return!1}else u[a]=(c||0)+1,this.length+=1;h.done||(a=f(p,h))}while(!h.done);return!0},r.prototype.removePath=function(t,e,n,r){var o=n||0,i=r||t.length-1,s=e||this.pathmaps[i+1];if(void 0===s||null===s)return!0;var u,a,c=0,p=t[o],h={};u=f(p,h);do if(a=s[u],void 0!==a&&null!==a){if(i>o){c+=this.removePath(t,a,o+1,i);var l=void 0;for(l in a)break;void 0===l&&delete s[u]}else a=s[u]=(a||1)-1,0===a&&delete s[u],c+=1,this.length-=1;h.done||(u=f(p,h))}while(!h.done);return c},r.prototype.getSourceObserver=function(t){var e=this;return i.create(function(n){n.jsonGraph=n.jsonGraph||n.jsong||n.values||n.value,n.index=e.index,t.onNext(n)},function(e){t.onError(e)},function(){t.onCompleted()})},r.prototype._subscribe=function(t){var e=this,n=this.queue;e.pending=!0;var r=!1,o=new a,i=u.create(function(){r||(r=!0,n&&n._remove(e))}),s=new c(o,i);try{o.setDisposable(this.model._source[this.method](this.getSourceArgs()).subscribe(this.getSourceObserver(t)))}catch(h){throw new p(h)}return s},e.exports=r},{143:143,159:159,9:9}],54:[function(t,e,n){function r(t,e){this.total=0,this.model=t,this.requests=[],this.scheduler=e}var o=t(58),i=t(40),s=t(90),u=t(100),a=t(143);r.prototype.set=function(t){return t.paths=a.collapse(t.paths),o.create(this.model,t)},r.prototype._remove=function(t){var e=this.requests,n=e.indexOf(t);-1!==n&&e.splice(n,1)},r.prototype.distributePaths=function(t,e,n){var r,o,i=this.model,s=-1,u=t.length,a=-1,c=e.length,p=[];t:for(;++s<u;){var h=t[s];for(a=-1;++a<c;)if(o=e[a],o.insertPath(h,o.pending)){p[a]=o;continue t}r||(r=n.create(this,i,this.total++),e[a]=r,p[c++]=r),r.insertPath(h,!1)}var f=[],l=-1;for(a=-1;++a<c;)o=p[a],null!=o&&(f[++l]=o);return f},r.prototype.mergeJSONGraphs=function(t,e){var n=0,r=[],o=[],a=[],c=t.index,p=e.index;t.index=Math.max(c,p),r[-1]=t.jsonGraph||{},o[-1]=e.jsonGraph||{};t:for(;n>-1;){for(var h=r[n-1],f=o[n-1],l=a[n-1]||(a[n-1]=Object.keys(f));l.length>0;){var d=l.pop();if(d[0]!==i)if(h.hasOwnProperty(d)){var v=h[d],y=s(v),b=f[d],m=s(b);if(u(v)&&u(b)&&!y&&!m){r[n]=v,o[n]=b,n+=1;continue t}p>c&&(h[d]=b)}else h[d]=f[d]}n-=1}return t},e.exports=r},{100:100,143:143,40:40,58:58,90:90}],55:[function(t,e,n){function r(t,e){this.model=t,this.scheduler=e,this.requests=this._requests=[]}var o=t(54),i=t(56);r.prototype.get=i.prototype.get,r.prototype.removeRequest=i.prototype.removeRequest,r.prototype.set=o.prototype.set,r.prototype.call=o.prototype.call,e.exports=r},{54:54,56:56}],56:[function(t,e,n){function r(t,e){this.model=t,this.scheduler=e,this.requests=this._requests=[]}var o=t(57),i=t(52);r.prototype={setScheduler:function(t){this.scheduler=t},get:function(t,e,n){function r(){v||(--h,0===h&&n())}var s,u,a,c=this,p=[],h=0,f=c._requests,l=e,d=t,v=!1;for(s=0,u=f.length;u>s;++s)if(a=f[s],a.type===o.GetRequest){if(a.sent){var y=a.add(d,l,r);y[0]&&(d=y[1],l=y[2],p[p.length]=y[3],++h)}else a.batch(d,l,r),l=[],d=[],++h;if(!l.length)break}if(l.length){a=new i(c.scheduler,c),f[f.length]=a,++h;var b=a.batch(d,l,r);p[p.length]=b}return function(){if(!v&&0!==h){v=!0;for(var t=p.length,e=0;t>e;++e)p[e]()}}},removeRequest:function(t){for(var e=this._requests,n=e.length;--n>=0;)if(e[n].id===t.id){e.splice(n,1);break}}},e.exports=r},{52:52,57:57}],57:[function(t,e,n){e.exports={GetRequest:"GET"}},{}],58:[function(t,e,n){function r(){s.call(this)}var o=t(159),i=o.Observer,s=t(53),u=t(83),a=t(76),c=t(78),p=new Array(0);r.create=function(t,e){var n=new r;return n.model=t,n.jsonGraphEnvelope=e,n},r.prototype=Object.create(s.prototype),r.prototype.constructor=r,r.prototype.method="set",r.prototype.insertPath=function(){return!1},r.prototype.removePath=function(){return 0},r.prototype.getSourceArgs=function(){return this.jsonGraphEnvelope},r.prototype.getSourceObserver=function(t){var e=this.model,n=e._path,r=this.jsonGraphEnvelope.paths,o=e._root,h=o.errorSelector,f=o.comparator;return s.prototype.getSourceObserver.call(this,i.create(function(o){e._path=p;var i=a(e,[{paths:r,jsonGraph:o.jsonGraph}],null,h,f);o.paths=i[1],e._path=n,t.onNext(o)},function(o){e._path=p,c(e,u(r,function(t){return{path:t,value:o}}),null,h,f),e._path=n,t.onError(o)},function(){t.onCompleted()}))},e.exports=r},{159:159,53:53,76:76,78:78,83:83}],59:[function(t,e,n){var r=t(143).hasIntersection,o=t(84);e.exports=function(t,e,n){for(var i=[],s=[],u=[],a=-1,c=-1,p=!1,h=0,f=e.length;f>h;++h){var l=e[h],d=n[l.length];d&&r(d,l,0)?(!p&&h>0&&(s=o(t,0,h),i=o(e,0,h)),u[++a]=t[h],p=!0):p&&(i[++c]=l,s[c]=t[h])}return p?[u,i,s]:null}},{143:143,84:84}],60:[function(t,e,n){var r=t(143),o=r.toTree,i=r.toPaths;e.exports=function(t,e,n){if(0===t._count)return void t.requestQueue.removeRequest(t);t.sent=!0,t.scheduled=!1;for(var r=t._pathMap,s=Object.keys(e),u=0,a=s.length;a>u;++u)for(var c=e[u],p=0,h=c.length;h>p;++p){var f=c[p],l=f.length;if(r[l]){var d=r[l];d[d.length]=f}else r[l]=[f]}for(var v=Object.keys(r),y=0,b=v.length;b>y;++y){var m=v[y];r[m]=o(r[m])}var g,w=t._collasped=i(r);t.requestQueue.model._source.get(w).subscribe(function(t){g=t},function(t){n(t,g)},function(){n(null,g)})}},{143:143}],61:[function(t,e,n){function r(t){u.call(this,t||i)}function o(t){return s.Observable.defer(function(){return t})}function i(t){function e(t){function e(t,e){if(Boolean(e.invalidated))t.invalidations.push(t.localThisPath.concat(e.path));else{var n=e.path,r=e.value;Boolean(r)&&"object"==typeof r&&r.$type===f?t.references.push({path:i(n),value:e.value}):t.values.push({path:i(n),value:e.value})}return t}function n(t){var e=t.values.concat(t.references);return e.length>0?o(g.set.apply(g,e)._toJSONG()).map(function(e){return{results:t,envelope:e}}):u["return"]({results:t,envelope:{jsonGraph:{},paths:[]}})}function r(t){var e,n=t.envelope,r=t.results,c=r.values,p=r.references,h=r.invalidations,f=c.map(a).map(i),l=p.reduce(s,[]),d=b.map(i),v=l.concat(d);return e=v.length>0?o(m.get.apply(m,f.concat(v))._toJSONG()):u["return"](n),e.doAction(function(t){t.invalidated=h})}function s(t,e){var n=e.path;return t.push.apply(t,y.map(function(t){return n.concat(t)})),t}function a(t){return t.path}var c=t&&t.localFn;if("function"==typeof c){var p=t.model,h=p._path,l=c.apply(p,v).reduce(e,{values:[],references:[],invalidations:[],localThisPath:h}).flatMap(n).flatMap(r);return u["return"](l)}return u.empty()}function n(t){function e(t){var e=t.invalidated;return e&&e.length&&m.invalidate.apply(m,e),t}return t&&"object"==typeof t?s.Observable.defer(function(){
3458 var e;try{e=t.call(x,v,y,b)}catch(n){e=u["throw"](new p(n))}return e}).map(e):u.empty()}function r(t){return o(g.set(t)).reduce(function(t){return t},null).map(function(){return{invalidated:t.invalidated,paths:t.paths.map(function(t){return t.slice(w.length)})}})}function i(t){return _.concat(t)}var c=this.args,l=this.model,d=h.fromPath(c[0]),v=c[1]||[],y=(c[2]||[]).map(h.fromPath),b=(c[3]||[]).map(h.fromPath),m=l._clone({_path:[]}),g=m.withoutDataSource(),w=l._path,x=w.concat(d),_=x.slice(0,-1),S=o(l.withoutDataSource().get(d)).map(function(t){for(var e=t.json,n=-1,r=d.length;e&&++n<r;)e=e[d[n]];var o=m._derefSync(_).boxValues();return{model:o,localFn:e}}).flatMap(e).defaultIfEmpty(n(l._source)).mergeAll().flatMap(r),E=new a;return E.add(S.subscribe(function(e){var n=e.paths,r=e.invalidated,i=l.get.apply(l,n);"AsJSONG"===t.outputFormat&&(i=o(i._toJSONG()).doAction(function(t){t.invalidated=r})),E.add(i.subscribe(t))},function(e){t.onError(e)})),E}var s=t(159)&&t(158),u=s.Observable,a=s.CompositeDisposable,c=t(64),p=t(9),h=t(134),f=t(120);r.create=c.create,r.prototype=Object.create(u.prototype),r.prototype.constructor=r,r.prototype.invokeSourceRequest=function(t){return this},r.prototype.ensureCollect=function(t){return this},r.prototype.initialize=function(){return this},e.exports=r},{120:120,134:134,158:158,159:159,64:64,9:9}],62:[function(t,e,n){function r(t){i.call(this,t)}var o=t(159),i=o.Observable,s=t(64),u=t(134),a=t(88),c=t(49),p=t(81),h=t(46),f=Array.isArray,l=t(101),d=t(98),v=t(99);r.create=s.create,r.prototype=Object.create(i.prototype),r.prototype.constructor=r,r.prototype.subscribeCount=0,r.prototype.subscribeLimit=10,r.prototype.initialize=function(){for(var t,e,n=this.model,r=this.outputFormat||"AsPathMap",o=this.isProgressive,i=[{}],s=[],a=this.args,c=-1,h=a.length;++c<h;){var y,b=a[c];f(b)||"string"==typeof b?(b=u.fromPath(b),y="PathValues"):l(b)?(b.path=u.fromPath(b.path),y="PathValues"):v(b)?y="JSONGs":d(b)&&(y="PathMaps"),e!==y&&(e=y,t={inputType:y,arguments:[]},s.push(t),t.values=i),t.arguments.push(b)}return this.boundPath=p(n._path),this.groups=s,this.outputFormat=r,this.isProgressive=o,this.isCompleted=!1,this.isMaster=null==n._source,this.values=i,this},r.prototype.invokeSourceRequest=function(t){return this},r.prototype.ensureCollect=function(t){var e=this["finally"](function(){var e=t._root,n=e.cache;e.collectionScheduler.schedule(function(){c(e,e.expired,a(n),t._maxSize,t._collectRatio,n[h])})});return new this.constructor(function(t){return e.subscribe(t)})},e.exports=r},{101:101,134:134,159:159,46:46,49:49,64:64,81:81,88:88,98:98,99:99}],63:[function(t,e,n){function r(t){u.call(this,t||o)}function o(t){for(var e=this.model,n=this.method,r=this.groups,o=-1,i=r.length;++o<i;){var u=r[o],a=u.inputType,c=u.arguments;if(c.length>0){var p="_"+n+a+"AsJSON",h=e[p];h(e,c)}}return t.onCompleted(),s.empty}var i=t(159),s=i.Disposable,u=t(62);r.create=u.create,r.prototype=Object.create(u.prototype),r.prototype.method="invalidate",r.prototype.constructor=r,e.exports=r},{159:159,62:62}],64:[function(t,e,n){function r(t){this._subscribe=t}function o(t){var e=this.model,n=new this.type;return n.model=e,n.args=this.args,n.outputFormat=t.outputFormat||"AsPathMap",n.isProgressive=t.isProgressive||!1,n.subscribeCount=0,n.subscribeLimit=t.retryLimit||10,n.initialize().invokeSourceRequest(e).ensureCollect(e).subscribe(t)}var i=t(32),s=t(159)&&t(158),u=s.Observable,a=t(84),c=t(105),p={outputFormat:{value:"AsJSONG"}},h={isProgressive:{value:!0}};r.create=function(t,e){var n=new r(o);return n.args=e,n.type=this,n.model=t,n},r.prototype=Object.create(u.prototype),r.prototype.constructor=r,r.prototype._mixin=function(){var t=this,e=a(arguments);return new t.constructor(function(n){return t.subscribe(e.reduce(function(t,e){return Object.create(t,e)},n))})},r.prototype._toJSONG=function(){return this._mixin(p)},r.prototype.progressively=function(){return this._mixin(h)},r.prototype.subscribe=function(t,e,n){var r=t;r&&"object"==typeof r||(r={onNext:t||c,onError:e||c,onCompleted:n||c});var o=this._subscribe(r);switch(typeof o){case"function":return{dispose:o};case"object":return o||{dispose:c};default:return{dispose:c}}},r.prototype.then=function(t,e){var n=this;return new i.Promise(function(t,e){var r,o=!1;n.toArray().subscribe(function(t){r=t.length<=1?t[0]:t},function(t){o=!0,e(t)},function(){o===!1&&t(r)})}).then(t,e)},e.exports=r},{105:105,158:158,159:159,32:32,84:84}],65:[function(t,e,n){function r(t){l.call(this,t||o)}function o(t){return this.isCompleted?s.call(this,t):i.call(this,t)}function i(t){if(this.subscribeCount++>this.subscribeLimit)return t.onError("Loop kill switch thrown."),h.empty;for(var e=[],n=[],r=this.model,o=this.isMaster,i=r._root,c=this.outputFormat,p=i.errorSelector,f=this.method,l=this.groups,d=-1,y=l.length;++d<y;){var b=l[d],m=b.inputType,g=b.arguments;if(g.length>0){var w="_"+f+m+c,x=r[w],_=x(r,g,null,p);n.push.apply(n,_[1]),"PathValues"===m?e.push.apply(e,g.map(u)):"JSONGs"===m?e.push.apply(e,v(g,a)):e.push.apply(e,_[0])}}return this.requestedPaths=e,o?(this.isCompleted=!0,s.call(this,t)):void t.onError({method:f,optimizedPaths:n,invokeSourceRequest:!0})}function s(t){var e=new f(this.model,this.requestedPaths);return"AsJSONG"===this.outputFormat&&(e=e._toJSONG()),this.isProgressive&&(e=e.progressively()),e.subscribe(t)}function u(t){return t.path}function a(t){return t.paths}var c=t(159),p=c.Observable,h=c.Disposable,f=t(67),l=t(62),d=t(9),v=t(82),y=new Array(0);r.create=l.create,r.prototype=Object.create(l.prototype),r.prototype.method="set",r.prototype.constructor=r,r.prototype.invokeSourceRequest=function(t){var e=this,n=this["catch"](function(r){var o;if(r&&r.invokeSourceRequest===!0){var i={},s=t._path,u=r.optimizedPaths;t._path=y,t._getPathValuesAsJSONG(t._materialize().withoutDataSource(),u,[i]),t._path=s,o=t._request.set(i)["do"](function(t){e.isCompleted=u.length===t.paths.length},function(){e.isCompleted=!0}).materialize().flatMap(function(t){if("C"===t.kind)return p.empty();if("E"===t.kind){var e=t.exception;if(d.is(e))return p["throw"](t.exception)}return n})}else o=p["throw"](r);return o});return new this.constructor(function(t){return n.subscribe(t)})},e.exports=r},{159:159,62:62,67:67,82:82,9:9}],66:[function(t,e,n){var r=function(t){this.disposed=!1,this.currentDisposable=t};r.prototype={dispose:function(){if(!this.disposed&&this.currentDisposable){this.disposed=!0;var t=this.currentDisposable;t.dispose?t.dispose():t()}}},e.exports=r},{}],67:[function(t,e,n){var r=t(64),o=t(68),i=t(69),s={dispose:function(){}},u=t(159).Observable,a=e.exports=function(t,e,n,r){this.model=t,this.currentRemainingPaths=e,this.isJSONGraph=n||!1,this.isProgressive=r||!1};a.prototype=Object.create(u.prototype),a.prototype.subscribe=r.prototype.subscribe,a.prototype.then=r.prototype.then,a.prototype._toJSONG=function(){return new a(this.model,this.currentRemainingPaths,!0,this.isProgressive)},a.prototype.progressively=function(){return new a(this.model,this.currentRemainingPaths,this.isJSONGraph,!0)},a.prototype._subscribe=function(t){var e=[{}],n=[],r=t.isJSONG=this.isJSONGraph,u=this.isProgressive,a=o(this.model,this.currentRemainingPaths,t,u,r,e,n);return a?i(this,this.model,a,t,e,n,1):s}},{159:159,64:64,68:68,69:69}],68:[function(t,e,n){var r=t(19),o=r.getWithPathsAsJSONGraph,i=r.getWithPathsAsPathMap;e.exports=function(t,e,n,r,s,u,a){var c;if(c=s?o(t,e,u):i(t,e,u),c.criticalError)return n.onError(c.criticalError),null;var p=c.hasValue,h=!c.requestedMissingPaths||!t._source,f=u[0].json||u[0].jsonGraph;if(c.errors)for(var l=c.errors,d=a.length,v=0,y=l.length;y>v;++v,++d)a[d]=l[v];if(p&&r||f&&h)try{++t._root.syncRefCount,n.onNext(u[0])}catch(b){throw b}finally{--t._root.syncRefCount}return h?(a.length?n.onError(a):n.onCompleted(),null):c}},{19:19}],69:[function(t,e,n){var r=t(68),o=t(10),i=t(30).fastCat,s=t(49),u=t(88),a=t(66),c=t(46);e.exports=function p(t,e,n,h,f,l,d){if(10===d)throw new o;var v=e._request,y=n.requestedMissingPaths,b=n.optimizedMissingPaths,m=new a,g=[],w=e._path;if(w.length)for(var x=0,_=y.length;_>x;++x)g[x]=i(w,y[x]);else g=y;var S=v.get(g,b,function(){var n=r(e,y,h,t.isProgressive,t.isJSONGraph,f,l);if(n)m.currentDisposable=p(t,e,n,h,f,l,d+1);else{var o=e._root,i=o.cache,a=i[c];s(o,o.expired,u(i),e._maxSize,e._collectRatio,a)}});return m.currentDisposable=S,m}},{10:10,30:30,46:46,49:49,66:66,68:68,88:88}],70:[function(t,e,n){var r=t(67);e.exports=function(t){return new r(this,t)}},{67:67}],71:[function(t,e,n){var r=t(134),o=t(64),i=t(72),s=t(116),u=t(67);e.exports=function(){var t=s(arguments,i,"get");if(t!==!0)return new o(function(e){e.onError(t)});var e=r.fromPathsOrPathValues(arguments);return new u(this,e)}},{116:116,134:134,64:64,67:67,72:72}],72:[function(t,e,n){e.exports={path:!0,pathSyntax:!0}},{}],73:[function(t,e,n){function r(){}var o=t(123),i=t(159),s=i.Disposable;r.prototype.schedule=function(t){return o(t),s.empty},r.prototype.scheduleWithState=function(t,e){var n=this;return o(function(){e(n,t)}),s.empty},e.exports=r},{123:123,159:159}],74:[function(t,e,n){function r(){}var o=t(159),i=o.Disposable;r.prototype.schedule=function(t){return t(),i.empty},r.prototype.scheduleWithState=function(t,e){return e(this,t),i.empty},e.exports=r},{159:159}],75:[function(t,e,n){function r(t){this.delay=t}var o=t(159),i=o.Disposable;r.prototype.schedule=function(t){var e=setTimeout(t,this.delay);return i.create(function(){void 0!==e&&(clearTimeout(e),e=void 0)})},r.prototype.scheduleWithState=function(t,e){var n=this,r=setTimeout(function(){e(n,t)},this.delay);return i.create(function(){void 0!==r&&(clearTimeout(r),r=void 0)})},e.exports=r},{159:159}],76:[function(t,e,n){function r(t,e,n,o,s,u,a,c,p,h,f,d,v,y,b,g,w){for(var x={},_=e<t.length-1,S=t[e],E=m(S,x),C=d.index;;){f.depth=e;var A=i(n,o,s,u,a,c,E,_,!1,f,d,v,y,b,g,w);f[e]=E,f.index=e,d[d.index++]=E;var N=A[0],k=A[1];if(N&&(_?r(t,e+1,n,k,N,u,A[3],A[2],p,h,f,d,v,y,b,g,w):(l(b,N),p.push(f.slice(0,f.index+1)),h.push(d.slice(0,d.index)))),E=m(S,x),x.done)break;d.index=C}}function o(t,e,n,r,o,s,c,f,v,m,g){var w=e.value;if(s.splice(0,s.length),s.push.apply(s,w),d(e))return s.index=w.length,b(e,f,v),[void 0,t,r,n];l(v,e);var x=0,_=e,S=w.length-1,E=e=t,C=r=n;do{var A=w[x],N=S>x,k=i(t,E,e,n,C,r,A,N,!0,o,s,c,f,v,m,g);if(e=k[0],y(e))return s.index=x,k;E=k[1],r=k[2],C=k[3]}while(x++<S);if(s.index=x,_[a]!==e){var O=e[h]||0;e[h]=O+1,e[u+O]=_,_[a]=e,_[p]=O}return[e,E,r,C]}function i(t,e,n,r,i,u,a,c,p,h,l,d,v,b,m,g){for(var x=n.$type;x===f;){var _=o(t,n,r,u,h,l,d,v,b,m,g);if(n=_[0],y(n))return _;e=_[1],u=_[2],i=_[3],x=n.$type}if(void 0!==x)return[n,e,u,i];if(null==a){if(c)throw new Error("`null` is not allowed in branch key positions.");n&&(a=n[s])}else e=n,i=u,n=e[a],u=i&&i[a];return n=w(e,n,u,a,h,l,d,v,b,m,g),[n,e,u,i]}var s=t(36),u=t(43),a=t(33),c=t(46),p=t(42),h=t(44),f=t(120),l=t(50),d=t(94),v=t(96),y=t(102),b=t(86),m=t(143).iterateKeySet,g=t(92),w=t(103);e.exports=function(t,e,n,o,i){for(var s=t._root,u=s,a=s.expired,p=g(),h=s.cache,f=h[c],l=[],d=[],y=[],b=[],m=-1,w=e.length;++m<w;)for(var x=e[m],_=x.paths,S=x.jsonGraph,E=-1,C=_.length;++E<C;){var A=_[E];d.index=0,r(A,0,h,h,h,S,S,S,y,b,l,d,p,a,u,i,o)}var N=h[c],k=s.onChange;return v(k)&&f!==N&&k(),[y,b]}},{102:102,103:103,120:120,143:143,33:33,36:36,42:42,43:43,44:44,46:46,50:50,86:86,92:92,94:94,96:96}],77:[function(t,e,n){function r(t,e,n,o,u,a,c,p,h,f,l,d,v,y){var b=s(t);if(b&&b.length)for(var g=0,x=b.length,_=h.index;;){var S=b[g],E=t[S],C=w(E)&&!E.$type;p.depth=e;var A=i(n,o,u,S,E,C,!1,p,h,f,l,d,v,y);p[e]=S,p.index=e,h[h.index++]=S;var N=A[0],k=A[1];if(N&&(C?r(E,e+1,n,k,N,a,c,p,h,f,l,d,v,y):(m(d,N),a.push(p.slice(0,p.index+1)),c.push(h.slice(0,h.index)))),++g>=x)break;h.index=_}}function o(t,e,n,r,o,s,u,c,f,v){var y=n.value;if(o.splice(0,o.length),o.push.apply(o,y),x(n))return o.index=y.length,E(n,u,c),[void 0,e];m(c,n);var b=n,g=e;if(n=n[h],null!=n)g=n[p]||e,o.index=y.length;else{var w=0,_=y.length-1;g=n=e;do{var C=y[w],A=_>w,N=i(e,g,n,C,t,A,!0,r,o,s,u,c,f,v);if(n=N[0],S(n))return o.index=w,N;g=N[1]}while(w++<_);if(o.index=w,b[h]!==n){var k=n[d]||0;n[d]=k+1,n[a+k]=b,b[h]=n,b[l]=k}}return[n,g]}function i(t,e,n,r,i,s,a,c,p,h,f,l,d,y){for(var b=n.$type;b===v;){var m=o(i,t,n,c,p,h,f,l,d,y);if(n=m[0],S(n))return m;e=m[1],b=n&&n.$type}if(void 0!==b)return[n,e];if(null==r){if(s)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[u])}else e=n,n=e[r];return n=A(e,n,r,i,s,a,c,p,h,f,l,d,y),[n,e]}function s(t){if(w(t)&&!t.$type){var e=[],n=0;b(t)&&(e[n++]="length");for(var r in t)r[0]!==c&&"$"!==r[0]&&g(t,r)&&(e[n++]=r);return e}}var u=t(36),a=t(43),c=t(40),p=t(39),h=t(33),f=t(46),l=t(42),d=t(44),v=t(120),y=t(13),b=Array.isArray,m=t(50),g=t(91),w=t(100),x=t(95),_=t(96),S=t(102),E=t(86),C=t(92),A=t(104);e.exports=function(t,e,n,o,i){for(var s=t._root,u=s,a=s.expired,c=C(),h=t._path,l=s.cache,d=h.length?y(t,h).value:l,v=d[p]||l,b=l[f],m=[],g=[],w=[],x=h.length,S=-1,E=e.length;++S<E;){var A=e[S],N=h.slice(0);N.index=x,r(A.json,0,l,v,d,g,w,m,N,c,a,u,i,o)}var k=l[f],O=s.onChange;return _(O)&&b!==k&&O(),[g,w]}},{100:100,102:102,104:104,120:120,13:13,33:33,36:36,39:39,40:40,42:42,43:43,44:44,46:46,50:50,86:86,91:91,92:92,95:95,96:96}],78:[function(t,e,n){function r(t,e,n,o,s,u,a,c,p,h,f,l,d,y,b){for(var m={},g=n<e.length-1,x=e[n],_=w(x,m),S=h.index;;){p.depth=n;var E=i(o,s,u,_,t,g,!1,p,h,f,l,d,y,b);p[n]=_,p.index=n,h[h.index++]=_;var C=E[0],A=E[1];if(C&&(g?r(t,e,n+1,o,A,C,a,c,p,h,f,l,d,y,b):(v(d,C),a.push(p.slice(0,p.index+1)),c.push(h.slice(0,h.index)))),_=w(x,m),m.done)break;h.index=S}}function o(t,e,n,r,o,s,p,l,d,b){var w=n.value;if(o.splice(0,o.length),o.push.apply(o,w),y(n))return o.index=w.length,g(n,p,l),[void 0,e];v(l,n);var x=n,_=e;if(n=n[c],null!=n)_=n[a]||e,o.index=w.length;else{var S=0,E=w.length-1;_=n=e;do{var C=w[S],A=E>S,N=i(e,_,n,C,t,A,!0,r,o,s,p,l,d,b);if(n=N[0],m(n))return o.index=S,N;_=N[1]}while(S++<E);if(o.index=S,x[c]!==n){var k=n[f]||0;n[f]=k+1,n[u+k]=x,x[c]=n,x[h]=k}}return[n,_]}function i(t,e,n,r,i,u,a,c,p,h,f,d,v,y){for(var b=n.$type;b===l;){var g=o(i,t,n,c,p,h,f,d,v,y);if(n=g[0],m(n))return g;e=g[1],b=n.$type}if(void 0!==b)return[n,e];if(null==r){if(u)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[s])}else e=n,n=e[r];return n=_(e,n,r,i,u,a,c,p,h,f,d,v,y),[n,e]}var s=t(36),u=t(43),a=t(39),c=t(33),p=t(46),h=t(42),f=t(44),l=t(120),d=t(13),v=t(50),y=t(95),b=t(96),m=t(102),g=t(86),w=t(143).iterateKeySet,x=t(92),_=t(104);e.exports=function(t,e,n,o,i){for(var s=t._root,u=s,c=s.expired,h=x(),f=t._path,l=s.cache,v=f.length?d(t,f).value:l,y=v[a]||l,m=l[p],g=[],w=[],_=[],S=f.length,E=-1,C=e.length;++E<C;){var A=e[E],N=A.path,k=A.value,O=f.slice(0);O.index=S,r(k,N,0,l,y,v,w,_,g,O,h,c,u,i,o)}var P=l[p],j=s.onChange;return b(j)&&m!==P&&j(),[w,_]}},{102:102,104:104,120:120,13:13,143:143,33:33,36:36,39:39,42:42,43:43,44:44,46:46,50:50,86:86,92:92,95:95,96:96}],79:[function(t,e,n){var r=t(130),o=t(64),i=t(101);e.exports=function(t,e){for(var n=i(t)?t:r.pathValue(t,e),s=0,u=n.path,a=u.length;++s<a;)if("object"==typeof u[s])return new o(function(t){t.onError(new Error("Paths must be simple paths"))});var c=this;return new o(function(t){return c._set(n).subscribe(function(e){for(var n=e.json,r=-1,o=u.length;n&&++r<o;)n=n[u[r]];t.onNext(n)},function(e){t.onError(e)},function(){t.onCompleted()})})}},{101:101,130:130,64:64}],80:[function(t,e,n){var r=t(134),o=t(101),i=t(78);e.exports=function(t,e,n,s){var u=r.fromPath(t),a=e,c=n,p=s;if(o(u)?(p=c,c=a,a=u):a={path:u,value:a},o(a)===!1)throw new Error("Model#setValueSync must be called with an Array path.");return"function"!=typeof c&&(c=this._root._errorSelector),"function"!=typeof p&&(p=this._root._comparator),this._syncCheck("setValueSync")?(i(this,[a]),this._getValueSync(this,a.path).value):void 0}},{101:101,134:134,78:78}],81:[function(t,e,n){e.exports=function(t){if(!t)return t;for(var e=-1,n=t.length,r=[];++e<n;)r[e]=t[e];return r}},{}],82:[function(t,e,n){e.exports=function(t,e){for(var n=-1,r=-1,o=t.length,i=[];++r<o;)for(var s=e(t[r],r,t),u=-1,a=s.length;++u<a;)i[++n]=s[u];return i}},{}],83:[function(t,e,n){e.exports=function(t,e){for(var n=-1,r=t.length,o=new Array(r);++n<r;)o[n]=e(t[n],n,t);return o}},{}],84:[function(t,e,n){e.exports=function(t,e,n){var r=e||0,o=-1,i=t.length-r;0>i&&(i=0),n>0&&i>n&&(i=n);for(var s=new Array(i);++o<i;)s[o]=t[o+r];return s}},{}],85:[function(t,e,n){var r=t(40),o=t(91),i=Array.isArray,s=t(100);e.exports=function(t){var e=t;if(s(e)){e=i(t)?[]:{};var n=t;for(var u in n)u[0]!==r&&o(n,u)&&(e[u]=n[u])}return e}},{100:100,40:40,91:91}],86:[function(t,e,n){var r=t(51),o=t(35);e.exports=function(t,e,n){return t[o]||(t[o]=!0,e.push(t),r(n,t)),t}},{35:35,51:51}],87:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&t.$expires||void 0}},{100:100}],88:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&t.$size||0}},{100:100}],89:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&t.$timestamp||void 0}},{100:100}],90:[function(t,e,n){var r=t(100);e.exports=function(t,e){var n=r(t)&&t.$type||void 0;return e&&n?"branch":n}},{100:100}],91:[function(t,e,n){var r=t(100),o=Object.prototype.hasOwnProperty;e.exports=function(t,e){return r(t)&&o.call(t,e)}},{100:100}],92:[function(t,e,n){var r=1;e.exports=function(){return r++}},{}],93:[function(t,e,n){var r=t(36),o=t(39),i=t(46);e.exports=function(t,e,n,s){return t[r]=n,t[o]=e,t[i]=s,e[n]=t,t}},{36:36,39:39,46:46}],94:[function(t,e,n){var r=t(106),o=t(122),i=t(121);e.exports=function(t){var e=t.$expires;return null!=e&&e!==i&&e!==o&&e<r()}},{106:106,121:121,122:122}],95:[function(t,e,n){var r=t(106),o=t(122),i=t(121);e.exports=function(t){var e=t.$expires;return null!=e&&e!==i&&(e===o||e<r())}},{106:106,121:121,122:122}],96:[function(t,e,n){var r="function";e.exports=function(t){return Boolean(t)&&typeof t===r}},{}],97:[function(t,e,n){var r=t(40);e.exports=function(t){return"$size"===t||t&&t.charAt(0)===r}},{40:40}],98:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&"json"in t}},{100:100}],99:[function(t,e,n){var r=Array.isArray,o=t(100);e.exports=function(t){return o(t)&&r(t.paths)&&(o(t.jsonGraph)||o(t.jsong)||o(t.json)||o(t.values)||o(t.value))}},{100:100}],100:[function(t,e,n){var r="object";e.exports=function(t){return null!==t&&typeof t===r}},{}],101:[function(t,e,n){var r=Array.isArray,o=t(100);e.exports=function(t){return o(t)&&(r(t.path)||"string"==typeof t.path)}},{100:100}],102:[function(t,e,n){var r="object";e.exports=function(t){return null==t||typeof t!==r}},{}],103:[function(t,e,n){var r=t(36),o=t(39),i=t(120),s=t(119),u=t(88),a=t(89),c=t(100),p=t(95),h=t(96),f=t(50),l=t(117),d=t(93),v=t(86),y=t(110),b=t(115),m=t(107);e.exports=function(t,e,n,g,w,x,_,S,E,C,A){var N,k,O,P,j,D,q;if(e===n){if(null===n)return e=l(n,void 0,n),t=b(t,-e.$size,E,_),e=d(e,t,g),f(E,e),e;if(void 0===n)return n;if(P=c(e),P&&(k=e.$type,null==k))return null==e[o]&&(e[r]=g,e[o]=t),e}else P=c(e),P&&(k=e.$type);if(k!==i){if(j=c(n),j&&(O=n.$type),P&&!k&&(null==n||j&&!O))return e}else{if(null==n)return p(e)?void v(e,S,E):e;if(j=c(n),j&&(O=n.$type,O===i))if(e===n){if(null!=e[o])return e}else if(D=e.$timestamp,q=n.$timestamp,!p(e)&&!p(n)&&D>q)return}if(k&&j&&!O)return d(y(e,n,t,g,E),t,g);if(O||!j){if(O===s&&h(A)&&(n=A(m(w,g),n)),O&&e===n)null==e[o]&&(e=l(e,k,e.value),t=b(t,-e.$size,E,_),e=d(e,t,g,_));else{var R=!0;!k&&P||(R=a(n)<a(e)==!1,(k||O)&&h(C)&&(R=!C(e,n,x.slice(0,x.index)))),R&&(n=l(n,O,O?n.value:n),N=u(e)-u(n),e=y(e,n,t,g,E),t=b(t,N,E,_),e=d(e,t,g,_))}p(e)?v(e,S,E):f(E,e)}else null==e&&(e=d(n,t,g));return e}},{100:100,107:107,110:110,115:115,117:117,119:119,120:120,36:36,39:39,50:50,86:86,88:88,89:89,93:93,95:95,96:96}],104:[function(t,e,n){var r=t(120),o=t(119),i=t(90),s=t(88),u=t(89),a=t(95),c=t(102),p=t(96),h=t(117),f=t(86),l=t(93),d=t(110),v=t(115),y=t(114),b=t(107);e.exports=function(t,e,n,m,g,w,x,_,S,E,C,A,N){var k=i(e,w);if(g||w)k&&a(e)&&(k="expired",f(e,E,C)),(k&&k!==r||c(e))&&(e=d(e,{},t,n,C),e=l(e,t,n,S),e=y(e,S));else{var O=m,P=i(O),j=u(O)<u(e)==!1;if((k||P)&&p(A)&&(j=!A(e,O,_.slice(0,_.index))),j){P===o&&p(N)&&(O=N(b(x,n),O)),O=h(O,P,P?O.value:O);var D=s(e)-s(O);e=d(e,O,t,n,C),t=v(t,D,C,S),e=l(e,t,n,S)}}return e}},{102:102,107:107,110:110,114:114,115:115,117:117,119:119,120:120,86:86,88:88,89:89,90:90,93:93,95:95,96:96}],105:[function(t,e,n){e.exports=function(){}},{}],106:[function(t,e,n){e.exports=Date.now},{}],107:[function(t,e,n){e.exports=function(t,e){var n=t.slice(0,t.depth);return n[n.length]=e,n}},{}],108:[function(t,e,n){var r=t(120),o=t(39),i=t(51),s=t(100),u=t(112),a=t(113);e.exports=function(t,e,n,c){if(s(t)){var p=t.$type;return Boolean(p)&&(p===r&&a(t),i(c,t)),u(t),e[n]=t[o]=void 0,!0}return!1}},{100:100,112:112,113:113,120:120,39:39,51:51}],109:[function(t,e,n){var r=t(91),o=t(40),i=t(108);e.exports=function s(t,e,n,u){if(i(t,e,n,u)){if(null==t.$type)for(var a in t)a[0]!==o&&"$"!==a[0]&&r(t,a)&&s(t[a],t,a,u);return!0}return!1}},{108:108,40:40,91:91}],110:[function(t,e,n){var r=t(100),o=t(111),i=t(109);e.exports=function(t,e,n,s,u){return t===e?t:(r(t)&&(o(t,e),i(t,n,s,u)),n[s]=e,e)}},{100:100,109:109,111:111}],111:[function(t,e,n){var r=t(43),o=t(33),i=t(44);e.exports=function(t,e){for(var n=t[i]||0,s=e[i]||0,u=-1;++u<n;){var a=t[r+u];void 0!==a&&(a[o]=e,e[r+(s+u)]=a,t[r+u]=void 0)}return e[i]=n+s,t[i]=void 0,e}},{33:33,43:43,44:44}],112:[function(t,e,n){var r=t(43),o=t(33),i=t(42),s=t(44);e.exports=function(t){for(var e=-1,n=t[s]||0;++e<n;){var u=t[r+e];null!=u&&(u[o]=u[i]=t[r+e]=void 0)}return t[s]=void 0,t}},{33:33,42:42,43:43,44:44}],113:[function(t,e,n){var r=t(43),o=t(33),i=t(42),s=t(44);e.exports=function(t){var e=t[o];if(e){for(var n=(t[i]||0)-1,u=(e[s]||0)-1;++n<=u;)e[r+n]=e[r+(n+1)];e[s]=u,t[i]=t[o]=e=void 0}return t}},{33:33,42:42,43:43,44:44}],114:[function(t,e,n){var r=t(43),o=t(39),i=t(46),s=t(44);e.exports=function(t,e){var n=[t],u=0;do{var a=n[u--];if(a&&a[i]!==e){a[i]=e,n[u++]=a[o];for(var c=-1,p=a[s]||0;++c<p;)n[u++]=a[r+c]}}while(u>-1);return t}},{39:39,43:43,44:44,46:46}],115:[function(t,e,n){var r=t(36),o=t(46),i=t(39),s=t(108),u=t(114);e.exports=function(t,e,n,a){var c=t;do{var p=c[i],h=c.$size=(c.$size||0)-e;0>=h&&null!=p?s(c,p,c[r],n):c[o]!==a&&u(c,a),c=p}while(c);return t}},{108:108,114:114,36:36,39:39,46:46}],116:[function(t,e,n){var r=Array.isArray,o=t(101),i=t(99),s=t(98),u=t(134);e.exports=function(t,e,n){for(var a=0,c=t.length;c>a;++a){var p=t[a],h=!1;if(r(p)&&e.path?h=!0:"string"==typeof p&&e.pathSyntax?h=!0:o(p)&&e.pathValue?(p.path=u.fromPath(p.path),h=!0):i(p)&&e.jsonGraph?h=!0:s(p)&&e.json?h=!0:"function"==typeof p&&a+1===c&&e.selector&&(h=!0),!h)return new Error("Unrecognized argument "+typeof p+" ["+String(p)+"] to Model#"+n)}return!0}},{101:101,134:134,98:98,99:99}],117:[function(t,e,n){var r=t(130),o=r.atom,i=t(106),s=t(122),u=t(37),a=50,c=t(85),p=Array.isArray,h=t(88),f=t(87);e.exports=function(t,e,n){var r=0,l=t,d=e;if(d?(l=c(l),r=h(l),l.$type=d):(l=o(n),d=l.$type,l[u]=!0),null==n)r=a+1;else if(null==r||0>=r)switch(typeof n){case"object":r=p(n)?a+n.length:a+1;break;case"string":r=a+n.length;break;default:r=a+1}var v=f(l);return"number"==typeof v&&s>v&&(l.$expires=i()+-1*v),l.$size=r,l}},{106:106,122:122,130:130,37:37,85:85,87:87,88:88}],118:[function(t,e,n){e.exports="atom"},{}],119:[function(t,e,n){e.exports="error"},{}],120:[function(t,e,n){e.exports="ref"},{}],121:[function(t,e,n){e.exports=1},{}],122:[function(t,e,n){e.exports=0},{}],123:[function(t,e,n){"use strict";function r(){if(a.length)throw a.shift()}function o(t){var e;e=u.length?u.pop():new i,e.task=t,s(e)}function i(){this.task=null}var s=t(124),u=[],a=[],c=s.makeRequestCallFromTimer(r);e.exports=o,i.prototype.call=function(){try{this.task.call()}catch(t){o.onerror?o.onerror(t):(a.push(t),c())}finally{this.task=null,u[u.length]=this}}},{124:124}],124:[function(t,e,n){(function(t){"use strict";function n(t){u.length||(s(),a=!0),u[u.length]=t}function r(){for(;c<u.length;){var t=c;if(c+=1,u[t].call(),c>p){for(var e=0,n=u.length-c;n>e;e++)u[e]=u[e+c];u.length-=c,c=0}}u.length=0,c=0,a=!1}function o(t){var e=1,n=new h(t),r=document.createTextNode("");return n.observe(r,{characterData:!0}),function(){e=-e,r.data=e}}function i(t){return function(){function e(){clearTimeout(n),clearInterval(r),t()}var n=setTimeout(e,0),r=setInterval(e,50)}}e.exports=n;var s,u=[],a=!1,c=0,p=1024,h=t.MutationObserver||t.WebKitMutationObserver;s="function"==typeof h?o(r):i(r),n.requestFlush=s,n.makeRequestCallFromTimer=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],125:[function(t,e,n){"use strict";function r(t,e){var n;for(n in e)t[n]=e[n];return t}function o(t,e){if(this._jsongUrl=t,"number"==typeof e){var n={timeout:e};e=n}this._config=r({timeout:15e3,headers:{}},e||{})}var i=t(129),s=t(126);Array.isArray;o.prototype={constructor:o,buildQueryObject:s,get:function(t){var e="GET",n=this.buildQueryObject(this._jsongUrl,e,{paths:t,method:"get"}),o=r(n,this._config),s=this;return i(e,o,s)},set:function(t){var e="POST",n=this.buildQueryObject(this._jsongUrl,e,{jsonGraph:t,method:"set"}),o=r(n,this._config);o.headers["Content-Type"]="application/x-www-form-urlencoded";var s=this;return i(e,o,s)},call:function(t,e,n,o){e=e||[],n=n||[],o=o||[];var s="POST",u=[];u.push("method=call"),u.push("callPath="+encodeURIComponent(JSON.stringify(t))),u.push("arguments="+encodeURIComponent(JSON.stringify(e))),u.push("pathSuffixes="+encodeURIComponent(JSON.stringify(n))),u.push("paths="+encodeURIComponent(JSON.stringify(o)));var a=this.buildQueryObject(this._jsongUrl,s,u.join("&")),c=r(a,this._config);c.headers["Content-Type"]="application/x-www-form-urlencoded";var p=this;return i(s,c,p)}},o.XMLHttpSource=o,o["default"]=o,e.exports=o},{126:126,129:129}],126:[function(t,e,n){"use strict";e.exports=function(t,e,n){var r,o=[],i={url:t},s=-1!==t.indexOf("?"),u=s?"&":"?";return"string"==typeof n?o.push(n):(r=Object.keys(n),r.forEach(function(t){var e="object"==typeof n[t]?JSON.stringify(n[t]):n[t];o.push(t+"="+encodeURIComponent(e))})),"GET"===e?i.url+=u+o.join("&"):i.data=o.join("&"),i}},{}],127:[function(t,e,n){(function(t){"use strict";e.exports=function(){var e=new t.XMLHttpRequest;if("withCredentials"in e)return e;if(t.XDomainRequest)return new XDomainRequest;throw new Error("CORS is not supported by your browser")}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],128:[function(t,e,n){(function(t){"use strict";e.exports=function(){var e,n,r;if(t.XMLHttpRequest)return new t.XMLHttpRequest;try{for(n=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],r=0;3>r;r++)try{if(e=n[r],new t.ActiveXObject(e))break}catch(o){}return new t.ActiveXObject(e)}catch(o){throw new Error("XMLHttpRequest is not supported by your browser")}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],129:[function(t,e,n){"use strict";function r(){}function o(t,e,n){return r.create(function(r){var o,i,h,f,l,d={method:t||"GET",crossDomain:!1,async:!0,headers:{},responseType:"json"};for(l in e)p.call(e,l)&&(d[l]=e[l]);d.crossDomain||d.headers["X-Requested-With"]||(d.headers["X-Requested-With"]="XMLHttpRequest"),null!=n.onBeforeRequest&&n.onBeforeRequest(d);try{o=d.crossDomain?c():a()}catch(v){r.onError(v)}try{d.user?o.open(d.method,d.url,d.async,d.user,d.password):o.open(d.method,d.url,d.async),o.timeout=d.timeout,o.withCredentials=d.withCredentials!==!1,h=d.headers;for(f in h)p.call(h,f)&&o.setRequestHeader(f,h[f]);if(d.responseType)try{o.responseType=d.responseType}catch(y){if("json"!==d.responseType)throw y}o.onreadystatechange=function(t){4===o.readyState&&(i||(i=!0,s(r,o,t)))},o.ontimeout=function(t){i||(i=!0,u(r,o,"timeout error",t))},o.send(d.data)}catch(y){r.onError(y)}return function(){i||4===o.readyState||(i=!0,o.abort())}})}function i(t,e,n){n||(n=new Error(e)),t.onError(n)}function s(t,e,n){var r,o;if(e&&t){o=e.responseType,r="response"in e?e.response:e.responseText;var s=1223===e.status?204:e.status;if(s>=200&&399>=s){try{"json"!==o&&(r=JSON.parse(r||"")),"string"==typeof r&&(r=JSON.parse(r||""))}catch(n){i(t,"invalid json",n)}return t.onNext(r),void t.onCompleted()}return 401===s||403===s||407===s?i(t,r):410===s?i(t,r):408===s||504===s?i(t,r):i(t,r||"Response code "+s)}}function u(t,e,n,r){i(t,n||e.statusText||"request error",r)}var a=t(128),c=t(127),p=Object.prototype.hasOwnProperty,h=function(){};r.create=function(t){var e=new r;return e.subscribe=function(e,n,r){var o,i;return o="function"==typeof e?{onNext:e,onError:n||h,onCompleted:r||h}:e,i=t(o),"function"==typeof i?{dispose:i}:i},e},e.exports=o},{127:127,128:128}],130:[function(t,e,n){function r(t,e,n){var r=Object.create(null);if(null!=n){for(var o in n)r[o]=n[o];return r.$type=t,r.value=e,r}return{$type:t,value:e}}var o=t(134);e.exports={ref:function(t,e){return r("ref",o.fromPath(t),e)},atom:function(t,e){return r("atom",t,e)},undefined:function(){return r("atom")},error:function(t,e){return r("error",t,e)},pathValue:function(t,e){return{path:o.fromPath(t),value:e}},pathInvalidation:function(t){return{path:o.fromPath(t),invalidated:!0}}}},{134:134}],131:[function(t,e,n){e.exports={integers:"integers",ranges:"ranges",keys:"keys"}},{}],132:[function(t,e,n){var r={token:"token",dotSeparator:".",commaSeparator:",",openingBracket:"[",closingBracket:"]",openingBrace:"{",closingBrace:"}",escape:"\\",space:" ",colon:":",quote:"quote",unknown:"unknown"};e.exports=r},{}],133:[function(t,e,n){e.exports={indexer:{nested:"Indexers cannot be nested.",needQuotes:"unquoted indexers must be numeric.",empty:"cannot have empty indexers.",leadingDot:"Indexers cannot have leading dots.",leadingComma:"Indexers cannot have leading comma.",requiresComma:"Indexers require commas between indexer args.",routedTokens:"Only one token can be used per indexer when specifying routed tokens."},range:{precedingNaN:"ranges must be preceded by numbers.",suceedingNaN:"ranges must be suceeded by numbers."},routed:{invalid:"Invalid routed token. only integers|ranges|keys are supported."},quote:{empty:"cannot have empty quoted keys.",illegalEscape:"Invalid escape character. Only quotes are escapable."},unexpectedToken:"Unexpected token.",invalidIdentifier:"Invalid Identifier.",invalidPath:"Please provide a valid path.",throwError:function(t,e,n){if(n)throw t+" -- "+e.parseString+" with next token: "+n;throw t+" -- "+e.parseString}}},{}],134:[function(t,e,n){var r=t(140),o=t(135),i=t(131),s=function(t,e){return o(new r(t,e))};e.exports=s,s.fromPathsOrPathValues=function(t,e){if(!t)return[];for(var n=[],r=0,o=t.length;o>r;r++)"string"==typeof t[r]?n[r]=s(t[r],e):"string"==typeof t[r].path?n[r]={path:s(t[r].path,e),value:t[r].value}:n[r]=t[r];return n},s.fromPath=function(t,e){return t?"string"==typeof t?s(t,e):t:[]},s.RoutedTokens=i},{131:131,135:135,140:140}],135:[function(t,e,n){var r=t(132),o=t(133),i=t(136);e.exports=function(t){for(var e=t.next(),n={},s=[];!e.done;){switch(e.type){case r.token:var u=+e.token[0];isNaN(u)||o.throwError(o.invalidIdentifier,t),s[s.length]=e.token;break;case r.dotSeparator:0===s.length&&o.throwError(o.unexpectedToken,t);break;case r.space:break;case r.openingBracket:i(t,e,n,s);break;default:o.throwError(o.unexpectedToken,t)}e=t.next()}return 0===s.length&&o.throwError(o.invalidPath,t),s}},{132:132,133:133,136:136}],136:[function(t,e,n){var r=t(132),o=t(133),i=o.indexer,s=t(138),u=t(137),a=t(139);e.exports=function(t,e,n,c){var p=t.next(),h=!1,f=1,l=!1;for(n.indexer=[];!p.done;){switch(p.type){case r.token:case r.quote:n.indexer.length===f&&o.throwError(i.requiresComma,t)}switch(p.type){case r.openingBrace:l=!0,a(t,p,n,c);break;case r.token:var d=+p.token;isNaN(d)&&o.throwError(i.needQuotes,t),n.indexer[n.indexer.length]=d;break;case r.dotSeparator:n.indexer.length||o.throwError(i.leadingDot,t),s(t,p,n,c);
3459 break;case r.space:break;case r.closingBracket:h=!0;break;case r.quote:u(t,p,n,c);break;case r.openingBracket:o.throwError(i.nested,t);break;case r.commaSeparator:++f;break;default:o.throwError(o.unexpectedToken,t)}if(h)break;p=t.next()}0===n.indexer.length&&o.throwError(i.empty,t),n.indexer.length>1&&l&&o.throwError(i.routedTokens,t),1===n.indexer.length&&(n.indexer=n.indexer[0]),c[c.length]=n.indexer,n.indexer=void 0}},{132:132,133:133,137:137,138:138,139:139}],137:[function(t,e,n){var r=t(132),o=t(133),i=o.quote;e.exports=function(t,e,n,s){for(var u=t.next(),a="",c=e.token,p=!1,h=!1;!u.done;){switch(u.type){case r.token:case r.space:case r.dotSeparator:case r.commaSeparator:case r.openingBracket:case r.closingBracket:case r.openingBrace:case r.closingBrace:p&&o.throwError(i.illegalEscape,t),a+=u.token;break;case r.quote:p?(a+=u.token,p=!1):u.token!==c?a+=u.token:h=!0;break;case r.escape:p=!0;break;default:o.throwError(o.unexpectedToken,t)}if(h)break;u=t.next()}0===a.length&&o.throwError(i.empty,t),n.indexer[n.indexer.length]=a}},{132:132,133:133}],138:[function(t,e,n){var r=t(140),o=t(132),i=t(133);e.exports=function(t,e,n,s){var u,a=t.peek(),c=1,p=!1,h=!0,f=n.indexer.length-1,l=r.toNumber(n.indexer[f]);for(isNaN(l)&&i.throwError(i.range.precedingNaN,t);!p&&!a.done;){switch(a.type){case o.dotSeparator:3===c&&i.throwError(i.unexpectedToken,t),++c,3===c&&(h=!1);break;case o.token:u=r.toNumber(t.next().token),isNaN(u)&&i.throwError(i.range.suceedingNaN,t),p=!0;break;default:p=!0}if(p)break;t.next(),a=t.peek()}n.indexer[f]={from:l,to:h?u:u-1}}},{132:132,133:133,140:140}],139:[function(t,e,n){var r=t(132),o=t(131),i=t(133),s=i.routed;e.exports=function(t,e,n,u){var a=t.next(),c=!1,p="";switch(a.token){case o.integers:case o.ranges:case o.keys:break;default:i.throwError(s.invalid,t)}var h=t.next();if(h.type===r.colon&&(c=!0,h=t.next(),h.type!==r.token&&i.throwError(s.invalid,t),p=h.token,h=t.next()),h.type===r.closingBrace){var f={type:a.token,named:c,name:p};n.indexer[n.indexer.length]=f}else i.throwError(s.invalid,t)}},{131:131,132:132,133:133}],140:[function(t,e,n){function r(t,e,n){return{token:t,done:n,type:e}}function o(t,e,n){var o,g=!1,w="",x=n?m:b;do{if(o=e+1>=t.length)break;var _=t[e+1];if(void 0===_||-1!==x.indexOf(_)){if(w.length)break;++e;var S;switch(_){case s:S=i.dotSeparator;break;case u:S=i.commaSeparator;break;case a:S=i.openingBracket;break;case c:S=i.closingBracket;break;case p:S=i.openingBrace;break;case h:S=i.closingBrace;break;case y:S=i.space;break;case d:case v:S=i.quote;break;case l:S=i.escape;break;case f:S=i.colon;break;default:S=i.unknown}g=r(_,S,!1);break}w+=_,++e}while(!o);return!g&&w.length&&(g=r(w,i.token,!1)),g||(g={done:!0}),{token:g,idx:e}}var i=t(132),s=".",u=",",a="[",c="]",p="{",h="}",f=":",l="\\",d='"',v="'",y=" ",b="\\'\"[]., ",m="\\{}'\"[]., :",g=e.exports=function(t,e){this._string=t,this._idx=-1,this._extended=e,this.parseString=""};g.prototype={next:function(){var t=this._nextToken?this._nextToken:o(this._string,this._idx,this._extended);return this._idx=t.idx,this._nextToken=!1,this.parseString+=t.token.token,t.token},peek:function(){var t=this._nextToken?this._nextToken:o(this._string,this._idx,this._extended);return this._nextToken=t,t.token}},g.toNumber=function(t){return isNaN(+t)?NaN:+t}},{132:132}],141:[function(t,e,n){var r=t(147),o=t(148);e.exports=function(t){var e=t.reduce(function(t,e){var n=e.length;return t[n]||(t[n]=[]),t[n].push(e),t},{});return Object.keys(e).forEach(function(t){e[t]=o(e[t])}),r(e)}},{147:147,148:148}],142:[function(t,e,n){var r=t(144);e.exports=function o(t,e,n){for(var i=t,s=!0;s&&n<e.length;++n){var u=e[n],a=typeof u;if(u&&"object"===a){var c={},p=r(u,c),h=n+1;do{var f=i[p];s=void 0!==f,s&&(s=o(f,e,h)),p=r(u,c)}while(s&&!c.done);break}i=i[u],s=void 0!==i}return s}},{144:144}],143:[function(t,e,n){e.exports={iterateKeySet:t(144),toTree:t(148),toTreeWithUnion:t(149),pathsComplementFromTree:t(146),pathsComplementFromLengthTree:t(145),hasIntersection:t(142),toPaths:t(147),collapse:t(141)}},{141:141,142:142,144:144,145:145,146:146,147:147,148:148,149:149}],144:[function(t,e,n){function r(t,e){var n=e.from=t.from||0,r=e.to=t.to||"number"==typeof t.length&&e.from+t.length-1||0;e.rangeOffset=e.from,e.loaded=!0,n>r&&(e.empty=!0)}function o(t,e){e.done=!1;var n=e.isObject=!(!t||"object"!=typeof t);e.isArray=n&&i(t),e.arrayOffset=0}var i=Array.isArray;e.exports=function(t,e){if(void 0===e.isArray&&o(t,e),e.isArray){var n;do{e.loaded&&e.rangeOffset>e.to&&(++e.arrayOffset,e.loaded=!1);var i=e.arrayOffset,s=t.length;if(i>=s){e.done=!0;break}var u=t[e.arrayOffset],a=typeof u;if("object"===a){if(e.loaded||r(u,e),e.empty)continue;n=e.rangeOffset++}else++e.arrayOffset,n=u}while(void 0===n);return n}return e.isObject?(e.loaded||r(t,e),e.rangeOffset>e.to?void(e.done=!0):e.rangeOffset++):(e.done=!0,t)}},{}],145:[function(t,e,n){var r=t(142);e.exports=function(t,e){for(var n=[],o=-1,i=0,s=t.length;s>i;++i){var u=t[i];r(e[u.length],u,0)||(n[++o]=u)}return n}},{142:142}],146:[function(t,e,n){var r=t(142);e.exports=function(t,e){for(var n=[],o=-1,i=0,s=t.length;s>i;++i)r(e,t[i],0)||(n[++o]=t[i]);return n}},{142:142}],147:[function(t,e,n){function r(t){return null!==t&&typeof t===f}function o(t,e,n){var r,i,s,u,h,f,l,d,v,y,b,m,g,w,x=c(String(e)),_=Object.create(null),S=[],E=-1,C=0,A=[],N=0;if(u=[],h=-1,n-1>e){for(f=a(t,u);++h<f;)r=u[h],i=o(t[r],e+1,n),s=i.code,_[s]?i=_[s]:(S[C++]=s,i=_[s]={keys:[],sets:i.sets}),x=c(x+r+s),p(r)&&i.keys.push(parseInt(r,10))||i.keys.push(r);for(;++E<C;)if(r=S[E],i=_[r],u=i.keys,f=u.length,f>0)for(l=i.sets,d=-1,v=l.length,g=u[0];++d<v;){for(y=l[d],b=-1,m=y.length,w=new Array(m+1),w[0]=f>1&&u||g;++b<m;)w[b+1]=y[b];A[N++]=w}}else for(f=a(t,u),f>1?A[N++]=[u]:A[N++]=u;++h<f;)x=c(x+u[h]);return{code:x,sets:A}}function i(t){for(var e=-1,n=t.length;++e<n;){var r=t[e];h(r)&&(t[e]=s(r))}return t}function s(t){for(var e=-1,n=t.length-1,r=n>0;++e<=n;){var o=t[e];if(!p(o)){r=!1;break}t[e]=parseInt(o,10)}if(r===!0){t.sort(u);var i=t[0],s=t[n];if(n>=s-i)return{from:i,to:s}}return t}function u(t,e){return t-e}function a(t,e,n){var r=0;for(var o in t)e[r++]=o;return r>1&&e.sort(n),r}function c(t){for(var e=5381,n=-1,r=t.length;++n<r;)e=(e<<5)+e+t.charCodeAt(n);return String(e)}function p(t){return!h(t)&&t-parseFloat(t)+1>=0}var h=Array.isArray,f="object";e.exports=function(t){var e,n=[],s=0;for(var u in t)if(p(u)&&r(e=t[u]))for(var a=o(e,0,parseInt(u,10)).sets,c=-1,h=a.length;++c<h;)n[s++]=i(a[c]);return n}},{}],148:[function(t,e,n){function r(t,e,n){var i,s=e[n],u={},a=n+1;i=o(s,u);do{var c=t[i];c||(a===e.length?t[i]=null:c=t[i]={}),a<e.length&&r(c,e,a),u.done||(i=o(s,u))}while(!u.done)}var o=t(144);Array.isArray;e.exports=function(t){return t.reduce(function(t,e){return r(t,e,0),t},{})}},{144:144}],149:[function(t,e,n){},{}],150:[function(t,e,n){function r(){p=!1,u.length?c=u.concat(c):h=-1,c.length&&o()}function o(){if(!p){var t=setTimeout(r);p=!0;for(var e=c.length;e;){for(u=c,c=[];++h<e;)u&&u[h].run();h=-1,e=c.length}u=null,p=!1,clearTimeout(t)}}function i(t,e){this.fun=t,this.array=e}function s(){}var u,a=e.exports={},c=[],p=!1,h=-1;a.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];c.push(new i(t,e)),1!==c.length||p||setTimeout(o,0)},i.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=s,a.addListener=s,a.once=s,a.off=s,a.removeListener=s,a.removeAllListeners=s,a.emit=s,a.binding=function(t){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(t){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},{}],151:[function(t,e,n){"use strict";e.exports=t(156)},{156:156}],152:[function(t,e,n){"use strict";function r(){}function o(t){try{return t.then}catch(e){return y=e,b}}function i(t,e){try{return t(e)}catch(n){return y=n,b}}function s(t,e,n){try{t(e,n)}catch(r){return y=r,b}}function u(t){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof t)throw new TypeError("not a function");this._37=0,this._12=null,this._59=[],t!==r&&d(t,this)}function a(t,e,n){return new t.constructor(function(o,i){var s=new u(r);s.then(o,i),c(t,new l(e,n,s))})}function c(t,e){for(;3===t._37;)t=t._12;return 0===t._37?void t._59.push(e):void v(function(){var n=1===t._37?e.onFulfilled:e.onRejected;if(null===n)return void(1===t._37?p(e.promise,t._12):h(e.promise,t._12));var r=i(n,t._12);r===b?h(e.promise,y):p(e.promise,r)})}function p(t,e){if(e===t)return h(t,new TypeError("A promise cannot be resolved with itself."));if(e&&("object"==typeof e||"function"==typeof e)){var n=o(e);if(n===b)return h(t,y);if(n===t.then&&e instanceof u)return t._37=3,t._12=e,void f(t);if("function"==typeof n)return void d(n.bind(e),t)}t._37=1,t._12=e,f(t)}function h(t,e){t._37=2,t._12=e,f(t)}function f(t){for(var e=0;e<t._59.length;e++)c(t,t._59[e]);t._59=null}function l(t,e,n){this.onFulfilled="function"==typeof t?t:null,this.onRejected="function"==typeof e?e:null,this.promise=n}function d(t,e){var n=!1,r=s(t,function(t){n||(n=!0,p(e,t))},function(t){n||(n=!0,h(e,t))});n||r!==b||(n=!0,h(e,y))}var v=t(124),y=null,b={};e.exports=u,u._99=r,u.prototype.then=function(t,e){if(this.constructor!==u)return a(this,t,e);var n=new u(r);return c(this,new l(t,e,n)),n}},{124:124}],153:[function(t,e,n){"use strict";var r=t(152);e.exports=r,r.prototype.done=function(t,e){var n=arguments.length?this.then.apply(this,arguments):this;n.then(null,function(t){setTimeout(function(){throw t},0)})}},{152:152}],154:[function(t,e,n){"use strict";function r(t){var e=new o(o._99);return e._37=1,e._12=t,e}var o=t(152);e.exports=o;var i=r(!0),s=r(!1),u=r(null),a=r(void 0),c=r(0),p=r("");o.resolve=function(t){if(t instanceof o)return t;if(null===t)return u;if(void 0===t)return a;if(t===!0)return i;if(t===!1)return s;if(0===t)return c;if(""===t)return p;if("object"==typeof t||"function"==typeof t)try{var e=t.then;if("function"==typeof e)return new o(e.bind(t))}catch(n){return new o(function(t,e){e(n)})}return r(t)},o.all=function(t){var e=Array.prototype.slice.call(t);return new o(function(t,n){function r(s,u){if(u&&("object"==typeof u||"function"==typeof u)){if(u instanceof o&&u.then===o.prototype.then){for(;3===u._37;)u=u._12;return 1===u._37?r(s,u._12):(2===u._37&&n(u._12),void u.then(function(t){r(s,t)},n))}var a=u.then;if("function"==typeof a){var c=new o(a.bind(u));return void c.then(function(t){r(s,t)},n)}}e[s]=u,0===--i&&t(e)}if(0===e.length)return t([]);for(var i=e.length,s=0;s<e.length;s++)r(s,e[s])})},o.reject=function(t){return new o(function(e,n){n(t)})},o.race=function(t){return new o(function(e,n){t.forEach(function(t){o.resolve(t).then(e,n)})})},o.prototype["catch"]=function(t){return this.then(null,t)}},{152:152}],155:[function(t,e,n){"use strict";var r=t(152);e.exports=r,r.prototype["finally"]=function(t){return this.then(function(e){return r.resolve(t()).then(function(){return e})},function(e){return r.resolve(t()).then(function(){throw e})})}},{152:152}],156:[function(t,e,n){"use strict";e.exports=t(152),t(153),t(155),t(154),t(157)},{152:152,153:153,154:154,155:155,157:157}],157:[function(t,e,n){"use strict";var r=t(152),o=t(123);e.exports=r,r.denodeify=function(t,e){return e=e||1/0,function(){var n=this,o=Array.prototype.slice.call(arguments,0,e>0?e:0);return new r(function(e,r){o.push(function(t,n){t?r(t):e(n)});var i=t.apply(n,o);!i||"object"!=typeof i&&"function"!=typeof i||"function"!=typeof i.then||e(i)})}},r.nodeify=function(t){return function(){var e=Array.prototype.slice.call(arguments),n="function"==typeof e[e.length-1]?e.pop():null,i=this;try{return t.apply(this,arguments).nodeify(n,i)}catch(s){if(null===n||"undefined"==typeof n)return new r(function(t,e){e(s)});o(function(){n.call(i,s)})}}},r.prototype.nodeify=function(t,e){return"function"!=typeof t?this:void this.then(function(n){o(function(){t.call(e,null,n)})},function(n){o(function(){t.call(e,n)})})}},{123:123,152:152}],158:[function(e,n,r){(function(o){(function(i){var s={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},u=s[typeof window]&&window||this,a=s[typeof r]&&r&&!r.nodeType&&r,c=s[typeof n]&&n&&!n.nodeType&&n,p=(c&&c.exports===a&&a,s[typeof o]&&o);!p||p.global!==p&&p.window!==p||(u=p),"function"==typeof t&&t.amd?t(["rx"],function(t,e){return i(u,e,t)}):"object"==typeof n&&n&&n.exports===a?n.exports=i(u,n.exports,e(159)):u.Rx=i(u,{},u.Rx)}).call(this,function(t,e,n,r){function o(){try{return l.apply(this,arguments)}catch(t){return M.e=t,M}}function i(t){if(!E(t))throw new TypeError("fn must be a function");return l=t,o}function s(t,e,n){return new b(function(r){var o=!1,i=null,s=[];return t.subscribe(function(t){var u,a;try{a=e(t)}catch(c){return void r.onError(c)}if(u=0,o)try{u=n(a,i)}catch(p){return void r.onError(p)}else o=!0,i=a;u>0&&(i=a,s=[]),u>=0&&s.push(t)},function(t){r.onError(t)},function(){r.onNext(s),r.onCompleted()})},t)}function u(t){if(0===t.length)throw new D;return t[0]}function a(t,e,n,r){if(0>e)throw new R;return new b(function(o){var i=e;return t.subscribe(function(t){0===i--&&(o.onNext(t),o.onCompleted())},function(t){o.onError(t)},function(){n?(o.onNext(r),o.onCompleted()):o.onError(new R)})},t)}function c(t,e,n){return new b(function(r){var o=n,i=!1;return t.subscribe(function(t){i?r.onError(new Error("Sequence contains more than one element")):(o=t,i=!0)},function(t){r.onError(t)},function(){i||e?(r.onNext(o),r.onCompleted()):r.onError(new D)})},t)}function p(t,e,n){return new b(function(r){return t.subscribe(function(t){r.onNext(t),r.onCompleted()},function(t){r.onError(t)},function(){e?(r.onNext(n),r.onCompleted()):r.onError(new D)})},t)}function h(t,e,n){return new b(function(r){var o=n,i=!1;return t.subscribe(function(t){o=t,i=!0},function(t){r.onError(t)},function(){i||e?(r.onNext(o),r.onCompleted()):r.onError(new D)})},t)}function f(t,e,n,o){var i=j(e,n,3);return new b(function(e){var n=0;return t.subscribe(function(r){var s;try{s=i(r,n,t)}catch(u){return void e.onError(u)}s?(e.onNext(o?n:r),e.onCompleted()):n++},function(t){e.onError(t)},function(){e.onNext(o?-1:r),e.onCompleted()})},t)}var l,d=n.Observable,v=d.prototype,y=n.CompositeDisposable,b=n.AnonymousObservable,m=n.Disposable.empty,g=(n.internals.isEqual,n.helpers),w=g.not,x=g.defaultComparer,_=g.identity,S=g.defaultSubComparer,E=g.isFunction,C=g.isPromise,A=g.isArrayLike,N=g.isIterable,k=n.internals.inherits,O=d.fromPromise,P=d.from,j=n.internals.bindCallback,D=n.EmptyError,q=n.ObservableBase,R=n.ArgumentOutOfRangeError,M={e:{}};v.aggregate=function(){var t,e,n=!1,r=this;return 2===arguments.length?(n=!0,e=arguments[0],t=arguments[1]):t=arguments[0],new b(function(o){var i,s,u;return r.subscribe(function(r){!u&&(u=!0);try{i?s=t(s,r):(s=n?t(e,r):r,i=!0)}catch(a){return o.onError(a)}},function(t){o.onError(t)},function(){u&&o.onNext(s),!u&&n&&o.onNext(e),!u&&!n&&o.onError(new D),o.onCompleted()})},r)};var T=function(t){function e(e,n,r,o){this.source=e,this.acc=n,this.hasSeed=r,this.seed=o,t.call(this)}function n(t,e){this.o=t,this.acc=e.acc,this.hasSeed=e.hasSeed,this.seed=e.seed,this.hasAccumulation=!1,this.result=null,this.hasValue=!1,this.isStopped=!1}return k(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t,this))},n.prototype.onNext=function(t){this.isStopped||(!this.hasValue&&(this.hasValue=!0),this.hasAccumulation?this.result=i(this.acc)(this.result,t):(this.result=this.hasSeed?i(this.acc)(this.seed,t):t,this.hasAccumulation=!0),this.result===M&&this.o.onError(this.result.e))},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.hasValue&&this.o.onNext(this.result),!this.hasValue&&this.hasSeed&&this.o.onNext(this.seed),!this.hasValue&&!this.hasSeed&&this.o.onError(new D),this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(q);return v.reduce=function(t){var e=!1;if(2===arguments.length){e=!0;var n=arguments[1]}return new T(this,t,e,n)},v.some=function(t,e){var n=this;return t?n.filter(t,e).some():new b(function(t){return n.subscribe(function(){t.onNext(!0),t.onCompleted()},function(e){t.onError(e)},function(){t.onNext(!1),t.onCompleted()})},n)},v.any=function(){return this.some.apply(this,arguments)},v.isEmpty=function(){return this.any().map(w)},v.every=function(t,e){return this.filter(function(e){return!t(e)},e).some().map(w)},v.all=function(){return this.every.apply(this,arguments)},v.includes=function(t,e){function n(t,e){return 0===t&&0===e||t===e||isNaN(t)&&isNaN(e)}var r=this;return new b(function(o){var i=0,s=+e||0;return Math.abs(s)===1/0&&(s=0),0>s?(o.onNext(!1),o.onCompleted(),m):r.subscribe(function(e){i++>=s&&n(e,t)&&(o.onNext(!0),o.onCompleted())},function(t){o.onError(t)},function(){o.onNext(!1),o.onCompleted()})},this)},v.contains=function(t,e){v.includes(t,e)},v.count=function(t,e){return t?this.filter(t,e).count():this.reduce(function(t){return t+1},0)},v.indexOf=function(t,e){var n=this;return new b(function(r){var o=0,i=+e||0;return Math.abs(i)===1/0&&(i=0),0>i?(r.onNext(-1),r.onCompleted(),m):n.subscribe(function(e){o>=i&&e===t&&(r.onNext(o),r.onCompleted()),o++},function(t){r.onError(t)},function(){r.onNext(-1),r.onCompleted()})},n)},v.sum=function(t,e){return t&&E(t)?this.map(t,e).sum():this.reduce(function(t,e){return t+e},0)},v.minBy=function(t,e){return e||(e=S),s(this,t,function(t,n){return-1*e(t,n)})},v.min=function(t){return this.minBy(_,t).map(function(t){return u(t)})},v.maxBy=function(t,e){return e||(e=S),s(this,t,e)},v.max=function(t){return this.maxBy(_,t).map(function(t){return u(t)})},v.average=function(t,e){return t&&E(t)?this.map(t,e).average():this.reduce(function(t,e){return{sum:t.sum+e,count:t.count+1}},{sum:0,count:0}).map(function(t){if(0===t.count)throw new D;return t.sum/t.count})},v.sequenceEqual=function(t,e){var n=this;return e||(e=x),new b(function(r){var o=!1,i=!1,s=[],u=[],a=n.subscribe(function(t){var n,o;if(u.length>0){o=u.shift();try{n=e(o,t)}catch(a){return void r.onError(a)}n||(r.onNext(!1),r.onCompleted())}else i?(r.onNext(!1),r.onCompleted()):s.push(t)},function(t){r.onError(t)},function(){o=!0,0===s.length&&(u.length>0?(r.onNext(!1),r.onCompleted()):i&&(r.onNext(!0),r.onCompleted()))});(A(t)||N(t))&&(t=P(t)),C(t)&&(t=O(t));var c=t.subscribe(function(t){var n;if(s.length>0){var i=s.shift();try{n=e(i,t)}catch(a){return void r.onError(a)}n||(r.onNext(!1),r.onCompleted())}else o?(r.onNext(!1),r.onCompleted()):u.push(t)},function(t){r.onError(t)},function(){i=!0,0===u.length&&(s.length>0?(r.onNext(!1),r.onCompleted()):o&&(r.onNext(!0),r.onCompleted()))});return new y(a,c)},n)},v.elementAt=function(t){return a(this,t,!1)},v.elementAtOrDefault=function(t,e){return a(this,t,!0,e)},v.single=function(t,e){return t&&E(t)?this.where(t,e).single():c(this,!1)},v.singleOrDefault=function(t,e,n){return t&&E(t)?this.filter(t,n).singleOrDefault(null,e):c(this,!0,e)},v.first=function(t,e){return t?this.where(t,e).first():p(this,!1)},v.firstOrDefault=function(t,e,n){return t?this.where(t).firstOrDefault(null,e):p(this,!0,e)},v.last=function(t,e){return t?this.where(t,e).last():h(this,!1)},v.lastOrDefault=function(t,e,n){return t?this.where(t,n).lastOrDefault(null,e):h(this,!0,e)},v.find=function(t,e){return f(this,t,e,!1)},v.findIndex=function(t,e){return f(this,t,e,!0)},v.toSet=function(){if("undefined"==typeof t.Set)throw new TypeError;var e=this;return new b(function(n){var r=new t.Set;return e.subscribe(function(t){r.add(t)},function(t){n.onError(t)},function(){n.onNext(r),n.onCompleted()})},e)},v.toMap=function(e,n){if("undefined"==typeof t.Map)throw new TypeError;var r=this;return new b(function(o){var i=new t.Map;return r.subscribe(function(t){var r;try{r=e(t)}catch(s){return void o.onError(s)}var u=t;if(n)try{u=n(t)}catch(s){return void o.onError(s)}i.set(r,u)},function(t){o.onError(t)},function(){o.onNext(i),o.onCompleted()})},r)},n})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{159:159}],159:[function(e,n,r){(function(e,o){(function(i){function u(t){for(var e=[],n=0,r=t.length;r>n;n++)e.push(t[n]);return e}function a(t,e){if(ct&&e.stack&&"object"==typeof t&&null!==t&&t.stack&&-1===t.stack.indexOf(lt)){for(var n=[],r=e;r;r=r.source)r.stack&&n.unshift(r.stack);n.unshift(t.stack);var o=n.join("\n"+lt+"\n");t.stack=c(o)}}function c(t){for(var e=t.split("\n"),n=[],r=0,o=e.length;o>r;r++){var i=e[r];p(i)||h(i)||!i||n.push(i)}return n.join("\n")}function p(t){var e=l(t);if(!e)return!1;var n=e[0],r=e[1];return n===ht&&r>=ft&&$n>=r}function h(t){return-1!==t.indexOf("(module.js:")||-1!==t.indexOf("(node.js:")}function f(){if(ct)try{throw new Error}catch(t){var e=t.stack.split("\n"),n=e[0].indexOf("@")>0?e[1]:e[2],r=l(n);if(!r)return;return ht=r[0],r[1]}}function l(t){var e=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(t);if(e)return[e[1],Number(e[2])];var n=/at ([^ ]+):(\d+):(?:\d+)$/.exec(t);if(n)return[n[1],Number(n[2])];var r=/.*@(.+):(\d+)$/.exec(t);return r?[r[1],Number(r[2])]:void 0}function d(t){var e=[];if(!Ht(t))return e;Ut.nonEnumArgs&&t.length&&Xt(t)&&(t=Yt.call(t));var n=Ut.enumPrototypes&&"function"==typeof t,r=Ut.enumErrorProps&&(t===Jt||t instanceof Error);for(var o in t)n&&"prototype"==o||r&&("message"==o||"name"==o)||e.push(o);if(Ut.nonEnumShadows&&t!==It){var i=t.constructor,s=-1,u=kt;if(t===(i&&i.prototype))var a=t===Lt?$t:t===Jt?qt:Wt.call(t),c=Ft[a];for(;++s<u;)o=Nt[s],c&&c[o]||!zt.call(t,o)||e.push(o)}return e}function v(t,e,n){for(var r=-1,o=n(t),i=o.length;++r<i;){var s=o[r];if(e(t[s],s,t)===!1)break}return t}function y(t,e){return v(t,e,d)}function b(t){return"function"!=typeof t.toString&&"string"==typeof(t+"")}function m(t,e,n,r){if(t===e)return 0!==t||1/t==1/e;var o=typeof t,i=typeof e;if(t===t&&(null==t||null==e||"function"!=o&&"object"!=o&&"function"!=i&&"object"!=i))return!1;var s=Wt.call(t),u=Wt.call(e);if(s==Ot&&(s=Tt),u==Ot&&(u=Tt),s!=u)return!1;switch(s){case jt:case Dt:return+t==+e;case Mt:return t!=+t?e!=+e:0==t?1/t==1/e:t==+e;case Vt:case $t:return t==String(e)}var a=s==Pt;if(!a){if(s!=Tt||!Ut.nodeClass&&(b(t)||b(e)))return!1;var c=!Ut.argsObject&&Xt(t)?Object:t.constructor,p=!Ut.argsObject&&Xt(e)?Object:e.constructor;if(!(c==p||zt.call(t,"constructor")&&zt.call(e,"constructor")||at(c)&&c instanceof c&&at(p)&&p instanceof p||!("constructor"in t&&"constructor"in e)))return!1}n||(n=[]),r||(r=[]);for(var h=n.length;h--;)if(n[h]==t)return r[h]==e;var f=0,l=!0;if(n.push(t),r.push(e),a){if(h=t.length,f=e.length,l=f==h)for(;f--;){var d=e[f];if(!(l=m(t[f],d,n,r)))break}}else y(e,function(e,o,i){return zt.call(i,o)?(f++,l=zt.call(t,o)&&m(t[o],e,n,r)):void 0}),l&&y(t,function(t,e,n){return zt.call(n,e)?l=--f>-1:void 0});return n.pop(),r.pop(),l}function g(t,e){for(var n=new Array(t),r=0;t>r;r++)n[r]=e();return n}function w(){try{return Qt.apply(this,arguments)}catch(t){return ne.e=t,ne}}function x(t){if(!at(t))throw new TypeError("fn must be a function");return Qt=t,w}function _(t){throw t}function S(t,e){this.id=t,this.value=e}function E(t,e){this.scheduler=t,this.disposable=e,this.isDisposed=!1}function C(t,e){e.isDisposed||(e.isDisposed=!0,e.disposable.dispose())}function A(t){this._s=s}function N(t){this._s=s,this._l=s.length,this._i=0}function k(t){this._a=t}function O(t){this._a=t,this._l=q(t),this._i=0}function P(t){return"number"==typeof t&&X.isFinite(t)}function j(t){var e,n=t[xt];if(!n&&"string"==typeof t)return e=new A(t),e[xt]();if(!n&&t.length!==i)return e=new k(t),e[xt]();if(!n)throw new TypeError("Object is not iterable");return t[xt]()}function D(t){var e=+t;return 0===e?e:isNaN(e)?e:0>e?-1:1}function q(t){var e=+t.length;return isNaN(e)?0:0!==e&&P(e)?(e=D(e)*Math.floor(Math.abs(e)),0>=e?0:e>en?en:e):e}function R(t,e){this.observer=t,this.parent=e}function M(t,e){return me(t)||(t=_e),new rn(e,t)}function T(t,e){this.observer=t,this.parent=e}function V(t,e){this.observer=t,this.parent=e}function $(t,e){return new qn(function(n){var r=new fe,o=new le;return o.setDisposable(r),r.setDisposable(t.subscribe(function(t){n.onNext(t)},function(t){try{var r=e(t)}catch(i){return n.onError(i)}ut(r)&&(r=Xe(r));var s=new fe;o.setDisposable(s),s.setDisposable(r.subscribe(n))},function(t){n.onCompleted(t)})),o},t)}function W(){return!1}function z(t,e){var n=this;return new qn(function(r){var o=0,i=t.length;return n.subscribe(function(n){if(i>o){var s=t[o++],u=x(e)(n,s);if(u===ne)return r.onError(u.e);r.onNext(u)}else r.onCompleted()},function(t){r.onError(t)},function(){r.onCompleted()})},n)}function W(){return!1}function G(){return[]}function W(){return!1}function J(){return[]}function I(t,e){this.observer=t,this.accumulator=e.accumulator,this.hasSeed=e.hasSeed,this.seed=e.seed,this.hasAccumulation=!1,this.accumulation=null,this.hasValue=!1,this.isStopped=!1}function L(t,e,n){var r=At(e,n,3);return t.map(function(e,n){var o=r(e,n,t);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o}).concatAll()}function B(t,e,n){for(var r=0,o=t.length;o>r;r++)if(n(t[r],e))return r;return-1}function F(t){this.comparer=t,this.set=[]}function U(t,e,n){var r=At(e,n,3);return t.map(function(e,n){var o=r(e,n,t);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o}).mergeAll()}var H={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},X=H[typeof window]&&window||this,Q=H[typeof r]&&r&&!r.nodeType&&r,K=H[typeof n]&&n&&!n.nodeType&&n,Y=K&&K.exports===Q&&Q,Z=H[typeof o]&&o;!Z||Z.global!==Z&&Z.window!==Z||(X=Z);var tt={internals:{},config:{Promise:X.Promise},helpers:{}},et=tt.helpers.noop=function(){},nt=(tt.helpers.notDefined=function(t){return"undefined"==typeof t},tt.helpers.identity=function(t){return t}),rt=(tt.helpers.pluck=function(t){return function(e){return e[t]}},tt.helpers.just=function(t){return function(){return t}},tt.helpers.defaultNow=Date.now),ot=tt.helpers.defaultComparer=function(t,e){return Kt(t,e)},it=tt.helpers.defaultSubComparer=function(t,e){return t>e?1:e>t?-1:0},st=(tt.helpers.defaultKeySerializer=function(t){return t.toString()},tt.helpers.defaultError=function(t){throw t}),ut=tt.helpers.isPromise=function(t){return!!t&&"function"!=typeof t.subscribe&&"function"==typeof t.then},at=(tt.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},tt.helpers.not=function(t){return!t},tt.helpers.isFunction=function(){var t=function(t){return"function"==typeof t||!1};return t(/x/)&&(t=function(t){return"function"==typeof t&&"[object Function]"==Wt.call(t)}),t}());tt.config.longStackSupport=!1;var ct=!1;try{throw new Error}catch(pt){ct=!!pt.stack}var ht,ft=f(),lt="From previous event:",dt=tt.EmptyError=function(){this.message="Sequence contains no elements.",Error.call(this)};dt.prototype=Error.prototype;var vt=tt.ObjectDisposedError=function(){this.message="Object has been disposed",Error.call(this)};vt.prototype=Error.prototype;var yt=tt.ArgumentOutOfRangeError=function(){this.message="Argument out of range",Error.call(this)};yt.prototype=Error.prototype;var bt=tt.NotSupportedError=function(t){this.message=t||"This operation is not supported",Error.call(this)};bt.prototype=Error.prototype;var mt=tt.NotImplementedError=function(t){this.message=t||"This operation is not implemented",Error.call(this)};mt.prototype=Error.prototype;var gt=tt.helpers.notImplemented=function(){throw new mt},wt=tt.helpers.notSupported=function(){throw new bt},xt="function"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";X.Set&&"function"==typeof(new X.Set)["@@iterator"]&&(xt="@@iterator");var _t=tt.doneEnumerator={done:!0,value:i},St=tt.helpers.isIterable=function(t){return t[xt]!==i},Et=tt.helpers.isArrayLike=function(t){return t&&t.length!==i};tt.helpers.iterator=xt;var Ct,At=tt.internals.bindCallback=function(t,e,n){if("undefined"==typeof e)return t;switch(n){case 0:return function(){return t.call(e)};case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,o){return t.call(e,n,r,o)}}return function(){return t.apply(e,arguments)}},Nt=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],kt=Nt.length,Ot="[object Arguments]",Pt="[object Array]",jt="[object Boolean]",Dt="[object Date]",qt="[object Error]",Rt="[object Function]",Mt="[object Number]",Tt="[object Object]",Vt="[object RegExp]",$t="[object String]",Wt=Object.prototype.toString,zt=Object.prototype.hasOwnProperty,Gt=Wt.call(arguments)==Ot,Jt=Error.prototype,It=Object.prototype,Lt=String.prototype,Bt=It.propertyIsEnumerable;try{Ct=!(Wt.call(document)==Tt&&!({toString:0}+""))}catch(pt){Ct=!0}var Ft={};Ft[Pt]=Ft[Dt]=Ft[Mt]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},Ft[jt]=Ft[$t]={constructor:!0,toString:!0,valueOf:!0},Ft[qt]=Ft[Rt]=Ft[Vt]={constructor:!0,toString:!0},Ft[Tt]={constructor:!0};var Ut={};!function(){var t=function(){this.x=1},e=[];t.prototype={valueOf:1,y:1};for(var n in new t)e.push(n);for(n in arguments);Ut.enumErrorProps=Bt.call(Jt,"message")||Bt.call(Jt,"name"),Ut.enumPrototypes=Bt.call(t,"prototype"),Ut.nonEnumArgs=0!=n,Ut.nonEnumShadows=!/valueOf/.test(e)}(1);var Ht=tt.internals.isObject=function(t){var e=typeof t;return t&&("function"==e||"object"==e)||!1},Xt=function(t){return t&&"object"==typeof t?Wt.call(t)==Ot:!1};Gt||(Xt=function(t){return t&&"object"==typeof t?zt.call(t,"callee"):!1});var Qt,Kt=tt.internals.isEqual=function(t,e){return m(t,e,[],[])},Yt=({}.hasOwnProperty,Array.prototype.slice),Zt=this.inherits=tt.internals.inherits=function(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n},te=tt.internals.addProperties=function(t){for(var e=[],n=1,r=arguments.length;r>n;n++)e.push(arguments[n]);for(var o=0,i=e.length;i>o;o++){var s=e[o];for(var u in s)t[u]=s[u]}},ee=tt.internals.addRef=function(t,e){return new qn(function(n){return new ie(e.getDisposable(),t.subscribe(n))})},ne={e:{}};S.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var re=tt.internals.PriorityQueue=function(t){this.items=new Array(t),this.length=0},oe=re.prototype;oe.isHigherPriority=function(t,e){return this.items[t].compareTo(this.items[e])<0},oe.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},oe.heapify=function(t){if(+t||(t=0),!(t>=this.length||0>t)){var e=2*t+1,n=2*t+2,r=t;if(e<this.length&&this.isHigherPriority(e,r)&&(r=e),n<this.length&&this.isHigherPriority(n,r)&&(r=n),r!==t){var o=this.items[t];this.items[t]=this.items[r],this.items[r]=o,this.heapify(r)}}},oe.peek=function(){return this.items[0].value},oe.removeAt=function(t){this.items[t]=this.items[--this.length],this.items[this.length]=i,this.heapify()},oe.dequeue=function(){var t=this.peek();return this.removeAt(0),t},oe.enqueue=function(t){var e=this.length++;this.items[e]=new S(re.count++,t),this.percolate(e)},oe.remove=function(t){for(var e=0;e<this.length;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},re.count=0;var ie=tt.CompositeDisposable=function(){var t,e,n=[];if(Array.isArray(arguments[0]))n=arguments[0],e=n.length;else for(e=arguments.length,n=new Array(e),t=0;e>t;t++)n[t]=arguments[t];for(t=0;e>t;t++)if(!pe(n[t]))throw new TypeError("Not a disposable");this.disposables=n,this.isDisposed=!1,this.length=n.length},se=ie.prototype;se.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},se.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},se.dispose=function(){
3460 if(!this.isDisposed){this.isDisposed=!0;for(var t=this.disposables.length,e=new Array(t),n=0;t>n;n++)e[n]=this.disposables[n];for(this.disposables=[],this.length=0,n=0;t>n;n++)e[n].dispose()}};var ue=tt.Disposable=function(t){this.isDisposed=!1,this.action=t||et};ue.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var ae=ue.create=function(t){return new ue(t)},ce=ue.empty={dispose:et},pe=ue.isDisposable=function(t){return t&&at(t.dispose)},he=ue.checkDisposed=function(t){if(t.isDisposed)throw new vt},fe=tt.SingleAssignmentDisposable=function(){this.isDisposed=!1,this.current=null};fe.prototype.getDisposable=function(){return this.current},fe.prototype.setDisposable=function(t){if(this.current)throw new Error("Disposable has already been assigned");var e=this.isDisposed;!e&&(this.current=t),e&&t&&t.dispose()},fe.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.current;this.current=null}t&&t.dispose()};var le=tt.SerialDisposable=function(){this.isDisposed=!1,this.current=null};le.prototype.getDisposable=function(){return this.current},le.prototype.setDisposable=function(t){var e=this.isDisposed;if(!e){var n=this.current;this.current=t}n&&n.dispose(),e&&t&&t.dispose()},le.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.current;this.current=null}t&&t.dispose()};var de=tt.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?ce:new t(this)},e}();E.prototype.dispose=function(){this.scheduler.scheduleWithState(this,C)};var ve=tt.internals.ScheduledItem=function(t,e,n,r,o){this.scheduler=t,this.state=e,this.action=n,this.dueTime=r,this.comparer=o||it,this.disposable=new fe};ve.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},ve.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},ve.prototype.isCancelled=function(){return this.disposable.isDisposed},ve.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var ye=tt.Scheduler=function(){function t(t,e,n,r){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=r}function e(t,e){return e(),ce}t.isScheduler=function(e){return e instanceof t};var n=t.prototype;return n.schedule=function(t){return this._schedule(t,e)},n.scheduleWithState=function(t,e){return this._schedule(t,e)},n.scheduleWithRelative=function(t,n){return this._scheduleRelative(n,t,e)},n.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},n.scheduleWithAbsolute=function(t,n){return this._scheduleAbsolute(n,t,e)},n.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},t.now=rt,t.normalize=function(t){return 0>t&&(t=0),t},t}(),be=ye.normalize,me=ye.isScheduler;!function(t){function e(t,e){function n(e){o(e,function(e){var r=!1,o=!1,s=t.scheduleWithState(e,function(t,e){return r?i.remove(s):o=!0,n(e),ce});o||(i.add(s),r=!0)})}var r=e[0],o=e[1],i=new ie;return n(r),i}function n(t,e,n){function r(e){i(e,function(e,o){var i=!1,u=!1,a=t[n](e,o,function(t,e){return i?s.remove(a):u=!0,r(e),ce});u||(s.add(a),i=!0)})}var o=e[0],i=e[1],s=new ie;return r(o),s}function r(t,e){t(function(n){e(t,n)})}t.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,r)},t.scheduleRecursiveWithState=function(t,n){return this.scheduleWithState([t,n],e)},t.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,r)},t.scheduleRecursiveWithRelativeAndState=function(t,e,r){return this._scheduleRelative([t,r],e,function(t,e){return n(t,e,"scheduleWithRelativeAndState")})},t.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,r)},t.scheduleRecursiveWithAbsoluteAndState=function(t,e,r){return this._scheduleAbsolute([t,r],e,function(t,e){return n(t,e,"scheduleWithAbsoluteAndState")})}}(ye.prototype),function(t){ye.prototype.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,e)},ye.prototype.schedulePeriodicWithState=function(t,e,n){if("undefined"==typeof X.setInterval)throw new bt;e=be(e);var r=t,o=X.setInterval(function(){r=n(r)},e);return ae(function(){X.clearInterval(o)})}}(ye.prototype),function(t){t.catchError=t["catch"]=function(t){return new Ae(this,t)}}(ye.prototype);var ge,we,xe=(tt.internals.SchedulePeriodicRecursive=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,r){this._scheduler=t,this._state=e,this._period=n,this._action=r}return e.prototype.start=function(){var e=new fe;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}(),ye.immediate=function(){function t(t,e){return e(this,t)}return new ye(rt,t,wt,wt)}()),_e=ye.currentThread=function(){function t(){for(;n.length>0;){var t=n.dequeue();!t.isCancelled()&&t.invoke()}}function e(e,r){var o=new ve(this,e,r,this.now());if(n)n.enqueue(o);else{n=new re(4),n.enqueue(o);var i=x(t)();if(n=null,i===ne)return _(i.e)}return o.disposable}var n,r=new ye(rt,e,wt,wt);return r.scheduleRequired=function(){return!n},r}(),Se=function(){var t,e=et;if(X.setTimeout)t=X.setTimeout,e=X.clearTimeout;else{if(!X.WScript)throw new bt;t=function(t,e){X.WScript.Sleep(e),t()}}return{setTimeout:t,clearTimeout:e}}(),Ee=Se.setTimeout,Ce=Se.clearTimeout;!function(){function t(e){if(s)Ee(function(){t(e)},0);else{var n=i[e];if(n){s=!0;var r=x(n)();if(we(e),s=!1,r===ne)return _(r.e)}}}function n(){if(!X.postMessage||X.importScripts)return!1;var t=!1,e=X.onmessage;return X.onmessage=function(){t=!0},X.postMessage("","*"),X.onmessage=e,t}function r(e){"string"==typeof e.data&&e.data.substring(0,c.length)===c&&t(e.data.substring(c.length))}var o=1,i={},s=!1;we=function(t){delete i[t]};var u=RegExp("^"+String(Wt).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),a="function"==typeof(a=Z&&Y&&Z.setImmediate)&&!u.test(a)&&a;if(at(a))ge=function(e){var n=o++;return i[n]=e,a(function(){t(n)}),n};else if("undefined"!=typeof e&&"[object process]"==={}.toString.call(e))ge=function(n){var r=o++;return i[r]=n,e.nextTick(function(){t(r)}),r};else if(n()){var c="ms.rx.schedule"+Math.random();X.addEventListener?X.addEventListener("message",r,!1):X.attachEvent?X.attachEvent("onmessage",r):X.onmessage=r,ge=function(t){var e=o++;return i[e]=t,X.postMessage(c+currentId,"*"),e}}else if(X.MessageChannel){var p=new X.MessageChannel;p.port1.onmessage=function(e){t(e.data)},ge=function(t){var e=o++;return i[e]=t,p.port2.postMessage(e),e}}else ge="document"in X&&"onreadystatechange"in X.document.createElement("script")?function(e){var n=X.document.createElement("script"),r=o++;return i[r]=e,n.onreadystatechange=function(){t(r),n.onreadystatechange=null,n.parentNode.removeChild(n),n=null},X.document.documentElement.appendChild(n),r}:function(e){var n=o++;return i[n]=e,Ee(function(){t(n)},0),n}}();var Ae=(ye.timeout=ye["default"]=function(){function t(t,e){var n=this,r=new fe,o=ge(function(){!r.isDisposed&&r.setDisposable(e(n,t))});return new ie(r,ae(function(){we(o)}))}function e(t,e,n){var r=this,o=ye.normalize(e),i=new fe;if(0===o)return r.scheduleWithState(t,n);var s=Ee(function(){!i.isDisposed&&i.setDisposable(n(r,t))},o);return new ie(i,ae(function(){Ce(s)}))}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new ye(rt,t,e,n)}(),function(t){function e(t,e){return this._scheduler.scheduleWithState(t,this._wrap(e))}function n(t,e,n){return this._scheduler.scheduleWithRelativeAndState(t,e,this._wrap(n))}function r(t,e,n){return this._scheduler.scheduleWithAbsoluteAndState(t,e,this._wrap(n))}function o(o,i){this._scheduler=o,this._handler=i,this._recursiveOriginal=null,this._recursiveWrapper=null,t.call(this,this._scheduler.now.bind(this._scheduler),e,n,r)}return Zt(o,t),o.prototype._clone=function(t){return new o(t,this._handler)},o.prototype._wrap=function(t){var e=this;return function(n,r){try{return t(e._getRecursiveWrapper(n),r)}catch(o){if(!e._handler(o))throw o;return ce}}},o.prototype._getRecursiveWrapper=function(t){if(this._recursiveOriginal!==t){this._recursiveOriginal=t;var e=this._clone(t);e._recursiveOriginal=t,e._recursiveWrapper=e,this._recursiveWrapper=e}return this._recursiveWrapper},o.prototype.schedulePeriodicWithState=function(t,e,n){var r=this,o=!1,i=new fe;return i.setDisposable(this._scheduler.schedulePeriodicWithState(t,e,function(t){if(o)return null;try{return n(t)}catch(e){if(o=!0,!r._handler(e))throw e;return i.dispose(),null}})),i},o}(ye)),Ne=tt.Notification=function(){function t(t,e,n,r,o,i){this.kind=t,this.value=e,this.exception=n,this._accept=r,this._acceptObservable=o,this.toString=i}return t.prototype.accept=function(t,e,n){return t&&"object"==typeof t?this._acceptObservable(t):this._accept(t,e,n)},t.prototype.toObservable=function(t){var e=this;return me(t)||(t=xe),new qn(function(n){return t.scheduleWithState(e,function(t,e){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},t}(),ke=Ne.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(r){return new Ne("N",r,null,t,e,n)}}(),Oe=Ne.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(r){return new Ne("E",null,r,t,e,n)}}(),Pe=Ne.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){return new Ne("C",null,null,t,e,n)}}(),je=tt.Observer=function(){};je.prototype.toNotifier=function(){var t=this;return function(e){return e.accept(t)}},je.prototype.asObserver=function(){return new Me(this.onNext.bind(this),this.onError.bind(this),this.onCompleted.bind(this))},je.prototype.checked=function(){return new Te(this)};var De=je.create=function(t,e,n){return t||(t=et),e||(e=st),n||(n=et),new Me(t,e,n)};je.fromNotifier=function(t,e){return new Me(function(n){return t.call(e,ke(n))},function(n){return t.call(e,Oe(n))},function(){return t.call(e,Pe())})},je.prototype.notifyOn=function(t){return new $e(t,this)},je.prototype.makeSafe=function(t){return new AnonymousSafeObserver(this._onNext,this._onError,this._onCompleted,t)};var qe,Re=tt.internals.AbstractObserver=function(t){function e(){this.isStopped=!1,t.call(this)}return Zt(e,t),e.prototype.next=gt,e.prototype.error=gt,e.prototype.completed=gt,e.prototype.onNext=function(t){this.isStopped||this.next(t)},e.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.error(t))},e.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.completed())},e.prototype.dispose=function(){this.isStopped=!0},e.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.error(t),!0)},e}(je),Me=tt.AnonymousObserver=function(t){function e(e,n,r){t.call(this),this._onNext=e,this._onError=n,this._onCompleted=r}return Zt(e,t),e.prototype.next=function(t){this._onNext(t)},e.prototype.error=function(t){this._onError(t)},e.prototype.completed=function(){this._onCompleted()},e}(Re),Te=function(t){function e(e){t.call(this),this._observer=e,this._state=0}Zt(e,t);var n=e.prototype;return n.onNext=function(t){this.checkAccess();var e=x(this._observer.onNext).call(this._observer,t);this._state=0,e===ne&&_(e.e)},n.onError=function(t){this.checkAccess();var e=x(this._observer.onError).call(this._observer,t);this._state=2,e===ne&&_(e.e)},n.onCompleted=function(){this.checkAccess();var t=x(this._observer.onCompleted).call(this._observer);this._state=2,t===ne&&_(t.e)},n.checkAccess=function(){if(1===this._state)throw new Error("Re-entrancy detected");if(2===this._state)throw new Error("Observer completed");0===this._state&&(this._state=1)},e}(je),Ve=tt.internals.ScheduledObserver=function(t){function e(e,n){t.call(this),this.scheduler=e,this.observer=n,this.isAcquired=!1,this.hasFaulted=!1,this.queue=[],this.disposable=new le}return Zt(e,t),e.prototype.next=function(t){var e=this;this.queue.push(function(){e.observer.onNext(t)})},e.prototype.error=function(t){var e=this;this.queue.push(function(){e.observer.onError(t)})},e.prototype.completed=function(){var t=this;this.queue.push(function(){t.observer.onCompleted()})},e.prototype.ensureActive=function(){var t=!1,e=this;!this.hasFaulted&&this.queue.length>0&&(t=!this.isAcquired,this.isAcquired=!0),t&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(t){var n;if(!(e.queue.length>0))return void(e.isAcquired=!1);n=e.queue.shift();try{n()}catch(r){throw e.queue=[],e.hasFaulted=!0,r}t()}))},e.prototype.dispose=function(){t.prototype.dispose.call(this),this.disposable.dispose()},e}(Re),$e=function(t){function e(e,n,r){t.call(this,e,n),this._cancel=r}return Zt(e,t),e.prototype.next=function(e){t.prototype.next.call(this,e),this.ensureActive()},e.prototype.error=function(e){t.prototype.error.call(this,e),this.ensureActive()},e.prototype.completed=function(){t.prototype.completed.call(this),this.ensureActive()},e.prototype.dispose=function(){t.prototype.dispose.call(this),this._cancel&&this._cancel.dispose(),this._cancel=null},e}(Ve),We=tt.Observable=function(){function t(t){if(tt.config.longStackSupport&&ct){try{throw new Error}catch(e){this.stack=e.stack.substring(e.stack.indexOf("\n")+1)}var n=this;this._subscribe=function(e){var r=e.onError.bind(e);return e.onError=function(t){a(t,n),r(t)},t.call(n,e)}}else this._subscribe=t}return qe=t.prototype,qe.subscribe=qe.forEach=function(t,e,n){return this._subscribe("object"==typeof t?t:De(t,e,n))},qe.subscribeOnNext=function(t,e){return this._subscribe(De("undefined"!=typeof e?function(n){t.call(e,n)}:t))},qe.subscribeOnError=function(t,e){return this._subscribe(De(null,"undefined"!=typeof e?function(n){t.call(e,n)}:t))},qe.subscribeOnCompleted=function(t,e){return this._subscribe(De(null,null,"undefined"!=typeof e?function(){t.call(e)}:t))},t}(),ze=tt.ObservableBase=function(t){function e(t){return t&&at(t.dispose)?t:at(t)?ae(t):ce}function n(t,n){var r=n[0],o=n[1],i=x(o.subscribeCore).call(o,r);return i!==ne||r.fail(ne.e)?void r.setDisposable(e(i)):_(ne.e)}function r(t){var e=new Rn(t),r=[e,this];return _e.scheduleRequired()?_e.scheduleWithState(r,n):n(null,r),e}function o(){t.call(this,r)}return Zt(o,t),o.prototype.subscribeCore=gt,o}(We),Ge=tt.internals.Enumerable=function(){},Je=function(t){function e(e){this.sources=e,t.call(this)}function n(t,e,n){this.o=t,this.s=e,this.e=n,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){var e,r=new le,o=xe.scheduleRecursiveWithState(this.sources[xt](),function(o,i){if(!e){var s=x(o.next).call(o);if(s===ne)return t.onError(s.e);if(s.done)return t.onCompleted();var u=s.value;ut(u)&&(u=Xe(u));var a=new fe;r.setDisposable(a),a.setDisposable(u.subscribe(new n(t,i,o)))}});return new ie(r,o,ae(function(){e=!0}))},n.prototype.onNext=function(t){this.isStopped||this.o.onNext(t)},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.s(this.e))},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);Ge.prototype.concat=function(){return new Je(this)};var Ie=function(t){function e(e){this.sources=e,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e,n=this.sources[xt](),r=new le,o=xe.scheduleRecursiveWithState(null,function(o,i){if(!e){var s=x(n.next).call(n);if(s===ne)return t.onError(s.e);if(s.done)return null!==o?t.onError(o):t.onCompleted();var u=s.value;ut(u)&&(u=Xe(u));var a=new fe;r.setDisposable(a),a.setDisposable(u.subscribe(function(e){t.onNext(e)},i,function(){t.onCompleted()}))}});return new ie(r,o,ae(function(){e=!0}))},e}(ze);Ge.prototype.catchError=function(){return new Ie(this)},Ge.prototype.catchErrorWhen=function(t){var e=this;return new qn(function(n){var r,o,i=new Tn,s=new Tn,u=t(i),a=u.subscribe(s),c=e[xt](),p=new le,h=xe.scheduleRecursive(function(t){if(!r){var e=x(c.next).call(c);if(e===ne)return n.onError(e.e);if(e.done)return void(o?n.onError(o):n.onCompleted());var u=e.value;ut(u)&&(u=Xe(u));var a=new fe,h=new fe;p.setDisposable(new ie(h,a)),a.setDisposable(u.subscribe(function(t){n.onNext(t)},function(e){h.setDisposable(s.subscribe(t,function(t){n.onError(t)},function(){n.onCompleted()})),i.onNext(e)},function(){n.onCompleted()}))}});return new ie(a,p,h,ae(function(){r=!0}))})};var Le=function(t){function e(t,e){this.v=t,this.c=null==e?-1:e}function n(t){this.v=t.v,this.l=t.c}return Zt(e,t),e.prototype[xt]=function(){return new n(this)},n.prototype.next=function(){return 0===this.l?_t:(this.l>0&&this.l--,{done:!1,value:this.v})},e}(Ge),Be=Ge.repeat=function(t,e){return new Le(t,e)},Fe=function(t){function e(t,e,n){this.s=t,this.fn=e?At(e,n,3):null}function n(t){this.i=-1,this.s=t.s,this.l=this.s.length,this.fn=t.fn}return Zt(e,t),e.prototype[xt]=function(){return new n(this)},n.prototype.next=function(){return++this.i<this.l?{done:!1,value:this.fn?this.fn(this.s[this.i],this.i,this.s):this.s[this.i]}:_t},e}(Ge),Ue=Ge.of=function(t,e,n){return new Fe(t,e,n)};qe.observeOn=function(t){var e=this;return new qn(function(n){return e.subscribe(new $e(t,n))},e)},qe.subscribeOn=function(t){var e=this;return new qn(function(n){var r=new fe,o=new le;return o.setDisposable(r),r.setDisposable(t.schedule(function(){o.setDisposable(new E(t,e.subscribe(n)))})),o},e)};var He=function(t){function e(e){this.p=e,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.p.then(function(e){t.onNext(e),t.onCompleted()},function(e){t.onError(e)}),ce},e}(ze),Xe=We.fromPromise=function(t){return new He(t)};qe.toPromise=function(t){if(t||(t=tt.config.Promise),!t)throw new bt("Promise type not provided nor in Rx.config.Promise");var e=this;return new t(function(t,n){var r,o=!1;e.subscribe(function(t){r=t,o=!0},n,function(){o&&t(r)})})};var Qe=function(t){function e(e){this.source=e,t.call(this)}function n(t){this.o=t,this.a=[],this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t))},n.prototype.onNext=function(t){this.isStopped||this.a.push(t)},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onNext(this.a),this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.toArray=function(){return new Qe(this)},We.create=We.createWithDisposable=function(t,e){return new qn(t,e)};var Ke=(We.defer=function(t){return new qn(function(e){var n;try{n=t()}catch(r){return dn(r).subscribe(e)}return ut(n)&&(n=Xe(n)),n.subscribe(e)})},function(t){function e(e){this.scheduler=e,t.call(this)}function n(t,e){this.observer=t,this.parent=e}function r(t,e){e.onCompleted()}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(t,this);return e.run()},n.prototype.run=function(){return this.parent.scheduler.scheduleWithState(this.observer,r)},e}(ze)),Ye=We.empty=function(t){return me(t)||(t=xe),new Ke(t)},Ze=function(t){function e(e,n,r){this.iterable=e,this.mapper=n,this.scheduler=r,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new tn(t,this);return e.run()},e}(ze),tn=function(){function t(t,e){this.observer=t,this.parent=e}return t.prototype.run=function(){function t(t,e){try{var i=n.next()}catch(s){return r.onError(s)}if(i.done)return r.onCompleted();var u=i.value;if(o)try{u=o(u,t)}catch(s){return r.onError(s)}r.onNext(u),e(t+1)}var e=Object(this.parent.iterable),n=j(e),r=this.observer,o=this.parent.mapper;return this.parent.scheduler.scheduleRecursiveWithState(0,t)},t}(),en=Math.pow(2,53)-1;A.prototype[xt]=function(){return new N(this._s)},N.prototype[xt]=function(){return this},N.prototype.next=function(){return this._i<this._l?{done:!1,value:this._s.charAt(this._i++)}:_t},k.prototype[xt]=function(){return new O(this._a)},O.prototype[xt]=function(){return this},O.prototype.next=function(){return this._i<this._l?{done:!1,value:this._a[this._i++]}:_t};var nn=We.from=function(t,e,n,r){if(null==t)throw new Error("iterable cannot be null.");if(e&&!at(e))throw new Error("mapFn when provided must be a function");if(e)var o=At(e,n,2);return me(r)||(r=_e),new Ze(t,o,r)},rn=function(t){function e(e,n){this.args=e,this.scheduler=n,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new R(t,this);return e.run()},e}(ze);R.prototype.run=function(){function t(t,o){r>t?(e.onNext(n[t]),o(t+1)):e.onCompleted()}var e=this.observer,n=this.parent.args,r=n.length;return this.parent.scheduler.scheduleRecursiveWithState(0,t)};var on=We.fromArray=function(t,e){return me(e)||(e=_e),new rn(t,e)};We.generate=function(t,e,n,r,o){return me(o)||(o=_e),new qn(function(i){var s=!0;return o.scheduleRecursiveWithState(t,function(t,o){var u,a;try{s?s=!1:t=n(t),u=e(t),u&&(a=r(t))}catch(c){return i.onError(c)}u?(i.onNext(a),o(t)):i.onCompleted()})})};var sn=function(t){function e(){t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){return ce},e}(ze),un=We.never=function(){return new sn};We.of=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];return new rn(e,_e)},We.ofWithScheduler=function(t){for(var e=arguments.length,n=new Array(e-1),r=1;e>r;r++)n[r-1]=arguments[r];return new rn(n,t)};var an=function(t){function e(e,n){this.obj=e,this.keys=Object.keys(e),this.scheduler=n,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new T(t,this);return e.run()},e}(ze);T.prototype.run=function(){function t(t,i){if(o>t){var s=r[t];e.onNext([s,n[s]]),i(t+1)}else e.onCompleted()}var e=this.observer,n=this.parent.obj,r=this.parent.keys,o=r.length;return this.parent.scheduler.scheduleRecursiveWithState(0,t)},We.pairs=function(t,e){return e||(e=_e),new an(t,e)};var cn=function(t){function e(e,n,r){this.start=e,this.rangeCount=n,this.scheduler=r,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new pn(t,this);return e.run()},e}(ze),pn=function(){function t(t,e){this.observer=t,this.parent=e}return t.prototype.run=function(){function t(t,o){n>t?(r.onNext(e+t),o(t+1)):r.onCompleted()}var e=this.parent.start,n=this.parent.rangeCount,r=this.observer;return this.parent.scheduler.scheduleRecursiveWithState(0,t)},t}();We.range=function(t,e,n){return me(n)||(n=_e),new cn(t,e,n)};var hn=function(t){function e(e,n,r){this.value=e,this.repeatCount=null==n?-1:n,this.scheduler=r,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new V(t,this);return e.run()},e}(ze);V.prototype.run=function(){function t(t,r){return(-1===t||t>0)&&(e.onNext(n),t>0&&t--),0===t?e.onCompleted():void r(t)}var e=this.observer,n=this.parent.value;return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount,t)},We.repeat=function(t,e,n){return me(n)||(n=_e),new hn(t,e,n)};var fn=function(t){function e(e,n){this.value=e,this.scheduler=n,t.call(this)}function n(t,e){this.observer=t,this.parent=e}function r(t,e){var n=e[0],r=e[1];r.onNext(n),r.onCompleted()}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(t,this);return e.run()},n.prototype.run=function(){return this.parent.scheduler.scheduleWithState([this.parent.value,this.observer],r)},e}(ze),ln=(We["return"]=We.just=We.returnValue=function(t,e){return me(e)||(e=xe),new fn(t,e)},function(t){function e(e,n){this.error=e,this.scheduler=n,t.call(this)}function n(t,e){this.o=t,this.p=e}function r(t,e){var n=e[0],r=e[1];r.onError(n)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(t,this);return e.run()},n.prototype.run=function(){return this.p.scheduler.scheduleWithState([this.p.error,this.o],r)},e}(ze)),dn=We["throw"]=We.throwError=We.throwException=function(t,e){return me(e)||(e=xe),new ln(t,e)};We.using=function(t,e){return new qn(function(n){var r,o,i=ce;try{r=t(),r&&(i=r),o=e(r)}catch(s){return new ie(dn(s).subscribe(n),i)}return new ie(o.subscribe(n),i)})},qe.amb=function(t){var e=this;return new qn(function(n){function r(){i||(i=s,c.dispose())}function o(){i||(i=u,a.dispose())}var i,s="L",u="R",a=new fe,c=new fe;return ut(t)&&(t=Xe(t)),a.setDisposable(e.subscribe(function(t){r(),i===s&&n.onNext(t)},function(t){r(),i===s&&n.onError(t)},function(){r(),i===s&&n.onCompleted()})),c.setDisposable(t.subscribe(function(t){o(),i===u&&n.onNext(t)},function(t){o(),i===u&&n.onError(t)},function(){o(),i===u&&n.onCompleted()})),new ie(a,c)})},We.amb=function(){function t(t,e){return t.amb(e)}var e=un(),n=[];if(Array.isArray(arguments[0]))n=arguments[0];else for(var r=0,o=arguments.length;o>r;r++)n.push(arguments[r]);for(var r=0,o=n.length;o>r;r++)e=t(e,n[r]);return e},qe["catch"]=qe.catchError=qe.catchException=function(t){return"function"==typeof t?$(this,t):vn([this,t])};var vn=We.catchError=We["catch"]=We.catchException=function(){var t=[];if(Array.isArray(arguments[0]))t=arguments[0];else for(var e=0,n=arguments.length;n>e;e++)t.push(arguments[e]);return Ue(t).catchError()};qe.combineLatest=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];return Array.isArray(e[0])?e[0].unshift(this):e.unshift(this),yn.apply(this,e)};var yn=We.combineLatest=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=e.pop();return Array.isArray(e[0])&&(e=e[0]),new qn(function(t){function n(e){if(u[e]=!0,a||(a=u.every(nt))){try{var n=r.apply(null,p)}catch(o){return t.onError(o)}t.onNext(n)}else c.filter(function(t,n){return n!==e}).every(nt)&&t.onCompleted()}function o(e){c[e]=!0,c.every(nt)&&t.onCompleted()}for(var i=e.length,s=function(){return!1},u=g(i,s),a=!1,c=g(i,s),p=new Array(i),h=new Array(i),f=0;i>f;f++)!function(r){var i=e[r],s=new fe;ut(i)&&(i=Xe(i)),s.setDisposable(i.subscribe(function(t){p[r]=t,n(r)},function(e){t.onError(e)},function(){o(r)})),h[r]=s}(f);return new ie(h)},this)};qe.concat=function(){for(var t=[],e=0,n=arguments.length;n>e;e++)t.push(arguments[e]);return t.unshift(this),mn.apply(null,t)};var bn=function(t){function e(e){this.sources=e,t.call(this)}function n(t,e){this.sources=t,this.o=e}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(this.sources,t);return e.run()},n.prototype.run=function(){var t,e=new le,n=this.sources,r=n.length,o=this.o,i=xe.scheduleRecursiveWithState(0,function(i,s){if(!t){if(i===r)return o.onCompleted();var u=n[i];ut(u)&&(u=Xe(u));var a=new fe;e.setDisposable(a),a.setDisposable(u.subscribe(function(t){o.onNext(t)},function(t){o.onError(t)},function(){s(i+1)}))}});return new ie(e,i,ae(function(){t=!0}))},e}(ze),mn=We.concat=function(){var t;if(Array.isArray(arguments[0]))t=arguments[0];else{t=new Array(arguments.length);for(var e=0,n=arguments.length;n>e;e++)t[e]=arguments[e]}return new bn(t)};qe.concatAll=qe.concatObservable=function(){return this.merge(1)};var gn=function(t){function e(e,n){this.source=e,this.maxConcurrent=n,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new ie;return e.add(this.source.subscribe(new wn(t,this.maxConcurrent,e))),e},e}(ze),wn=function(){function t(t,e,n){this.o=t,this.max=e,this.g=n,this.done=!1,this.q=[],this.activeCount=0,this.isStopped=!1}function e(t,e){this.parent=t,this.sad=e,this.isStopped=!1}return t.prototype.handleSubscribe=function(t){var n=new fe;this.g.add(n),ut(t)&&(t=Xe(t)),n.setDisposable(t.subscribe(new e(this,n)))},t.prototype.onNext=function(t){this.isStopped||(this.activeCount<this.max?(this.activeCount++,this.handleSubscribe(t)):this.q.push(t))},t.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},t.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.done=!0,0===this.activeCount&&this.o.onCompleted())},t.prototype.dispose=function(){this.isStopped=!0},t.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e.prototype.onNext=function(t){this.isStopped||this.parent.o.onNext(t)},e.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.parent.o.onError(t))},e.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=!0;var t=this.parent;t.g.remove(this.sad),t.q.length>0?t.handleSubscribe(t.q.shift()):(t.activeCount--,t.done&&0===t.activeCount&&t.o.onCompleted())}},e.prototype.dispose=function(){this.isStopped=!0},e.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(t),!0)},t}();qe.merge=function(t){return"number"!=typeof t?xn(this,t):new gn(this,t)};var xn=We.merge=function(){var t,e,n=[],r=arguments.length;if(arguments[0])if(me(arguments[0]))for(t=arguments[0],e=1;r>e;e++)n.push(arguments[e]);else for(t=xe,e=0;r>e;e++)n.push(arguments[e]);else for(t=xe,e=1;r>e;e++)n.push(arguments[e]);return Array.isArray(n[0])&&(n=n[0]),M(t,n).mergeAll()},_n=tt.CompositeError=function(t){this.name="NotImplementedError",this.innerErrors=t,this.message="This contains multiple errors. Check the innerErrors",Error.call(this)};_n.prototype=Error.prototype,We.mergeDelayError=function(){var t;if(Array.isArray(arguments[0]))t=arguments[0];else{var e=arguments.length;t=new Array(e);for(var n=0;e>n;n++)t[n]=arguments[n]}var r=M(null,t);return new qn(function(t){function e(){0===s.length?t.onCompleted():1===s.length?t.onError(s[0]):t.onError(new _n(s))}var n=new ie,o=new fe,i=!1,s=[];return n.add(o),o.setDisposable(r.subscribe(function(r){var o=new fe;n.add(o),ut(r)&&(r=Xe(r)),o.setDisposable(r.subscribe(function(e){t.onNext(e)},function(t){s.push(t),n.remove(o),i&&1===n.length&&e()},function(){n.remove(o),i&&1===n.length&&e()}))},function(t){s.push(t),i=!0,1===n.length&&e()},function(){i=!0,1===n.length&&e()})),n})};var Sn=function(t){function e(e){this.source=e,t.call(this)}function n(t,e){this.o=t,this.g=e,this.isStopped=!1,this.done=!1}function r(t,e,n){this.parent=t,this.g=e,this.sad=n,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new ie,r=new fe;return e.add(r),r.setDisposable(this.source.subscribe(new n(t,e))),e},n.prototype.onNext=function(t){if(!this.isStopped){var e=new fe;this.g.add(e),ut(t)&&(t=Xe(t)),e.setDisposable(t.subscribe(new r(this,this.g,e)))}},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.done=!0,1===this.g.length&&this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},r.prototype.onNext=function(t){this.isStopped||this.parent.o.onNext(t)},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.parent.o.onError(t))},r.prototype.onCompleted=function(){if(!this.isStopped){var t=this.parent;this.isStopped=!0,t.g.remove(this.sad),t.done&&1===t.g.length&&t.o.onCompleted()}},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(t),!0)},e}(ze);qe.mergeAll=qe.mergeObservable=function(){
3461 return new Sn(this)},qe.onErrorResumeNext=function(t){if(!t)throw new Error("Second observable is required");return En([this,t])};var En=We.onErrorResumeNext=function(){var t=[];if(Array.isArray(arguments[0]))t=arguments[0];else for(var e=0,n=arguments.length;n>e;e++)t.push(arguments[e]);return new qn(function(e){var n=0,r=new le,o=xe.scheduleRecursive(function(o){var i,s;n<t.length?(i=t[n++],ut(i)&&(i=Xe(i)),s=new fe,r.setDisposable(s),s.setDisposable(i.subscribe(e.onNext.bind(e),o,o))):e.onCompleted()});return new ie(r,o)})};qe.skipUntil=function(t){var e=this;return new qn(function(n){var r=!1,o=new ie(e.subscribe(function(t){r&&n.onNext(t)},function(t){n.onError(t)},function(){r&&n.onCompleted()}));ut(t)&&(t=Xe(t));var i=new fe;return o.add(i),i.setDisposable(t.subscribe(function(){r=!0,i.dispose()},function(t){n.onError(t)},function(){i.dispose()})),o},e)};var Cn=function(t){function e(e){this.source=e,t.call(this)}function n(t,e){this.o=t,this.inner=e,this.stopped=!1,this.latest=0,this.hasLatest=!1,this.isStopped=!1}function r(t,e){this.parent=t,this.id=e,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new le,r=this.source.subscribe(new n(t,e));return new ie(r,e)},n.prototype.onNext=function(t){if(!this.isStopped){var e=new fe,n=++this.latest;this.hasLatest=!0,this.inner.setDisposable(e),ut(t)&&(t=Xe(t)),e.setDisposable(t.subscribe(new r(this,n)))}},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.stopped=!0,!this.hasLatest&&this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},r.prototype.onNext=function(t){this.isStopped||this.parent.latest===this.id&&this.parent.o.onNext(t)},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.parent.latest===this.id&&this.parent.o.onError(t))},r.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.parent.latest===this.id&&(this.parent.hasLatest=!1,this.parent.isStopped&&this.parent.o.onCompleted()))},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(t),!0)},e}(ze);qe["switch"]=qe.switchLatest=function(){return new Cn(this)};var An=function(t){function e(e,n){this.source=e,this.other=ut(n)?Xe(n):n,t.call(this)}function n(t){this.o=t,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return new ie(this.source.subscribe(t),this.other.subscribe(new n(t)))},n.prototype.onNext=function(t){this.isStopped||this.o.onCompleted()},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){!this.isStopped&&(this.isStopped=!0)},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.takeUntil=function(t){return new An(this,t)},qe.withLatestFrom=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=e.pop(),o=this;return Array.isArray(e[0])&&(e=e[0]),new qn(function(t){for(var n=e.length,i=g(n,W),s=!1,u=new Array(n),a=new Array(n+1),c=0;n>c;c++)!function(n){var r=e[n],o=new fe;ut(r)&&(r=Xe(r)),o.setDisposable(r.subscribe(function(t){u[n]=t,i[n]=!0,s=i.every(nt)},function(e){t.onError(e)},et)),a[n]=o}(c);var p=new fe;return p.setDisposable(o.subscribe(function(e){var n=[e].concat(u);if(s){var o=x(r).apply(null,n);return o===ne?t.onError(o.e):void t.onNext(o)}},function(e){t.onError(e)},function(){t.onCompleted()})),a[n]=p,new ie(a)},this)},qe.zip=function(){if(Array.isArray(arguments[0]))return z.apply(this,arguments);for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=this,o=e.pop();return e.unshift(r),new qn(function(t){for(var n=e.length,i=g(n,G),s=g(n,W),u=new Array(n),a=0;n>a;a++)!function(n){var a=e[n],c=new fe;ut(a)&&(a=Xe(a)),c.setDisposable(a.subscribe(function(e){if(i[n].push(e),i.every(function(t){return t.length>0})){var u=i.map(function(t){return t.shift()}),a=x(o).apply(r,u);if(a===ne)return t.onError(a.e);t.onNext(a)}else s.filter(function(t,e){return e!==n}).every(nt)&&t.onCompleted()},function(e){t.onError(e)},function(){s[n]=!0,s.every(nt)&&t.onCompleted()})),u[n]=c}(a);return new ie(u)},r)},We.zip=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=e.shift();return r.zip.apply(r,e)},We.zipArray=function(){var t;if(Array.isArray(arguments[0]))t=arguments[0];else{var e=arguments.length;t=new Array(e);for(var n=0;e>n;n++)t[n]=arguments[n]}return new qn(function(e){for(var n=t.length,r=g(n,J),o=g(n,W),i=new Array(n),s=0;n>s;s++)!function(n){i[n]=new fe,i[n].setDisposable(t[n].subscribe(function(t){if(r[n].push(t),r.every(function(t){return t.length>0})){var i=r.map(function(t){return t.shift()});e.onNext(i)}else if(o.filter(function(t,e){return e!==n}).every(nt))return e.onCompleted()},function(t){e.onError(t)},function(){o[n]=!0,o.every(nt)&&e.onCompleted()}))}(s);return new ie(i)})},qe.asObservable=function(){var t=this;return new qn(function(e){return t.subscribe(e)},t)},qe.bufferWithCount=function(t,e){return"number"!=typeof e&&(e=t),this.windowWithCount(t,e).selectMany(function(t){return t.toArray()}).where(function(t){return t.length>0})},qe.dematerialize=function(){var t=this;return new qn(function(e){return t.subscribe(function(t){return t.accept(e)},function(t){e.onError(t)},function(){e.onCompleted()})},this)},qe.distinctUntilChanged=function(t,e){var n=this;return e||(e=ot),new qn(function(r){var o,i=!1;return n.subscribe(function(n){var s=n;if(t&&(s=x(t)(n),s===ne))return r.onError(s.e);if(i){var u=x(e)(o,s);if(u===ne)return r.onError(u.e)}i&&u||(i=!0,o=s,r.onNext(n))},function(t){r.onError(t)},function(){r.onCompleted()})},this)};var Nn=function(t){function e(e,n,r,o){this.source=e,this.t=!n||at(n)?De(n||et,r||et,o||et):n,t.call(this)}function n(t,e){this.o=t,this.t=e,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t,this.t))},n.prototype.onNext=function(t){if(!this.isStopped){var e=x(this.t.onNext).call(this.t,t);e===ne&&this.o.onError(e.e),this.o.onNext(t)}},n.prototype.onError=function(t){if(!this.isStopped){this.isStopped=!0;var e=x(this.t.onError).call(this.t,t);if(e===ne)return this.o.onError(e.e);this.o.onError(t)}},n.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=!0;var t=x(this.t.onCompleted).call(this.t);if(t===ne)return this.o.onError(t.e);this.o.onCompleted()}},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe["do"]=qe.tap=qe.doAction=function(t,e,n){return new Nn(this,t,e,n)},qe.doOnNext=qe.tapOnNext=function(t,e){return this.tap("undefined"!=typeof e?function(n){t.call(e,n)}:t)},qe.doOnError=qe.tapOnError=function(t,e){return this.tap(et,"undefined"!=typeof e?function(n){t.call(e,n)}:t)},qe.doOnCompleted=qe.tapOnCompleted=function(t,e){return this.tap(et,null,"undefined"!=typeof e?function(){t.call(e)}:t)},qe["finally"]=qe.ensure=function(t){var e=this;return new qn(function(n){var r;try{r=e.subscribe(n)}catch(o){throw t(),o}return ae(function(){try{r.dispose()}catch(e){throw e}finally{t()}})},this)},qe.finallyAction=function(t){return this.ensure(t)};var kn=function(t){function e(e){this.source=e,t.call(this)}function n(t){this.o=t,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t))},n.prototype.onNext=et,n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.observer.onError(t),!0)},e}(ze);qe.ignoreElements=function(){return new kn(this)},qe.materialize=function(){var t=this;return new qn(function(e){return t.subscribe(function(t){e.onNext(ke(t))},function(t){e.onNext(Oe(t)),e.onCompleted()},function(){e.onNext(Pe()),e.onCompleted()})},t)},qe.repeat=function(t){return Be(this,t).concat()},qe.retry=function(t){return Be(this,t).catchError()},qe.retryWhen=function(t){return Be(this).catchErrorWhen(t)};var On=function(t){function e(e,n,r,o){this.source=e,this.accumulator=n,this.hasSeed=r,this.seed=o,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new I(t,this))},e}(ze);I.prototype.onNext=function(t){if(!this.isStopped){!this.hasValue&&(this.hasValue=!0);try{this.hasAccumulation?this.accumulation=this.accumulator(this.accumulation,t):(this.accumulation=this.hasSeed?this.accumulator(this.seed,t):t,this.hasAccumulation=!0)}catch(e){return this.observer.onError(e)}this.observer.onNext(this.accumulation)}},I.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.observer.onError(t))},I.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,!this.hasValue&&this.hasSeed&&this.observer.onNext(this.seed),this.observer.onCompleted())},I.prototype.dispose=function(){this.isStopped=!0},I.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.observer.onError(t),!0)},qe.scan=function(){var t,e,n=!1;return 2===arguments.length?(n=!0,t=arguments[0],e=arguments[1]):e=arguments[0],new On(this,e,n,t)},qe.skipLast=function(t){if(0>t)throw new yt;var e=this;return new qn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&n.onNext(r.shift())},function(t){n.onError(t)},function(){n.onCompleted()})},e)},qe.startWith=function(){var t,e=0;arguments.length&&me(arguments[0])?(t=arguments[0],e=1):t=xe;for(var n=[],r=e,o=arguments.length;o>r;r++)n.push(arguments[r]);return Ue([on(n,t),this]).concat()},qe.takeLast=function(t){if(0>t)throw new yt;var e=this;return new qn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},function(t){n.onError(t)},function(){for(;r.length>0;)n.onNext(r.shift());n.onCompleted()})},e)},qe.takeLastBuffer=function(t){var e=this;return new qn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},function(t){n.onError(t)},function(){n.onNext(r),n.onCompleted()})},e)},qe.windowWithCount=function(t,e){var n=this;if(+t||(t=0),Math.abs(t)===1/0&&(t=0),0>=t)throw new yt;if(null==e&&(e=t),+e||(e=0),Math.abs(e)===1/0&&(e=0),0>=e)throw new yt;return new qn(function(r){function o(){var t=new Tn;a.push(t),r.onNext(ee(t,s))}var i=new fe,s=new de(i),u=0,a=[];return o(),i.setDisposable(n.subscribe(function(n){for(var r=0,i=a.length;i>r;r++)a[r].onNext(n);var s=u-t+1;s>=0&&s%e===0&&a.shift().onCompleted(),++u%e===0&&o()},function(t){for(;a.length>0;)a.shift().onError(t);r.onError(t)},function(){for(;a.length>0;)a.shift().onCompleted();r.onCompleted()})),s},n)},qe.selectConcat=qe.concatMap=function(t,e,n){return at(t)&&at(e)?this.concatMap(function(n,r){var o=t(n,r);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o.map(function(t,o){return e(n,t,r,o)})}):at(t)?L(this,t,n):L(this,function(){return t})},qe.concatMapObserver=qe.selectConcatObserver=function(t,e,n,r){var o=this,i=At(t,r,2),s=At(e,r,1),u=At(n,r,0);return new qn(function(t){var e=0;return o.subscribe(function(n){var r;try{r=i(n,e++)}catch(o){return void t.onError(o)}ut(r)&&(r=Xe(r)),t.onNext(r)},function(e){var n;try{n=s(e)}catch(r){return void t.onError(r)}ut(n)&&(n=Xe(n)),t.onNext(n),t.onCompleted()},function(){var e;try{e=u()}catch(n){return void t.onError(n)}ut(e)&&(e=Xe(e)),t.onNext(e),t.onCompleted()})},this).concatAll()},qe.defaultIfEmpty=function(t){var e=this;return t===i&&(t=null),new qn(function(n){var r=!1;return e.subscribe(function(t){r=!0,n.onNext(t)},function(t){n.onError(t)},function(){!r&&n.onNext(t),n.onCompleted()})},e)},F.prototype.push=function(t){var e=-1===B(this.set,t,this.comparer);return e&&this.set.push(t),e},qe.distinct=function(t,e){var n=this;return e||(e=ot),new qn(function(r){var o=new F(e);return n.subscribe(function(e){var n=e;if(t)try{n=t(e)}catch(i){return void r.onError(i)}o.push(n)&&r.onNext(e)},function(t){r.onError(t)},function(){r.onCompleted()})},this)};var Pn=function(t){function e(e,n,r){this.source=e,this.selector=At(n,r,3),t.call(this)}function n(t,e){return function(n,r,o){return t.call(this,e.selector(n,r,o),r,o)}}function r(t,e,n){this.o=t,this.selector=e,this.source=n,this.i=0,this.isStopped=!1}return Zt(e,t),e.prototype.internalMap=function(t,r){return new e(this.source,n(t,this),r)},e.prototype.subscribeCore=function(t){return this.source.subscribe(new r(t,this.selector,this))},r.prototype.onNext=function(t){if(!this.isStopped){var e=x(this.selector)(t,this.i++,this.source);return e===ne?this.o.onError(e.e):void this.o.onNext(e)}},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},r.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.map=qe.select=function(t,e){var n="function"==typeof t?t:function(){return t};return this instanceof Pn?this.internalMap(n,e):new Pn(this,n,e)},qe.pluck=function(){var t=arguments,e=arguments.length;if(0===e)throw new Error("List of properties cannot be empty.");return this.map(function(n){for(var r=n,o=0;e>o;o++){var s=r[t[o]];if("undefined"==typeof s)return i;r=s}return r})},qe.flatMapObserver=qe.selectManyObserver=function(t,e,n,r){var o=this;return new qn(function(i){var s=0;return o.subscribe(function(e){var n;try{n=t.call(r,e,s++)}catch(o){return void i.onError(o)}ut(n)&&(n=Xe(n)),i.onNext(n)},function(t){var n;try{n=e.call(r,t)}catch(o){return void i.onError(o)}ut(n)&&(n=Xe(n)),i.onNext(n),i.onCompleted()},function(){var t;try{t=n.call(r)}catch(e){return void i.onError(e)}ut(t)&&(t=Xe(t)),i.onNext(t),i.onCompleted()})},o).mergeAll()},qe.selectMany=qe.flatMap=function(t,e,n){return at(t)&&at(e)?this.flatMap(function(n,r){var o=t(n,r);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o.map(function(t,o){return e(n,t,r,o)})},n):at(t)?U(this,t,n):U(this,function(){return t})},qe.selectSwitch=qe.flatMapLatest=qe.switchMap=function(t,e){return this.select(t,e).switchLatest()};var jn=function(t){function e(e,n){this.source=e,this.skipCount=n,t.call(this)}function n(t,e){this.c=e,this.r=e,this.o=t,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t,this.skipCount))},n.prototype.onNext=function(t){this.isStopped||(this.r<=0?this.o.onNext(t):this.r--)},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.skip=function(t){if(0>t)throw new yt;return new jn(this,t)},qe.skipWhile=function(t,e){var n=this,r=At(t,e,3);return new qn(function(t){var e=0,o=!1;return n.subscribe(function(i){if(!o)try{o=!r(i,e++,n)}catch(s){return void t.onError(s)}o&&t.onNext(i)},function(e){t.onError(e)},function(){t.onCompleted()})},n)},qe.take=function(t,e){if(0>t)throw new yt;if(0===t)return Ye(e);var n=this;return new qn(function(e){var r=t;return n.subscribe(function(t){r-- >0&&(e.onNext(t),0>=r&&e.onCompleted())},function(t){e.onError(t)},function(){e.onCompleted()})},n)},qe.takeWhile=function(t,e){var n=this,r=At(t,e,3);return new qn(function(t){var e=0,o=!0;return n.subscribe(function(i){if(o){try{o=r(i,e++,n)}catch(s){return void t.onError(s)}o?t.onNext(i):t.onCompleted()}},function(e){t.onError(e)},function(){t.onCompleted()})},n)};var Dn=function(t){function e(e,n,r){this.source=e,this.predicate=At(n,r,3),t.call(this)}function n(t,e){return function(n,r,o){return e.predicate(n,r,o)&&t.call(this,n,r,o)}}function r(t,e,n){this.o=t,this.predicate=e,this.source=n,this.i=0,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new r(t,this.predicate,this))},e.prototype.internalFilter=function(t,r){return new e(this.source,n(t,this),r)},r.prototype.onNext=function(t){if(!this.isStopped){var e=x(this.predicate)(t,this.i++,this.source);return e===ne?this.o.onError(e.e):void(e&&this.o.onNext(t))}},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},r.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.filter=qe.where=function(t,e){return this instanceof Dn?this.internalFilter(t,e):new Dn(this,t,e)},qe.transduce=function(t){function e(t){return{"@@transducer/init":function(){return t},"@@transducer/step":function(t,e){return t.onNext(e)},"@@transducer/result":function(t){return t.onCompleted()}}}var n=this;return new qn(function(r){var o=t(e(r));return n.subscribe(function(t){try{o["@@transducer/step"](r,t)}catch(e){r.onError(e)}},function(t){r.onError(t)},function(){o["@@transducer/result"](r)})},n)};var qn=tt.AnonymousObservable=function(t){function e(t){return t&&at(t.dispose)?t:at(t)?ae(t):ce}function n(t,n){var r=n[0],o=n[1],i=x(o)(r);return i!==ne||r.fail(ne.e)?void r.setDisposable(e(i)):_(ne.e)}function r(e,r){function o(t){var r=new Rn(t),o=[r,e];return _e.scheduleRequired()?_e.scheduleWithState(o,n):n(null,o),r}this.source=r,t.call(this,o)}return Zt(r,t),r}(We),Rn=function(t){function e(e){t.call(this),this.observer=e,this.m=new fe}Zt(e,t);var n=e.prototype;return n.next=function(t){var e=x(this.observer.onNext).call(this.observer,t);e===ne&&(this.dispose(),_(e.e))},n.error=function(t){var e=x(this.observer.onError).call(this.observer,t);this.dispose(),e===ne&&_(e.e)},n.completed=function(){var t=x(this.observer.onCompleted).call(this.observer);this.dispose(),t===ne&&_(t.e)},n.setDisposable=function(t){this.m.setDisposable(t)},n.getDisposable=function(){return this.m.getDisposable()},n.dispose=function(){t.prototype.dispose.call(this),this.m.dispose()},e}(Re),Mn=function(t,e){this.subject=t,this.observer=e};Mn.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var Tn=tt.Subject=function(t){function e(t){return he(this),this.isStopped?this.hasError?(t.onError(this.error),ce):(t.onCompleted(),ce):(this.observers.push(t),new Mn(this,t))}function n(){t.call(this,e),this.isDisposed=!1,this.isStopped=!1,this.observers=[],this.hasError=!1}return Zt(n,t),te(n.prototype,je.prototype,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(he(this),!this.isStopped){this.isStopped=!0;for(var t=0,e=u(this.observers),n=e.length;n>t;t++)e[t].onCompleted();this.observers.length=0}},onError:function(t){if(he(this),!this.isStopped){this.isStopped=!0,this.error=t,this.hasError=!0;for(var e=0,n=u(this.observers),r=n.length;r>e;e++)n[e].onError(t);this.observers.length=0}},onNext:function(t){if(he(this),!this.isStopped)for(var e=0,n=u(this.observers),r=n.length;r>e;e++)n[e].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),n.create=function(t,e){return new Vn(t,e)},n}(We),Vn=(tt.AsyncSubject=function(t){function e(t){return he(this),this.isStopped?(this.hasError?t.onError(this.error):this.hasValue?(t.onNext(this.value),t.onCompleted()):t.onCompleted(),ce):(this.observers.push(t),new Mn(this,t))}function n(){t.call(this,e),this.isDisposed=!1,this.isStopped=!1,this.hasValue=!1,this.observers=[],this.hasError=!1}return Zt(n,t),te(n.prototype,je,{hasObservers:function(){return he(this),this.observers.length>0},onCompleted:function(){var t,e;if(he(this),!this.isStopped){this.isStopped=!0;var n=u(this.observers),e=n.length;if(this.hasValue)for(t=0;e>t;t++){var r=n[t];r.onNext(this.value),r.onCompleted()}else for(t=0;e>t;t++)n[t].onCompleted();this.observers.length=0}},onError:function(t){if(he(this),!this.isStopped){this.isStopped=!0,this.hasError=!0,this.error=t;for(var e=0,n=u(this.observers),r=n.length;r>e;e++)n[e].onError(t);this.observers.length=0}},onNext:function(t){he(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),n}(We),tt.AnonymousSubject=function(t){function e(t){return this.observable.subscribe(t)}function n(n,r){this.observer=n,this.observable=r,t.call(this,e)}return Zt(n,t),te(n.prototype,je.prototype,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),n}(We));"function"==typeof t&&"object"==typeof t.amd&&t.amd?(X.Rx=tt,t(function(){return tt})):Q&&K?Y?(K.exports=tt).Rx=tt:Q.Rx=tt:X.Rx=tt;var $n=f()}).call(this)}).call(this,e(150),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{150:150}]},{},[1])(1)});
3462 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3464 },{}],16:[function(require,module,exports){
3466 var topLevel = typeof global !== 'undefined' ? global :
3467 typeof window !== 'undefined' ? window : {}
3468 var minDoc = require('min-document');
3472 if (typeof document !== 'undefined') {
3475 doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
3478 doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
3482 module.exports = doccy;
3484 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3486 },{"min-document":4}],17:[function(require,module,exports){
3487 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
3489 var eLen = nBytes * 8 - mLen - 1
3490 var eMax = (1 << eLen) - 1
3491 var eBias = eMax >> 1
3493 var i = isLE ? (nBytes - 1) : 0
3494 var d = isLE ? -1 : 1
3495 var s = buffer[offset + i]
3499 e = s & ((1 << (-nBits)) - 1)
3502 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3504 m = e & ((1 << (-nBits)) - 1)
3507 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3511 } else if (e === eMax) {
3512 return m ? NaN : ((s ? -1 : 1) * Infinity)
3514 m = m + Math.pow(2, mLen)
3517 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
3520 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
3522 var eLen = nBytes * 8 - mLen - 1
3523 var eMax = (1 << eLen) - 1
3524 var eBias = eMax >> 1
3525 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
3526 var i = isLE ? 0 : (nBytes - 1)
3527 var d = isLE ? 1 : -1
3528 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
3530 value = Math.abs(value)
3532 if (isNaN(value) || value === Infinity) {
3533 m = isNaN(value) ? 1 : 0
3536 e = Math.floor(Math.log(value) / Math.LN2)
3537 if (value * (c = Math.pow(2, -e)) < 1) {
3541 if (e + eBias >= 1) {
3544 value += rt * Math.pow(2, 1 - eBias)
3546 if (value * c >= 2) {
3551 if (e + eBias >= eMax) {
3554 } else if (e + eBias >= 1) {
3555 m = (value * c - 1) * Math.pow(2, mLen)
3558 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
3563 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
3567 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
3569 buffer[offset + i - d] |= s * 128
3572 },{}],18:[function(require,module,exports){
3576 /*global window, global*/
3578 var root = typeof window !== 'undefined' ?
3579 window : typeof global !== 'undefined' ?
3582 module.exports = Individual;
3584 function Individual(key, value) {
3594 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3596 },{}],19:[function(require,module,exports){
3599 var Individual = require('./index.js');
3601 module.exports = OneVersion;
3603 function OneVersion(moduleName, version, defaultValue) {
3604 var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName;
3605 var enforceKey = key + '_ENFORCE_SINGLETON';
3607 var versionValue = Individual(enforceKey, version);
3609 if (versionValue !== version) {
3610 throw new Error('Can only have one copy of ' +
3611 moduleName + '.\n' +
3612 'You already have version ' + versionValue +
3614 'This means you cannot install version ' + version);
3617 return Individual(key, defaultValue);
3620 },{"./index.js":18}],20:[function(require,module,exports){
3623 module.exports = function isObject(x) {
3624 return typeof x === "object" && x !== null;
3627 },{}],21:[function(require,module,exports){
3628 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3629 /* Geohash encoding/decoding and associated functions (c) Chris Veness 2014-2016 / MIT Licence */
3630 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3636 * Geohash encode, decode, bounds, neighbours.
3642 /* (Geohash-specific) Base32 map */
3643 Geohash.base32 = '0123456789bcdefghjkmnpqrstuvwxyz';
3646 * Encodes latitude/longitude to geohash, either to specified precision or to automatically
3647 * evaluated precision.
3649 * @param {number} lat - Latitude in degrees.
3650 * @param {number} lon - Longitude in degrees.
3651 * @param {number} [precision] - Number of characters in resulting geohash.
3652 * @returns {string} Geohash of supplied latitude/longitude.
3653 * @throws Invalid geohash.
3656 * var geohash = Geohash.encode(52.205, 0.119, 7); // geohash: 'u120fxw'
3658 Geohash.encode = function(lat, lon, precision) {
3660 if (typeof precision == 'undefined') {
3661 // refine geohash until it matches precision of supplied lat/lon
3662 for (var p=1; p<=12; p++) {
3663 var hash = Geohash.encode(lat, lon, p);
3664 var posn = Geohash.decode(hash);
3665 if (posn.lat==lat && posn.lon==lon) return hash;
3667 precision = 12; // set to maximum
3672 precision = Number(precision);
3674 if (isNaN(lat) || isNaN(lon) || isNaN(precision)) throw new Error('Invalid geohash');
3676 var idx = 0; // index into base32 map
3677 var bit = 0; // each char holds 5 bits
3681 var latMin = -90, latMax = 90;
3682 var lonMin = -180, lonMax = 180;
3684 while (geohash.length < precision) {
3686 // bisect E-W longitude
3687 var lonMid = (lonMin + lonMax) / 2;
3688 if (lon >= lonMid) {
3696 // bisect N-S latitude
3697 var latMid = (latMin + latMax) / 2;
3698 if (lat >= latMid) {
3709 // 5 bits gives us a character: append it and start over
3710 geohash += Geohash.base32.charAt(idx);
3721 * Decode geohash to latitude/longitude (location is approximate centre of geohash cell,
3722 * to reasonable precision).
3724 * @param {string} geohash - Geohash string to be converted to latitude/longitude.
3725 * @returns {{lat:number, lon:number}} (Center of) geohashed location.
3726 * @throws Invalid geohash.
3729 * var latlon = Geohash.decode('u120fxw'); // latlon: { lat: 52.205, lon: 0.1188 }
3731 Geohash.decode = function(geohash) {
3733 var bounds = Geohash.bounds(geohash); // <-- the hard work
3734 // now just determine the centre of the cell...
3736 var latMin = bounds.sw.lat, lonMin = bounds.sw.lon;
3737 var latMax = bounds.ne.lat, lonMax = bounds.ne.lon;
3740 var lat = (latMin + latMax)/2;
3741 var lon = (lonMin + lonMax)/2;
3743 // round to close to centre without excessive precision: ⌊2-log10(Δ°)⌋ decimal places
3744 lat = lat.toFixed(Math.floor(2-Math.log(latMax-latMin)/Math.LN10));
3745 lon = lon.toFixed(Math.floor(2-Math.log(lonMax-lonMin)/Math.LN10));
3747 return { lat: Number(lat), lon: Number(lon) };
3752 * Returns SW/NE latitude/longitude bounds of specified geohash.
3754 * @param {string} geohash - Cell that bounds are required of.
3755 * @returns {{sw: {lat: number, lon: number}, ne: {lat: number, lon: number}}}
3756 * @throws Invalid geohash.
3758 Geohash.bounds = function(geohash) {
3759 if (geohash.length === 0) throw new Error('Invalid geohash');
3761 geohash = geohash.toLowerCase();
3764 var latMin = -90, latMax = 90;
3765 var lonMin = -180, lonMax = 180;
3767 for (var i=0; i<geohash.length; i++) {
3768 var chr = geohash.charAt(i);
3769 var idx = Geohash.base32.indexOf(chr);
3770 if (idx == -1) throw new Error('Invalid geohash');
3772 for (var n=4; n>=0; n--) {
3773 var bitN = idx >> n & 1;
3776 var lonMid = (lonMin+lonMax) / 2;
3784 var latMid = (latMin+latMax) / 2;
3796 sw: { lat: latMin, lon: lonMin },
3797 ne: { lat: latMax, lon: lonMax },
3805 * Determines adjacent cell in given direction.
3807 * @param geohash - Cell to which adjacent cell is required.
3808 * @param direction - Direction from geohash (N/S/E/W).
3809 * @returns {string} Geocode of adjacent cell.
3810 * @throws Invalid geohash.
3812 Geohash.adjacent = function(geohash, direction) {
3813 // based on github.com/davetroy/geohash-js
3815 geohash = geohash.toLowerCase();
3816 direction = direction.toLowerCase();
3818 if (geohash.length === 0) throw new Error('Invalid geohash');
3819 if ('nsew'.indexOf(direction) == -1) throw new Error('Invalid direction');
3822 n: [ 'p0r21436x8zb9dcf5h7kjnmqesgutwvy', 'bc01fg45238967deuvhjyznpkmstqrwx' ],
3823 s: [ '14365h7k9dcfesgujnmqp0r2twvyx8zb', '238967debc01fg45kmstqrwxuvhjyznp' ],
3824 e: [ 'bc01fg45238967deuvhjyznpkmstqrwx', 'p0r21436x8zb9dcf5h7kjnmqesgutwvy' ],
3825 w: [ '238967debc01fg45kmstqrwxuvhjyznp', '14365h7k9dcfesgujnmqp0r2twvyx8zb' ],
3828 n: [ 'prxz', 'bcfguvyz' ],
3829 s: [ '028b', '0145hjnp' ],
3830 e: [ 'bcfguvyz', 'prxz' ],
3831 w: [ '0145hjnp', '028b' ],
3834 var lastCh = geohash.slice(-1); // last character of hash
3835 var parent = geohash.slice(0, -1); // hash without last character
3837 var type = geohash.length % 2;
3839 // check for edge-cases which don't share common prefix
3840 if (border[direction][type].indexOf(lastCh) != -1 && parent !== '') {
3841 parent = Geohash.adjacent(parent, direction);
3844 // append letter for direction to parent
3845 return parent + Geohash.base32.charAt(neighbour[direction][type].indexOf(lastCh));
3850 * Returns all 8 adjacent cells to specified geohash.
3852 * @param {string} geohash - Geohash neighbours are required of.
3853 * @returns {{n,ne,e,se,s,sw,w,nw: string}}
3854 * @throws Invalid geohash.
3856 Geohash.neighbours = function(geohash) {
3858 'n': Geohash.adjacent(geohash, 'n'),
3859 'ne': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'e'),
3860 'e': Geohash.adjacent(geohash, 'e'),
3861 'se': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'e'),
3862 's': Geohash.adjacent(geohash, 's'),
3863 'sw': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'w'),
3864 'w': Geohash.adjacent(geohash, 'w'),
3865 'nw': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'w'),
3870 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3871 if (typeof module != 'undefined' && module.exports) module.exports = Geohash; // CommonJS, node.js
3873 },{}],22:[function(require,module,exports){
3874 (function (process){
3875 // Copyright Joyent, Inc. and other Node contributors.
3877 // Permission is hereby granted, free of charge, to any person obtaining a
3878 // copy of this software and associated documentation files (the
3879 // "Software"), to deal in the Software without restriction, including
3880 // without limitation the rights to use, copy, modify, merge, publish,
3881 // distribute, sublicense, and/or sell copies of the Software, and to permit
3882 // persons to whom the Software is furnished to do so, subject to the
3883 // following conditions:
3885 // The above copyright notice and this permission notice shall be included
3886 // in all copies or substantial portions of the Software.
3888 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3889 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3890 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3891 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3892 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3893 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3894 // USE OR OTHER DEALINGS IN THE SOFTWARE.
3896 // resolves . and .. elements in a path array with directory names there
3897 // must be no slashes, empty elements, or device names (c:\) in the array
3898 // (so also no leading and trailing slashes - it does not distinguish
3899 // relative and absolute paths)
3900 function normalizeArray(parts, allowAboveRoot) {
3901 // if the path tries to go above the root, `up` ends up > 0
3903 for (var i = parts.length - 1; i >= 0; i--) {
3904 var last = parts[i];
3907 } else if (last === '..') {
3916 // if the path is allowed to go above the root, restore leading ..s
3917 if (allowAboveRoot) {
3919 parts.unshift('..');
3926 // Split a filename into [root, dir, basename, ext], unix version
3927 // 'root' is just a slash, or nothing.
3929 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
3930 var splitPath = function(filename) {
3931 return splitPathRe.exec(filename).slice(1);
3934 // path.resolve([from ...], to)
3936 exports.resolve = function() {
3937 var resolvedPath = '',
3938 resolvedAbsolute = false;
3940 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
3941 var path = (i >= 0) ? arguments[i] : process.cwd();
3943 // Skip empty and invalid entries
3944 if (typeof path !== 'string') {
3945 throw new TypeError('Arguments to path.resolve must be strings');
3950 resolvedPath = path + '/' + resolvedPath;
3951 resolvedAbsolute = path.charAt(0) === '/';
3954 // At this point the path should be resolved to a full absolute path, but
3955 // handle relative paths to be safe (might happen when process.cwd() fails)
3957 // Normalize the path
3958 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
3960 }), !resolvedAbsolute).join('/');
3962 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
3965 // path.normalize(path)
3967 exports.normalize = function(path) {
3968 var isAbsolute = exports.isAbsolute(path),
3969 trailingSlash = substr(path, -1) === '/';
3971 // Normalize the path
3972 path = normalizeArray(filter(path.split('/'), function(p) {
3974 }), !isAbsolute).join('/');
3976 if (!path && !isAbsolute) {
3979 if (path && trailingSlash) {
3983 return (isAbsolute ? '/' : '') + path;
3987 exports.isAbsolute = function(path) {
3988 return path.charAt(0) === '/';
3992 exports.join = function() {
3993 var paths = Array.prototype.slice.call(arguments, 0);
3994 return exports.normalize(filter(paths, function(p, index) {
3995 if (typeof p !== 'string') {
3996 throw new TypeError('Arguments to path.join must be strings');
4003 // path.relative(from, to)
4005 exports.relative = function(from, to) {
4006 from = exports.resolve(from).substr(1);
4007 to = exports.resolve(to).substr(1);
4009 function trim(arr) {
4011 for (; start < arr.length; start++) {
4012 if (arr[start] !== '') break;
4015 var end = arr.length - 1;
4016 for (; end >= 0; end--) {
4017 if (arr[end] !== '') break;
4020 if (start > end) return [];
4021 return arr.slice(start, end - start + 1);
4024 var fromParts = trim(from.split('/'));
4025 var toParts = trim(to.split('/'));
4027 var length = Math.min(fromParts.length, toParts.length);
4028 var samePartsLength = length;
4029 for (var i = 0; i < length; i++) {
4030 if (fromParts[i] !== toParts[i]) {
4031 samePartsLength = i;
4036 var outputParts = [];
4037 for (var i = samePartsLength; i < fromParts.length; i++) {
4038 outputParts.push('..');
4041 outputParts = outputParts.concat(toParts.slice(samePartsLength));
4043 return outputParts.join('/');
4047 exports.delimiter = ':';
4049 exports.dirname = function(path) {
4050 var result = splitPath(path),
4054 if (!root && !dir) {
4055 // No dirname whatsoever
4060 // It has a dirname, strip trailing slash
4061 dir = dir.substr(0, dir.length - 1);
4068 exports.basename = function(path, ext) {
4069 var f = splitPath(path)[2];
4070 // TODO: make this comparison case-insensitive on windows?
4071 if (ext && f.substr(-1 * ext.length) === ext) {
4072 f = f.substr(0, f.length - ext.length);
4078 exports.extname = function(path) {
4079 return splitPath(path)[3];
4082 function filter (xs, f) {
4083 if (xs.filter) return xs.filter(f);
4085 for (var i = 0; i < xs.length; i++) {
4086 if (f(xs[i], i, xs)) res.push(xs[i]);
4091 // String.prototype.substr - negative index don't work in IE8
4092 var substr = 'ab'.substr(-1) === 'b'
4093 ? function (str, start, len) { return str.substr(start, len) }
4094 : function (str, start, len) {
4095 if (start < 0) start = str.length + start;
4096 return str.substr(start, len);
4100 }).call(this,require('_process'))
4102 },{"_process":6}],23:[function(require,module,exports){
4105 module.exports = Pbf;
4107 var ieee754 = require('ieee754');
4110 this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);
4113 this.length = this.buf.length;
4116 Pbf.Varint = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum
4117 Pbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64
4118 Pbf.Bytes = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields
4119 Pbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32
4121 var SHIFT_LEFT_32 = (1 << 16) * (1 << 16),
4122 SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
4126 destroy: function() {
4130 // === READING =================================================================
4132 readFields: function(readField, result, end) {
4133 end = end || this.length;
4135 while (this.pos < end) {
4136 var val = this.readVarint(),
4138 startPos = this.pos;
4140 this.type = val & 0x7;
4141 readField(tag, result, this);
4143 if (this.pos === startPos) this.skip(val);
4148 readMessage: function(readField, result) {
4149 return this.readFields(readField, result, this.readVarint() + this.pos);
4152 readFixed32: function() {
4153 var val = readUInt32(this.buf, this.pos);
4158 readSFixed32: function() {
4159 var val = readInt32(this.buf, this.pos);
4164 // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)
4166 readFixed64: function() {
4167 var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4172 readSFixed64: function() {
4173 var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4178 readFloat: function() {
4179 var val = ieee754.read(this.buf, this.pos, true, 23, 4);
4184 readDouble: function() {
4185 var val = ieee754.read(this.buf, this.pos, true, 52, 8);
4190 readVarint: function(isSigned) {
4194 b = buf[this.pos++]; val = b & 0x7f; if (b < 0x80) return val;
4195 b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val;
4196 b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;
4197 b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;
4198 b = buf[this.pos]; val |= (b & 0x0f) << 28;
4200 return readVarintRemainder(val, isSigned, this);
4203 readVarint64: function() { // for compatibility with v2.0.1
4204 return this.readVarint(true);
4207 readSVarint: function() {
4208 var num = this.readVarint();
4209 return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding
4212 readBoolean: function() {
4213 return Boolean(this.readVarint());
4216 readString: function() {
4217 var end = this.readVarint() + this.pos,
4218 str = readUtf8(this.buf, this.pos, end);
4223 readBytes: function() {
4224 var end = this.readVarint() + this.pos,
4225 buffer = this.buf.subarray(this.pos, end);
4230 // verbose for performance reasons; doesn't affect gzipped size
4232 readPackedVarint: function(arr, isSigned) {
4233 var end = readPackedEnd(this);
4235 while (this.pos < end) arr.push(this.readVarint(isSigned));
4238 readPackedSVarint: function(arr) {
4239 var end = readPackedEnd(this);
4241 while (this.pos < end) arr.push(this.readSVarint());
4244 readPackedBoolean: function(arr) {
4245 var end = readPackedEnd(this);
4247 while (this.pos < end) arr.push(this.readBoolean());
4250 readPackedFloat: function(arr) {
4251 var end = readPackedEnd(this);
4253 while (this.pos < end) arr.push(this.readFloat());
4256 readPackedDouble: function(arr) {
4257 var end = readPackedEnd(this);
4259 while (this.pos < end) arr.push(this.readDouble());
4262 readPackedFixed32: function(arr) {
4263 var end = readPackedEnd(this);
4265 while (this.pos < end) arr.push(this.readFixed32());
4268 readPackedSFixed32: function(arr) {
4269 var end = readPackedEnd(this);
4271 while (this.pos < end) arr.push(this.readSFixed32());
4274 readPackedFixed64: function(arr) {
4275 var end = readPackedEnd(this);
4277 while (this.pos < end) arr.push(this.readFixed64());
4280 readPackedSFixed64: function(arr) {
4281 var end = readPackedEnd(this);
4283 while (this.pos < end) arr.push(this.readSFixed64());
4287 skip: function(val) {
4288 var type = val & 0x7;
4289 if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}
4290 else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos;
4291 else if (type === Pbf.Fixed32) this.pos += 4;
4292 else if (type === Pbf.Fixed64) this.pos += 8;
4293 else throw new Error('Unimplemented type: ' + type);
4296 // === WRITING =================================================================
4298 writeTag: function(tag, type) {
4299 this.writeVarint((tag << 3) | type);
4302 realloc: function(min) {
4303 var length = this.length || 16;
4305 while (length < this.pos + min) length *= 2;
4307 if (length !== this.length) {
4308 var buf = new Uint8Array(length);
4311 this.length = length;
4315 finish: function() {
4316 this.length = this.pos;
4318 return this.buf.subarray(0, this.length);
4321 writeFixed32: function(val) {
4323 writeInt32(this.buf, val, this.pos);
4327 writeSFixed32: function(val) {
4329 writeInt32(this.buf, val, this.pos);
4333 writeFixed64: function(val) {
4335 writeInt32(this.buf, val & -1, this.pos);
4336 writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4340 writeSFixed64: function(val) {
4342 writeInt32(this.buf, val & -1, this.pos);
4343 writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4347 writeVarint: function(val) {
4350 if (val > 0xfffffff || val < 0) {
4351 writeBigVarint(val, this);
4357 this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4358 this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4359 this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4360 this.buf[this.pos++] = (val >>> 7) & 0x7f;
4363 writeSVarint: function(val) {
4364 this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
4367 writeBoolean: function(val) {
4368 this.writeVarint(Boolean(val));
4371 writeString: function(str) {
4373 this.realloc(str.length * 4);
4375 this.pos++; // reserve 1 byte for short string length
4377 var startPos = this.pos;
4378 // write the string directly to the buffer and see how much was written
4379 this.pos = writeUtf8(this.buf, str, this.pos);
4380 var len = this.pos - startPos;
4382 if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4384 // finally, write the message length in the reserved place and restore the position
4385 this.pos = startPos - 1;
4386 this.writeVarint(len);
4390 writeFloat: function(val) {
4392 ieee754.write(this.buf, val, this.pos, true, 23, 4);
4396 writeDouble: function(val) {
4398 ieee754.write(this.buf, val, this.pos, true, 52, 8);
4402 writeBytes: function(buffer) {
4403 var len = buffer.length;
4404 this.writeVarint(len);
4406 for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];
4409 writeRawMessage: function(fn, obj) {
4410 this.pos++; // reserve 1 byte for short message length
4412 // write the message directly to the buffer and see how much was written
4413 var startPos = this.pos;
4415 var len = this.pos - startPos;
4417 if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4419 // finally, write the message length in the reserved place and restore the position
4420 this.pos = startPos - 1;
4421 this.writeVarint(len);
4425 writeMessage: function(tag, fn, obj) {
4426 this.writeTag(tag, Pbf.Bytes);
4427 this.writeRawMessage(fn, obj);
4430 writePackedVarint: function(tag, arr) { this.writeMessage(tag, writePackedVarint, arr); },
4431 writePackedSVarint: function(tag, arr) { this.writeMessage(tag, writePackedSVarint, arr); },
4432 writePackedBoolean: function(tag, arr) { this.writeMessage(tag, writePackedBoolean, arr); },
4433 writePackedFloat: function(tag, arr) { this.writeMessage(tag, writePackedFloat, arr); },
4434 writePackedDouble: function(tag, arr) { this.writeMessage(tag, writePackedDouble, arr); },
4435 writePackedFixed32: function(tag, arr) { this.writeMessage(tag, writePackedFixed32, arr); },
4436 writePackedSFixed32: function(tag, arr) { this.writeMessage(tag, writePackedSFixed32, arr); },
4437 writePackedFixed64: function(tag, arr) { this.writeMessage(tag, writePackedFixed64, arr); },
4438 writePackedSFixed64: function(tag, arr) { this.writeMessage(tag, writePackedSFixed64, arr); },
4440 writeBytesField: function(tag, buffer) {
4441 this.writeTag(tag, Pbf.Bytes);
4442 this.writeBytes(buffer);
4444 writeFixed32Field: function(tag, val) {
4445 this.writeTag(tag, Pbf.Fixed32);
4446 this.writeFixed32(val);
4448 writeSFixed32Field: function(tag, val) {
4449 this.writeTag(tag, Pbf.Fixed32);
4450 this.writeSFixed32(val);
4452 writeFixed64Field: function(tag, val) {
4453 this.writeTag(tag, Pbf.Fixed64);
4454 this.writeFixed64(val);
4456 writeSFixed64Field: function(tag, val) {
4457 this.writeTag(tag, Pbf.Fixed64);
4458 this.writeSFixed64(val);
4460 writeVarintField: function(tag, val) {
4461 this.writeTag(tag, Pbf.Varint);
4462 this.writeVarint(val);
4464 writeSVarintField: function(tag, val) {
4465 this.writeTag(tag, Pbf.Varint);
4466 this.writeSVarint(val);
4468 writeStringField: function(tag, str) {
4469 this.writeTag(tag, Pbf.Bytes);
4470 this.writeString(str);
4472 writeFloatField: function(tag, val) {
4473 this.writeTag(tag, Pbf.Fixed32);
4474 this.writeFloat(val);
4476 writeDoubleField: function(tag, val) {
4477 this.writeTag(tag, Pbf.Fixed64);
4478 this.writeDouble(val);
4480 writeBooleanField: function(tag, val) {
4481 this.writeVarintField(tag, Boolean(val));
4485 function readVarintRemainder(l, s, p) {
4489 b = buf[p.pos++]; h = (b & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s);
4490 b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s);
4491 b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);
4492 b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);
4493 b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);
4494 b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);
4496 throw new Error('Expected varint not more than 10 bytes');
4499 function readPackedEnd(pbf) {
4500 return pbf.type === Pbf.Bytes ?
4501 pbf.readVarint() + pbf.pos : pbf.pos + 1;
4504 function toNum(low, high, isSigned) {
4506 return high * 0x100000000 + (low >>> 0);
4509 return ((high >>> 0) * 0x100000000) + (low >>> 0);
4512 function writeBigVarint(val, pbf) {
4516 low = (val % 0x100000000) | 0;
4517 high = (val / 0x100000000) | 0;
4519 low = ~(-val % 0x100000000);
4520 high = ~(-val / 0x100000000);
4522 if (low ^ 0xffffffff) {
4523 low = (low + 1) | 0;
4526 high = (high + 1) | 0;
4530 if (val >= 0x10000000000000000 || val < -0x10000000000000000) {
4531 throw new Error('Given varint doesn\'t fit into 10 bytes');
4536 writeBigVarintLow(low, high, pbf);
4537 writeBigVarintHigh(high, pbf);
4540 function writeBigVarintLow(low, high, pbf) {
4541 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4542 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4543 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4544 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4545 pbf.buf[pbf.pos] = low & 0x7f;
4548 function writeBigVarintHigh(high, pbf) {
4549 var lsb = (high & 0x07) << 4;
4551 pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return;
4552 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4553 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4554 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4555 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4556 pbf.buf[pbf.pos++] = high & 0x7f;
4559 function makeRoomForExtraLength(startPos, len, pbf) {
4562 len <= 0x1fffff ? 2 :
4563 len <= 0xfffffff ? 3 : Math.ceil(Math.log(len) / (Math.LN2 * 7));
4565 // if 1 byte isn't enough for encoding message length, shift the data to the right
4566 pbf.realloc(extraLen);
4567 for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];
4570 function writePackedVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]); }
4571 function writePackedSVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]); }
4572 function writePackedFloat(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]); }
4573 function writePackedDouble(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]); }
4574 function writePackedBoolean(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]); }
4575 function writePackedFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]); }
4576 function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); }
4577 function writePackedFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]); }
4578 function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); }
4580 // Buffer code below from https://github.com/feross/buffer, MIT-licensed
4582 function readUInt32(buf, pos) {
4583 return ((buf[pos]) |
4584 (buf[pos + 1] << 8) |
4585 (buf[pos + 2] << 16)) +
4586 (buf[pos + 3] * 0x1000000);
4589 function writeInt32(buf, val, pos) {
4591 buf[pos + 1] = (val >>> 8);
4592 buf[pos + 2] = (val >>> 16);
4593 buf[pos + 3] = (val >>> 24);
4596 function readInt32(buf, pos) {
4597 return ((buf[pos]) |
4598 (buf[pos + 1] << 8) |
4599 (buf[pos + 2] << 16)) +
4600 (buf[pos + 3] << 24);
4603 function readUtf8(buf, pos, end) {
4609 var c = null; // codepoint
4610 var bytesPerSequence =
4615 if (i + bytesPerSequence > end) break;
4619 if (bytesPerSequence === 1) {
4623 } else if (bytesPerSequence === 2) {
4625 if ((b1 & 0xC0) === 0x80) {
4626 c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);
4631 } else if (bytesPerSequence === 3) {
4634 if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {
4635 c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);
4636 if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {
4640 } else if (bytesPerSequence === 4) {
4644 if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
4645 c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);
4646 if (c <= 0xFFFF || c >= 0x110000) {
4654 bytesPerSequence = 1;
4656 } else if (c > 0xFFFF) {
4658 str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);
4659 c = 0xDC00 | c & 0x3FF;
4662 str += String.fromCharCode(c);
4663 i += bytesPerSequence;
4669 function writeUtf8(buf, str, pos) {
4670 for (var i = 0, c, lead; i < str.length; i++) {
4671 c = str.charCodeAt(i); // code point
4673 if (c > 0xD7FF && c < 0xE000) {
4682 c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;
4686 if (c > 0xDBFF || (i + 1 === str.length)) {
4706 buf[pos++] = c >> 0x6 | 0xC0;
4709 buf[pos++] = c >> 0xC | 0xE0;
4711 buf[pos++] = c >> 0x12 | 0xF0;
4712 buf[pos++] = c >> 0xC & 0x3F | 0x80;
4714 buf[pos++] = c >> 0x6 & 0x3F | 0x80;
4716 buf[pos++] = c & 0x3F | 0x80;
4722 },{"ieee754":17}],24:[function(require,module,exports){
4725 module.exports = partialSort;
4727 // Floyd-Rivest selection algorithm:
4728 // Rearrange items so that all items in the [left, k] range are smaller than all items in (k, right];
4729 // The k-th element will have the (k - left + 1)th smallest value in [left, right]
4731 function partialSort(arr, k, left, right, compare) {
4733 right = right || (arr.length - 1);
4734 compare = compare || defaultCompare;
4736 while (right > left) {
4737 if (right - left > 600) {
4738 var n = right - left + 1;
4739 var m = k - left + 1;
4740 var z = Math.log(n);
4741 var s = 0.5 * Math.exp(2 * z / 3);
4742 var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
4743 var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
4744 var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
4745 partialSort(arr, k, newLeft, newRight, compare);
4753 if (compare(arr[right], t) > 0) swap(arr, left, right);
4759 while (compare(arr[i], t) < 0) i++;
4760 while (compare(arr[j], t) > 0) j--;
4763 if (compare(arr[left], t) === 0) swap(arr, left, j);
4766 swap(arr, j, right);
4769 if (j <= k) left = j + 1;
4770 if (k <= j) right = j - 1;
4774 function swap(arr, i, j) {
4780 function defaultCompare(a, b) {
4781 return a < b ? -1 : a > b ? 1 : 0;
4784 },{}],25:[function(require,module,exports){
4787 module.exports = rbush;
4789 var quickselect = require('quickselect');
4791 function rbush(maxEntries, format) {
4792 if (!(this instanceof rbush)) return new rbush(maxEntries, format);
4794 // max entries in a node is 9 by default; min node fill is 40% for best performance
4795 this._maxEntries = Math.max(4, maxEntries || 9);
4796 this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
4799 this._initFormat(format);
4808 return this._all(this.data, []);
4811 search: function (bbox) {
4813 var node = this.data,
4815 toBBox = this.toBBox;
4817 if (!intersects(bbox, node)) return result;
4819 var nodesToSearch = [],
4820 i, len, child, childBBox;
4823 for (i = 0, len = node.children.length; i < len; i++) {
4825 child = node.children[i];
4826 childBBox = node.leaf ? toBBox(child) : child;
4828 if (intersects(bbox, childBBox)) {
4829 if (node.leaf) result.push(child);
4830 else if (contains(bbox, childBBox)) this._all(child, result);
4831 else nodesToSearch.push(child);
4834 node = nodesToSearch.pop();
4840 collides: function (bbox) {
4842 var node = this.data,
4843 toBBox = this.toBBox;
4845 if (!intersects(bbox, node)) return false;
4847 var nodesToSearch = [],
4848 i, len, child, childBBox;
4851 for (i = 0, len = node.children.length; i < len; i++) {
4853 child = node.children[i];
4854 childBBox = node.leaf ? toBBox(child) : child;
4856 if (intersects(bbox, childBBox)) {
4857 if (node.leaf || contains(bbox, childBBox)) return true;
4858 nodesToSearch.push(child);
4861 node = nodesToSearch.pop();
4867 load: function (data) {
4868 if (!(data && data.length)) return this;
4870 if (data.length < this._minEntries) {
4871 for (var i = 0, len = data.length; i < len; i++) {
4872 this.insert(data[i]);
4877 // recursively build the tree with the given data from stratch using OMT algorithm
4878 var node = this._build(data.slice(), 0, data.length - 1, 0);
4880 if (!this.data.children.length) {
4881 // save as is if tree is empty
4884 } else if (this.data.height === node.height) {
4885 // split root if trees have the same height
4886 this._splitRoot(this.data, node);
4889 if (this.data.height < node.height) {
4890 // swap trees if inserted one is bigger
4891 var tmpNode = this.data;
4896 // insert the small tree into the large tree at appropriate level
4897 this._insert(node, this.data.height - node.height - 1, true);
4903 insert: function (item) {
4904 if (item) this._insert(item, this.data.height - 1);
4908 clear: function () {
4909 this.data = createNode([]);
4913 remove: function (item, equalsFn) {
4914 if (!item) return this;
4916 var node = this.data,
4917 bbox = this.toBBox(item),
4920 i, parent, index, goingUp;
4922 // depth-first iterative tree traversal
4923 while (node || path.length) {
4925 if (!node) { // go up
4927 parent = path[path.length - 1];
4932 if (node.leaf) { // check current node
4933 index = findItem(item, node.children, equalsFn);
4936 // item found, remove the item and condense tree upwards
4937 node.children.splice(index, 1);
4939 this._condense(path);
4944 if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
4949 node = node.children[0];
4951 } else if (parent) { // go right
4953 node = parent.children[i];
4956 } else node = null; // nothing found
4962 toBBox: function (item) { return item; },
4964 compareMinX: compareNodeMinX,
4965 compareMinY: compareNodeMinY,
4967 toJSON: function () { return this.data; },
4969 fromJSON: function (data) {
4974 _all: function (node, result) {
4975 var nodesToSearch = [];
4977 if (node.leaf) result.push.apply(result, node.children);
4978 else nodesToSearch.push.apply(nodesToSearch, node.children);
4980 node = nodesToSearch.pop();
4985 _build: function (items, left, right, height) {
4987 var N = right - left + 1,
4988 M = this._maxEntries,
4992 // reached leaf level; return leaf
4993 node = createNode(items.slice(left, right + 1));
4994 calcBBox(node, this.toBBox);
4999 // target height of the bulk-loaded tree
5000 height = Math.ceil(Math.log(N) / Math.log(M));
5002 // target number of root entries to maximize storage utilization
5003 M = Math.ceil(N / Math.pow(M, height - 1));
5006 node = createNode([]);
5008 node.height = height;
5010 // split the items into M mostly square tiles
5012 var N2 = Math.ceil(N / M),
5013 N1 = N2 * Math.ceil(Math.sqrt(M)),
5014 i, j, right2, right3;
5016 multiSelect(items, left, right, N1, this.compareMinX);
5018 for (i = left; i <= right; i += N1) {
5020 right2 = Math.min(i + N1 - 1, right);
5022 multiSelect(items, i, right2, N2, this.compareMinY);
5024 for (j = i; j <= right2; j += N2) {
5026 right3 = Math.min(j + N2 - 1, right2);
5028 // pack each entry recursively
5029 node.children.push(this._build(items, j, right3, height - 1));
5033 calcBBox(node, this.toBBox);
5038 _chooseSubtree: function (bbox, node, level, path) {
5040 var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
5045 if (node.leaf || path.length - 1 === level) break;
5047 minArea = minEnlargement = Infinity;
5049 for (i = 0, len = node.children.length; i < len; i++) {
5050 child = node.children[i];
5051 area = bboxArea(child);
5052 enlargement = enlargedArea(bbox, child) - area;
5054 // choose entry with the least area enlargement
5055 if (enlargement < minEnlargement) {
5056 minEnlargement = enlargement;
5057 minArea = area < minArea ? area : minArea;
5060 } else if (enlargement === minEnlargement) {
5061 // otherwise choose one with the smallest area
5062 if (area < minArea) {
5069 node = targetNode || node.children[0];
5075 _insert: function (item, level, isNode) {
5077 var toBBox = this.toBBox,
5078 bbox = isNode ? item : toBBox(item),
5081 // find the best node for accommodating the item, saving all nodes along the path too
5082 var node = this._chooseSubtree(bbox, this.data, level, insertPath);
5084 // put the item into the node
5085 node.children.push(item);
5088 // split on node overflow; propagate upwards if necessary
5089 while (level >= 0) {
5090 if (insertPath[level].children.length > this._maxEntries) {
5091 this._split(insertPath, level);
5096 // adjust bboxes along the insertion path
5097 this._adjustParentBBoxes(bbox, insertPath, level);
5100 // split overflowed node into two
5101 _split: function (insertPath, level) {
5103 var node = insertPath[level],
5104 M = node.children.length,
5105 m = this._minEntries;
5107 this._chooseSplitAxis(node, m, M);
5109 var splitIndex = this._chooseSplitIndex(node, m, M);
5111 var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
5112 newNode.height = node.height;
5113 newNode.leaf = node.leaf;
5115 calcBBox(node, this.toBBox);
5116 calcBBox(newNode, this.toBBox);
5118 if (level) insertPath[level - 1].children.push(newNode);
5119 else this._splitRoot(node, newNode);
5122 _splitRoot: function (node, newNode) {
5124 this.data = createNode([node, newNode]);
5125 this.data.height = node.height + 1;
5126 this.data.leaf = false;
5127 calcBBox(this.data, this.toBBox);
5130 _chooseSplitIndex: function (node, m, M) {
5132 var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
5134 minOverlap = minArea = Infinity;
5136 for (i = m; i <= M - m; i++) {
5137 bbox1 = distBBox(node, 0, i, this.toBBox);
5138 bbox2 = distBBox(node, i, M, this.toBBox);
5140 overlap = intersectionArea(bbox1, bbox2);
5141 area = bboxArea(bbox1) + bboxArea(bbox2);
5143 // choose distribution with minimum overlap
5144 if (overlap < minOverlap) {
5145 minOverlap = overlap;
5148 minArea = area < minArea ? area : minArea;
5150 } else if (overlap === minOverlap) {
5151 // otherwise choose distribution with minimum area
5152 if (area < minArea) {
5162 // sorts node children by the best axis for split
5163 _chooseSplitAxis: function (node, m, M) {
5165 var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
5166 compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
5167 xMargin = this._allDistMargin(node, m, M, compareMinX),
5168 yMargin = this._allDistMargin(node, m, M, compareMinY);
5170 // if total distributions margin value is minimal for x, sort by minX,
5171 // otherwise it's already sorted by minY
5172 if (xMargin < yMargin) node.children.sort(compareMinX);
5175 // total margin of all possible split distributions where each node is at least m full
5176 _allDistMargin: function (node, m, M, compare) {
5178 node.children.sort(compare);
5180 var toBBox = this.toBBox,
5181 leftBBox = distBBox(node, 0, m, toBBox),
5182 rightBBox = distBBox(node, M - m, M, toBBox),
5183 margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
5186 for (i = m; i < M - m; i++) {
5187 child = node.children[i];
5188 extend(leftBBox, node.leaf ? toBBox(child) : child);
5189 margin += bboxMargin(leftBBox);
5192 for (i = M - m - 1; i >= m; i--) {
5193 child = node.children[i];
5194 extend(rightBBox, node.leaf ? toBBox(child) : child);
5195 margin += bboxMargin(rightBBox);
5201 _adjustParentBBoxes: function (bbox, path, level) {
5202 // adjust bboxes along the given tree path
5203 for (var i = level; i >= 0; i--) {
5204 extend(path[i], bbox);
5208 _condense: function (path) {
5209 // go through the path, removing empty nodes and updating bboxes
5210 for (var i = path.length - 1, siblings; i >= 0; i--) {
5211 if (path[i].children.length === 0) {
5213 siblings = path[i - 1].children;
5214 siblings.splice(siblings.indexOf(path[i]), 1);
5216 } else this.clear();
5218 } else calcBBox(path[i], this.toBBox);
5222 _initFormat: function (format) {
5223 // data format (minX, minY, maxX, maxY accessors)
5225 // uses eval-type function compilation instead of just accepting a toBBox function
5226 // because the algorithms are very sensitive to sorting functions performance,
5227 // so they should be dead simple and without inner calls
5229 var compareArr = ['return a', ' - b', ';'];
5231 this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
5232 this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
5234 this.toBBox = new Function('a',
5235 'return {minX: a' + format[0] +
5236 ', minY: a' + format[1] +
5237 ', maxX: a' + format[2] +
5238 ', maxY: a' + format[3] + '};');
5242 function findItem(item, items, equalsFn) {
5243 if (!equalsFn) return items.indexOf(item);
5245 for (var i = 0; i < items.length; i++) {
5246 if (equalsFn(item, items[i])) return i;
5251 // calculate node's bbox from bboxes of its children
5252 function calcBBox(node, toBBox) {
5253 distBBox(node, 0, node.children.length, toBBox, node);
5256 // min bounding rectangle of node children from k to p-1
5257 function distBBox(node, k, p, toBBox, destNode) {
5258 if (!destNode) destNode = createNode(null);
5259 destNode.minX = Infinity;
5260 destNode.minY = Infinity;
5261 destNode.maxX = -Infinity;
5262 destNode.maxY = -Infinity;
5264 for (var i = k, child; i < p; i++) {
5265 child = node.children[i];
5266 extend(destNode, node.leaf ? toBBox(child) : child);
5272 function extend(a, b) {
5273 a.minX = Math.min(a.minX, b.minX);
5274 a.minY = Math.min(a.minY, b.minY);
5275 a.maxX = Math.max(a.maxX, b.maxX);
5276 a.maxY = Math.max(a.maxY, b.maxY);
5280 function compareNodeMinX(a, b) { return a.minX - b.minX; }
5281 function compareNodeMinY(a, b) { return a.minY - b.minY; }
5283 function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); }
5284 function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
5286 function enlargedArea(a, b) {
5287 return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
5288 (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
5291 function intersectionArea(a, b) {
5292 var minX = Math.max(a.minX, b.minX),
5293 minY = Math.max(a.minY, b.minY),
5294 maxX = Math.min(a.maxX, b.maxX),
5295 maxY = Math.min(a.maxY, b.maxY);
5297 return Math.max(0, maxX - minX) *
5298 Math.max(0, maxY - minY);
5301 function contains(a, b) {
5302 return a.minX <= b.minX &&
5308 function intersects(a, b) {
5309 return b.minX <= a.maxX &&
5315 function createNode(children) {
5327 // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
5328 // combines selection algorithm with binary divide & conquer approach
5330 function multiSelect(arr, left, right, n, compare) {
5331 var stack = [left, right],
5334 while (stack.length) {
5335 right = stack.pop();
5338 if (right - left <= n) continue;
5340 mid = left + Math.ceil((right - left) / n / 2) * n;
5341 quickselect(arr, mid, left, right, compare);
5343 stack.push(left, mid, mid, right);
5347 },{"quickselect":24}],26:[function(require,module,exports){
5349 var __extends = (this && this.__extends) || function (d, b) {
5350 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5351 function __() { this.constructor = d; }
5352 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5354 var Subject_1 = require('./Subject');
5355 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5357 * @class BehaviorSubject<T>
5359 var BehaviorSubject = (function (_super) {
5360 __extends(BehaviorSubject, _super);
5361 function BehaviorSubject(_value) {
5363 this._value = _value;
5365 Object.defineProperty(BehaviorSubject.prototype, "value", {
5367 return this.getValue();
5372 BehaviorSubject.prototype._subscribe = function (subscriber) {
5373 var subscription = _super.prototype._subscribe.call(this, subscriber);
5374 if (subscription && !subscription.closed) {
5375 subscriber.next(this._value);
5377 return subscription;
5379 BehaviorSubject.prototype.getValue = function () {
5380 if (this.hasError) {
5381 throw this.thrownError;
5383 else if (this.closed) {
5384 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5390 BehaviorSubject.prototype.next = function (value) {
5391 _super.prototype.next.call(this, this._value = value);
5393 return BehaviorSubject;
5394 }(Subject_1.Subject));
5395 exports.BehaviorSubject = BehaviorSubject;
5397 },{"./Subject":34,"./util/ObjectUnsubscribedError":220}],27:[function(require,module,exports){
5399 var __extends = (this && this.__extends) || function (d, b) {
5400 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5401 function __() { this.constructor = d; }
5402 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5404 var Subscriber_1 = require('./Subscriber');
5406 * We need this JSDoc comment for affecting ESDoc.
5408 * @extends {Ignored}
5410 var InnerSubscriber = (function (_super) {
5411 __extends(InnerSubscriber, _super);
5412 function InnerSubscriber(parent, outerValue, outerIndex) {
5414 this.parent = parent;
5415 this.outerValue = outerValue;
5416 this.outerIndex = outerIndex;
5419 InnerSubscriber.prototype._next = function (value) {
5420 this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
5422 InnerSubscriber.prototype._error = function (error) {
5423 this.parent.notifyError(error, this);
5426 InnerSubscriber.prototype._complete = function () {
5427 this.parent.notifyComplete(this);
5430 return InnerSubscriber;
5431 }(Subscriber_1.Subscriber));
5432 exports.InnerSubscriber = InnerSubscriber;
5434 },{"./Subscriber":36}],28:[function(require,module,exports){
5436 var Observable_1 = require('./Observable');
5438 * Represents a push-based event or value that an {@link Observable} can emit.
5439 * This class is particularly useful for operators that manage notifications,
5440 * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and
5441 * others. Besides wrapping the actual delivered value, it also annotates it
5442 * with metadata of, for instance, what type of push message it is (`next`,
5443 * `error`, or `complete`).
5445 * @see {@link materialize}
5446 * @see {@link dematerialize}
5447 * @see {@link observeOn}
5449 * @class Notification<T>
5451 var Notification = (function () {
5452 function Notification(kind, value, error) {
5456 this.hasValue = kind === 'N';
5459 * Delivers to the given `observer` the value wrapped by this Notification.
5460 * @param {Observer} observer
5463 Notification.prototype.observe = function (observer) {
5464 switch (this.kind) {
5466 return observer.next && observer.next(this.value);
5468 return observer.error && observer.error(this.error);
5470 return observer.complete && observer.complete();
5474 * Given some {@link Observer} callbacks, deliver the value represented by the
5475 * current Notification to the correctly corresponding callback.
5476 * @param {function(value: T): void} next An Observer `next` callback.
5477 * @param {function(err: any): void} [error] An Observer `error` callback.
5478 * @param {function(): void} [complete] An Observer `complete` callback.
5481 Notification.prototype.do = function (next, error, complete) {
5482 var kind = this.kind;
5485 return next && next(this.value);
5487 return error && error(this.error);
5489 return complete && complete();
5493 * Takes an Observer or its individual callback functions, and calls `observe`
5494 * or `do` methods accordingly.
5495 * @param {Observer|function(value: T): void} nextOrObserver An Observer or
5496 * the `next` callback.
5497 * @param {function(err: any): void} [error] An Observer `error` callback.
5498 * @param {function(): void} [complete] An Observer `complete` callback.
5501 Notification.prototype.accept = function (nextOrObserver, error, complete) {
5502 if (nextOrObserver && typeof nextOrObserver.next === 'function') {
5503 return this.observe(nextOrObserver);
5506 return this.do(nextOrObserver, error, complete);
5510 * Returns a simple Observable that just delivers the notification represented
5511 * by this Notification instance.
5514 Notification.prototype.toObservable = function () {
5515 var kind = this.kind;
5518 return Observable_1.Observable.of(this.value);
5520 return Observable_1.Observable.throw(this.error);
5522 return Observable_1.Observable.empty();
5524 throw new Error('unexpected notification kind value');
5527 * A shortcut to create a Notification instance of the type `next` from a
5529 * @param {T} value The `next` value.
5530 * @return {Notification<T>} The "next" Notification representing the
5533 Notification.createNext = function (value) {
5534 if (typeof value !== 'undefined') {
5535 return new Notification('N', value);
5537 return Notification.undefinedValueNotification;
5540 * A shortcut to create a Notification instance of the type `error` from a
5542 * @param {any} [err] The `error` error.
5543 * @return {Notification<T>} The "error" Notification representing the
5546 Notification.createError = function (err) {
5547 return new Notification('E', undefined, err);
5550 * A shortcut to create a Notification instance of the type `complete`.
5551 * @return {Notification<any>} The valueless "complete" Notification.
5553 Notification.createComplete = function () {
5554 return Notification.completeNotification;
5556 Notification.completeNotification = new Notification('C');
5557 Notification.undefinedValueNotification = new Notification('N', undefined);
5558 return Notification;
5560 exports.Notification = Notification;
5562 },{"./Observable":29}],29:[function(require,module,exports){
5564 var root_1 = require('./util/root');
5565 var toSubscriber_1 = require('./util/toSubscriber');
5566 var observable_1 = require('./symbol/observable');
5567 var pipe_1 = require('./util/pipe');
5569 * A representation of any set of values over any amount of time. This is the most basic building block
5572 * @class Observable<T>
5574 var Observable = (function () {
5577 * @param {Function} subscribe the function that is called when the Observable is
5578 * initially subscribed to. This function is given a Subscriber, to which new values
5579 * can be `next`ed, or an `error` method can be called to raise an error, or
5580 * `complete` can be called to notify of a successful completion.
5582 function Observable(subscribe) {
5583 this._isScalar = false;
5585 this._subscribe = subscribe;
5589 * Creates a new Observable, with this Observable as the source, and the passed
5590 * operator defined as the new observable's operator.
5592 * @param {Operator} operator the operator defining the operation to take on the observable
5593 * @return {Observable} a new observable with the Operator applied
5595 Observable.prototype.lift = function (operator) {
5596 var observable = new Observable();
5597 observable.source = this;
5598 observable.operator = operator;
5602 * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
5604 * <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
5606 * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It
5607 * might be for example a function that you passed to a {@link create} static factory, but most of the time it is
5608 * a library implementation, which defines what and when will be emitted by an Observable. This means that calling
5609 * `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
5612 * Apart from starting the execution of an Observable, this method allows you to listen for values
5613 * that an Observable emits, as well as for when it completes or errors. You can achieve this in two
5616 * The first way is creating an object that implements {@link Observer} interface. It should have methods
5617 * defined by that interface, but note that it should be just a regular JavaScript object, which you can create
5618 * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do
5619 * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
5620 * that your object does not have to implement all methods. If you find yourself creating a method that doesn't
5621 * do anything, you can simply omit it. Note however, that if `error` method is not provided, all errors will
5624 * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
5625 * This means you can provide three functions as arguments to `subscribe`, where first function is equivalent
5626 * of a `next` method, second of an `error` method and third of a `complete` method. Just as in case of Observer,
5627 * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,
5628 * since `subscribe` recognizes these functions by where they were placed in function call. When it comes
5629 * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.
5631 * Whatever style of calling `subscribe` you use, in both cases it returns a Subscription object.
5632 * This object allows you to call `unsubscribe` on it, which in turn will stop work that an Observable does and will clean
5633 * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
5634 * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
5636 * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
5637 * It is an Observable itself that decides when these functions will be called. For example {@link of}
5638 * by default emits all its values synchronously. Always check documentation for how given Observable
5639 * will behave when subscribed and if its default behavior can be modified with a {@link Scheduler}.
5641 * @example <caption>Subscribe with an Observer</caption>
5642 * const sumObserver = {
5645 * console.log('Adding: ' + value);
5646 * this.sum = this.sum + value;
5648 * error() { // We actually could just remove this method,
5649 * }, // since we do not really care about errors right now.
5651 * console.log('Sum equals: ' + this.sum);
5655 * Rx.Observable.of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
5656 * .subscribe(sumObserver);
5662 * // "Sum equals: 6"
5665 * @example <caption>Subscribe with functions</caption>
5668 * Rx.Observable.of(1, 2, 3)
5671 * console.log('Adding: ' + value);
5672 * sum = sum + value;
5676 * console.log('Sum equals: ' + sum);
5684 * // "Sum equals: 6"
5687 * @example <caption>Cancel a subscription</caption>
5688 * const subscription = Rx.Observable.interval(1000).subscribe(
5689 * num => console.log(num),
5691 * () => console.log('completed!') // Will not be called, even
5692 * ); // when cancelling subscription
5695 * setTimeout(() => {
5696 * subscription.unsubscribe();
5697 * console.log('unsubscribed!');
5703 * // "unsubscribed!" after 2.5s
5706 * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,
5707 * or the first of three possible handlers, which is the handler for each value emitted from the subscribed
5709 * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,
5710 * the error will be thrown as unhandled.
5711 * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.
5712 * @return {ISubscription} a subscription reference to the registered handlers
5715 Observable.prototype.subscribe = function (observerOrNext, error, complete) {
5716 var operator = this.operator;
5717 var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
5719 operator.call(sink, this.source);
5722 sink.add(this.source ? this._subscribe(sink) : this._trySubscribe(sink));
5724 if (sink.syncErrorThrowable) {
5725 sink.syncErrorThrowable = false;
5726 if (sink.syncErrorThrown) {
5727 throw sink.syncErrorValue;
5732 Observable.prototype._trySubscribe = function (sink) {
5734 return this._subscribe(sink);
5737 sink.syncErrorThrown = true;
5738 sink.syncErrorValue = err;
5744 * @param {Function} next a handler for each value emitted by the observable
5745 * @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
5746 * @return {Promise} a promise that either resolves on observable completion or
5747 * rejects with the handled error
5749 Observable.prototype.forEach = function (next, PromiseCtor) {
5752 if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
5753 PromiseCtor = root_1.root.Rx.config.Promise;
5755 else if (root_1.root.Promise) {
5756 PromiseCtor = root_1.root.Promise;
5760 throw new Error('no Promise impl found');
5762 return new PromiseCtor(function (resolve, reject) {
5763 // Must be declared in a separate statement to avoid a RefernceError when
5764 // accessing subscription below in the closure due to Temporal Dead Zone.
5766 subscription = _this.subscribe(function (value) {
5768 // if there is a subscription, then we can surmise
5769 // the next handling is asynchronous. Any errors thrown
5770 // need to be rejected explicitly and unsubscribe must be
5777 subscription.unsubscribe();
5781 // if there is NO subscription, then we're getting a nexted
5782 // value synchronously during subscription. We can just call it.
5783 // If it errors, Observable's `subscribe` will ensure the
5784 // unsubscription logic is called, then synchronously rethrow the error.
5785 // After that, Promise will trap the error and send it
5786 // down the rejection path.
5789 }, reject, resolve);
5792 Observable.prototype._subscribe = function (subscriber) {
5793 return this.source.subscribe(subscriber);
5796 * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
5797 * @method Symbol.observable
5798 * @return {Observable} this instance of the observable
5800 Observable.prototype[observable_1.observable] = function () {
5803 /* tslint:enable:max-line-length */
5805 * Used to stitch together functional operators into a chain.
5807 * @return {Observable} the Observable result of all of the operators having
5808 * been called in the order they were passed in.
5812 * import { map, filter, scan } from 'rxjs/operators';
5814 * Rx.Observable.interval(1000)
5816 * filter(x => x % 2 === 0),
5818 * scan((acc, x) => acc + x)
5820 * .subscribe(x => console.log(x))
5822 Observable.prototype.pipe = function () {
5823 var operations = [];
5824 for (var _i = 0; _i < arguments.length; _i++) {
5825 operations[_i - 0] = arguments[_i];
5827 if (operations.length === 0) {
5830 return pipe_1.pipeFromArray(operations)(this);
5832 /* tslint:enable:max-line-length */
5833 Observable.prototype.toPromise = function (PromiseCtor) {
5836 if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
5837 PromiseCtor = root_1.root.Rx.config.Promise;
5839 else if (root_1.root.Promise) {
5840 PromiseCtor = root_1.root.Promise;
5844 throw new Error('no Promise impl found');
5846 return new PromiseCtor(function (resolve, reject) {
5848 _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });
5851 // HACK: Since TypeScript inherits static properties too, we have to
5852 // fight against TypeScript here so Subject can have a different static create signature
5854 * Creates a new cold Observable by calling the Observable constructor
5858 * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
5859 * @return {Observable} a new cold observable
5861 Observable.create = function (subscribe) {
5862 return new Observable(subscribe);
5866 exports.Observable = Observable;
5868 },{"./symbol/observable":215,"./util/pipe":235,"./util/root":236,"./util/toSubscriber":238}],30:[function(require,module,exports){
5872 next: function (value) { },
5873 error: function (err) { throw err; },
5874 complete: function () { }
5877 },{}],31:[function(require,module,exports){
5879 var __extends = (this && this.__extends) || function (d, b) {
5880 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5881 function __() { this.constructor = d; }
5882 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5884 var Subscriber_1 = require('./Subscriber');
5886 * We need this JSDoc comment for affecting ESDoc.
5888 * @extends {Ignored}
5890 var OuterSubscriber = (function (_super) {
5891 __extends(OuterSubscriber, _super);
5892 function OuterSubscriber() {
5893 _super.apply(this, arguments);
5895 OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
5896 this.destination.next(innerValue);
5898 OuterSubscriber.prototype.notifyError = function (error, innerSub) {
5899 this.destination.error(error);
5901 OuterSubscriber.prototype.notifyComplete = function (innerSub) {
5902 this.destination.complete();
5904 return OuterSubscriber;
5905 }(Subscriber_1.Subscriber));
5906 exports.OuterSubscriber = OuterSubscriber;
5908 },{"./Subscriber":36}],32:[function(require,module,exports){
5910 var __extends = (this && this.__extends) || function (d, b) {
5911 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5912 function __() { this.constructor = d; }
5913 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5915 var Subject_1 = require('./Subject');
5916 var queue_1 = require('./scheduler/queue');
5917 var Subscription_1 = require('./Subscription');
5918 var observeOn_1 = require('./operators/observeOn');
5919 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5920 var SubjectSubscription_1 = require('./SubjectSubscription');
5922 * @class ReplaySubject<T>
5924 var ReplaySubject = (function (_super) {
5925 __extends(ReplaySubject, _super);
5926 function ReplaySubject(bufferSize, windowTime, scheduler) {
5927 if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
5928 if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
5930 this.scheduler = scheduler;
5932 this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
5933 this._windowTime = windowTime < 1 ? 1 : windowTime;
5935 ReplaySubject.prototype.next = function (value) {
5936 var now = this._getNow();
5937 this._events.push(new ReplayEvent(now, value));
5938 this._trimBufferThenGetEvents();
5939 _super.prototype.next.call(this, value);
5941 ReplaySubject.prototype._subscribe = function (subscriber) {
5942 var _events = this._trimBufferThenGetEvents();
5943 var scheduler = this.scheduler;
5946 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5948 else if (this.hasError) {
5949 subscription = Subscription_1.Subscription.EMPTY;
5951 else if (this.isStopped) {
5952 subscription = Subscription_1.Subscription.EMPTY;
5955 this.observers.push(subscriber);
5956 subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber);
5959 subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler));
5961 var len = _events.length;
5962 for (var i = 0; i < len && !subscriber.closed; i++) {
5963 subscriber.next(_events[i].value);
5965 if (this.hasError) {
5966 subscriber.error(this.thrownError);
5968 else if (this.isStopped) {
5969 subscriber.complete();
5971 return subscription;
5973 ReplaySubject.prototype._getNow = function () {
5974 return (this.scheduler || queue_1.queue).now();
5976 ReplaySubject.prototype._trimBufferThenGetEvents = function () {
5977 var now = this._getNow();
5978 var _bufferSize = this._bufferSize;
5979 var _windowTime = this._windowTime;
5980 var _events = this._events;
5981 var eventsCount = _events.length;
5982 var spliceCount = 0;
5983 // Trim events that fall out of the time window.
5984 // Start at the front of the list. Break early once
5985 // we encounter an event that falls within the window.
5986 while (spliceCount < eventsCount) {
5987 if ((now - _events[spliceCount].time) < _windowTime) {
5992 if (eventsCount > _bufferSize) {
5993 spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
5995 if (spliceCount > 0) {
5996 _events.splice(0, spliceCount);
6000 return ReplaySubject;
6001 }(Subject_1.Subject));
6002 exports.ReplaySubject = ReplaySubject;
6003 var ReplayEvent = (function () {
6004 function ReplayEvent(time, value) {
6011 },{"./Subject":34,"./SubjectSubscription":35,"./Subscription":37,"./operators/observeOn":183,"./scheduler/queue":213,"./util/ObjectUnsubscribedError":220}],33:[function(require,module,exports){
6014 * An execution context and a data structure to order tasks and schedule their
6015 * execution. Provides a notion of (potentially virtual) time, through the
6016 * `now()` getter method.
6018 * Each unit of work in a Scheduler is called an {@link Action}.
6023 * schedule(work, delay?, state?): Subscription;
6029 var Scheduler = (function () {
6030 function Scheduler(SchedulerAction, now) {
6031 if (now === void 0) { now = Scheduler.now; }
6032 this.SchedulerAction = SchedulerAction;
6036 * Schedules a function, `work`, for execution. May happen at some point in
6037 * the future, according to the `delay` parameter, if specified. May be passed
6038 * some context object, `state`, which will be passed to the `work` function.
6040 * The given arguments will be processed an stored as an Action object in a
6043 * @param {function(state: ?T): ?Subscription} work A function representing a
6044 * task, or some unit of work to be executed by the Scheduler.
6045 * @param {number} [delay] Time to wait before executing the work, where the
6046 * time unit is implicit and defined by the Scheduler itself.
6047 * @param {T} [state] Some contextual data that the `work` function uses when
6048 * called by the Scheduler.
6049 * @return {Subscription} A subscription in order to be able to unsubscribe
6050 * the scheduled work.
6052 Scheduler.prototype.schedule = function (work, delay, state) {
6053 if (delay === void 0) { delay = 0; }
6054 return new this.SchedulerAction(this, work).schedule(state, delay);
6056 Scheduler.now = Date.now ? Date.now : function () { return +new Date(); };
6059 exports.Scheduler = Scheduler;
6061 },{}],34:[function(require,module,exports){
6063 var __extends = (this && this.__extends) || function (d, b) {
6064 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6065 function __() { this.constructor = d; }
6066 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6068 var Observable_1 = require('./Observable');
6069 var Subscriber_1 = require('./Subscriber');
6070 var Subscription_1 = require('./Subscription');
6071 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
6072 var SubjectSubscription_1 = require('./SubjectSubscription');
6073 var rxSubscriber_1 = require('./symbol/rxSubscriber');
6075 * @class SubjectSubscriber<T>
6077 var SubjectSubscriber = (function (_super) {
6078 __extends(SubjectSubscriber, _super);
6079 function SubjectSubscriber(destination) {
6080 _super.call(this, destination);
6081 this.destination = destination;
6083 return SubjectSubscriber;
6084 }(Subscriber_1.Subscriber));
6085 exports.SubjectSubscriber = SubjectSubscriber;
6089 var Subject = (function (_super) {
6090 __extends(Subject, _super);
6091 function Subject() {
6093 this.observers = [];
6094 this.closed = false;
6095 this.isStopped = false;
6096 this.hasError = false;
6097 this.thrownError = null;
6099 Subject.prototype[rxSubscriber_1.rxSubscriber] = function () {
6100 return new SubjectSubscriber(this);
6102 Subject.prototype.lift = function (operator) {
6103 var subject = new AnonymousSubject(this, this);
6104 subject.operator = operator;
6107 Subject.prototype.next = function (value) {
6109 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6111 if (!this.isStopped) {
6112 var observers = this.observers;
6113 var len = observers.length;
6114 var copy = observers.slice();
6115 for (var i = 0; i < len; i++) {
6116 copy[i].next(value);
6120 Subject.prototype.error = function (err) {
6122 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6124 this.hasError = true;
6125 this.thrownError = err;
6126 this.isStopped = true;
6127 var observers = this.observers;
6128 var len = observers.length;
6129 var copy = observers.slice();
6130 for (var i = 0; i < len; i++) {
6133 this.observers.length = 0;
6135 Subject.prototype.complete = function () {
6137 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6139 this.isStopped = true;
6140 var observers = this.observers;
6141 var len = observers.length;
6142 var copy = observers.slice();
6143 for (var i = 0; i < len; i++) {
6146 this.observers.length = 0;
6148 Subject.prototype.unsubscribe = function () {
6149 this.isStopped = true;
6151 this.observers = null;
6153 Subject.prototype._trySubscribe = function (subscriber) {
6155 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6158 return _super.prototype._trySubscribe.call(this, subscriber);
6161 Subject.prototype._subscribe = function (subscriber) {
6163 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6165 else if (this.hasError) {
6166 subscriber.error(this.thrownError);
6167 return Subscription_1.Subscription.EMPTY;
6169 else if (this.isStopped) {
6170 subscriber.complete();
6171 return Subscription_1.Subscription.EMPTY;
6174 this.observers.push(subscriber);
6175 return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
6178 Subject.prototype.asObservable = function () {
6179 var observable = new Observable_1.Observable();
6180 observable.source = this;
6183 Subject.create = function (destination, source) {
6184 return new AnonymousSubject(destination, source);
6187 }(Observable_1.Observable));
6188 exports.Subject = Subject;
6190 * @class AnonymousSubject<T>
6192 var AnonymousSubject = (function (_super) {
6193 __extends(AnonymousSubject, _super);
6194 function AnonymousSubject(destination, source) {
6196 this.destination = destination;
6197 this.source = source;
6199 AnonymousSubject.prototype.next = function (value) {
6200 var destination = this.destination;
6201 if (destination && destination.next) {
6202 destination.next(value);
6205 AnonymousSubject.prototype.error = function (err) {
6206 var destination = this.destination;
6207 if (destination && destination.error) {
6208 this.destination.error(err);
6211 AnonymousSubject.prototype.complete = function () {
6212 var destination = this.destination;
6213 if (destination && destination.complete) {
6214 this.destination.complete();
6217 AnonymousSubject.prototype._subscribe = function (subscriber) {
6218 var source = this.source;
6220 return this.source.subscribe(subscriber);
6223 return Subscription_1.Subscription.EMPTY;
6226 return AnonymousSubject;
6228 exports.AnonymousSubject = AnonymousSubject;
6230 },{"./Observable":29,"./SubjectSubscription":35,"./Subscriber":36,"./Subscription":37,"./symbol/rxSubscriber":216,"./util/ObjectUnsubscribedError":220}],35:[function(require,module,exports){
6232 var __extends = (this && this.__extends) || function (d, b) {
6233 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6234 function __() { this.constructor = d; }
6235 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6237 var Subscription_1 = require('./Subscription');
6239 * We need this JSDoc comment for affecting ESDoc.
6241 * @extends {Ignored}
6243 var SubjectSubscription = (function (_super) {
6244 __extends(SubjectSubscription, _super);
6245 function SubjectSubscription(subject, subscriber) {
6247 this.subject = subject;
6248 this.subscriber = subscriber;
6249 this.closed = false;
6251 SubjectSubscription.prototype.unsubscribe = function () {
6256 var subject = this.subject;
6257 var observers = subject.observers;
6258 this.subject = null;
6259 if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
6262 var subscriberIndex = observers.indexOf(this.subscriber);
6263 if (subscriberIndex !== -1) {
6264 observers.splice(subscriberIndex, 1);
6267 return SubjectSubscription;
6268 }(Subscription_1.Subscription));
6269 exports.SubjectSubscription = SubjectSubscription;
6271 },{"./Subscription":37}],36:[function(require,module,exports){
6273 var __extends = (this && this.__extends) || function (d, b) {
6274 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6275 function __() { this.constructor = d; }
6276 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6278 var isFunction_1 = require('./util/isFunction');
6279 var Subscription_1 = require('./Subscription');
6280 var Observer_1 = require('./Observer');
6281 var rxSubscriber_1 = require('./symbol/rxSubscriber');
6283 * Implements the {@link Observer} interface and extends the
6284 * {@link Subscription} class. While the {@link Observer} is the public API for
6285 * consuming the values of an {@link Observable}, all Observers get converted to
6286 * a Subscriber, in order to provide Subscription-like capabilities such as
6287 * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
6288 * implementing operators, but it is rarely used as a public API.
6290 * @class Subscriber<T>
6292 var Subscriber = (function (_super) {
6293 __extends(Subscriber, _super);
6295 * @param {Observer|function(value: T): void} [destinationOrNext] A partially
6296 * defined Observer or a `next` callback function.
6297 * @param {function(e: ?any): void} [error] The `error` callback of an
6299 * @param {function(): void} [complete] The `complete` callback of an
6302 function Subscriber(destinationOrNext, error, complete) {
6304 this.syncErrorValue = null;
6305 this.syncErrorThrown = false;
6306 this.syncErrorThrowable = false;
6307 this.isStopped = false;
6308 switch (arguments.length) {
6310 this.destination = Observer_1.empty;
6313 if (!destinationOrNext) {
6314 this.destination = Observer_1.empty;
6317 if (typeof destinationOrNext === 'object') {
6318 if (destinationOrNext instanceof Subscriber) {
6319 this.destination = destinationOrNext;
6320 this.destination.add(this);
6323 this.syncErrorThrowable = true;
6324 this.destination = new SafeSubscriber(this, destinationOrNext);
6329 this.syncErrorThrowable = true;
6330 this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
6334 Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function () { return this; };
6336 * A static factory for a Subscriber, given a (potentially partial) definition
6338 * @param {function(x: ?T): void} [next] The `next` callback of an Observer.
6339 * @param {function(e: ?any): void} [error] The `error` callback of an
6341 * @param {function(): void} [complete] The `complete` callback of an
6343 * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
6344 * Observer represented by the given arguments.
6346 Subscriber.create = function (next, error, complete) {
6347 var subscriber = new Subscriber(next, error, complete);
6348 subscriber.syncErrorThrowable = false;
6352 * The {@link Observer} callback to receive notifications of type `next` from
6353 * the Observable, with a value. The Observable may call this method 0 or more
6355 * @param {T} [value] The `next` value.
6358 Subscriber.prototype.next = function (value) {
6359 if (!this.isStopped) {
6364 * The {@link Observer} callback to receive notifications of type `error` from
6365 * the Observable, with an attached {@link Error}. Notifies the Observer that
6366 * the Observable has experienced an error condition.
6367 * @param {any} [err] The `error` exception.
6370 Subscriber.prototype.error = function (err) {
6371 if (!this.isStopped) {
6372 this.isStopped = true;
6377 * The {@link Observer} callback to receive a valueless notification of type
6378 * `complete` from the Observable. Notifies the Observer that the Observable
6379 * has finished sending push-based notifications.
6382 Subscriber.prototype.complete = function () {
6383 if (!this.isStopped) {
6384 this.isStopped = true;
6388 Subscriber.prototype.unsubscribe = function () {
6392 this.isStopped = true;
6393 _super.prototype.unsubscribe.call(this);
6395 Subscriber.prototype._next = function (value) {
6396 this.destination.next(value);
6398 Subscriber.prototype._error = function (err) {
6399 this.destination.error(err);
6402 Subscriber.prototype._complete = function () {
6403 this.destination.complete();
6406 Subscriber.prototype._unsubscribeAndRecycle = function () {
6407 var _a = this, _parent = _a._parent, _parents = _a._parents;
6408 this._parent = null;
6409 this._parents = null;
6411 this.closed = false;
6412 this.isStopped = false;
6413 this._parent = _parent;
6414 this._parents = _parents;
6418 }(Subscription_1.Subscription));
6419 exports.Subscriber = Subscriber;
6421 * We need this JSDoc comment for affecting ESDoc.
6423 * @extends {Ignored}
6425 var SafeSubscriber = (function (_super) {
6426 __extends(SafeSubscriber, _super);
6427 function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
6429 this._parentSubscriber = _parentSubscriber;
6432 if (isFunction_1.isFunction(observerOrNext)) {
6433 next = observerOrNext;
6435 else if (observerOrNext) {
6436 next = observerOrNext.next;
6437 error = observerOrNext.error;
6438 complete = observerOrNext.complete;
6439 if (observerOrNext !== Observer_1.empty) {
6440 context = Object.create(observerOrNext);
6441 if (isFunction_1.isFunction(context.unsubscribe)) {
6442 this.add(context.unsubscribe.bind(context));
6444 context.unsubscribe = this.unsubscribe.bind(this);
6447 this._context = context;
6449 this._error = error;
6450 this._complete = complete;
6452 SafeSubscriber.prototype.next = function (value) {
6453 if (!this.isStopped && this._next) {
6454 var _parentSubscriber = this._parentSubscriber;
6455 if (!_parentSubscriber.syncErrorThrowable) {
6456 this.__tryOrUnsub(this._next, value);
6458 else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
6463 SafeSubscriber.prototype.error = function (err) {
6464 if (!this.isStopped) {
6465 var _parentSubscriber = this._parentSubscriber;
6467 if (!_parentSubscriber.syncErrorThrowable) {
6468 this.__tryOrUnsub(this._error, err);
6472 this.__tryOrSetError(_parentSubscriber, this._error, err);
6476 else if (!_parentSubscriber.syncErrorThrowable) {
6481 _parentSubscriber.syncErrorValue = err;
6482 _parentSubscriber.syncErrorThrown = true;
6487 SafeSubscriber.prototype.complete = function () {
6489 if (!this.isStopped) {
6490 var _parentSubscriber = this._parentSubscriber;
6491 if (this._complete) {
6492 var wrappedComplete = function () { return _this._complete.call(_this._context); };
6493 if (!_parentSubscriber.syncErrorThrowable) {
6494 this.__tryOrUnsub(wrappedComplete);
6498 this.__tryOrSetError(_parentSubscriber, wrappedComplete);
6507 SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
6509 fn.call(this._context, value);
6516 SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
6518 fn.call(this._context, value);
6521 parent.syncErrorValue = err;
6522 parent.syncErrorThrown = true;
6527 SafeSubscriber.prototype._unsubscribe = function () {
6528 var _parentSubscriber = this._parentSubscriber;
6529 this._context = null;
6530 this._parentSubscriber = null;
6531 _parentSubscriber.unsubscribe();
6533 return SafeSubscriber;
6536 },{"./Observer":30,"./Subscription":37,"./symbol/rxSubscriber":216,"./util/isFunction":229}],37:[function(require,module,exports){
6538 var isArray_1 = require('./util/isArray');
6539 var isObject_1 = require('./util/isObject');
6540 var isFunction_1 = require('./util/isFunction');
6541 var tryCatch_1 = require('./util/tryCatch');
6542 var errorObject_1 = require('./util/errorObject');
6543 var UnsubscriptionError_1 = require('./util/UnsubscriptionError');
6545 * Represents a disposable resource, such as the execution of an Observable. A
6546 * Subscription has one important method, `unsubscribe`, that takes no argument
6547 * and just disposes the resource held by the subscription.
6549 * Additionally, subscriptions may be grouped together through the `add()`
6550 * method, which will attach a child Subscription to the current Subscription.
6551 * When a Subscription is unsubscribed, all its children (and its grandchildren)
6552 * will be unsubscribed as well.
6554 * @class Subscription
6556 var Subscription = (function () {
6558 * @param {function(): void} [unsubscribe] A function describing how to
6559 * perform the disposal of resources when the `unsubscribe` method is called.
6561 function Subscription(unsubscribe) {
6563 * A flag to indicate whether this Subscription has already been unsubscribed.
6566 this.closed = false;
6567 this._parent = null;
6568 this._parents = null;
6569 this._subscriptions = null;
6571 this._unsubscribe = unsubscribe;
6575 * Disposes the resources held by the subscription. May, for instance, cancel
6576 * an ongoing Observable execution or cancel any other type of work that
6577 * started when the Subscription was created.
6580 Subscription.prototype.unsubscribe = function () {
6581 var hasErrors = false;
6586 var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
6588 this._parent = null;
6589 this._parents = null;
6590 // null out _subscriptions first so any child subscriptions that attempt
6591 // to remove themselves from this subscription will noop
6592 this._subscriptions = null;
6594 var len = _parents ? _parents.length : 0;
6595 // if this._parent is null, then so is this._parents, and we
6596 // don't have to remove ourselves from any parent subscriptions.
6598 _parent.remove(this);
6599 // if this._parents is null or index >= len,
6600 // then _parent is set to null, and the loop exits
6601 _parent = ++index < len && _parents[index] || null;
6603 if (isFunction_1.isFunction(_unsubscribe)) {
6604 var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
6605 if (trial === errorObject_1.errorObject) {
6607 errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ?
6608 flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]);
6611 if (isArray_1.isArray(_subscriptions)) {
6613 len = _subscriptions.length;
6614 while (++index < len) {
6615 var sub = _subscriptions[index];
6616 if (isObject_1.isObject(sub)) {
6617 var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
6618 if (trial === errorObject_1.errorObject) {
6620 errors = errors || [];
6621 var err = errorObject_1.errorObject.e;
6622 if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
6623 errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
6633 throw new UnsubscriptionError_1.UnsubscriptionError(errors);
6637 * Adds a tear down to be called during the unsubscribe() of this
6640 * If the tear down being added is a subscription that is already
6641 * unsubscribed, is the same reference `add` is being called on, or is
6642 * `Subscription.EMPTY`, it will not be added.
6644 * If this subscription is already in an `closed` state, the passed
6645 * tear down logic will be executed immediately.
6647 * @param {TeardownLogic} teardown The additional logic to execute on
6649 * @return {Subscription} Returns the Subscription used or created to be
6650 * added to the inner subscriptions list. This Subscription can be used with
6651 * `remove()` to remove the passed teardown logic from the inner subscriptions
6654 Subscription.prototype.add = function (teardown) {
6655 if (!teardown || (teardown === Subscription.EMPTY)) {
6656 return Subscription.EMPTY;
6658 if (teardown === this) {
6661 var subscription = teardown;
6662 switch (typeof teardown) {
6664 subscription = new Subscription(teardown);
6666 if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
6667 return subscription;
6669 else if (this.closed) {
6670 subscription.unsubscribe();
6671 return subscription;
6673 else if (typeof subscription._addParent !== 'function' /* quack quack */) {
6674 var tmp = subscription;
6675 subscription = new Subscription();
6676 subscription._subscriptions = [tmp];
6680 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
6682 var subscriptions = this._subscriptions || (this._subscriptions = []);
6683 subscriptions.push(subscription);
6684 subscription._addParent(this);
6685 return subscription;
6688 * Removes a Subscription from the internal list of subscriptions that will
6689 * unsubscribe during the unsubscribe process of this Subscription.
6690 * @param {Subscription} subscription The subscription to remove.
6693 Subscription.prototype.remove = function (subscription) {
6694 var subscriptions = this._subscriptions;
6695 if (subscriptions) {
6696 var subscriptionIndex = subscriptions.indexOf(subscription);
6697 if (subscriptionIndex !== -1) {
6698 subscriptions.splice(subscriptionIndex, 1);
6702 Subscription.prototype._addParent = function (parent) {
6703 var _a = this, _parent = _a._parent, _parents = _a._parents;
6704 if (!_parent || _parent === parent) {
6705 // If we don't have a parent, or the new parent is the same as the
6706 // current parent, then set this._parent to the new parent.
6707 this._parent = parent;
6709 else if (!_parents) {
6710 // If there's already one parent, but not multiple, allocate an Array to
6711 // store the rest of the parent Subscriptions.
6712 this._parents = [parent];
6714 else if (_parents.indexOf(parent) === -1) {
6715 // Only add the new parent to the _parents list if it's not already there.
6716 _parents.push(parent);
6719 Subscription.EMPTY = (function (empty) {
6720 empty.closed = true;
6722 }(new Subscription()));
6723 return Subscription;
6725 exports.Subscription = Subscription;
6726 function flattenUnsubscriptionErrors(errors) {
6727 return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []);
6730 },{"./util/UnsubscriptionError":223,"./util/errorObject":224,"./util/isArray":226,"./util/isFunction":229,"./util/isObject":231,"./util/tryCatch":239}],38:[function(require,module,exports){
6732 var Observable_1 = require('../../Observable');
6733 var combineLatest_1 = require('../../observable/combineLatest');
6734 Observable_1.Observable.combineLatest = combineLatest_1.combineLatest;
6736 },{"../../Observable":29,"../../observable/combineLatest":104}],39:[function(require,module,exports){
6738 var Observable_1 = require('../../Observable');
6739 var concat_1 = require('../../observable/concat');
6740 Observable_1.Observable.concat = concat_1.concat;
6742 },{"../../Observable":29,"../../observable/concat":105}],40:[function(require,module,exports){
6744 var Observable_1 = require('../../Observable');
6745 var defer_1 = require('../../observable/defer');
6746 Observable_1.Observable.defer = defer_1.defer;
6748 },{"../../Observable":29,"../../observable/defer":106}],41:[function(require,module,exports){
6750 var Observable_1 = require('../../Observable');
6751 var empty_1 = require('../../observable/empty');
6752 Observable_1.Observable.empty = empty_1.empty;
6754 },{"../../Observable":29,"../../observable/empty":107}],42:[function(require,module,exports){
6756 var Observable_1 = require('../../Observable');
6757 var from_1 = require('../../observable/from');
6758 Observable_1.Observable.from = from_1.from;
6760 },{"../../Observable":29,"../../observable/from":108}],43:[function(require,module,exports){
6762 var Observable_1 = require('../../Observable');
6763 var fromEvent_1 = require('../../observable/fromEvent');
6764 Observable_1.Observable.fromEvent = fromEvent_1.fromEvent;
6766 },{"../../Observable":29,"../../observable/fromEvent":109}],44:[function(require,module,exports){
6768 var Observable_1 = require('../../Observable');
6769 var fromPromise_1 = require('../../observable/fromPromise');
6770 Observable_1.Observable.fromPromise = fromPromise_1.fromPromise;
6772 },{"../../Observable":29,"../../observable/fromPromise":110}],45:[function(require,module,exports){
6774 var Observable_1 = require('../../Observable');
6775 var merge_1 = require('../../observable/merge');
6776 Observable_1.Observable.merge = merge_1.merge;
6778 },{"../../Observable":29,"../../observable/merge":111}],46:[function(require,module,exports){
6780 var Observable_1 = require('../../Observable');
6781 var of_1 = require('../../observable/of');
6782 Observable_1.Observable.of = of_1.of;
6784 },{"../../Observable":29,"../../observable/of":112}],47:[function(require,module,exports){
6786 var Observable_1 = require('../../Observable');
6787 var throw_1 = require('../../observable/throw');
6788 Observable_1.Observable.throw = throw_1._throw;
6790 },{"../../Observable":29,"../../observable/throw":113}],48:[function(require,module,exports){
6792 var Observable_1 = require('../../Observable');
6793 var timer_1 = require('../../observable/timer');
6794 Observable_1.Observable.timer = timer_1.timer;
6796 },{"../../Observable":29,"../../observable/timer":114}],49:[function(require,module,exports){
6798 var Observable_1 = require('../../Observable');
6799 var zip_1 = require('../../observable/zip');
6800 Observable_1.Observable.zip = zip_1.zip;
6802 },{"../../Observable":29,"../../observable/zip":115}],50:[function(require,module,exports){
6804 var Observable_1 = require('../../Observable');
6805 var auditTime_1 = require('../../operator/auditTime');
6806 Observable_1.Observable.prototype.auditTime = auditTime_1.auditTime;
6808 },{"../../Observable":29,"../../operator/auditTime":116}],51:[function(require,module,exports){
6810 var Observable_1 = require('../../Observable');
6811 var buffer_1 = require('../../operator/buffer');
6812 Observable_1.Observable.prototype.buffer = buffer_1.buffer;
6814 },{"../../Observable":29,"../../operator/buffer":117}],52:[function(require,module,exports){
6816 var Observable_1 = require('../../Observable');
6817 var bufferCount_1 = require('../../operator/bufferCount');
6818 Observable_1.Observable.prototype.bufferCount = bufferCount_1.bufferCount;
6820 },{"../../Observable":29,"../../operator/bufferCount":118}],53:[function(require,module,exports){
6822 var Observable_1 = require('../../Observable');
6823 var bufferWhen_1 = require('../../operator/bufferWhen');
6824 Observable_1.Observable.prototype.bufferWhen = bufferWhen_1.bufferWhen;
6826 },{"../../Observable":29,"../../operator/bufferWhen":119}],54:[function(require,module,exports){
6828 var Observable_1 = require('../../Observable');
6829 var catch_1 = require('../../operator/catch');
6830 Observable_1.Observable.prototype.catch = catch_1._catch;
6831 Observable_1.Observable.prototype._catch = catch_1._catch;
6833 },{"../../Observable":29,"../../operator/catch":120}],55:[function(require,module,exports){
6835 var Observable_1 = require('../../Observable');
6836 var combineLatest_1 = require('../../operator/combineLatest');
6837 Observable_1.Observable.prototype.combineLatest = combineLatest_1.combineLatest;
6839 },{"../../Observable":29,"../../operator/combineLatest":121}],56:[function(require,module,exports){
6841 var Observable_1 = require('../../Observable');
6842 var concat_1 = require('../../operator/concat');
6843 Observable_1.Observable.prototype.concat = concat_1.concat;
6845 },{"../../Observable":29,"../../operator/concat":122}],57:[function(require,module,exports){
6847 var Observable_1 = require('../../Observable');
6848 var count_1 = require('../../operator/count');
6849 Observable_1.Observable.prototype.count = count_1.count;
6851 },{"../../Observable":29,"../../operator/count":123}],58:[function(require,module,exports){
6853 var Observable_1 = require('../../Observable');
6854 var debounceTime_1 = require('../../operator/debounceTime');
6855 Observable_1.Observable.prototype.debounceTime = debounceTime_1.debounceTime;
6857 },{"../../Observable":29,"../../operator/debounceTime":124}],59:[function(require,module,exports){
6859 var Observable_1 = require('../../Observable');
6860 var delay_1 = require('../../operator/delay');
6861 Observable_1.Observable.prototype.delay = delay_1.delay;
6863 },{"../../Observable":29,"../../operator/delay":125}],60:[function(require,module,exports){
6865 var Observable_1 = require('../../Observable');
6866 var distinct_1 = require('../../operator/distinct');
6867 Observable_1.Observable.prototype.distinct = distinct_1.distinct;
6869 },{"../../Observable":29,"../../operator/distinct":126}],61:[function(require,module,exports){
6871 var Observable_1 = require('../../Observable');
6872 var distinctUntilChanged_1 = require('../../operator/distinctUntilChanged');
6873 Observable_1.Observable.prototype.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged;
6875 },{"../../Observable":29,"../../operator/distinctUntilChanged":127}],62:[function(require,module,exports){
6877 var Observable_1 = require('../../Observable');
6878 var do_1 = require('../../operator/do');
6879 Observable_1.Observable.prototype.do = do_1._do;
6880 Observable_1.Observable.prototype._do = do_1._do;
6882 },{"../../Observable":29,"../../operator/do":128}],63:[function(require,module,exports){
6884 var Observable_1 = require('../../Observable');
6885 var expand_1 = require('../../operator/expand');
6886 Observable_1.Observable.prototype.expand = expand_1.expand;
6888 },{"../../Observable":29,"../../operator/expand":129}],64:[function(require,module,exports){
6890 var Observable_1 = require('../../Observable');
6891 var filter_1 = require('../../operator/filter');
6892 Observable_1.Observable.prototype.filter = filter_1.filter;
6894 },{"../../Observable":29,"../../operator/filter":130}],65:[function(require,module,exports){
6896 var Observable_1 = require('../../Observable');
6897 var finally_1 = require('../../operator/finally');
6898 Observable_1.Observable.prototype.finally = finally_1._finally;
6899 Observable_1.Observable.prototype._finally = finally_1._finally;
6901 },{"../../Observable":29,"../../operator/finally":131}],66:[function(require,module,exports){
6903 var Observable_1 = require('../../Observable');
6904 var first_1 = require('../../operator/first');
6905 Observable_1.Observable.prototype.first = first_1.first;
6907 },{"../../Observable":29,"../../operator/first":132}],67:[function(require,module,exports){
6909 var Observable_1 = require('../../Observable');
6910 var last_1 = require('../../operator/last');
6911 Observable_1.Observable.prototype.last = last_1.last;
6913 },{"../../Observable":29,"../../operator/last":133}],68:[function(require,module,exports){
6915 var Observable_1 = require('../../Observable');
6916 var map_1 = require('../../operator/map');
6917 Observable_1.Observable.prototype.map = map_1.map;
6919 },{"../../Observable":29,"../../operator/map":134}],69:[function(require,module,exports){
6921 var Observable_1 = require('../../Observable');
6922 var merge_1 = require('../../operator/merge');
6923 Observable_1.Observable.prototype.merge = merge_1.merge;
6925 },{"../../Observable":29,"../../operator/merge":135}],70:[function(require,module,exports){
6927 var Observable_1 = require('../../Observable');
6928 var mergeAll_1 = require('../../operator/mergeAll');
6929 Observable_1.Observable.prototype.mergeAll = mergeAll_1.mergeAll;
6931 },{"../../Observable":29,"../../operator/mergeAll":136}],71:[function(require,module,exports){
6933 var Observable_1 = require('../../Observable');
6934 var mergeMap_1 = require('../../operator/mergeMap');
6935 Observable_1.Observable.prototype.mergeMap = mergeMap_1.mergeMap;
6936 Observable_1.Observable.prototype.flatMap = mergeMap_1.mergeMap;
6938 },{"../../Observable":29,"../../operator/mergeMap":137}],72:[function(require,module,exports){
6940 var Observable_1 = require('../../Observable');
6941 var pairwise_1 = require('../../operator/pairwise');
6942 Observable_1.Observable.prototype.pairwise = pairwise_1.pairwise;
6944 },{"../../Observable":29,"../../operator/pairwise":138}],73:[function(require,module,exports){
6946 var Observable_1 = require('../../Observable');
6947 var pluck_1 = require('../../operator/pluck');
6948 Observable_1.Observable.prototype.pluck = pluck_1.pluck;
6950 },{"../../Observable":29,"../../operator/pluck":139}],74:[function(require,module,exports){
6952 var Observable_1 = require('../../Observable');
6953 var publish_1 = require('../../operator/publish');
6954 Observable_1.Observable.prototype.publish = publish_1.publish;
6956 },{"../../Observable":29,"../../operator/publish":140}],75:[function(require,module,exports){
6958 var Observable_1 = require('../../Observable');
6959 var publishReplay_1 = require('../../operator/publishReplay');
6960 Observable_1.Observable.prototype.publishReplay = publishReplay_1.publishReplay;
6962 },{"../../Observable":29,"../../operator/publishReplay":141}],76:[function(require,module,exports){
6964 var Observable_1 = require('../../Observable');
6965 var reduce_1 = require('../../operator/reduce');
6966 Observable_1.Observable.prototype.reduce = reduce_1.reduce;
6968 },{"../../Observable":29,"../../operator/reduce":142}],77:[function(require,module,exports){
6970 var Observable_1 = require('../../Observable');
6971 var retry_1 = require('../../operator/retry');
6972 Observable_1.Observable.prototype.retry = retry_1.retry;
6974 },{"../../Observable":29,"../../operator/retry":143}],78:[function(require,module,exports){
6976 var Observable_1 = require('../../Observable');
6977 var sample_1 = require('../../operator/sample');
6978 Observable_1.Observable.prototype.sample = sample_1.sample;
6980 },{"../../Observable":29,"../../operator/sample":144}],79:[function(require,module,exports){
6982 var Observable_1 = require('../../Observable');
6983 var scan_1 = require('../../operator/scan');
6984 Observable_1.Observable.prototype.scan = scan_1.scan;
6986 },{"../../Observable":29,"../../operator/scan":145}],80:[function(require,module,exports){
6988 var Observable_1 = require('../../Observable');
6989 var share_1 = require('../../operator/share');
6990 Observable_1.Observable.prototype.share = share_1.share;
6992 },{"../../Observable":29,"../../operator/share":146}],81:[function(require,module,exports){
6994 var Observable_1 = require('../../Observable');
6995 var skip_1 = require('../../operator/skip');
6996 Observable_1.Observable.prototype.skip = skip_1.skip;
6998 },{"../../Observable":29,"../../operator/skip":147}],82:[function(require,module,exports){
7000 var Observable_1 = require('../../Observable');
7001 var skipUntil_1 = require('../../operator/skipUntil');
7002 Observable_1.Observable.prototype.skipUntil = skipUntil_1.skipUntil;
7004 },{"../../Observable":29,"../../operator/skipUntil":148}],83:[function(require,module,exports){
7006 var Observable_1 = require('../../Observable');
7007 var skipWhile_1 = require('../../operator/skipWhile');
7008 Observable_1.Observable.prototype.skipWhile = skipWhile_1.skipWhile;
7010 },{"../../Observable":29,"../../operator/skipWhile":149}],84:[function(require,module,exports){
7012 var Observable_1 = require('../../Observable');
7013 var startWith_1 = require('../../operator/startWith');
7014 Observable_1.Observable.prototype.startWith = startWith_1.startWith;
7016 },{"../../Observable":29,"../../operator/startWith":150}],85:[function(require,module,exports){
7018 var Observable_1 = require('../../Observable');
7019 var switchMap_1 = require('../../operator/switchMap');
7020 Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap;
7022 },{"../../Observable":29,"../../operator/switchMap":151}],86:[function(require,module,exports){
7024 var Observable_1 = require('../../Observable');
7025 var take_1 = require('../../operator/take');
7026 Observable_1.Observable.prototype.take = take_1.take;
7028 },{"../../Observable":29,"../../operator/take":152}],87:[function(require,module,exports){
7030 var Observable_1 = require('../../Observable');
7031 var takeUntil_1 = require('../../operator/takeUntil');
7032 Observable_1.Observable.prototype.takeUntil = takeUntil_1.takeUntil;
7034 },{"../../Observable":29,"../../operator/takeUntil":153}],88:[function(require,module,exports){
7036 var Observable_1 = require('../../Observable');
7037 var takeWhile_1 = require('../../operator/takeWhile');
7038 Observable_1.Observable.prototype.takeWhile = takeWhile_1.takeWhile;
7040 },{"../../Observable":29,"../../operator/takeWhile":154}],89:[function(require,module,exports){
7042 var Observable_1 = require('../../Observable');
7043 var timeout_1 = require('../../operator/timeout');
7044 Observable_1.Observable.prototype.timeout = timeout_1.timeout;
7046 },{"../../Observable":29,"../../operator/timeout":155}],90:[function(require,module,exports){
7048 var Observable_1 = require('../../Observable');
7049 var withLatestFrom_1 = require('../../operator/withLatestFrom');
7050 Observable_1.Observable.prototype.withLatestFrom = withLatestFrom_1.withLatestFrom;
7052 },{"../../Observable":29,"../../operator/withLatestFrom":156}],91:[function(require,module,exports){
7054 var Observable_1 = require('../../Observable');
7055 var zip_1 = require('../../operator/zip');
7056 Observable_1.Observable.prototype.zip = zip_1.zipProto;
7058 },{"../../Observable":29,"../../operator/zip":157}],92:[function(require,module,exports){
7060 var __extends = (this && this.__extends) || function (d, b) {
7061 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7062 function __() { this.constructor = d; }
7063 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7065 var Observable_1 = require('../Observable');
7066 var ScalarObservable_1 = require('./ScalarObservable');
7067 var EmptyObservable_1 = require('./EmptyObservable');
7069 * We need this JSDoc comment for affecting ESDoc.
7070 * @extends {Ignored}
7073 var ArrayLikeObservable = (function (_super) {
7074 __extends(ArrayLikeObservable, _super);
7075 function ArrayLikeObservable(arrayLike, scheduler) {
7077 this.arrayLike = arrayLike;
7078 this.scheduler = scheduler;
7079 if (!scheduler && arrayLike.length === 1) {
7080 this._isScalar = true;
7081 this.value = arrayLike[0];
7084 ArrayLikeObservable.create = function (arrayLike, scheduler) {
7085 var length = arrayLike.length;
7087 return new EmptyObservable_1.EmptyObservable();
7089 else if (length === 1) {
7090 return new ScalarObservable_1.ScalarObservable(arrayLike[0], scheduler);
7093 return new ArrayLikeObservable(arrayLike, scheduler);
7096 ArrayLikeObservable.dispatch = function (state) {
7097 var arrayLike = state.arrayLike, index = state.index, length = state.length, subscriber = state.subscriber;
7098 if (subscriber.closed) {
7101 if (index >= length) {
7102 subscriber.complete();
7105 subscriber.next(arrayLike[index]);
7106 state.index = index + 1;
7107 this.schedule(state);
7109 ArrayLikeObservable.prototype._subscribe = function (subscriber) {
7111 var _a = this, arrayLike = _a.arrayLike, scheduler = _a.scheduler;
7112 var length = arrayLike.length;
7114 return scheduler.schedule(ArrayLikeObservable.dispatch, 0, {
7115 arrayLike: arrayLike, index: index, length: length, subscriber: subscriber
7119 for (var i = 0; i < length && !subscriber.closed; i++) {
7120 subscriber.next(arrayLike[i]);
7122 subscriber.complete();
7125 return ArrayLikeObservable;
7126 }(Observable_1.Observable));
7127 exports.ArrayLikeObservable = ArrayLikeObservable;
7129 },{"../Observable":29,"./EmptyObservable":96,"./ScalarObservable":102}],93:[function(require,module,exports){
7131 var __extends = (this && this.__extends) || function (d, b) {
7132 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7133 function __() { this.constructor = d; }
7134 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7136 var Observable_1 = require('../Observable');
7137 var ScalarObservable_1 = require('./ScalarObservable');
7138 var EmptyObservable_1 = require('./EmptyObservable');
7139 var isScheduler_1 = require('../util/isScheduler');
7141 * We need this JSDoc comment for affecting ESDoc.
7142 * @extends {Ignored}
7145 var ArrayObservable = (function (_super) {
7146 __extends(ArrayObservable, _super);
7147 function ArrayObservable(array, scheduler) {
7150 this.scheduler = scheduler;
7151 if (!scheduler && array.length === 1) {
7152 this._isScalar = true;
7153 this.value = array[0];
7156 ArrayObservable.create = function (array, scheduler) {
7157 return new ArrayObservable(array, scheduler);
7160 * Creates an Observable that emits some values you specify as arguments,
7161 * immediately one after the other, and then emits a complete notification.
7163 * <span class="informal">Emits the arguments you provide, then completes.
7166 * <img src="./img/of.png" width="100%">
7168 * This static operator is useful for creating a simple Observable that only
7169 * emits the arguments given, and the complete notification thereafter. It can
7170 * be used for composing with other Observables, such as with {@link concat}.
7171 * By default, it uses a `null` IScheduler, which means the `next`
7172 * notifications are sent synchronously, although with a different IScheduler
7173 * it is possible to determine when those notifications will be delivered.
7175 * @example <caption>Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second.</caption>
7176 * var numbers = Rx.Observable.of(10, 20, 30);
7177 * var letters = Rx.Observable.of('a', 'b', 'c');
7178 * var interval = Rx.Observable.interval(1000);
7179 * var result = numbers.concat(letters).concat(interval);
7180 * result.subscribe(x => console.log(x));
7182 * @see {@link create}
7183 * @see {@link empty}
7184 * @see {@link never}
7185 * @see {@link throw}
7187 * @param {...T} values Arguments that represent `next` values to be emitted.
7188 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7189 * the emissions of the `next` notifications.
7190 * @return {Observable<T>} An Observable that emits each given input value.
7195 ArrayObservable.of = function () {
7197 for (var _i = 0; _i < arguments.length; _i++) {
7198 array[_i - 0] = arguments[_i];
7200 var scheduler = array[array.length - 1];
7201 if (isScheduler_1.isScheduler(scheduler)) {
7207 var len = array.length;
7209 return new ArrayObservable(array, scheduler);
7211 else if (len === 1) {
7212 return new ScalarObservable_1.ScalarObservable(array[0], scheduler);
7215 return new EmptyObservable_1.EmptyObservable(scheduler);
7218 ArrayObservable.dispatch = function (state) {
7219 var array = state.array, index = state.index, count = state.count, subscriber = state.subscriber;
7220 if (index >= count) {
7221 subscriber.complete();
7224 subscriber.next(array[index]);
7225 if (subscriber.closed) {
7228 state.index = index + 1;
7229 this.schedule(state);
7231 ArrayObservable.prototype._subscribe = function (subscriber) {
7233 var array = this.array;
7234 var count = array.length;
7235 var scheduler = this.scheduler;
7237 return scheduler.schedule(ArrayObservable.dispatch, 0, {
7238 array: array, index: index, count: count, subscriber: subscriber
7242 for (var i = 0; i < count && !subscriber.closed; i++) {
7243 subscriber.next(array[i]);
7245 subscriber.complete();
7248 return ArrayObservable;
7249 }(Observable_1.Observable));
7250 exports.ArrayObservable = ArrayObservable;
7252 },{"../Observable":29,"../util/isScheduler":233,"./EmptyObservable":96,"./ScalarObservable":102}],94:[function(require,module,exports){
7254 var __extends = (this && this.__extends) || function (d, b) {
7255 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7256 function __() { this.constructor = d; }
7257 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7259 var Subject_1 = require('../Subject');
7260 var Observable_1 = require('../Observable');
7261 var Subscriber_1 = require('../Subscriber');
7262 var Subscription_1 = require('../Subscription');
7263 var refCount_1 = require('../operators/refCount');
7265 * @class ConnectableObservable<T>
7267 var ConnectableObservable = (function (_super) {
7268 __extends(ConnectableObservable, _super);
7269 function ConnectableObservable(source, subjectFactory) {
7271 this.source = source;
7272 this.subjectFactory = subjectFactory;
7274 this._isComplete = false;
7276 ConnectableObservable.prototype._subscribe = function (subscriber) {
7277 return this.getSubject().subscribe(subscriber);
7279 ConnectableObservable.prototype.getSubject = function () {
7280 var subject = this._subject;
7281 if (!subject || subject.isStopped) {
7282 this._subject = this.subjectFactory();
7284 return this._subject;
7286 ConnectableObservable.prototype.connect = function () {
7287 var connection = this._connection;
7289 this._isComplete = false;
7290 connection = this._connection = new Subscription_1.Subscription();
7291 connection.add(this.source
7292 .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
7293 if (connection.closed) {
7294 this._connection = null;
7295 connection = Subscription_1.Subscription.EMPTY;
7298 this._connection = connection;
7303 ConnectableObservable.prototype.refCount = function () {
7304 return refCount_1.refCount()(this);
7306 return ConnectableObservable;
7307 }(Observable_1.Observable));
7308 exports.ConnectableObservable = ConnectableObservable;
7309 var connectableProto = ConnectableObservable.prototype;
7310 exports.connectableObservableDescriptor = {
7311 operator: { value: null },
7312 _refCount: { value: 0, writable: true },
7313 _subject: { value: null, writable: true },
7314 _connection: { value: null, writable: true },
7315 _subscribe: { value: connectableProto._subscribe },
7316 _isComplete: { value: connectableProto._isComplete, writable: true },
7317 getSubject: { value: connectableProto.getSubject },
7318 connect: { value: connectableProto.connect },
7319 refCount: { value: connectableProto.refCount }
7321 var ConnectableSubscriber = (function (_super) {
7322 __extends(ConnectableSubscriber, _super);
7323 function ConnectableSubscriber(destination, connectable) {
7324 _super.call(this, destination);
7325 this.connectable = connectable;
7327 ConnectableSubscriber.prototype._error = function (err) {
7328 this._unsubscribe();
7329 _super.prototype._error.call(this, err);
7331 ConnectableSubscriber.prototype._complete = function () {
7332 this.connectable._isComplete = true;
7333 this._unsubscribe();
7334 _super.prototype._complete.call(this);
7336 ConnectableSubscriber.prototype._unsubscribe = function () {
7337 var connectable = this.connectable;
7339 this.connectable = null;
7340 var connection = connectable._connection;
7341 connectable._refCount = 0;
7342 connectable._subject = null;
7343 connectable._connection = null;
7345 connection.unsubscribe();
7349 return ConnectableSubscriber;
7350 }(Subject_1.SubjectSubscriber));
7351 var RefCountOperator = (function () {
7352 function RefCountOperator(connectable) {
7353 this.connectable = connectable;
7355 RefCountOperator.prototype.call = function (subscriber, source) {
7356 var connectable = this.connectable;
7357 connectable._refCount++;
7358 var refCounter = new RefCountSubscriber(subscriber, connectable);
7359 var subscription = source.subscribe(refCounter);
7360 if (!refCounter.closed) {
7361 refCounter.connection = connectable.connect();
7363 return subscription;
7365 return RefCountOperator;
7367 var RefCountSubscriber = (function (_super) {
7368 __extends(RefCountSubscriber, _super);
7369 function RefCountSubscriber(destination, connectable) {
7370 _super.call(this, destination);
7371 this.connectable = connectable;
7373 RefCountSubscriber.prototype._unsubscribe = function () {
7374 var connectable = this.connectable;
7376 this.connection = null;
7379 this.connectable = null;
7380 var refCount = connectable._refCount;
7381 if (refCount <= 0) {
7382 this.connection = null;
7385 connectable._refCount = refCount - 1;
7387 this.connection = null;
7391 // Compare the local RefCountSubscriber's connection Subscription to the
7392 // connection Subscription on the shared ConnectableObservable. In cases
7393 // where the ConnectableObservable source synchronously emits values, and
7394 // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
7395 // execution continues to here before the RefCountOperator has a chance to
7396 // supply the RefCountSubscriber with the shared connection Subscription.
7399 // Observable.range(0, 10)
7405 // In order to account for this case, RefCountSubscriber should only dispose
7406 // the ConnectableObservable's shared connection Subscription if the
7407 // connection Subscription exists, *and* either:
7408 // a. RefCountSubscriber doesn't have a reference to the shared connection
7409 // Subscription yet, or,
7410 // b. RefCountSubscriber's connection Subscription reference is identical
7411 // to the shared connection Subscription
7413 var connection = this.connection;
7414 var sharedConnection = connectable._connection;
7415 this.connection = null;
7416 if (sharedConnection && (!connection || sharedConnection === connection)) {
7417 sharedConnection.unsubscribe();
7420 return RefCountSubscriber;
7421 }(Subscriber_1.Subscriber));
7423 },{"../Observable":29,"../Subject":34,"../Subscriber":36,"../Subscription":37,"../operators/refCount":189}],95:[function(require,module,exports){
7425 var __extends = (this && this.__extends) || function (d, b) {
7426 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7427 function __() { this.constructor = d; }
7428 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7430 var Observable_1 = require('../Observable');
7431 var subscribeToResult_1 = require('../util/subscribeToResult');
7432 var OuterSubscriber_1 = require('../OuterSubscriber');
7434 * We need this JSDoc comment for affecting ESDoc.
7435 * @extends {Ignored}
7438 var DeferObservable = (function (_super) {
7439 __extends(DeferObservable, _super);
7440 function DeferObservable(observableFactory) {
7442 this.observableFactory = observableFactory;
7445 * Creates an Observable that, on subscribe, calls an Observable factory to
7446 * make an Observable for each new Observer.
7448 * <span class="informal">Creates the Observable lazily, that is, only when it
7452 * <img src="./img/defer.png" width="100%">
7454 * `defer` allows you to create the Observable only when the Observer
7455 * subscribes, and create a fresh Observable for each Observer. It waits until
7456 * an Observer subscribes to it, and then it generates an Observable,
7457 * typically with an Observable factory function. It does this afresh for each
7458 * subscriber, so although each subscriber may think it is subscribing to the
7459 * same Observable, in fact each subscriber gets its own individual
7462 * @example <caption>Subscribe to either an Observable of clicks or an Observable of interval, at random</caption>
7463 * var clicksOrInterval = Rx.Observable.defer(function () {
7464 * if (Math.random() > 0.5) {
7465 * return Rx.Observable.fromEvent(document, 'click');
7467 * return Rx.Observable.interval(1000);
7470 * clicksOrInterval.subscribe(x => console.log(x));
7472 * // Results in the following behavior:
7473 * // If the result of Math.random() is greater than 0.5 it will listen
7474 * // for clicks anywhere on the "document"; when document is clicked it
7475 * // will log a MouseEvent object to the console. If the result is less
7476 * // than 0.5 it will emit ascending numbers, one every second(1000ms).
7478 * @see {@link create}
7480 * @param {function(): SubscribableOrPromise} observableFactory The Observable
7481 * factory function to invoke for each Observer that subscribes to the output
7482 * Observable. May also return a Promise, which will be converted on the fly
7484 * @return {Observable} An Observable whose Observers' subscriptions trigger
7485 * an invocation of the given Observable factory function.
7490 DeferObservable.create = function (observableFactory) {
7491 return new DeferObservable(observableFactory);
7493 DeferObservable.prototype._subscribe = function (subscriber) {
7494 return new DeferSubscriber(subscriber, this.observableFactory);
7496 return DeferObservable;
7497 }(Observable_1.Observable));
7498 exports.DeferObservable = DeferObservable;
7499 var DeferSubscriber = (function (_super) {
7500 __extends(DeferSubscriber, _super);
7501 function DeferSubscriber(destination, factory) {
7502 _super.call(this, destination);
7503 this.factory = factory;
7506 DeferSubscriber.prototype.tryDefer = function () {
7508 this._callFactory();
7514 DeferSubscriber.prototype._callFactory = function () {
7515 var result = this.factory();
7517 this.add(subscribeToResult_1.subscribeToResult(this, result));
7520 return DeferSubscriber;
7521 }(OuterSubscriber_1.OuterSubscriber));
7523 },{"../Observable":29,"../OuterSubscriber":31,"../util/subscribeToResult":237}],96:[function(require,module,exports){
7525 var __extends = (this && this.__extends) || function (d, b) {
7526 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7527 function __() { this.constructor = d; }
7528 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7530 var Observable_1 = require('../Observable');
7532 * We need this JSDoc comment for affecting ESDoc.
7533 * @extends {Ignored}
7536 var EmptyObservable = (function (_super) {
7537 __extends(EmptyObservable, _super);
7538 function EmptyObservable(scheduler) {
7540 this.scheduler = scheduler;
7543 * Creates an Observable that emits no items to the Observer and immediately
7544 * emits a complete notification.
7546 * <span class="informal">Just emits 'complete', and nothing else.
7549 * <img src="./img/empty.png" width="100%">
7551 * This static operator is useful for creating a simple Observable that only
7552 * emits the complete notification. It can be used for composing with other
7553 * Observables, such as in a {@link mergeMap}.
7555 * @example <caption>Emit the number 7, then complete.</caption>
7556 * var result = Rx.Observable.empty().startWith(7);
7557 * result.subscribe(x => console.log(x));
7559 * @example <caption>Map and flatten only odd numbers to the sequence 'a', 'b', 'c'</caption>
7560 * var interval = Rx.Observable.interval(1000);
7561 * var result = interval.mergeMap(x =>
7562 * x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.empty()
7564 * result.subscribe(x => console.log(x));
7566 * // Results in the following to the console:
7567 * // x is equal to the count on the interval eg(0,1,2,3,...)
7568 * // x will occur every 1000ms
7569 * // if x % 2 is equal to 1 print abc
7570 * // if x % 2 is not equal to 1 nothing will be output
7572 * @see {@link create}
7573 * @see {@link never}
7575 * @see {@link throw}
7577 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7578 * the emission of the complete notification.
7579 * @return {Observable} An "empty" Observable: emits only the complete
7585 EmptyObservable.create = function (scheduler) {
7586 return new EmptyObservable(scheduler);
7588 EmptyObservable.dispatch = function (arg) {
7589 var subscriber = arg.subscriber;
7590 subscriber.complete();
7592 EmptyObservable.prototype._subscribe = function (subscriber) {
7593 var scheduler = this.scheduler;
7595 return scheduler.schedule(EmptyObservable.dispatch, 0, { subscriber: subscriber });
7598 subscriber.complete();
7601 return EmptyObservable;
7602 }(Observable_1.Observable));
7603 exports.EmptyObservable = EmptyObservable;
7605 },{"../Observable":29}],97:[function(require,module,exports){
7607 var __extends = (this && this.__extends) || function (d, b) {
7608 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7609 function __() { this.constructor = d; }
7610 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7612 var Observable_1 = require('../Observable');
7614 * We need this JSDoc comment for affecting ESDoc.
7615 * @extends {Ignored}
7618 var ErrorObservable = (function (_super) {
7619 __extends(ErrorObservable, _super);
7620 function ErrorObservable(error, scheduler) {
7623 this.scheduler = scheduler;
7626 * Creates an Observable that emits no items to the Observer and immediately
7627 * emits an error notification.
7629 * <span class="informal">Just emits 'error', and nothing else.
7632 * <img src="./img/throw.png" width="100%">
7634 * This static operator is useful for creating a simple Observable that only
7635 * emits the error notification. It can be used for composing with other
7636 * Observables, such as in a {@link mergeMap}.
7638 * @example <caption>Emit the number 7, then emit an error.</caption>
7639 * var result = Rx.Observable.throw(new Error('oops!')).startWith(7);
7640 * result.subscribe(x => console.log(x), e => console.error(e));
7642 * @example <caption>Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 13</caption>
7643 * var interval = Rx.Observable.interval(1000);
7644 * var result = interval.mergeMap(x =>
7646 * Rx.Observable.throw('Thirteens are bad') :
7647 * Rx.Observable.of('a', 'b', 'c')
7649 * result.subscribe(x => console.log(x), e => console.error(e));
7651 * @see {@link create}
7652 * @see {@link empty}
7653 * @see {@link never}
7656 * @param {any} error The particular Error to pass to the error notification.
7657 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7658 * the emission of the error notification.
7659 * @return {Observable} An error Observable: emits only the error notification
7660 * using the given error argument.
7665 ErrorObservable.create = function (error, scheduler) {
7666 return new ErrorObservable(error, scheduler);
7668 ErrorObservable.dispatch = function (arg) {
7669 var error = arg.error, subscriber = arg.subscriber;
7670 subscriber.error(error);
7672 ErrorObservable.prototype._subscribe = function (subscriber) {
7673 var error = this.error;
7674 var scheduler = this.scheduler;
7675 subscriber.syncErrorThrowable = true;
7677 return scheduler.schedule(ErrorObservable.dispatch, 0, {
7678 error: error, subscriber: subscriber
7682 subscriber.error(error);
7685 return ErrorObservable;
7686 }(Observable_1.Observable));
7687 exports.ErrorObservable = ErrorObservable;
7689 },{"../Observable":29}],98:[function(require,module,exports){
7691 var __extends = (this && this.__extends) || function (d, b) {
7692 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7693 function __() { this.constructor = d; }
7694 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7696 var Observable_1 = require('../Observable');
7697 var tryCatch_1 = require('../util/tryCatch');
7698 var isFunction_1 = require('../util/isFunction');
7699 var errorObject_1 = require('../util/errorObject');
7700 var Subscription_1 = require('../Subscription');
7701 var toString = Object.prototype.toString;
7702 function isNodeStyleEventEmitter(sourceObj) {
7703 return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
7705 function isJQueryStyleEventEmitter(sourceObj) {
7706 return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
7708 function isNodeList(sourceObj) {
7709 return !!sourceObj && toString.call(sourceObj) === '[object NodeList]';
7711 function isHTMLCollection(sourceObj) {
7712 return !!sourceObj && toString.call(sourceObj) === '[object HTMLCollection]';
7714 function isEventTarget(sourceObj) {
7715 return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
7718 * We need this JSDoc comment for affecting ESDoc.
7719 * @extends {Ignored}
7722 var FromEventObservable = (function (_super) {
7723 __extends(FromEventObservable, _super);
7724 function FromEventObservable(sourceObj, eventName, selector, options) {
7726 this.sourceObj = sourceObj;
7727 this.eventName = eventName;
7728 this.selector = selector;
7729 this.options = options;
7731 /* tslint:enable:max-line-length */
7733 * Creates an Observable that emits events of a specific type coming from the
7734 * given event target.
7736 * <span class="informal">Creates an Observable from DOM events, or Node.js
7737 * EventEmitter events or others.</span>
7739 * <img src="./img/fromEvent.png" width="100%">
7741 * `fromEvent` accepts as a first argument event target, which is an object with methods
7742 * for registering event handler functions. As a second argument it takes string that indicates
7743 * type of event we want to listen for. `fromEvent` supports selected types of event targets,
7744 * which are described in detail below. If your event target does not match any of the ones listed,
7745 * you should use {@link fromEventPattern}, which can be used on arbitrary APIs.
7746 * When it comes to APIs supported by `fromEvent`, their methods for adding and removing event
7747 * handler functions have different names, but they all accept a string describing event type
7748 * and function itself, which will be called whenever said event happens.
7750 * Every time resulting Observable is subscribed, event handler function will be registered
7751 * to event target on given event type. When that event fires, value
7752 * passed as a first argument to registered function will be emitted by output Observable.
7753 * When Observable is unsubscribed, function will be unregistered from event target.
7755 * Note that if event target calls registered function with more than one argument, second
7756 * and following arguments will not appear in resulting stream. In order to get access to them,
7757 * you can pass to `fromEvent` optional project function, which will be called with all arguments
7758 * passed to event handler. Output Observable will then emit value returned by project function,
7759 * instead of the usual value.
7761 * Remember that event targets listed below are checked via duck typing. It means that
7762 * no matter what kind of object you have and no matter what environment you work in,
7763 * you can safely use `fromEvent` on that object if it exposes described methods (provided
7764 * of course they behave as was described above). So for example if Node.js library exposes
7765 * event target which has the same method names as DOM EventTarget, `fromEvent` is still
7768 * If the API you use is more callback then event handler oriented (subscribed
7769 * callback function fires only once and thus there is no need to manually
7770 * unregister it), you should use {@link bindCallback} or {@link bindNodeCallback}
7773 * `fromEvent` supports following types of event targets:
7775 * **DOM EventTarget**
7777 * This is an object with `addEventListener` and `removeEventListener` methods.
7779 * In the browser, `addEventListener` accepts - apart from event type string and event
7780 * handler function arguments - optional third parameter, which is either an object or boolean,
7781 * both used for additional configuration how and when passed function will be called. When
7782 * `fromEvent` is used with event target of that type, you can provide this values
7783 * as third parameter as well.
7785 * **Node.js EventEmitter**
7787 * An object with `addListener` and `removeListener` methods.
7789 * **JQuery-style event target**
7791 * An object with `on` and `off` methods
7795 * List of DOM Nodes, returned for example by `document.querySelectorAll` or `Node.childNodes`.
7797 * Although this collection is not event target in itself, `fromEvent` will iterate over all Nodes
7798 * it contains and install event handler function in every of them. When returned Observable
7799 * is unsubscribed, function will be removed from all Nodes.
7801 * **DOM HtmlCollection**
7803 * Just as in case of NodeList it is a collection of DOM nodes. Here as well event handler function is
7804 * installed and removed in each of elements.
7807 * @example <caption>Emits clicks happening on the DOM document</caption>
7808 * var clicks = Rx.Observable.fromEvent(document, 'click');
7809 * clicks.subscribe(x => console.log(x));
7812 * // MouseEvent object logged to console every time a click
7813 * // occurs on the document.
7816 * @example <caption>Use addEventListener with capture option</caption>
7817 * var clicksInDocument = Rx.Observable.fromEvent(document, 'click', true); // note optional configuration parameter
7818 * // which will be passed to addEventListener
7819 * var clicksInDiv = Rx.Observable.fromEvent(someDivInDocument, 'click');
7821 * clicksInDocument.subscribe(() => console.log('document'));
7822 * clicksInDiv.subscribe(() => console.log('div'));
7824 * // By default events bubble UP in DOM tree, so normally
7825 * // when we would click on div in document
7826 * // "div" would be logged first and then "document".
7827 * // Since we specified optional `capture` option, document
7828 * // will catch event when it goes DOWN DOM tree, so console
7829 * // will log "document" and then "div".
7831 * @see {@link bindCallback}
7832 * @see {@link bindNodeCallback}
7833 * @see {@link fromEventPattern}
7835 * @param {EventTargetLike} target The DOM EventTarget, Node.js
7836 * EventEmitter, JQuery-like event target, NodeList or HTMLCollection to attach the event handler to.
7837 * @param {string} eventName The event name of interest, being emitted by the
7839 * @param {EventListenerOptions} [options] Options to pass through to addEventListener
7840 * @param {SelectorMethodSignature<T>} [selector] An optional function to
7841 * post-process results. It takes the arguments from the event handler and
7842 * should return a single value.
7843 * @return {Observable<T>}
7848 FromEventObservable.create = function (target, eventName, options, selector) {
7849 if (isFunction_1.isFunction(options)) {
7851 options = undefined;
7853 return new FromEventObservable(target, eventName, selector, options);
7855 FromEventObservable.setupSubscription = function (sourceObj, eventName, handler, subscriber, options) {
7857 if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
7858 for (var i = 0, len = sourceObj.length; i < len; i++) {
7859 FromEventObservable.setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
7862 else if (isEventTarget(sourceObj)) {
7863 var source_1 = sourceObj;
7864 sourceObj.addEventListener(eventName, handler, options);
7865 unsubscribe = function () { return source_1.removeEventListener(eventName, handler); };
7867 else if (isJQueryStyleEventEmitter(sourceObj)) {
7868 var source_2 = sourceObj;
7869 sourceObj.on(eventName, handler);
7870 unsubscribe = function () { return source_2.off(eventName, handler); };
7872 else if (isNodeStyleEventEmitter(sourceObj)) {
7873 var source_3 = sourceObj;
7874 sourceObj.addListener(eventName, handler);
7875 unsubscribe = function () { return source_3.removeListener(eventName, handler); };
7878 throw new TypeError('Invalid event target');
7880 subscriber.add(new Subscription_1.Subscription(unsubscribe));
7882 FromEventObservable.prototype._subscribe = function (subscriber) {
7883 var sourceObj = this.sourceObj;
7884 var eventName = this.eventName;
7885 var options = this.options;
7886 var selector = this.selector;
7887 var handler = selector ? function () {
7889 for (var _i = 0; _i < arguments.length; _i++) {
7890 args[_i - 0] = arguments[_i];
7892 var result = tryCatch_1.tryCatch(selector).apply(void 0, args);
7893 if (result === errorObject_1.errorObject) {
7894 subscriber.error(errorObject_1.errorObject.e);
7897 subscriber.next(result);
7899 } : function (e) { return subscriber.next(e); };
7900 FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber, options);
7902 return FromEventObservable;
7903 }(Observable_1.Observable));
7904 exports.FromEventObservable = FromEventObservable;
7906 },{"../Observable":29,"../Subscription":37,"../util/errorObject":224,"../util/isFunction":229,"../util/tryCatch":239}],99:[function(require,module,exports){
7908 var __extends = (this && this.__extends) || function (d, b) {
7909 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7910 function __() { this.constructor = d; }
7911 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7913 var isArray_1 = require('../util/isArray');
7914 var isArrayLike_1 = require('../util/isArrayLike');
7915 var isPromise_1 = require('../util/isPromise');
7916 var PromiseObservable_1 = require('./PromiseObservable');
7917 var IteratorObservable_1 = require('./IteratorObservable');
7918 var ArrayObservable_1 = require('./ArrayObservable');
7919 var ArrayLikeObservable_1 = require('./ArrayLikeObservable');
7920 var iterator_1 = require('../symbol/iterator');
7921 var Observable_1 = require('../Observable');
7922 var observeOn_1 = require('../operators/observeOn');
7923 var observable_1 = require('../symbol/observable');
7925 * We need this JSDoc comment for affecting ESDoc.
7926 * @extends {Ignored}
7929 var FromObservable = (function (_super) {
7930 __extends(FromObservable, _super);
7931 function FromObservable(ish, scheduler) {
7932 _super.call(this, null);
7934 this.scheduler = scheduler;
7937 * Creates an Observable from an Array, an array-like object, a Promise, an
7938 * iterable object, or an Observable-like object.
7940 * <span class="informal">Converts almost anything to an Observable.</span>
7942 * <img src="./img/from.png" width="100%">
7944 * Convert various other objects and data types into Observables. `from`
7945 * converts a Promise or an array-like or an
7946 * [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)
7947 * object into an Observable that emits the items in that promise or array or
7948 * iterable. A String, in this context, is treated as an array of characters.
7949 * Observable-like objects (contains a function named with the ES2015 Symbol
7950 * for Observable) can also be converted through this operator.
7952 * @example <caption>Converts an array to an Observable</caption>
7953 * var array = [10, 20, 30];
7954 * var result = Rx.Observable.from(array);
7955 * result.subscribe(x => console.log(x));
7957 * // Results in the following:
7960 * @example <caption>Convert an infinite iterable (from a generator) to an Observable</caption>
7961 * function* generateDoubles(seed) {
7965 * i = 2 * i; // double it
7969 * var iterator = generateDoubles(3);
7970 * var result = Rx.Observable.from(iterator).take(10);
7971 * result.subscribe(x => console.log(x));
7973 * // Results in the following:
7974 * // 3 6 12 24 48 96 192 384 768 1536
7976 * @see {@link create}
7977 * @see {@link fromEvent}
7978 * @see {@link fromEventPattern}
7979 * @see {@link fromPromise}
7981 * @param {ObservableInput<T>} ish A subscribable object, a Promise, an
7982 * Observable-like, an Array, an iterable or an array-like object to be
7984 * @param {Scheduler} [scheduler] The scheduler on which to schedule the
7985 * emissions of values.
7986 * @return {Observable<T>} The Observable whose values are originally from the
7987 * input object that was converted.
7992 FromObservable.create = function (ish, scheduler) {
7994 if (typeof ish[observable_1.observable] === 'function') {
7995 if (ish instanceof Observable_1.Observable && !scheduler) {
7998 return new FromObservable(ish, scheduler);
8000 else if (isArray_1.isArray(ish)) {
8001 return new ArrayObservable_1.ArrayObservable(ish, scheduler);
8003 else if (isPromise_1.isPromise(ish)) {
8004 return new PromiseObservable_1.PromiseObservable(ish, scheduler);
8006 else if (typeof ish[iterator_1.iterator] === 'function' || typeof ish === 'string') {
8007 return new IteratorObservable_1.IteratorObservable(ish, scheduler);
8009 else if (isArrayLike_1.isArrayLike(ish)) {
8010 return new ArrayLikeObservable_1.ArrayLikeObservable(ish, scheduler);
8013 throw new TypeError((ish !== null && typeof ish || ish) + ' is not observable');
8015 FromObservable.prototype._subscribe = function (subscriber) {
8017 var scheduler = this.scheduler;
8018 if (scheduler == null) {
8019 return ish[observable_1.observable]().subscribe(subscriber);
8022 return ish[observable_1.observable]().subscribe(new observeOn_1.ObserveOnSubscriber(subscriber, scheduler, 0));
8025 return FromObservable;
8026 }(Observable_1.Observable));
8027 exports.FromObservable = FromObservable;
8029 },{"../Observable":29,"../operators/observeOn":183,"../symbol/iterator":214,"../symbol/observable":215,"../util/isArray":226,"../util/isArrayLike":227,"../util/isPromise":232,"./ArrayLikeObservable":92,"./ArrayObservable":93,"./IteratorObservable":100,"./PromiseObservable":101}],100:[function(require,module,exports){
8031 var __extends = (this && this.__extends) || function (d, b) {
8032 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8033 function __() { this.constructor = d; }
8034 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8036 var root_1 = require('../util/root');
8037 var Observable_1 = require('../Observable');
8038 var iterator_1 = require('../symbol/iterator');
8040 * We need this JSDoc comment for affecting ESDoc.
8041 * @extends {Ignored}
8044 var IteratorObservable = (function (_super) {
8045 __extends(IteratorObservable, _super);
8046 function IteratorObservable(iterator, scheduler) {
8048 this.scheduler = scheduler;
8049 if (iterator == null) {
8050 throw new Error('iterator cannot be null.');
8052 this.iterator = getIterator(iterator);
8054 IteratorObservable.create = function (iterator, scheduler) {
8055 return new IteratorObservable(iterator, scheduler);
8057 IteratorObservable.dispatch = function (state) {
8058 var index = state.index, hasError = state.hasError, iterator = state.iterator, subscriber = state.subscriber;
8060 subscriber.error(state.error);
8063 var result = iterator.next();
8065 subscriber.complete();
8068 subscriber.next(result.value);
8069 state.index = index + 1;
8070 if (subscriber.closed) {
8071 if (typeof iterator.return === 'function') {
8076 this.schedule(state);
8078 IteratorObservable.prototype._subscribe = function (subscriber) {
8080 var _a = this, iterator = _a.iterator, scheduler = _a.scheduler;
8082 return scheduler.schedule(IteratorObservable.dispatch, 0, {
8083 index: index, iterator: iterator, subscriber: subscriber
8088 var result = iterator.next();
8090 subscriber.complete();
8094 subscriber.next(result.value);
8096 if (subscriber.closed) {
8097 if (typeof iterator.return === 'function') {
8105 return IteratorObservable;
8106 }(Observable_1.Observable));
8107 exports.IteratorObservable = IteratorObservable;
8108 var StringIterator = (function () {
8109 function StringIterator(str, idx, len) {
8110 if (idx === void 0) { idx = 0; }
8111 if (len === void 0) { len = str.length; }
8116 StringIterator.prototype[iterator_1.iterator] = function () { return (this); };
8117 StringIterator.prototype.next = function () {
8118 return this.idx < this.len ? {
8120 value: this.str.charAt(this.idx++)
8126 return StringIterator;
8128 var ArrayIterator = (function () {
8129 function ArrayIterator(arr, idx, len) {
8130 if (idx === void 0) { idx = 0; }
8131 if (len === void 0) { len = toLength(arr); }
8136 ArrayIterator.prototype[iterator_1.iterator] = function () { return this; };
8137 ArrayIterator.prototype.next = function () {
8138 return this.idx < this.len ? {
8140 value: this.arr[this.idx++]
8146 return ArrayIterator;
8148 function getIterator(obj) {
8149 var i = obj[iterator_1.iterator];
8150 if (!i && typeof obj === 'string') {
8151 return new StringIterator(obj);
8153 if (!i && obj.length !== undefined) {
8154 return new ArrayIterator(obj);
8157 throw new TypeError('object is not iterable');
8159 return obj[iterator_1.iterator]();
8161 var maxSafeInteger = Math.pow(2, 53) - 1;
8162 function toLength(o) {
8163 var len = +o.length;
8167 if (len === 0 || !numberIsFinite(len)) {
8170 len = sign(len) * Math.floor(Math.abs(len));
8174 if (len > maxSafeInteger) {
8175 return maxSafeInteger;
8179 function numberIsFinite(value) {
8180 return typeof value === 'number' && root_1.root.isFinite(value);
8182 function sign(value) {
8183 var valueAsNumber = +value;
8184 if (valueAsNumber === 0) {
8185 return valueAsNumber;
8187 if (isNaN(valueAsNumber)) {
8188 return valueAsNumber;
8190 return valueAsNumber < 0 ? -1 : 1;
8193 },{"../Observable":29,"../symbol/iterator":214,"../util/root":236}],101:[function(require,module,exports){
8195 var __extends = (this && this.__extends) || function (d, b) {
8196 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8197 function __() { this.constructor = d; }
8198 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8200 var root_1 = require('../util/root');
8201 var Observable_1 = require('../Observable');
8203 * We need this JSDoc comment for affecting ESDoc.
8204 * @extends {Ignored}
8207 var PromiseObservable = (function (_super) {
8208 __extends(PromiseObservable, _super);
8209 function PromiseObservable(promise, scheduler) {
8211 this.promise = promise;
8212 this.scheduler = scheduler;
8215 * Converts a Promise to an Observable.
8217 * <span class="informal">Returns an Observable that just emits the Promise's
8218 * resolved value, then completes.</span>
8220 * Converts an ES2015 Promise or a Promises/A+ spec compliant Promise to an
8221 * Observable. If the Promise resolves with a value, the output Observable
8222 * emits that resolved value as a `next`, and then completes. If the Promise
8223 * is rejected, then the output Observable emits the corresponding Error.
8225 * @example <caption>Convert the Promise returned by Fetch to an Observable</caption>
8226 * var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
8227 * result.subscribe(x => console.log(x), e => console.error(e));
8229 * @see {@link bindCallback}
8232 * @param {PromiseLike<T>} promise The promise to be converted.
8233 * @param {Scheduler} [scheduler] An optional IScheduler to use for scheduling
8234 * the delivery of the resolved value (or the rejection).
8235 * @return {Observable<T>} An Observable which wraps the Promise.
8240 PromiseObservable.create = function (promise, scheduler) {
8241 return new PromiseObservable(promise, scheduler);
8243 PromiseObservable.prototype._subscribe = function (subscriber) {
8245 var promise = this.promise;
8246 var scheduler = this.scheduler;
8247 if (scheduler == null) {
8248 if (this._isScalar) {
8249 if (!subscriber.closed) {
8250 subscriber.next(this.value);
8251 subscriber.complete();
8255 promise.then(function (value) {
8256 _this.value = value;
8257 _this._isScalar = true;
8258 if (!subscriber.closed) {
8259 subscriber.next(value);
8260 subscriber.complete();
8263 if (!subscriber.closed) {
8264 subscriber.error(err);
8267 .then(null, function (err) {
8268 // escape the promise trap, throw unhandled errors
8269 root_1.root.setTimeout(function () { throw err; });
8274 if (this._isScalar) {
8275 if (!subscriber.closed) {
8276 return scheduler.schedule(dispatchNext, 0, { value: this.value, subscriber: subscriber });
8280 promise.then(function (value) {
8281 _this.value = value;
8282 _this._isScalar = true;
8283 if (!subscriber.closed) {
8284 subscriber.add(scheduler.schedule(dispatchNext, 0, { value: value, subscriber: subscriber }));
8287 if (!subscriber.closed) {
8288 subscriber.add(scheduler.schedule(dispatchError, 0, { err: err, subscriber: subscriber }));
8291 .then(null, function (err) {
8292 // escape the promise trap, throw unhandled errors
8293 root_1.root.setTimeout(function () { throw err; });
8298 return PromiseObservable;
8299 }(Observable_1.Observable));
8300 exports.PromiseObservable = PromiseObservable;
8301 function dispatchNext(arg) {
8302 var value = arg.value, subscriber = arg.subscriber;
8303 if (!subscriber.closed) {
8304 subscriber.next(value);
8305 subscriber.complete();
8308 function dispatchError(arg) {
8309 var err = arg.err, subscriber = arg.subscriber;
8310 if (!subscriber.closed) {
8311 subscriber.error(err);
8315 },{"../Observable":29,"../util/root":236}],102:[function(require,module,exports){
8317 var __extends = (this && this.__extends) || function (d, b) {
8318 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8319 function __() { this.constructor = d; }
8320 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8322 var Observable_1 = require('../Observable');
8324 * We need this JSDoc comment for affecting ESDoc.
8325 * @extends {Ignored}
8328 var ScalarObservable = (function (_super) {
8329 __extends(ScalarObservable, _super);
8330 function ScalarObservable(value, scheduler) {
8333 this.scheduler = scheduler;
8334 this._isScalar = true;
8336 this._isScalar = false;
8339 ScalarObservable.create = function (value, scheduler) {
8340 return new ScalarObservable(value, scheduler);
8342 ScalarObservable.dispatch = function (state) {
8343 var done = state.done, value = state.value, subscriber = state.subscriber;
8345 subscriber.complete();
8348 subscriber.next(value);
8349 if (subscriber.closed) {
8353 this.schedule(state);
8355 ScalarObservable.prototype._subscribe = function (subscriber) {
8356 var value = this.value;
8357 var scheduler = this.scheduler;
8359 return scheduler.schedule(ScalarObservable.dispatch, 0, {
8360 done: false, value: value, subscriber: subscriber
8364 subscriber.next(value);
8365 if (!subscriber.closed) {
8366 subscriber.complete();
8370 return ScalarObservable;
8371 }(Observable_1.Observable));
8372 exports.ScalarObservable = ScalarObservable;
8374 },{"../Observable":29}],103:[function(require,module,exports){
8376 var __extends = (this && this.__extends) || function (d, b) {
8377 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8378 function __() { this.constructor = d; }
8379 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8381 var isNumeric_1 = require('../util/isNumeric');
8382 var Observable_1 = require('../Observable');
8383 var async_1 = require('../scheduler/async');
8384 var isScheduler_1 = require('../util/isScheduler');
8385 var isDate_1 = require('../util/isDate');
8387 * We need this JSDoc comment for affecting ESDoc.
8388 * @extends {Ignored}
8391 var TimerObservable = (function (_super) {
8392 __extends(TimerObservable, _super);
8393 function TimerObservable(dueTime, period, scheduler) {
8394 if (dueTime === void 0) { dueTime = 0; }
8398 if (isNumeric_1.isNumeric(period)) {
8399 this.period = Number(period) < 1 && 1 || Number(period);
8401 else if (isScheduler_1.isScheduler(period)) {
8404 if (!isScheduler_1.isScheduler(scheduler)) {
8405 scheduler = async_1.async;
8407 this.scheduler = scheduler;
8408 this.dueTime = isDate_1.isDate(dueTime) ?
8409 (+dueTime - this.scheduler.now()) :
8413 * Creates an Observable that starts emitting after an `initialDelay` and
8414 * emits ever increasing numbers after each `period` of time thereafter.
8416 * <span class="informal">Its like {@link interval}, but you can specify when
8417 * should the emissions start.</span>
8419 * <img src="./img/timer.png" width="100%">
8421 * `timer` returns an Observable that emits an infinite sequence of ascending
8422 * integers, with a constant interval of time, `period` of your choosing
8423 * between those emissions. The first emission happens after the specified
8424 * `initialDelay`. The initial delay may be a {@link Date}. By default, this
8425 * operator uses the `async` IScheduler to provide a notion of time, but you
8426 * may pass any IScheduler to it. If `period` is not specified, the output
8427 * Observable emits only one value, `0`. Otherwise, it emits an infinite
8430 * @example <caption>Emits ascending numbers, one every second (1000ms), starting after 3 seconds</caption>
8431 * var numbers = Rx.Observable.timer(3000, 1000);
8432 * numbers.subscribe(x => console.log(x));
8434 * @example <caption>Emits one number after five seconds</caption>
8435 * var numbers = Rx.Observable.timer(5000);
8436 * numbers.subscribe(x => console.log(x));
8438 * @see {@link interval}
8439 * @see {@link delay}
8441 * @param {number|Date} initialDelay The initial delay time to wait before
8442 * emitting the first value of `0`.
8443 * @param {number} [period] The period of time between emissions of the
8444 * subsequent numbers.
8445 * @param {Scheduler} [scheduler=async] The IScheduler to use for scheduling
8446 * the emission of values, and providing a notion of "time".
8447 * @return {Observable} An Observable that emits a `0` after the
8448 * `initialDelay` and ever increasing numbers after each `period` of time
8454 TimerObservable.create = function (initialDelay, period, scheduler) {
8455 if (initialDelay === void 0) { initialDelay = 0; }
8456 return new TimerObservable(initialDelay, period, scheduler);
8458 TimerObservable.dispatch = function (state) {
8459 var index = state.index, period = state.period, subscriber = state.subscriber;
8461 subscriber.next(index);
8462 if (subscriber.closed) {
8465 else if (period === -1) {
8466 return subscriber.complete();
8468 state.index = index + 1;
8469 action.schedule(state, period);
8471 TimerObservable.prototype._subscribe = function (subscriber) {
8473 var _a = this, period = _a.period, dueTime = _a.dueTime, scheduler = _a.scheduler;
8474 return scheduler.schedule(TimerObservable.dispatch, dueTime, {
8475 index: index, period: period, subscriber: subscriber
8478 return TimerObservable;
8479 }(Observable_1.Observable));
8480 exports.TimerObservable = TimerObservable;
8482 },{"../Observable":29,"../scheduler/async":212,"../util/isDate":228,"../util/isNumeric":230,"../util/isScheduler":233}],104:[function(require,module,exports){
8484 var isScheduler_1 = require('../util/isScheduler');
8485 var isArray_1 = require('../util/isArray');
8486 var ArrayObservable_1 = require('./ArrayObservable');
8487 var combineLatest_1 = require('../operators/combineLatest');
8488 /* tslint:enable:max-line-length */
8490 * Combines multiple Observables to create an Observable whose values are
8491 * calculated from the latest values of each of its input Observables.
8493 * <span class="informal">Whenever any input Observable emits a value, it
8494 * computes a formula using the latest values from all the inputs, then emits
8495 * the output of that formula.</span>
8497 * <img src="./img/combineLatest.png" width="100%">
8499 * `combineLatest` combines the values from all the Observables passed as
8500 * arguments. This is done by subscribing to each Observable in order and,
8501 * whenever any Observable emits, collecting an array of the most recent
8502 * values from each Observable. So if you pass `n` Observables to operator,
8503 * returned Observable will always emit an array of `n` values, in order
8504 * corresponding to order of passed Observables (value from the first Observable
8505 * on the first place and so on).
8507 * Static version of `combineLatest` accepts either an array of Observables
8508 * or each Observable can be put directly as an argument. Note that array of
8509 * Observables is good choice, if you don't know beforehand how many Observables
8510 * you will combine. Passing empty array will result in Observable that
8511 * completes immediately.
8513 * To ensure output array has always the same length, `combineLatest` will
8514 * actually wait for all input Observables to emit at least once,
8515 * before it starts emitting results. This means if some Observable emits
8516 * values before other Observables started emitting, all that values but last
8517 * will be lost. On the other hand, is some Observable does not emit value but
8518 * completes, resulting Observable will complete at the same moment without
8519 * emitting anything, since it will be now impossible to include value from
8520 * completed Observable in resulting array. Also, if some input Observable does
8521 * not emit any value and never completes, `combineLatest` will also never emit
8522 * and never complete, since, again, it will wait for all streams to emit some
8525 * If at least one Observable was passed to `combineLatest` and all passed Observables
8526 * emitted something, resulting Observable will complete when all combined
8527 * streams complete. So even if some Observable completes, result of
8528 * `combineLatest` will still emit values when other Observables do. In case
8529 * of completed Observable, its value from now on will always be the last
8530 * emitted value. On the other hand, if any Observable errors, `combineLatest`
8531 * will error immediately as well, and all other Observables will be unsubscribed.
8533 * `combineLatest` accepts as optional parameter `project` function, which takes
8534 * as arguments all values that would normally be emitted by resulting Observable.
8535 * `project` can return any kind of value, which will be then emitted by Observable
8536 * instead of default array. Note that `project` does not take as argument that array
8537 * of values, but values themselves. That means default `project` can be imagined
8538 * as function that takes all its arguments and puts them into an array.
8541 * @example <caption>Combine two timer Observables</caption>
8542 * const firstTimer = Rx.Observable.timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
8543 * const secondTimer = Rx.Observable.timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now
8544 * const combinedTimers = Rx.Observable.combineLatest(firstTimer, secondTimer);
8545 * combinedTimers.subscribe(value => console.log(value));
8547 * // [0, 0] after 0.5s
8548 * // [1, 0] after 1s
8549 * // [1, 1] after 1.5s
8550 * // [2, 1] after 2s
8553 * @example <caption>Combine an array of Observables</caption>
8554 * const observables = [1, 5, 10].map(
8555 * n => Rx.Observable.of(n).delay(n * 1000).startWith(0) // emit 0 and then emit n after n seconds
8557 * const combined = Rx.Observable.combineLatest(observables);
8558 * combined.subscribe(value => console.log(value));
8560 * // [0, 0, 0] immediately
8561 * // [1, 0, 0] after 1s
8562 * // [1, 5, 0] after 5s
8563 * // [1, 5, 10] after 10s
8566 * @example <caption>Use project function to dynamically calculate the Body-Mass Index</caption>
8567 * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8568 * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8569 * var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => w / (h * h));
8570 * bmi.subscribe(x => console.log('BMI is ' + x));
8572 * // With output to console:
8573 * // BMI is 24.212293388429753
8574 * // BMI is 23.93948099205209
8575 * // BMI is 23.671253629592222
8578 * @see {@link combineAll}
8579 * @see {@link merge}
8580 * @see {@link withLatestFrom}
8582 * @param {ObservableInput} observable1 An input Observable to combine with other Observables.
8583 * @param {ObservableInput} observable2 An input Observable to combine with other Observables.
8584 * More than one input Observables may be given as arguments
8585 * or an array of Observables may be given as the first argument.
8586 * @param {function} [project] An optional function to project the values from
8587 * the combined latest values into a new value on the output Observable.
8588 * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
8589 * each input Observable.
8590 * @return {Observable} An Observable of projected values from the most recent
8591 * values from each input Observable, or an array of the most recent values from
8592 * each input Observable.
8594 * @name combineLatest
8597 function combineLatest() {
8598 var observables = [];
8599 for (var _i = 0; _i < arguments.length; _i++) {
8600 observables[_i - 0] = arguments[_i];
8603 var scheduler = null;
8604 if (isScheduler_1.isScheduler(observables[observables.length - 1])) {
8605 scheduler = observables.pop();
8607 if (typeof observables[observables.length - 1] === 'function') {
8608 project = observables.pop();
8610 // if the first and only other argument besides the resultSelector is an array
8611 // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
8612 if (observables.length === 1 && isArray_1.isArray(observables[0])) {
8613 observables = observables[0];
8615 return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new combineLatest_1.CombineLatestOperator(project));
8617 exports.combineLatest = combineLatest;
8619 },{"../operators/combineLatest":164,"../util/isArray":226,"../util/isScheduler":233,"./ArrayObservable":93}],105:[function(require,module,exports){
8621 var isScheduler_1 = require('../util/isScheduler');
8622 var of_1 = require('./of');
8623 var from_1 = require('./from');
8624 var concatAll_1 = require('../operators/concatAll');
8625 /* tslint:enable:max-line-length */
8627 * Creates an output Observable which sequentially emits all values from given
8628 * Observable and then moves on to the next.
8630 * <span class="informal">Concatenates multiple Observables together by
8631 * sequentially emitting their values, one Observable after the other.</span>
8633 * <img src="./img/concat.png" width="100%">
8635 * `concat` joins multiple Observables together, by subscribing to them one at a time and
8636 * merging their results into the output Observable. You can pass either an array of
8637 * Observables, or put them directly as arguments. Passing an empty array will result
8638 * in Observable that completes immediately.
8640 * `concat` will subscribe to first input Observable and emit all its values, without
8641 * changing or affecting them in any way. When that Observable completes, it will
8642 * subscribe to then next Observable passed and, again, emit its values. This will be
8643 * repeated, until the operator runs out of Observables. When last input Observable completes,
8644 * `concat` will complete as well. At any given moment only one Observable passed to operator
8645 * emits values. If you would like to emit values from passed Observables concurrently, check out
8646 * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,
8647 * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.
8649 * Note that if some input Observable never completes, `concat` will also never complete
8650 * and Observables following the one that did not complete will never be subscribed. On the other
8651 * hand, if some Observable simply completes immediately after it is subscribed, it will be
8652 * invisible for `concat`, which will just move on to the next Observable.
8654 * If any Observable in chain errors, instead of passing control to the next Observable,
8655 * `concat` will error immediately as well. Observables that would be subscribed after
8656 * the one that emitted error, never will.
8658 * If you pass to `concat` the same Observable many times, its stream of values
8659 * will be "replayed" on every subscription, which means you can repeat given Observable
8660 * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,
8661 * you can always use {@link repeat}.
8663 * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
8664 * var timer = Rx.Observable.interval(1000).take(4);
8665 * var sequence = Rx.Observable.range(1, 10);
8666 * var result = Rx.Observable.concat(timer, sequence);
8667 * result.subscribe(x => console.log(x));
8670 * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
8673 * @example <caption>Concatenate an array of 3 Observables</caption>
8674 * var timer1 = Rx.Observable.interval(1000).take(10);
8675 * var timer2 = Rx.Observable.interval(2000).take(6);
8676 * var timer3 = Rx.Observable.interval(500).take(10);
8677 * var result = Rx.Observable.concat([timer1, timer2, timer3]); // note that array is passed
8678 * result.subscribe(x => console.log(x));
8680 * // results in the following:
8681 * // (Prints to console sequentially)
8682 * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
8683 * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
8684 * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
8687 * @example <caption>Concatenate the same Observable to repeat it</caption>
8688 * const timer = Rx.Observable.interval(1000).take(2);
8690 * Rx.Observable.concat(timer, timer) // concating the same Observable!
8692 * value => console.log(value),
8694 * () => console.log('...and it is done!')
8702 * // "...and it is done!" also after 4s
8704 * @see {@link concatAll}
8705 * @see {@link concatMap}
8706 * @see {@link concatMapTo}
8708 * @param {ObservableInput} input1 An input Observable to concatenate with others.
8709 * @param {ObservableInput} input2 An input Observable to concatenate with others.
8710 * More than one input Observables may be given as argument.
8711 * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
8712 * Observable subscription on.
8713 * @return {Observable} All values of each passed Observable merged into a
8714 * single Observable, in order, in serial fashion.
8720 var observables = [];
8721 for (var _i = 0; _i < arguments.length; _i++) {
8722 observables[_i - 0] = arguments[_i];
8724 if (observables.length === 1 || (observables.length === 2 && isScheduler_1.isScheduler(observables[1]))) {
8725 return from_1.from(observables[0]);
8727 return concatAll_1.concatAll()(of_1.of.apply(void 0, observables));
8729 exports.concat = concat;
8731 },{"../operators/concatAll":166,"../util/isScheduler":233,"./from":108,"./of":112}],106:[function(require,module,exports){
8733 var DeferObservable_1 = require('./DeferObservable');
8734 exports.defer = DeferObservable_1.DeferObservable.create;
8736 },{"./DeferObservable":95}],107:[function(require,module,exports){
8738 var EmptyObservable_1 = require('./EmptyObservable');
8739 exports.empty = EmptyObservable_1.EmptyObservable.create;
8741 },{"./EmptyObservable":96}],108:[function(require,module,exports){
8743 var FromObservable_1 = require('./FromObservable');
8744 exports.from = FromObservable_1.FromObservable.create;
8746 },{"./FromObservable":99}],109:[function(require,module,exports){
8748 var FromEventObservable_1 = require('./FromEventObservable');
8749 exports.fromEvent = FromEventObservable_1.FromEventObservable.create;
8751 },{"./FromEventObservable":98}],110:[function(require,module,exports){
8753 var PromiseObservable_1 = require('./PromiseObservable');
8754 exports.fromPromise = PromiseObservable_1.PromiseObservable.create;
8756 },{"./PromiseObservable":101}],111:[function(require,module,exports){
8758 var merge_1 = require('../operator/merge');
8759 exports.merge = merge_1.mergeStatic;
8761 },{"../operator/merge":135}],112:[function(require,module,exports){
8763 var ArrayObservable_1 = require('./ArrayObservable');
8764 exports.of = ArrayObservable_1.ArrayObservable.of;
8766 },{"./ArrayObservable":93}],113:[function(require,module,exports){
8768 var ErrorObservable_1 = require('./ErrorObservable');
8769 exports._throw = ErrorObservable_1.ErrorObservable.create;
8771 },{"./ErrorObservable":97}],114:[function(require,module,exports){
8773 var TimerObservable_1 = require('./TimerObservable');
8774 exports.timer = TimerObservable_1.TimerObservable.create;
8776 },{"./TimerObservable":103}],115:[function(require,module,exports){
8778 var zip_1 = require('../operators/zip');
8779 exports.zip = zip_1.zipStatic;
8781 },{"../operators/zip":206}],116:[function(require,module,exports){
8783 var async_1 = require('../scheduler/async');
8784 var auditTime_1 = require('../operators/auditTime');
8786 * Ignores source values for `duration` milliseconds, then emits the most recent
8787 * value from the source Observable, then repeats this process.
8789 * <span class="informal">When it sees a source values, it ignores that plus
8790 * the next ones for `duration` milliseconds, and then it emits the most recent
8791 * value from the source.</span>
8793 * <img src="./img/auditTime.png" width="100%">
8795 * `auditTime` is similar to `throttleTime`, but emits the last value from the
8796 * silenced time window, instead of the first value. `auditTime` emits the most
8797 * recent value from the source Observable on the output Observable as soon as
8798 * its internal timer becomes disabled, and ignores source values while the
8799 * timer is enabled. Initially, the timer is disabled. As soon as the first
8800 * source value arrives, the timer is enabled. After `duration` milliseconds (or
8801 * the time unit determined internally by the optional `scheduler`) has passed,
8802 * the timer is disabled, then the most recent source value is emitted on the
8803 * output Observable, and this process repeats for the next source value.
8804 * Optionally takes a {@link IScheduler} for managing timers.
8806 * @example <caption>Emit clicks at a rate of at most one click per second</caption>
8807 * var clicks = Rx.Observable.fromEvent(document, 'click');
8808 * var result = clicks.auditTime(1000);
8809 * result.subscribe(x => console.log(x));
8811 * @see {@link audit}
8812 * @see {@link debounceTime}
8813 * @see {@link delay}
8814 * @see {@link sampleTime}
8815 * @see {@link throttleTime}
8817 * @param {number} duration Time to wait before emitting the most recent source
8818 * value, measured in milliseconds or the time unit determined internally
8819 * by the optional `scheduler`.
8820 * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
8821 * managing the timers that handle the rate-limiting behavior.
8822 * @return {Observable<T>} An Observable that performs rate-limiting of
8823 * emissions from the source Observable.
8827 function auditTime(duration, scheduler) {
8828 if (scheduler === void 0) { scheduler = async_1.async; }
8829 return auditTime_1.auditTime(duration, scheduler)(this);
8831 exports.auditTime = auditTime;
8833 },{"../operators/auditTime":159,"../scheduler/async":212}],117:[function(require,module,exports){
8835 var buffer_1 = require('../operators/buffer');
8837 * Buffers the source Observable values until `closingNotifier` emits.
8839 * <span class="informal">Collects values from the past as an array, and emits
8840 * that array only when another Observable emits.</span>
8842 * <img src="./img/buffer.png" width="100%">
8844 * Buffers the incoming Observable values until the given `closingNotifier`
8845 * Observable emits a value, at which point it emits the buffer on the output
8846 * Observable and starts a new buffer internally, awaiting the next time
8847 * `closingNotifier` emits.
8849 * @example <caption>On every click, emit array of most recent interval events</caption>
8850 * var clicks = Rx.Observable.fromEvent(document, 'click');
8851 * var interval = Rx.Observable.interval(1000);
8852 * var buffered = interval.buffer(clicks);
8853 * buffered.subscribe(x => console.log(x));
8855 * @see {@link bufferCount}
8856 * @see {@link bufferTime}
8857 * @see {@link bufferToggle}
8858 * @see {@link bufferWhen}
8859 * @see {@link window}
8861 * @param {Observable<any>} closingNotifier An Observable that signals the
8862 * buffer to be emitted on the output Observable.
8863 * @return {Observable<T[]>} An Observable of buffers, which are arrays of
8868 function buffer(closingNotifier) {
8869 return buffer_1.buffer(closingNotifier)(this);
8871 exports.buffer = buffer;
8873 },{"../operators/buffer":160}],118:[function(require,module,exports){
8875 var bufferCount_1 = require('../operators/bufferCount');
8877 * Buffers the source Observable values until the size hits the maximum
8878 * `bufferSize` given.
8880 * <span class="informal">Collects values from the past as an array, and emits
8881 * that array only when its size reaches `bufferSize`.</span>
8883 * <img src="./img/bufferCount.png" width="100%">
8885 * Buffers a number of values from the source Observable by `bufferSize` then
8886 * emits the buffer and clears it, and starts a new buffer each
8887 * `startBufferEvery` values. If `startBufferEvery` is not provided or is
8888 * `null`, then new buffers are started immediately at the start of the source
8889 * and when each buffer closes and is emitted.
8891 * @example <caption>Emit the last two click events as an array</caption>
8892 * var clicks = Rx.Observable.fromEvent(document, 'click');
8893 * var buffered = clicks.bufferCount(2);
8894 * buffered.subscribe(x => console.log(x));
8896 * @example <caption>On every click, emit the last two click events as an array</caption>
8897 * var clicks = Rx.Observable.fromEvent(document, 'click');
8898 * var buffered = clicks.bufferCount(2, 1);
8899 * buffered.subscribe(x => console.log(x));
8901 * @see {@link buffer}
8902 * @see {@link bufferTime}
8903 * @see {@link bufferToggle}
8904 * @see {@link bufferWhen}
8905 * @see {@link pairwise}
8906 * @see {@link windowCount}
8908 * @param {number} bufferSize The maximum size of the buffer emitted.
8909 * @param {number} [startBufferEvery] Interval at which to start a new buffer.
8910 * For example if `startBufferEvery` is `2`, then a new buffer will be started
8911 * on every other value from the source. A new buffer is started at the
8912 * beginning of the source by default.
8913 * @return {Observable<T[]>} An Observable of arrays of buffered values.
8914 * @method bufferCount
8917 function bufferCount(bufferSize, startBufferEvery) {
8918 if (startBufferEvery === void 0) { startBufferEvery = null; }
8919 return bufferCount_1.bufferCount(bufferSize, startBufferEvery)(this);
8921 exports.bufferCount = bufferCount;
8923 },{"../operators/bufferCount":161}],119:[function(require,module,exports){
8925 var bufferWhen_1 = require('../operators/bufferWhen');
8927 * Buffers the source Observable values, using a factory function of closing
8928 * Observables to determine when to close, emit, and reset the buffer.
8930 * <span class="informal">Collects values from the past as an array. When it
8931 * starts collecting values, it calls a function that returns an Observable that
8932 * tells when to close the buffer and restart collecting.</span>
8934 * <img src="./img/bufferWhen.png" width="100%">
8936 * Opens a buffer immediately, then closes the buffer when the observable
8937 * returned by calling `closingSelector` function emits a value. When it closes
8938 * the buffer, it immediately opens a new buffer and repeats the process.
8940 * @example <caption>Emit an array of the last clicks every [1-5] random seconds</caption>
8941 * var clicks = Rx.Observable.fromEvent(document, 'click');
8942 * var buffered = clicks.bufferWhen(() =>
8943 * Rx.Observable.interval(1000 + Math.random() * 4000)
8945 * buffered.subscribe(x => console.log(x));
8947 * @see {@link buffer}
8948 * @see {@link bufferCount}
8949 * @see {@link bufferTime}
8950 * @see {@link bufferToggle}
8951 * @see {@link windowWhen}
8953 * @param {function(): Observable} closingSelector A function that takes no
8954 * arguments and returns an Observable that signals buffer closure.
8955 * @return {Observable<T[]>} An observable of arrays of buffered values.
8956 * @method bufferWhen
8959 function bufferWhen(closingSelector) {
8960 return bufferWhen_1.bufferWhen(closingSelector)(this);
8962 exports.bufferWhen = bufferWhen;
8964 },{"../operators/bufferWhen":162}],120:[function(require,module,exports){
8966 var catchError_1 = require('../operators/catchError');
8968 * Catches errors on the observable to be handled by returning a new observable or throwing an error.
8970 * <img src="./img/catch.png" width="100%">
8972 * @example <caption>Continues with a different Observable when there's an error</caption>
8974 * Observable.of(1, 2, 3, 4, 5)
8981 * .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
8982 * .subscribe(x => console.log(x));
8983 * // 1, 2, 3, I, II, III, IV, V
8985 * @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
8987 * Observable.of(1, 2, 3, 4, 5)
8994 * .catch((err, caught) => caught)
8996 * .subscribe(x => console.log(x));
8997 * // 1, 2, 3, 1, 2, 3, ...
8999 * @example <caption>Throws a new error when the source Observable throws an error</caption>
9001 * Observable.of(1, 2, 3, 4, 5)
9009 * throw 'error in source. Details: ' + err;
9012 * x => console.log(x),
9013 * err => console.log(err)
9015 * // 1, 2, 3, error in source. Details: four!
9017 * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
9018 * is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
9019 * is returned by the `selector` will be used to continue the observable chain.
9020 * @return {Observable} An observable that originates from either the source or the observable returned by the
9021 * catch `selector` function.
9026 function _catch(selector) {
9027 return catchError_1.catchError(selector)(this);
9029 exports._catch = _catch;
9031 },{"../operators/catchError":163}],121:[function(require,module,exports){
9033 var combineLatest_1 = require('../operators/combineLatest');
9034 /* tslint:enable:max-line-length */
9036 * Combines multiple Observables to create an Observable whose values are
9037 * calculated from the latest values of each of its input Observables.
9039 * <span class="informal">Whenever any input Observable emits a value, it
9040 * computes a formula using the latest values from all the inputs, then emits
9041 * the output of that formula.</span>
9043 * <img src="./img/combineLatest.png" width="100%">
9045 * `combineLatest` combines the values from this Observable with values from
9046 * Observables passed as arguments. This is done by subscribing to each
9047 * Observable, in order, and collecting an array of each of the most recent
9048 * values any time any of the input Observables emits, then either taking that
9049 * array and passing it as arguments to an optional `project` function and
9050 * emitting the return value of that, or just emitting the array of recent
9051 * values directly if there is no `project` function.
9053 * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
9054 * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
9055 * var height = Rx.Observable.of(1.76, 1.77, 1.78);
9056 * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
9057 * bmi.subscribe(x => console.log('BMI is ' + x));
9059 * // With output to console:
9060 * // BMI is 24.212293388429753
9061 * // BMI is 23.93948099205209
9062 * // BMI is 23.671253629592222
9064 * @see {@link combineAll}
9065 * @see {@link merge}
9066 * @see {@link withLatestFrom}
9068 * @param {ObservableInput} other An input Observable to combine with the source
9069 * Observable. More than one input Observables may be given as argument.
9070 * @param {function} [project] An optional function to project the values from
9071 * the combined latest values into a new value on the output Observable.
9072 * @return {Observable} An Observable of projected values from the most recent
9073 * values from each input Observable, or an array of the most recent values from
9074 * each input Observable.
9075 * @method combineLatest
9078 function combineLatest() {
9079 var observables = [];
9080 for (var _i = 0; _i < arguments.length; _i++) {
9081 observables[_i - 0] = arguments[_i];
9083 return combineLatest_1.combineLatest.apply(void 0, observables)(this);
9085 exports.combineLatest = combineLatest;
9087 },{"../operators/combineLatest":164}],122:[function(require,module,exports){
9089 var concat_1 = require('../operators/concat');
9090 /* tslint:enable:max-line-length */
9092 * Creates an output Observable which sequentially emits all values from every
9093 * given input Observable after the current Observable.
9095 * <span class="informal">Concatenates multiple Observables together by
9096 * sequentially emitting their values, one Observable after the other.</span>
9098 * <img src="./img/concat.png" width="100%">
9100 * Joins this Observable with multiple other Observables by subscribing to them
9101 * one at a time, starting with the source, and merging their results into the
9102 * output Observable. Will wait for each Observable to complete before moving
9105 * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
9106 * var timer = Rx.Observable.interval(1000).take(4);
9107 * var sequence = Rx.Observable.range(1, 10);
9108 * var result = timer.concat(sequence);
9109 * result.subscribe(x => console.log(x));
9112 * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
9114 * @example <caption>Concatenate 3 Observables</caption>
9115 * var timer1 = Rx.Observable.interval(1000).take(10);
9116 * var timer2 = Rx.Observable.interval(2000).take(6);
9117 * var timer3 = Rx.Observable.interval(500).take(10);
9118 * var result = timer1.concat(timer2, timer3);
9119 * result.subscribe(x => console.log(x));
9121 * // results in the following:
9122 * // (Prints to console sequentially)
9123 * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
9124 * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
9125 * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
9127 * @see {@link concatAll}
9128 * @see {@link concatMap}
9129 * @see {@link concatMapTo}
9131 * @param {ObservableInput} other An input Observable to concatenate after the source
9132 * Observable. More than one input Observables may be given as argument.
9133 * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
9134 * Observable subscription on.
9135 * @return {Observable} All values of each passed Observable merged into a
9136 * single Observable, in order, in serial fashion.
9141 var observables = [];
9142 for (var _i = 0; _i < arguments.length; _i++) {
9143 observables[_i - 0] = arguments[_i];
9145 return concat_1.concat.apply(void 0, observables)(this);
9147 exports.concat = concat;
9149 },{"../operators/concat":165}],123:[function(require,module,exports){
9151 var count_1 = require('../operators/count');
9153 * Counts the number of emissions on the source and emits that number when the
9156 * <span class="informal">Tells how many values were emitted, when the source
9159 * <img src="./img/count.png" width="100%">
9161 * `count` transforms an Observable that emits values into an Observable that
9162 * emits a single value that represents the number of values emitted by the
9163 * source Observable. If the source Observable terminates with an error, `count`
9164 * will pass this error notification along without emitting a value first. If
9165 * the source Observable does not terminate at all, `count` will neither emit
9166 * a value nor terminate. This operator takes an optional `predicate` function
9167 * as argument, in which case the output emission will represent the number of
9168 * source values that matched `true` with the `predicate`.
9170 * @example <caption>Counts how many seconds have passed before the first click happened</caption>
9171 * var seconds = Rx.Observable.interval(1000);
9172 * var clicks = Rx.Observable.fromEvent(document, 'click');
9173 * var secondsBeforeClick = seconds.takeUntil(clicks);
9174 * var result = secondsBeforeClick.count();
9175 * result.subscribe(x => console.log(x));
9177 * @example <caption>Counts how many odd numbers are there between 1 and 7</caption>
9178 * var numbers = Rx.Observable.range(1, 7);
9179 * var result = numbers.count(i => i % 2 === 1);
9180 * result.subscribe(x => console.log(x));
9187 * @see {@link reduce}
9189 * @param {function(value: T, i: number, source: Observable<T>): boolean} [predicate] A
9190 * boolean function to select what values are to be counted. It is provided with
9192 * - `value`: the value from the source Observable.
9193 * - `index`: the (zero-based) "index" of the value from the source Observable.
9194 * - `source`: the source Observable instance itself.
9195 * @return {Observable} An Observable of one number that represents the count as
9200 function count(predicate) {
9201 return count_1.count(predicate)(this);
9203 exports.count = count;
9205 },{"../operators/count":167}],124:[function(require,module,exports){
9207 var async_1 = require('../scheduler/async');
9208 var debounceTime_1 = require('../operators/debounceTime');
9210 * Emits a value from the source Observable only after a particular time span
9211 * has passed without another source emission.
9213 * <span class="informal">It's like {@link delay}, but passes only the most
9214 * recent value from each burst of emissions.</span>
9216 * <img src="./img/debounceTime.png" width="100%">
9218 * `debounceTime` delays values emitted by the source Observable, but drops
9219 * previous pending delayed emissions if a new value arrives on the source
9220 * Observable. This operator keeps track of the most recent value from the
9221 * source Observable, and emits that only when `dueTime` enough time has passed
9222 * without any other value appearing on the source Observable. If a new value
9223 * appears before `dueTime` silence occurs, the previous value will be dropped
9224 * and will not be emitted on the output Observable.
9226 * This is a rate-limiting operator, because it is impossible for more than one
9227 * value to be emitted in any time window of duration `dueTime`, but it is also
9228 * a delay-like operator since output emissions do not occur at the same time as
9229 * they did on the source Observable. Optionally takes a {@link IScheduler} for
9232 * @example <caption>Emit the most recent click after a burst of clicks</caption>
9233 * var clicks = Rx.Observable.fromEvent(document, 'click');
9234 * var result = clicks.debounceTime(1000);
9235 * result.subscribe(x => console.log(x));
9237 * @see {@link auditTime}
9238 * @see {@link debounce}
9239 * @see {@link delay}
9240 * @see {@link sampleTime}
9241 * @see {@link throttleTime}
9243 * @param {number} dueTime The timeout duration in milliseconds (or the time
9244 * unit determined internally by the optional `scheduler`) for the window of
9245 * time required to wait for emission silence before emitting the most recent
9247 * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
9248 * managing the timers that handle the timeout for each value.
9249 * @return {Observable} An Observable that delays the emissions of the source
9250 * Observable by the specified `dueTime`, and may drop some values if they occur
9252 * @method debounceTime
9255 function debounceTime(dueTime, scheduler) {
9256 if (scheduler === void 0) { scheduler = async_1.async; }
9257 return debounceTime_1.debounceTime(dueTime, scheduler)(this);
9259 exports.debounceTime = debounceTime;
9261 },{"../operators/debounceTime":168,"../scheduler/async":212}],125:[function(require,module,exports){
9263 var async_1 = require('../scheduler/async');
9264 var delay_1 = require('../operators/delay');
9266 * Delays the emission of items from the source Observable by a given timeout or
9267 * until a given Date.
9269 * <span class="informal">Time shifts each item by some specified amount of
9270 * milliseconds.</span>
9272 * <img src="./img/delay.png" width="100%">
9274 * If the delay argument is a Number, this operator time shifts the source
9275 * Observable by that amount of time expressed in milliseconds. The relative
9276 * time intervals between the values are preserved.
9278 * If the delay argument is a Date, this operator time shifts the start of the
9279 * Observable execution until the given date occurs.
9281 * @example <caption>Delay each click by one second</caption>
9282 * var clicks = Rx.Observable.fromEvent(document, 'click');
9283 * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
9284 * delayedClicks.subscribe(x => console.log(x));
9286 * @example <caption>Delay all clicks until a future date happens</caption>
9287 * var clicks = Rx.Observable.fromEvent(document, 'click');
9288 * var date = new Date('March 15, 2050 12:00:00'); // in the future
9289 * var delayedClicks = clicks.delay(date); // click emitted only after that date
9290 * delayedClicks.subscribe(x => console.log(x));
9292 * @see {@link debounceTime}
9293 * @see {@link delayWhen}
9295 * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
9296 * a `Date` until which the emission of the source items is delayed.
9297 * @param {Scheduler} [scheduler=async] The IScheduler to use for
9298 * managing the timers that handle the time-shift for each item.
9299 * @return {Observable} An Observable that delays the emissions of the source
9300 * Observable by the specified timeout or Date.
9304 function delay(delay, scheduler) {
9305 if (scheduler === void 0) { scheduler = async_1.async; }
9306 return delay_1.delay(delay, scheduler)(this);
9308 exports.delay = delay;
9310 },{"../operators/delay":170,"../scheduler/async":212}],126:[function(require,module,exports){
9312 var distinct_1 = require('../operators/distinct');
9314 * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
9316 * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
9317 * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
9318 * source observable directly with an equality check against previous values.
9320 * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
9322 * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
9323 * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
9324 * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
9325 * that the internal `Set` can be "flushed", basically clearing it of values.
9327 * @example <caption>A simple example with numbers</caption>
9328 * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
9330 * .subscribe(x => console.log(x)); // 1, 2, 3, 4
9332 * @example <caption>An example using a keySelector function</caption>
9333 * interface Person {
9338 * Observable.of<Person>(
9339 * { age: 4, name: 'Foo'},
9340 * { age: 7, name: 'Bar'},
9341 * { age: 5, name: 'Foo'})
9342 * .distinct((p: Person) => p.name)
9343 * .subscribe(x => console.log(x));
9346 * // { age: 4, name: 'Foo' }
9347 * // { age: 7, name: 'Bar' }
9349 * @see {@link distinctUntilChanged}
9350 * @see {@link distinctUntilKeyChanged}
9352 * @param {function} [keySelector] Optional function to select which value you want to check as distinct.
9353 * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.
9354 * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9358 function distinct(keySelector, flushes) {
9359 return distinct_1.distinct(keySelector, flushes)(this);
9361 exports.distinct = distinct;
9363 },{"../operators/distinct":171}],127:[function(require,module,exports){
9365 var distinctUntilChanged_1 = require('../operators/distinctUntilChanged');
9366 /* tslint:enable:max-line-length */
9368 * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
9370 * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.
9372 * If a comparator function is not provided, an equality check is used by default.
9374 * @example <caption>A simple example with numbers</caption>
9375 * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
9376 * .distinctUntilChanged()
9377 * .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
9379 * @example <caption>An example using a compare function</caption>
9380 * interface Person {
9385 * Observable.of<Person>(
9386 * { age: 4, name: 'Foo'},
9387 * { age: 7, name: 'Bar'},
9388 * { age: 5, name: 'Foo'})
9389 * { age: 6, name: 'Foo'})
9390 * .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
9391 * .subscribe(x => console.log(x));
9394 * // { age: 4, name: 'Foo' }
9395 * // { age: 7, name: 'Bar' }
9396 * // { age: 5, name: 'Foo' }
9398 * @see {@link distinct}
9399 * @see {@link distinctUntilKeyChanged}
9401 * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
9402 * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9403 * @method distinctUntilChanged
9406 function distinctUntilChanged(compare, keySelector) {
9407 return distinctUntilChanged_1.distinctUntilChanged(compare, keySelector)(this);
9409 exports.distinctUntilChanged = distinctUntilChanged;
9411 },{"../operators/distinctUntilChanged":172}],128:[function(require,module,exports){
9413 var tap_1 = require('../operators/tap');
9414 /* tslint:enable:max-line-length */
9416 * Perform a side effect for every emission on the source Observable, but return
9417 * an Observable that is identical to the source.
9419 * <span class="informal">Intercepts each emission on the source and runs a
9420 * function, but returns an output which is identical to the source as long as errors don't occur.</span>
9422 * <img src="./img/do.png" width="100%">
9424 * Returns a mirrored Observable of the source Observable, but modified so that
9425 * the provided Observer is called to perform a side effect for every value,
9426 * error, and completion emitted by the source. Any errors that are thrown in
9427 * the aforementioned Observer or handlers are safely sent down the error path
9428 * of the output Observable.
9430 * This operator is useful for debugging your Observables for the correct values
9431 * or performing other side effects.
9433 * Note: this is different to a `subscribe` on the Observable. If the Observable
9434 * returned by `do` is not subscribed, the side effects specified by the
9435 * Observer will never happen. `do` therefore simply spies on existing
9436 * execution, it does not trigger an execution to happen like `subscribe` does.
9438 * @example <caption>Map every click to the clientX position of that click, while also logging the click event</caption>
9439 * var clicks = Rx.Observable.fromEvent(document, 'click');
9440 * var positions = clicks
9441 * .do(ev => console.log(ev))
9442 * .map(ev => ev.clientX);
9443 * positions.subscribe(x => console.log(x));
9446 * @see {@link subscribe}
9448 * @param {Observer|function} [nextOrObserver] A normal Observer object or a
9449 * callback for `next`.
9450 * @param {function} [error] Callback for errors in the source.
9451 * @param {function} [complete] Callback for the completion of the source.
9452 * @return {Observable} An Observable identical to the source, but runs the
9453 * specified Observer or callback(s) for each item.
9458 function _do(nextOrObserver, error, complete) {
9459 return tap_1.tap(nextOrObserver, error, complete)(this);
9463 },{"../operators/tap":203}],129:[function(require,module,exports){
9465 var expand_1 = require('../operators/expand');
9466 /* tslint:enable:max-line-length */
9468 * Recursively projects each source value to an Observable which is merged in
9469 * the output Observable.
9471 * <span class="informal">It's similar to {@link mergeMap}, but applies the
9472 * projection function to every source value as well as every output value.
9473 * It's recursive.</span>
9475 * <img src="./img/expand.png" width="100%">
9477 * Returns an Observable that emits items based on applying a function that you
9478 * supply to each item emitted by the source Observable, where that function
9479 * returns an Observable, and then merging those resulting Observables and
9480 * emitting the results of this merger. *Expand* will re-emit on the output
9481 * Observable every source value. Then, each output value is given to the
9482 * `project` function which returns an inner Observable to be merged on the
9483 * output Observable. Those output values resulting from the projection are also
9484 * given to the `project` function to produce new output values. This is how
9485 * *expand* behaves recursively.
9487 * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
9488 * var clicks = Rx.Observable.fromEvent(document, 'click');
9489 * var powersOfTwo = clicks
9491 * .expand(x => Rx.Observable.of(2 * x).delay(1000))
9493 * powersOfTwo.subscribe(x => console.log(x));
9495 * @see {@link mergeMap}
9496 * @see {@link mergeScan}
9498 * @param {function(value: T, index: number) => Observable} project A function
9499 * that, when applied to an item emitted by the source or the output Observable,
9500 * returns an Observable.
9501 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9502 * Observables being subscribed to concurrently.
9503 * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
9504 * each projected inner Observable.
9505 * @return {Observable} An Observable that emits the source values and also
9506 * result of applying the projection function to each value emitted on the
9507 * output Observable and and merging the results of the Observables obtained
9508 * from this transformation.
9512 function expand(project, concurrent, scheduler) {
9513 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9514 if (scheduler === void 0) { scheduler = undefined; }
9515 concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
9516 return expand_1.expand(project, concurrent, scheduler)(this);
9518 exports.expand = expand;
9520 },{"../operators/expand":173}],130:[function(require,module,exports){
9522 var filter_1 = require('../operators/filter');
9523 /* tslint:enable:max-line-length */
9525 * Filter items emitted by the source Observable by only emitting those that
9526 * satisfy a specified predicate.
9528 * <span class="informal">Like
9529 * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
9530 * it only emits a value from the source if it passes a criterion function.</span>
9532 * <img src="./img/filter.png" width="100%">
9534 * Similar to the well-known `Array.prototype.filter` method, this operator
9535 * takes values from the source Observable, passes them through a `predicate`
9536 * function and only emits those values that yielded `true`.
9538 * @example <caption>Emit only click events whose target was a DIV element</caption>
9539 * var clicks = Rx.Observable.fromEvent(document, 'click');
9540 * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
9541 * clicksOnDivs.subscribe(x => console.log(x));
9543 * @see {@link distinct}
9544 * @see {@link distinctUntilChanged}
9545 * @see {@link distinctUntilKeyChanged}
9546 * @see {@link ignoreElements}
9547 * @see {@link partition}
9550 * @param {function(value: T, index: number): boolean} predicate A function that
9551 * evaluates each value emitted by the source Observable. If it returns `true`,
9552 * the value is emitted, if `false` the value is not passed to the output
9553 * Observable. The `index` parameter is the number `i` for the i-th source
9554 * emission that has happened since the subscription, starting from the number
9556 * @param {any} [thisArg] An optional argument to determine the value of `this`
9557 * in the `predicate` function.
9558 * @return {Observable} An Observable of values from the source that were
9559 * allowed by the `predicate` function.
9563 function filter(predicate, thisArg) {
9564 return filter_1.filter(predicate, thisArg)(this);
9566 exports.filter = filter;
9568 },{"../operators/filter":174}],131:[function(require,module,exports){
9570 var finalize_1 = require('../operators/finalize');
9572 * Returns an Observable that mirrors the source Observable, but will call a specified function when
9573 * the source terminates on complete or error.
9574 * @param {function} callback Function to be called when source terminates.
9575 * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.
9579 function _finally(callback) {
9580 return finalize_1.finalize(callback)(this);
9582 exports._finally = _finally;
9584 },{"../operators/finalize":175}],132:[function(require,module,exports){
9586 var first_1 = require('../operators/first');
9588 * Emits only the first value (or the first value that meets some condition)
9589 * emitted by the source Observable.
9591 * <span class="informal">Emits only the first value. Or emits only the first
9592 * value that passes some test.</span>
9594 * <img src="./img/first.png" width="100%">
9596 * If called with no arguments, `first` emits the first value of the source
9597 * Observable, then completes. If called with a `predicate` function, `first`
9598 * emits the first value of the source that matches the specified condition. It
9599 * may also take a `resultSelector` function to produce the output value from
9600 * the input value, and a `defaultValue` to emit in case the source completes
9601 * before it is able to emit a valid value. Throws an error if `defaultValue`
9602 * was not provided and a matching element is not found.
9604 * @example <caption>Emit only the first click that happens on the DOM</caption>
9605 * var clicks = Rx.Observable.fromEvent(document, 'click');
9606 * var result = clicks.first();
9607 * result.subscribe(x => console.log(x));
9609 * @example <caption>Emits the first click that happens on a DIV</caption>
9610 * var clicks = Rx.Observable.fromEvent(document, 'click');
9611 * var result = clicks.first(ev => ev.target.tagName === 'DIV');
9612 * result.subscribe(x => console.log(x));
9614 * @see {@link filter}
9618 * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
9619 * callback if the Observable completes before any `next` notification was sent.
9621 * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
9622 * An optional function called with each item to test for condition matching.
9623 * @param {function(value: T, index: number): R} [resultSelector] A function to
9624 * produce the value on the output Observable based on the values
9625 * and the indices of the source Observable. The arguments passed to this
9627 * - `value`: the value that was emitted on the source.
9628 * - `index`: the "index" of the value from the source.
9629 * @param {R} [defaultValue] The default value emitted in case no valid value
9630 * was found on the source.
9631 * @return {Observable<T|R>} An Observable of the first item that matches the
9636 function first(predicate, resultSelector, defaultValue) {
9637 return first_1.first(predicate, resultSelector, defaultValue)(this);
9639 exports.first = first;
9641 },{"../operators/first":176}],133:[function(require,module,exports){
9643 var last_1 = require('../operators/last');
9644 /* tslint:enable:max-line-length */
9646 * Returns an Observable that emits only the last item emitted by the source Observable.
9647 * It optionally takes a predicate function as a parameter, in which case, rather than emitting
9648 * the last item from the source Observable, the resulting Observable will emit the last item
9649 * from the source Observable that satisfies the predicate.
9651 * <img src="./img/last.png" width="100%">
9653 * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
9654 * callback if the Observable completes before any `next` notification was sent.
9655 * @param {function} predicate - The condition any source emitted item has to satisfy.
9656 * @return {Observable} An Observable that emits only the last item satisfying the given condition
9657 * from the source, or an NoSuchElementException if no such items are emitted.
9658 * @throws - Throws if no items that match the predicate are emitted by the source Observable.
9662 function last(predicate, resultSelector, defaultValue) {
9663 return last_1.last(predicate, resultSelector, defaultValue)(this);
9665 exports.last = last;
9667 },{"../operators/last":177}],134:[function(require,module,exports){
9669 var map_1 = require('../operators/map');
9671 * Applies a given `project` function to each value emitted by the source
9672 * Observable, and emits the resulting values as an Observable.
9674 * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
9675 * it passes each source value through a transformation function to get
9676 * corresponding output values.</span>
9678 * <img src="./img/map.png" width="100%">
9680 * Similar to the well known `Array.prototype.map` function, this operator
9681 * applies a projection to each value and emits that projection in the output
9684 * @example <caption>Map every click to the clientX position of that click</caption>
9685 * var clicks = Rx.Observable.fromEvent(document, 'click');
9686 * var positions = clicks.map(ev => ev.clientX);
9687 * positions.subscribe(x => console.log(x));
9689 * @see {@link mapTo}
9690 * @see {@link pluck}
9692 * @param {function(value: T, index: number): R} project The function to apply
9693 * to each `value` emitted by the source Observable. The `index` parameter is
9694 * the number `i` for the i-th emission that has happened since the
9695 * subscription, starting from the number `0`.
9696 * @param {any} [thisArg] An optional argument to define what `this` is in the
9697 * `project` function.
9698 * @return {Observable<R>} An Observable that emits the values from the source
9699 * Observable transformed by the given `project` function.
9703 function map(project, thisArg) {
9704 return map_1.map(project, thisArg)(this);
9708 },{"../operators/map":178}],135:[function(require,module,exports){
9710 var merge_1 = require('../operators/merge');
9711 var merge_2 = require('../operators/merge');
9712 exports.mergeStatic = merge_2.mergeStatic;
9713 /* tslint:enable:max-line-length */
9715 * Creates an output Observable which concurrently emits all values from every
9716 * given input Observable.
9718 * <span class="informal">Flattens multiple Observables together by blending
9719 * their values into one Observable.</span>
9721 * <img src="./img/merge.png" width="100%">
9723 * `merge` subscribes to each given input Observable (either the source or an
9724 * Observable given as argument), and simply forwards (without doing any
9725 * transformation) all the values from all the input Observables to the output
9726 * Observable. The output Observable only completes once all input Observables
9727 * have completed. Any error delivered by an input Observable will be immediately
9728 * emitted on the output Observable.
9730 * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
9731 * var clicks = Rx.Observable.fromEvent(document, 'click');
9732 * var timer = Rx.Observable.interval(1000);
9733 * var clicksOrTimer = clicks.merge(timer);
9734 * clicksOrTimer.subscribe(x => console.log(x));
9736 * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
9737 * var timer1 = Rx.Observable.interval(1000).take(10);
9738 * var timer2 = Rx.Observable.interval(2000).take(6);
9739 * var timer3 = Rx.Observable.interval(500).take(10);
9740 * var concurrent = 2; // the argument
9741 * var merged = timer1.merge(timer2, timer3, concurrent);
9742 * merged.subscribe(x => console.log(x));
9744 * @see {@link mergeAll}
9745 * @see {@link mergeMap}
9746 * @see {@link mergeMapTo}
9747 * @see {@link mergeScan}
9749 * @param {ObservableInput} other An input Observable to merge with the source
9750 * Observable. More than one input Observables may be given as argument.
9751 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9752 * Observables being subscribed to concurrently.
9753 * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
9754 * concurrency of input Observables.
9755 * @return {Observable} An Observable that emits items that are the result of
9756 * every input Observable.
9761 var observables = [];
9762 for (var _i = 0; _i < arguments.length; _i++) {
9763 observables[_i - 0] = arguments[_i];
9765 return merge_1.merge.apply(void 0, observables)(this);
9767 exports.merge = merge;
9769 },{"../operators/merge":179}],136:[function(require,module,exports){
9771 var mergeAll_1 = require('../operators/mergeAll');
9773 * Converts a higher-order Observable into a first-order Observable which
9774 * concurrently delivers all values that are emitted on the inner Observables.
9776 * <span class="informal">Flattens an Observable-of-Observables.</span>
9778 * <img src="./img/mergeAll.png" width="100%">
9780 * `mergeAll` subscribes to an Observable that emits Observables, also known as
9781 * a higher-order Observable. Each time it observes one of these emitted inner
9782 * Observables, it subscribes to that and delivers all the values from the
9783 * inner Observable on the output Observable. The output Observable only
9784 * completes once all inner Observables have completed. Any error delivered by
9785 * a inner Observable will be immediately emitted on the output Observable.
9787 * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
9788 * var clicks = Rx.Observable.fromEvent(document, 'click');
9789 * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
9790 * var firstOrder = higherOrder.mergeAll();
9791 * firstOrder.subscribe(x => console.log(x));
9793 * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
9794 * var clicks = Rx.Observable.fromEvent(document, 'click');
9795 * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
9796 * var firstOrder = higherOrder.mergeAll(2);
9797 * firstOrder.subscribe(x => console.log(x));
9799 * @see {@link combineAll}
9800 * @see {@link concatAll}
9801 * @see {@link exhaust}
9802 * @see {@link merge}
9803 * @see {@link mergeMap}
9804 * @see {@link mergeMapTo}
9805 * @see {@link mergeScan}
9806 * @see {@link switch}
9807 * @see {@link zipAll}
9809 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
9810 * Observables being subscribed to concurrently.
9811 * @return {Observable} An Observable that emits values coming from all the
9812 * inner Observables emitted by the source Observable.
9816 function mergeAll(concurrent) {
9817 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9818 return mergeAll_1.mergeAll(concurrent)(this);
9820 exports.mergeAll = mergeAll;
9822 },{"../operators/mergeAll":180}],137:[function(require,module,exports){
9824 var mergeMap_1 = require('../operators/mergeMap');
9825 /* tslint:enable:max-line-length */
9827 * Projects each source value to an Observable which is merged in the output
9830 * <span class="informal">Maps each value to an Observable, then flattens all of
9831 * these inner Observables using {@link mergeAll}.</span>
9833 * <img src="./img/mergeMap.png" width="100%">
9835 * Returns an Observable that emits items based on applying a function that you
9836 * supply to each item emitted by the source Observable, where that function
9837 * returns an Observable, and then merging those resulting Observables and
9838 * emitting the results of this merger.
9840 * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
9841 * var letters = Rx.Observable.of('a', 'b', 'c');
9842 * var result = letters.mergeMap(x =>
9843 * Rx.Observable.interval(1000).map(i => x+i)
9845 * result.subscribe(x => console.log(x));
9847 * // Results in the following:
9854 * // continues to list a,b,c with respective ascending integers
9856 * @see {@link concatMap}
9857 * @see {@link exhaustMap}
9858 * @see {@link merge}
9859 * @see {@link mergeAll}
9860 * @see {@link mergeMapTo}
9861 * @see {@link mergeScan}
9862 * @see {@link switchMap}
9864 * @param {function(value: T, ?index: number): ObservableInput} project A function
9865 * that, when applied to an item emitted by the source Observable, returns an
9867 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
9868 * A function to produce the value on the output Observable based on the values
9869 * and the indices of the source (outer) emission and the inner Observable
9870 * emission. The arguments passed to this function are:
9871 * - `outerValue`: the value that came from the source
9872 * - `innerValue`: the value that came from the projected Observable
9873 * - `outerIndex`: the "index" of the value that came from the source
9874 * - `innerIndex`: the "index" of the value from the projected Observable
9875 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9876 * Observables being subscribed to concurrently.
9877 * @return {Observable} An Observable that emits the result of applying the
9878 * projection function (and the optional `resultSelector`) to each item emitted
9879 * by the source Observable and merging the results of the Observables obtained
9880 * from this transformation.
9884 function mergeMap(project, resultSelector, concurrent) {
9885 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9886 return mergeMap_1.mergeMap(project, resultSelector, concurrent)(this);
9888 exports.mergeMap = mergeMap;
9890 },{"../operators/mergeMap":181}],138:[function(require,module,exports){
9892 var pairwise_1 = require('../operators/pairwise');
9894 * Groups pairs of consecutive emissions together and emits them as an array of
9897 * <span class="informal">Puts the current value and previous value together as
9898 * an array, and emits that.</span>
9900 * <img src="./img/pairwise.png" width="100%">
9902 * The Nth emission from the source Observable will cause the output Observable
9903 * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
9904 * pair. For this reason, `pairwise` emits on the second and subsequent
9905 * emissions from the source Observable, but not on the first emission, because
9906 * there is no previous value in that case.
9908 * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
9909 * var clicks = Rx.Observable.fromEvent(document, 'click');
9910 * var pairs = clicks.pairwise();
9911 * var distance = pairs.map(pair => {
9912 * var x0 = pair[0].clientX;
9913 * var y0 = pair[0].clientY;
9914 * var x1 = pair[1].clientX;
9915 * var y1 = pair[1].clientY;
9916 * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
9918 * distance.subscribe(x => console.log(x));
9920 * @see {@link buffer}
9921 * @see {@link bufferCount}
9923 * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
9924 * consecutive values from the source Observable.
9928 function pairwise() {
9929 return pairwise_1.pairwise()(this);
9931 exports.pairwise = pairwise;
9933 },{"../operators/pairwise":184}],139:[function(require,module,exports){
9935 var pluck_1 = require('../operators/pluck');
9937 * Maps each source value (an object) to its specified nested property.
9939 * <span class="informal">Like {@link map}, but meant only for picking one of
9940 * the nested properties of every emitted object.</span>
9942 * <img src="./img/pluck.png" width="100%">
9944 * Given a list of strings describing a path to an object property, retrieves
9945 * the value of a specified nested property from all values in the source
9946 * Observable. If a property can't be resolved, it will return `undefined` for
9949 * @example <caption>Map every click to the tagName of the clicked target element</caption>
9950 * var clicks = Rx.Observable.fromEvent(document, 'click');
9951 * var tagNames = clicks.pluck('target', 'tagName');
9952 * tagNames.subscribe(x => console.log(x));
9956 * @param {...string} properties The nested properties to pluck from each source
9957 * value (an object).
9958 * @return {Observable} A new Observable of property values from the source values.
9963 var properties = [];
9964 for (var _i = 0; _i < arguments.length; _i++) {
9965 properties[_i - 0] = arguments[_i];
9967 return pluck_1.pluck.apply(void 0, properties)(this);
9969 exports.pluck = pluck;
9971 },{"../operators/pluck":185}],140:[function(require,module,exports){
9973 var publish_1 = require('../operators/publish');
9974 /* tslint:enable:max-line-length */
9976 * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
9977 * before it begins emitting items to those Observers that have subscribed to it.
9979 * <img src="./img/publish.png" width="100%">
9981 * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
9982 * as needed, without causing multiple subscriptions to the source sequence.
9983 * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
9984 * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
9988 function publish(selector) {
9989 return publish_1.publish(selector)(this);
9991 exports.publish = publish;
9993 },{"../operators/publish":186}],141:[function(require,module,exports){
9995 var publishReplay_1 = require('../operators/publishReplay');
9996 /* tslint:enable:max-line-length */
10000 * @param selectorOrScheduler
10002 * @return {Observable<T> | ConnectableObservable<T>}
10003 * @method publishReplay
10004 * @owner Observable
10006 function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) {
10007 return publishReplay_1.publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler)(this);
10009 exports.publishReplay = publishReplay;
10011 },{"../operators/publishReplay":187}],142:[function(require,module,exports){
10013 var reduce_1 = require('../operators/reduce');
10014 /* tslint:enable:max-line-length */
10016 * Applies an accumulator function over the source Observable, and returns the
10017 * accumulated result when the source completes, given an optional seed value.
10019 * <span class="informal">Combines together all values emitted on the source,
10020 * using an accumulator function that knows how to join a new source value into
10021 * the accumulation from the past.</span>
10023 * <img src="./img/reduce.png" width="100%">
10026 * [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce),
10027 * `reduce` applies an `accumulator` function against an accumulation and each
10028 * value of the source Observable (from the past) to reduce it to a single
10029 * value, emitted on the output Observable. Note that `reduce` will only emit
10030 * one value, only when the source Observable completes. It is equivalent to
10031 * applying operator {@link scan} followed by operator {@link last}.
10033 * Returns an Observable that applies a specified `accumulator` function to each
10034 * item emitted by the source Observable. If a `seed` value is specified, then
10035 * that value will be used as the initial value for the accumulator. If no seed
10036 * value is specified, the first item of the source is used as the seed.
10038 * @example <caption>Count the number of click events that happened in 5 seconds</caption>
10039 * var clicksInFiveSeconds = Rx.Observable.fromEvent(document, 'click')
10040 * .takeUntil(Rx.Observable.interval(5000));
10041 * var ones = clicksInFiveSeconds.mapTo(1);
10043 * var count = ones.reduce((acc, one) => acc + one, seed);
10044 * count.subscribe(x => console.log(x));
10046 * @see {@link count}
10047 * @see {@link expand}
10048 * @see {@link mergeScan}
10049 * @see {@link scan}
10051 * @param {function(acc: R, value: T, index: number): R} accumulator The accumulator function
10052 * called on each source value.
10053 * @param {R} [seed] The initial accumulation value.
10054 * @return {Observable<R>} An Observable that emits a single value that is the
10055 * result of accumulating the values emitted by the source Observable.
10057 * @owner Observable
10059 function reduce(accumulator, seed) {
10060 // providing a seed of `undefined` *should* be valid and trigger
10061 // hasSeed! so don't use `seed !== undefined` checks!
10062 // For this reason, we have to check it here at the original call site
10063 // otherwise inside Operator/Subscriber we won't know if `undefined`
10064 // means they didn't provide anything or if they literally provided `undefined`
10065 if (arguments.length >= 2) {
10066 return reduce_1.reduce(accumulator, seed)(this);
10068 return reduce_1.reduce(accumulator)(this);
10070 exports.reduce = reduce;
10072 },{"../operators/reduce":188}],143:[function(require,module,exports){
10074 var retry_1 = require('../operators/retry');
10076 * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
10077 * calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given
10078 * as a number parameter) rather than propagating the `error` call.
10080 * <img src="./img/retry.png" width="100%">
10082 * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted
10083 * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second
10084 * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications
10085 * would be: [1, 2, 1, 2, 3, 4, 5, `complete`].
10086 * @param {number} count - Number of retry attempts before failing.
10087 * @return {Observable} The source Observable modified with the retry logic.
10089 * @owner Observable
10091 function retry(count) {
10092 if (count === void 0) { count = -1; }
10093 return retry_1.retry(count)(this);
10095 exports.retry = retry;
10097 },{"../operators/retry":190}],144:[function(require,module,exports){
10099 var sample_1 = require('../operators/sample');
10101 * Emits the most recently emitted value from the source Observable whenever
10102 * another Observable, the `notifier`, emits.
10104 * <span class="informal">It's like {@link sampleTime}, but samples whenever
10105 * the `notifier` Observable emits something.</span>
10107 * <img src="./img/sample.png" width="100%">
10109 * Whenever the `notifier` Observable emits a value or completes, `sample`
10110 * looks at the source Observable and emits whichever value it has most recently
10111 * emitted since the previous sampling, unless the source has not emitted
10112 * anything since the previous sampling. The `notifier` is subscribed to as soon
10113 * as the output Observable is subscribed.
10115 * @example <caption>On every click, sample the most recent "seconds" timer</caption>
10116 * var seconds = Rx.Observable.interval(1000);
10117 * var clicks = Rx.Observable.fromEvent(document, 'click');
10118 * var result = seconds.sample(clicks);
10119 * result.subscribe(x => console.log(x));
10121 * @see {@link audit}
10122 * @see {@link debounce}
10123 * @see {@link sampleTime}
10124 * @see {@link throttle}
10126 * @param {Observable<any>} notifier The Observable to use for sampling the
10127 * source Observable.
10128 * @return {Observable<T>} An Observable that emits the results of sampling the
10129 * values emitted by the source Observable whenever the notifier Observable
10130 * emits value or completes.
10132 * @owner Observable
10134 function sample(notifier) {
10135 return sample_1.sample(notifier)(this);
10137 exports.sample = sample;
10139 },{"../operators/sample":191}],145:[function(require,module,exports){
10141 var scan_1 = require('../operators/scan');
10142 /* tslint:enable:max-line-length */
10144 * Applies an accumulator function over the source Observable, and returns each
10145 * intermediate result, with an optional seed value.
10147 * <span class="informal">It's like {@link reduce}, but emits the current
10148 * accumulation whenever the source emits a value.</span>
10150 * <img src="./img/scan.png" width="100%">
10152 * Combines together all values emitted on the source, using an accumulator
10153 * function that knows how to join a new source value into the accumulation from
10154 * the past. Is similar to {@link reduce}, but emits the intermediate
10157 * Returns an Observable that applies a specified `accumulator` function to each
10158 * item emitted by the source Observable. If a `seed` value is specified, then
10159 * that value will be used as the initial value for the accumulator. If no seed
10160 * value is specified, the first item of the source is used as the seed.
10162 * @example <caption>Count the number of click events</caption>
10163 * var clicks = Rx.Observable.fromEvent(document, 'click');
10164 * var ones = clicks.mapTo(1);
10166 * var count = ones.scan((acc, one) => acc + one, seed);
10167 * count.subscribe(x => console.log(x));
10169 * @see {@link expand}
10170 * @see {@link mergeScan}
10171 * @see {@link reduce}
10173 * @param {function(acc: R, value: T, index: number): R} accumulator
10174 * The accumulator function called on each source value.
10175 * @param {T|R} [seed] The initial accumulation value.
10176 * @return {Observable<R>} An observable of the accumulated values.
10178 * @owner Observable
10180 function scan(accumulator, seed) {
10181 if (arguments.length >= 2) {
10182 return scan_1.scan(accumulator, seed)(this);
10184 return scan_1.scan(accumulator)(this);
10186 exports.scan = scan;
10188 },{"../operators/scan":192}],146:[function(require,module,exports){
10190 var share_1 = require('../operators/share');
10192 * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
10193 * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
10194 * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
10196 * This behaves similarly to .publish().refCount(), with a behavior difference when the source observable emits complete.
10197 * .publish().refCount() will not resubscribe to the original source, however .share() will resubscribe to the original source.
10198 * Observable.of("test").publish().refCount() will not re-emit "test" on new subscriptions, Observable.of("test").share() will
10199 * re-emit "test" to new subscriptions.
10201 * <img src="./img/share.png" width="100%">
10203 * @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.
10205 * @owner Observable
10208 return share_1.share()(this);
10210 exports.share = share;
10213 },{"../operators/share":193}],147:[function(require,module,exports){
10215 var skip_1 = require('../operators/skip');
10217 * Returns an Observable that skips the first `count` items emitted by the source Observable.
10219 * <img src="./img/skip.png" width="100%">
10221 * @param {Number} count - The number of times, items emitted by source Observable should be skipped.
10222 * @return {Observable} An Observable that skips values emitted by the source Observable.
10225 * @owner Observable
10227 function skip(count) {
10228 return skip_1.skip(count)(this);
10230 exports.skip = skip;
10232 },{"../operators/skip":194}],148:[function(require,module,exports){
10234 var skipUntil_1 = require('../operators/skipUntil');
10236 * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
10238 * <img src="./img/skipUntil.png" width="100%">
10240 * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to
10241 * be mirrored by the resulting Observable.
10242 * @return {Observable<T>} An Observable that skips items from the source Observable until the second Observable emits
10243 * an item, then emits the remaining items.
10244 * @method skipUntil
10245 * @owner Observable
10247 function skipUntil(notifier) {
10248 return skipUntil_1.skipUntil(notifier)(this);
10250 exports.skipUntil = skipUntil;
10252 },{"../operators/skipUntil":195}],149:[function(require,module,exports){
10254 var skipWhile_1 = require('../operators/skipWhile');
10256 * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
10257 * true, but emits all further source items as soon as the condition becomes false.
10259 * <img src="./img/skipWhile.png" width="100%">
10261 * @param {Function} predicate - A function to test each item emitted from the source Observable.
10262 * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the
10263 * specified predicate becomes false.
10264 * @method skipWhile
10265 * @owner Observable
10267 function skipWhile(predicate) {
10268 return skipWhile_1.skipWhile(predicate)(this);
10270 exports.skipWhile = skipWhile;
10272 },{"../operators/skipWhile":196}],150:[function(require,module,exports){
10274 var startWith_1 = require('../operators/startWith');
10275 /* tslint:enable:max-line-length */
10277 * Returns an Observable that emits the items you specify as arguments before it begins to emit
10278 * items emitted by the source Observable.
10280 * <img src="./img/startWith.png" width="100%">
10282 * @param {...T} values - Items you want the modified Observable to emit first.
10283 * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling
10284 * the emissions of the `next` notifications.
10285 * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items
10286 * emitted by the source Observable.
10287 * @method startWith
10288 * @owner Observable
10290 function startWith() {
10292 for (var _i = 0; _i < arguments.length; _i++) {
10293 array[_i - 0] = arguments[_i];
10295 return startWith_1.startWith.apply(void 0, array)(this);
10297 exports.startWith = startWith;
10299 },{"../operators/startWith":197}],151:[function(require,module,exports){
10301 var switchMap_1 = require('../operators/switchMap');
10302 /* tslint:enable:max-line-length */
10304 * Projects each source value to an Observable which is merged in the output
10305 * Observable, emitting values only from the most recently projected Observable.
10307 * <span class="informal">Maps each value to an Observable, then flattens all of
10308 * these inner Observables using {@link switch}.</span>
10310 * <img src="./img/switchMap.png" width="100%">
10312 * Returns an Observable that emits items based on applying a function that you
10313 * supply to each item emitted by the source Observable, where that function
10314 * returns an (so-called "inner") Observable. Each time it observes one of these
10315 * inner Observables, the output Observable begins emitting the items emitted by
10316 * that inner Observable. When a new inner Observable is emitted, `switchMap`
10317 * stops emitting items from the earlier-emitted inner Observable and begins
10318 * emitting items from the new one. It continues to behave like this for
10319 * subsequent inner Observables.
10321 * @example <caption>Rerun an interval Observable on every click event</caption>
10322 * var clicks = Rx.Observable.fromEvent(document, 'click');
10323 * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
10324 * result.subscribe(x => console.log(x));
10326 * @see {@link concatMap}
10327 * @see {@link exhaustMap}
10328 * @see {@link mergeMap}
10329 * @see {@link switch}
10330 * @see {@link switchMapTo}
10332 * @param {function(value: T, ?index: number): ObservableInput} project A function
10333 * that, when applied to an item emitted by the source Observable, returns an
10335 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
10336 * A function to produce the value on the output Observable based on the values
10337 * and the indices of the source (outer) emission and the inner Observable
10338 * emission. The arguments passed to this function are:
10339 * - `outerValue`: the value that came from the source
10340 * - `innerValue`: the value that came from the projected Observable
10341 * - `outerIndex`: the "index" of the value that came from the source
10342 * - `innerIndex`: the "index" of the value from the projected Observable
10343 * @return {Observable} An Observable that emits the result of applying the
10344 * projection function (and the optional `resultSelector`) to each item emitted
10345 * by the source Observable and taking only the values from the most recently
10346 * projected inner Observable.
10347 * @method switchMap
10348 * @owner Observable
10350 function switchMap(project, resultSelector) {
10351 return switchMap_1.switchMap(project, resultSelector)(this);
10353 exports.switchMap = switchMap;
10355 },{"../operators/switchMap":198}],152:[function(require,module,exports){
10357 var take_1 = require('../operators/take');
10359 * Emits only the first `count` values emitted by the source Observable.
10361 * <span class="informal">Takes the first `count` values from the source, then
10362 * completes.</span>
10364 * <img src="./img/take.png" width="100%">
10366 * `take` returns an Observable that emits only the first `count` values emitted
10367 * by the source Observable. If the source emits fewer than `count` values then
10368 * all of its values are emitted. After that, it completes, regardless if the
10369 * source completes.
10371 * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
10372 * var interval = Rx.Observable.interval(1000);
10373 * var five = interval.take(5);
10374 * five.subscribe(x => console.log(x));
10376 * @see {@link takeLast}
10377 * @see {@link takeUntil}
10378 * @see {@link takeWhile}
10379 * @see {@link skip}
10381 * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
10382 * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
10384 * @param {number} count The maximum number of `next` values to emit.
10385 * @return {Observable<T>} An Observable that emits only the first `count`
10386 * values emitted by the source Observable, or all of the values from the source
10387 * if the source emits fewer than `count` values.
10389 * @owner Observable
10391 function take(count) {
10392 return take_1.take(count)(this);
10394 exports.take = take;
10396 },{"../operators/take":199}],153:[function(require,module,exports){
10398 var takeUntil_1 = require('../operators/takeUntil');
10400 * Emits the values emitted by the source Observable until a `notifier`
10401 * Observable emits a value.
10403 * <span class="informal">Lets values pass until a second Observable,
10404 * `notifier`, emits something. Then, it completes.</span>
10406 * <img src="./img/takeUntil.png" width="100%">
10408 * `takeUntil` subscribes and begins mirroring the source Observable. It also
10409 * monitors a second Observable, `notifier` that you provide. If the `notifier`
10410 * emits a value, the output Observable stops mirroring the source Observable
10413 * @example <caption>Tick every second until the first click happens</caption>
10414 * var interval = Rx.Observable.interval(1000);
10415 * var clicks = Rx.Observable.fromEvent(document, 'click');
10416 * var result = interval.takeUntil(clicks);
10417 * result.subscribe(x => console.log(x));
10419 * @see {@link take}
10420 * @see {@link takeLast}
10421 * @see {@link takeWhile}
10422 * @see {@link skip}
10424 * @param {Observable} notifier The Observable whose first emitted value will
10425 * cause the output Observable of `takeUntil` to stop emitting values from the
10426 * source Observable.
10427 * @return {Observable<T>} An Observable that emits the values from the source
10428 * Observable until such time as `notifier` emits its first value.
10429 * @method takeUntil
10430 * @owner Observable
10432 function takeUntil(notifier) {
10433 return takeUntil_1.takeUntil(notifier)(this);
10435 exports.takeUntil = takeUntil;
10437 },{"../operators/takeUntil":201}],154:[function(require,module,exports){
10439 var takeWhile_1 = require('../operators/takeWhile');
10441 * Emits values emitted by the source Observable so long as each value satisfies
10442 * the given `predicate`, and then completes as soon as this `predicate` is not
10445 * <span class="informal">Takes values from the source only while they pass the
10446 * condition given. When the first value does not satisfy, it completes.</span>
10448 * <img src="./img/takeWhile.png" width="100%">
10450 * `takeWhile` subscribes and begins mirroring the source Observable. Each value
10451 * emitted on the source is given to the `predicate` function which returns a
10452 * boolean, representing a condition to be satisfied by the source values. The
10453 * output Observable emits the source values until such time as the `predicate`
10454 * returns false, at which point `takeWhile` stops mirroring the source
10455 * Observable and completes the output Observable.
10457 * @example <caption>Emit click events only while the clientX property is greater than 200</caption>
10458 * var clicks = Rx.Observable.fromEvent(document, 'click');
10459 * var result = clicks.takeWhile(ev => ev.clientX > 200);
10460 * result.subscribe(x => console.log(x));
10462 * @see {@link take}
10463 * @see {@link takeLast}
10464 * @see {@link takeUntil}
10465 * @see {@link skip}
10467 * @param {function(value: T, index: number): boolean} predicate A function that
10468 * evaluates a value emitted by the source Observable and returns a boolean.
10469 * Also takes the (zero-based) index as the second argument.
10470 * @return {Observable<T>} An Observable that emits the values from the source
10471 * Observable so long as each value satisfies the condition defined by the
10472 * `predicate`, then completes.
10473 * @method takeWhile
10474 * @owner Observable
10476 function takeWhile(predicate) {
10477 return takeWhile_1.takeWhile(predicate)(this);
10479 exports.takeWhile = takeWhile;
10481 },{"../operators/takeWhile":202}],155:[function(require,module,exports){
10483 var async_1 = require('../scheduler/async');
10484 var timeout_1 = require('../operators/timeout');
10487 * Errors if Observable does not emit a value in given time span.
10489 * <span class="informal">Timeouts on Observable that doesn't emit values fast enough.</span>
10491 * <img src="./img/timeout.png" width="100%">
10493 * `timeout` operator accepts as an argument either a number or a Date.
10495 * If number was provided, it returns an Observable that behaves like a source
10496 * Observable, unless there is a period of time where there is no value emitted.
10497 * So if you provide `100` as argument and first value comes after 50ms from
10498 * the moment of subscription, this value will be simply re-emitted by the resulting
10499 * Observable. If however after that 100ms passes without a second value being emitted,
10500 * stream will end with an error and source Observable will be unsubscribed.
10501 * These checks are performed throughout whole lifecycle of Observable - from the moment
10502 * it was subscribed to, until it completes or errors itself. Thus every value must be
10503 * emitted within specified period since previous value.
10505 * If provided argument was Date, returned Observable behaves differently. It throws
10506 * if Observable did not complete before provided Date. This means that periods between
10507 * emission of particular values do not matter in this case. If Observable did not complete
10508 * before provided Date, source Observable will be unsubscribed. Other than that, resulting
10509 * stream behaves just as source Observable.
10511 * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments)
10512 * when returned Observable will check if source stream emitted value or completed.
10514 * @example <caption>Check if ticks are emitted within certain timespan</caption>
10515 * const seconds = Rx.Observable.interval(1000);
10517 * seconds.timeout(1100) // Let's use bigger timespan to be safe,
10518 * // since `interval` might fire a bit later then scheduled.
10520 * value => console.log(value), // Will emit numbers just as regular `interval` would.
10521 * err => console.log(err) // Will never be called.
10524 * seconds.timeout(900).subscribe(
10525 * value => console.log(value), // Will never be called.
10526 * err => console.log(err) // Will emit error before even first value is emitted,
10527 * // since it did not arrive within 900ms period.
10530 * @example <caption>Use Date to check if Observable completed</caption>
10531 * const seconds = Rx.Observable.interval(1000);
10533 * seconds.timeout(new Date("December 17, 2020 03:24:00"))
10535 * value => console.log(value), // Will emit values as regular `interval` would
10536 * // until December 17, 2020 at 03:24:00.
10537 * err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error,
10538 * // since Observable did not complete by then.
10541 * @see {@link timeoutWith}
10543 * @param {number|Date} due Number specifying period within which Observable must emit values
10544 * or Date specifying before when Observable should complete
10545 * @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur.
10546 * @return {Observable<T>} Observable that mirrors behaviour of source, unless timeout checks fail.
10548 * @owner Observable
10550 function timeout(due, scheduler) {
10551 if (scheduler === void 0) { scheduler = async_1.async; }
10552 return timeout_1.timeout(due, scheduler)(this);
10554 exports.timeout = timeout;
10556 },{"../operators/timeout":204,"../scheduler/async":212}],156:[function(require,module,exports){
10558 var withLatestFrom_1 = require('../operators/withLatestFrom');
10559 /* tslint:enable:max-line-length */
10561 * Combines the source Observable with other Observables to create an Observable
10562 * whose values are calculated from the latest values of each, only when the
10565 * <span class="informal">Whenever the source Observable emits a value, it
10566 * computes a formula using that value plus the latest values from other input
10567 * Observables, then emits the output of that formula.</span>
10569 * <img src="./img/withLatestFrom.png" width="100%">
10571 * `withLatestFrom` combines each value from the source Observable (the
10572 * instance) with the latest values from the other input Observables only when
10573 * the source emits a value, optionally using a `project` function to determine
10574 * the value to be emitted on the output Observable. All input Observables must
10575 * emit at least one value before the output Observable will emit a value.
10577 * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
10578 * var clicks = Rx.Observable.fromEvent(document, 'click');
10579 * var timer = Rx.Observable.interval(1000);
10580 * var result = clicks.withLatestFrom(timer);
10581 * result.subscribe(x => console.log(x));
10583 * @see {@link combineLatest}
10585 * @param {ObservableInput} other An input Observable to combine with the source
10586 * Observable. More than one input Observables may be given as argument.
10587 * @param {Function} [project] Projection function for combining values
10588 * together. Receives all values in order of the Observables passed, where the
10589 * first parameter is a value from the source Observable. (e.g.
10590 * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
10591 * passed, arrays will be emitted on the output Observable.
10592 * @return {Observable} An Observable of projected values from the most recent
10593 * values from each input Observable, or an array of the most recent values from
10594 * each input Observable.
10595 * @method withLatestFrom
10596 * @owner Observable
10598 function withLatestFrom() {
10600 for (var _i = 0; _i < arguments.length; _i++) {
10601 args[_i - 0] = arguments[_i];
10603 return withLatestFrom_1.withLatestFrom.apply(void 0, args)(this);
10605 exports.withLatestFrom = withLatestFrom;
10607 },{"../operators/withLatestFrom":205}],157:[function(require,module,exports){
10609 var zip_1 = require('../operators/zip');
10610 /* tslint:enable:max-line-length */
10612 * @param observables
10613 * @return {Observable<R>}
10615 * @owner Observable
10617 function zipProto() {
10618 var observables = [];
10619 for (var _i = 0; _i < arguments.length; _i++) {
10620 observables[_i - 0] = arguments[_i];
10622 return zip_1.zip.apply(void 0, observables)(this);
10624 exports.zipProto = zipProto;
10626 },{"../operators/zip":206}],158:[function(require,module,exports){
10628 var __extends = (this && this.__extends) || function (d, b) {
10629 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10630 function __() { this.constructor = d; }
10631 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10633 var tryCatch_1 = require('../util/tryCatch');
10634 var errorObject_1 = require('../util/errorObject');
10635 var OuterSubscriber_1 = require('../OuterSubscriber');
10636 var subscribeToResult_1 = require('../util/subscribeToResult');
10638 * Ignores source values for a duration determined by another Observable, then
10639 * emits the most recent value from the source Observable, then repeats this
10642 * <span class="informal">It's like {@link auditTime}, but the silencing
10643 * duration is determined by a second Observable.</span>
10645 * <img src="./img/audit.png" width="100%">
10647 * `audit` is similar to `throttle`, but emits the last value from the silenced
10648 * time window, instead of the first value. `audit` emits the most recent value
10649 * from the source Observable on the output Observable as soon as its internal
10650 * timer becomes disabled, and ignores source values while the timer is enabled.
10651 * Initially, the timer is disabled. As soon as the first source value arrives,
10652 * the timer is enabled by calling the `durationSelector` function with the
10653 * source value, which returns the "duration" Observable. When the duration
10654 * Observable emits a value or completes, the timer is disabled, then the most
10655 * recent source value is emitted on the output Observable, and this process
10656 * repeats for the next source value.
10658 * @example <caption>Emit clicks at a rate of at most one click per second</caption>
10659 * var clicks = Rx.Observable.fromEvent(document, 'click');
10660 * var result = clicks.audit(ev => Rx.Observable.interval(1000));
10661 * result.subscribe(x => console.log(x));
10663 * @see {@link auditTime}
10664 * @see {@link debounce}
10665 * @see {@link delayWhen}
10666 * @see {@link sample}
10667 * @see {@link throttle}
10669 * @param {function(value: T): SubscribableOrPromise} durationSelector A function
10670 * that receives a value from the source Observable, for computing the silencing
10671 * duration, returned as an Observable or a Promise.
10672 * @return {Observable<T>} An Observable that performs rate-limiting of
10673 * emissions from the source Observable.
10675 * @owner Observable
10677 function audit(durationSelector) {
10678 return function auditOperatorFunction(source) {
10679 return source.lift(new AuditOperator(durationSelector));
10682 exports.audit = audit;
10683 var AuditOperator = (function () {
10684 function AuditOperator(durationSelector) {
10685 this.durationSelector = durationSelector;
10687 AuditOperator.prototype.call = function (subscriber, source) {
10688 return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector));
10690 return AuditOperator;
10693 * We need this JSDoc comment for affecting ESDoc.
10695 * @extends {Ignored}
10697 var AuditSubscriber = (function (_super) {
10698 __extends(AuditSubscriber, _super);
10699 function AuditSubscriber(destination, durationSelector) {
10700 _super.call(this, destination);
10701 this.durationSelector = durationSelector;
10702 this.hasValue = false;
10704 AuditSubscriber.prototype._next = function (value) {
10705 this.value = value;
10706 this.hasValue = true;
10707 if (!this.throttled) {
10708 var duration = tryCatch_1.tryCatch(this.durationSelector)(value);
10709 if (duration === errorObject_1.errorObject) {
10710 this.destination.error(errorObject_1.errorObject.e);
10713 var innerSubscription = subscribeToResult_1.subscribeToResult(this, duration);
10714 if (innerSubscription.closed) {
10715 this.clearThrottle();
10718 this.add(this.throttled = innerSubscription);
10723 AuditSubscriber.prototype.clearThrottle = function () {
10724 var _a = this, value = _a.value, hasValue = _a.hasValue, throttled = _a.throttled;
10726 this.remove(throttled);
10727 this.throttled = null;
10728 throttled.unsubscribe();
10732 this.hasValue = false;
10733 this.destination.next(value);
10736 AuditSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
10737 this.clearThrottle();
10739 AuditSubscriber.prototype.notifyComplete = function () {
10740 this.clearThrottle();
10742 return AuditSubscriber;
10743 }(OuterSubscriber_1.OuterSubscriber));
10745 },{"../OuterSubscriber":31,"../util/errorObject":224,"../util/subscribeToResult":237,"../util/tryCatch":239}],159:[function(require,module,exports){
10747 var async_1 = require('../scheduler/async');
10748 var audit_1 = require('./audit');
10749 var timer_1 = require('../observable/timer');
10751 * Ignores source values for `duration` milliseconds, then emits the most recent
10752 * value from the source Observable, then repeats this process.
10754 * <span class="informal">When it sees a source values, it ignores that plus
10755 * the next ones for `duration` milliseconds, and then it emits the most recent
10756 * value from the source.</span>
10758 * <img src="./img/auditTime.png" width="100%">
10760 * `auditTime` is similar to `throttleTime`, but emits the last value from the
10761 * silenced time window, instead of the first value. `auditTime` emits the most
10762 * recent value from the source Observable on the output Observable as soon as
10763 * its internal timer becomes disabled, and ignores source values while the
10764 * timer is enabled. Initially, the timer is disabled. As soon as the first
10765 * source value arrives, the timer is enabled. After `duration` milliseconds (or
10766 * the time unit determined internally by the optional `scheduler`) has passed,
10767 * the timer is disabled, then the most recent source value is emitted on the
10768 * output Observable, and this process repeats for the next source value.
10769 * Optionally takes a {@link IScheduler} for managing timers.
10771 * @example <caption>Emit clicks at a rate of at most one click per second</caption>
10772 * var clicks = Rx.Observable.fromEvent(document, 'click');
10773 * var result = clicks.auditTime(1000);
10774 * result.subscribe(x => console.log(x));
10776 * @see {@link audit}
10777 * @see {@link debounceTime}
10778 * @see {@link delay}
10779 * @see {@link sampleTime}
10780 * @see {@link throttleTime}
10782 * @param {number} duration Time to wait before emitting the most recent source
10783 * value, measured in milliseconds or the time unit determined internally
10784 * by the optional `scheduler`.
10785 * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
10786 * managing the timers that handle the rate-limiting behavior.
10787 * @return {Observable<T>} An Observable that performs rate-limiting of
10788 * emissions from the source Observable.
10789 * @method auditTime
10790 * @owner Observable
10792 function auditTime(duration, scheduler) {
10793 if (scheduler === void 0) { scheduler = async_1.async; }
10794 return audit_1.audit(function () { return timer_1.timer(duration, scheduler); });
10796 exports.auditTime = auditTime;
10798 },{"../observable/timer":114,"../scheduler/async":212,"./audit":158}],160:[function(require,module,exports){
10800 var __extends = (this && this.__extends) || function (d, b) {
10801 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10802 function __() { this.constructor = d; }
10803 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10805 var OuterSubscriber_1 = require('../OuterSubscriber');
10806 var subscribeToResult_1 = require('../util/subscribeToResult');
10808 * Buffers the source Observable values until `closingNotifier` emits.
10810 * <span class="informal">Collects values from the past as an array, and emits
10811 * that array only when another Observable emits.</span>
10813 * <img src="./img/buffer.png" width="100%">
10815 * Buffers the incoming Observable values until the given `closingNotifier`
10816 * Observable emits a value, at which point it emits the buffer on the output
10817 * Observable and starts a new buffer internally, awaiting the next time
10818 * `closingNotifier` emits.
10820 * @example <caption>On every click, emit array of most recent interval events</caption>
10821 * var clicks = Rx.Observable.fromEvent(document, 'click');
10822 * var interval = Rx.Observable.interval(1000);
10823 * var buffered = interval.buffer(clicks);
10824 * buffered.subscribe(x => console.log(x));
10826 * @see {@link bufferCount}
10827 * @see {@link bufferTime}
10828 * @see {@link bufferToggle}
10829 * @see {@link bufferWhen}
10830 * @see {@link window}
10832 * @param {Observable<any>} closingNotifier An Observable that signals the
10833 * buffer to be emitted on the output Observable.
10834 * @return {Observable<T[]>} An Observable of buffers, which are arrays of
10837 * @owner Observable
10839 function buffer(closingNotifier) {
10840 return function bufferOperatorFunction(source) {
10841 return source.lift(new BufferOperator(closingNotifier));
10844 exports.buffer = buffer;
10845 var BufferOperator = (function () {
10846 function BufferOperator(closingNotifier) {
10847 this.closingNotifier = closingNotifier;
10849 BufferOperator.prototype.call = function (subscriber, source) {
10850 return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
10852 return BufferOperator;
10855 * We need this JSDoc comment for affecting ESDoc.
10857 * @extends {Ignored}
10859 var BufferSubscriber = (function (_super) {
10860 __extends(BufferSubscriber, _super);
10861 function BufferSubscriber(destination, closingNotifier) {
10862 _super.call(this, destination);
10864 this.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
10866 BufferSubscriber.prototype._next = function (value) {
10867 this.buffer.push(value);
10869 BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10870 var buffer = this.buffer;
10872 this.destination.next(buffer);
10874 return BufferSubscriber;
10875 }(OuterSubscriber_1.OuterSubscriber));
10877 },{"../OuterSubscriber":31,"../util/subscribeToResult":237}],161:[function(require,module,exports){
10879 var __extends = (this && this.__extends) || function (d, b) {
10880 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10881 function __() { this.constructor = d; }
10882 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10884 var Subscriber_1 = require('../Subscriber');
10886 * Buffers the source Observable values until the size hits the maximum
10887 * `bufferSize` given.
10889 * <span class="informal">Collects values from the past as an array, and emits
10890 * that array only when its size reaches `bufferSize`.</span>
10892 * <img src="./img/bufferCount.png" width="100%">
10894 * Buffers a number of values from the source Observable by `bufferSize` then
10895 * emits the buffer and clears it, and starts a new buffer each
10896 * `startBufferEvery` values. If `startBufferEvery` is not provided or is
10897 * `null`, then new buffers are started immediately at the start of the source
10898 * and when each buffer closes and is emitted.
10900 * @example <caption>Emit the last two click events as an array</caption>
10901 * var clicks = Rx.Observable.fromEvent(document, 'click');
10902 * var buffered = clicks.bufferCount(2);
10903 * buffered.subscribe(x => console.log(x));
10905 * @example <caption>On every click, emit the last two click events as an array</caption>
10906 * var clicks = Rx.Observable.fromEvent(document, 'click');
10907 * var buffered = clicks.bufferCount(2, 1);
10908 * buffered.subscribe(x => console.log(x));
10910 * @see {@link buffer}
10911 * @see {@link bufferTime}
10912 * @see {@link bufferToggle}
10913 * @see {@link bufferWhen}
10914 * @see {@link pairwise}
10915 * @see {@link windowCount}
10917 * @param {number} bufferSize The maximum size of the buffer emitted.
10918 * @param {number} [startBufferEvery] Interval at which to start a new buffer.
10919 * For example if `startBufferEvery` is `2`, then a new buffer will be started
10920 * on every other value from the source. A new buffer is started at the
10921 * beginning of the source by default.
10922 * @return {Observable<T[]>} An Observable of arrays of buffered values.
10923 * @method bufferCount
10924 * @owner Observable
10926 function bufferCount(bufferSize, startBufferEvery) {
10927 if (startBufferEvery === void 0) { startBufferEvery = null; }
10928 return function bufferCountOperatorFunction(source) {
10929 return source.lift(new BufferCountOperator(bufferSize, startBufferEvery));
10932 exports.bufferCount = bufferCount;
10933 var BufferCountOperator = (function () {
10934 function BufferCountOperator(bufferSize, startBufferEvery) {
10935 this.bufferSize = bufferSize;
10936 this.startBufferEvery = startBufferEvery;
10937 if (!startBufferEvery || bufferSize === startBufferEvery) {
10938 this.subscriberClass = BufferCountSubscriber;
10941 this.subscriberClass = BufferSkipCountSubscriber;
10944 BufferCountOperator.prototype.call = function (subscriber, source) {
10945 return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
10947 return BufferCountOperator;
10950 * We need this JSDoc comment for affecting ESDoc.
10952 * @extends {Ignored}
10954 var BufferCountSubscriber = (function (_super) {
10955 __extends(BufferCountSubscriber, _super);
10956 function BufferCountSubscriber(destination, bufferSize) {
10957 _super.call(this, destination);
10958 this.bufferSize = bufferSize;
10961 BufferCountSubscriber.prototype._next = function (value) {
10962 var buffer = this.buffer;
10963 buffer.push(value);
10964 if (buffer.length == this.bufferSize) {
10965 this.destination.next(buffer);
10969 BufferCountSubscriber.prototype._complete = function () {
10970 var buffer = this.buffer;
10971 if (buffer.length > 0) {
10972 this.destination.next(buffer);
10974 _super.prototype._complete.call(this);
10976 return BufferCountSubscriber;
10977 }(Subscriber_1.Subscriber));
10979 * We need this JSDoc comment for affecting ESDoc.
10981 * @extends {Ignored}
10983 var BufferSkipCountSubscriber = (function (_super) {
10984 __extends(BufferSkipCountSubscriber, _super);
10985 function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) {
10986 _super.call(this, destination);
10987 this.bufferSize = bufferSize;
10988 this.startBufferEvery = startBufferEvery;
10992 BufferSkipCountSubscriber.prototype._next = function (value) {
10993 var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count;
10995 if (count % startBufferEvery === 0) {
10998 for (var i = buffers.length; i--;) {
10999 var buffer = buffers[i];
11000 buffer.push(value);
11001 if (buffer.length === bufferSize) {
11002 buffers.splice(i, 1);
11003 this.destination.next(buffer);
11007 BufferSkipCountSubscriber.prototype._complete = function () {
11008 var _a = this, buffers = _a.buffers, destination = _a.destination;
11009 while (buffers.length > 0) {
11010 var buffer = buffers.shift();
11011 if (buffer.length > 0) {
11012 destination.next(buffer);
11015 _super.prototype._complete.call(this);
11017 return BufferSkipCountSubscriber;
11018 }(Subscriber_1.Subscriber));
11020 },{"../Subscriber":36}],162:[function(require,module,exports){
11022 var __extends = (this && this.__extends) || function (d, b) {
11023 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11024 function __() { this.constructor = d; }
11025 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11027 var Subscription_1 = require('../Subscription');
11028 var tryCatch_1 = require('../util/tryCatch');
11029 var errorObject_1 = require('../util/errorObject');
11030 var OuterSubscriber_1 = require('../OuterSubscriber');
11031 var subscribeToResult_1 = require('../util/subscribeToResult');
11033 * Buffers the source Observable values, using a factory function of closing
11034 * Observables to determine when to close, emit, and reset the buffer.
11036 * <span class="informal">Collects values from the past as an array. When it
11037 * starts collecting values, it calls a function that returns an Observable that
11038 * tells when to close the buffer and restart collecting.</span>
11040 * <img src="./img/bufferWhen.png" width="100%">
11042 * Opens a buffer immediately, then closes the buffer when the observable
11043 * returned by calling `closingSelector` function emits a value. When it closes
11044 * the buffer, it immediately opens a new buffer and repeats the process.
11046 * @example <caption>Emit an array of the last clicks every [1-5] random seconds</caption>
11047 * var clicks = Rx.Observable.fromEvent(document, 'click');
11048 * var buffered = clicks.bufferWhen(() =>
11049 * Rx.Observable.interval(1000 + Math.random() * 4000)
11051 * buffered.subscribe(x => console.log(x));
11053 * @see {@link buffer}
11054 * @see {@link bufferCount}
11055 * @see {@link bufferTime}
11056 * @see {@link bufferToggle}
11057 * @see {@link windowWhen}
11059 * @param {function(): Observable} closingSelector A function that takes no
11060 * arguments and returns an Observable that signals buffer closure.
11061 * @return {Observable<T[]>} An observable of arrays of buffered values.
11062 * @method bufferWhen
11063 * @owner Observable
11065 function bufferWhen(closingSelector) {
11066 return function (source) {
11067 return source.lift(new BufferWhenOperator(closingSelector));
11070 exports.bufferWhen = bufferWhen;
11071 var BufferWhenOperator = (function () {
11072 function BufferWhenOperator(closingSelector) {
11073 this.closingSelector = closingSelector;
11075 BufferWhenOperator.prototype.call = function (subscriber, source) {
11076 return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
11078 return BufferWhenOperator;
11081 * We need this JSDoc comment for affecting ESDoc.
11083 * @extends {Ignored}
11085 var BufferWhenSubscriber = (function (_super) {
11086 __extends(BufferWhenSubscriber, _super);
11087 function BufferWhenSubscriber(destination, closingSelector) {
11088 _super.call(this, destination);
11089 this.closingSelector = closingSelector;
11090 this.subscribing = false;
11093 BufferWhenSubscriber.prototype._next = function (value) {
11094 this.buffer.push(value);
11096 BufferWhenSubscriber.prototype._complete = function () {
11097 var buffer = this.buffer;
11099 this.destination.next(buffer);
11101 _super.prototype._complete.call(this);
11103 BufferWhenSubscriber.prototype._unsubscribe = function () {
11104 this.buffer = null;
11105 this.subscribing = false;
11107 BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11110 BufferWhenSubscriber.prototype.notifyComplete = function () {
11111 if (this.subscribing) {
11118 BufferWhenSubscriber.prototype.openBuffer = function () {
11119 var closingSubscription = this.closingSubscription;
11120 if (closingSubscription) {
11121 this.remove(closingSubscription);
11122 closingSubscription.unsubscribe();
11124 var buffer = this.buffer;
11126 this.destination.next(buffer);
11129 var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)();
11130 if (closingNotifier === errorObject_1.errorObject) {
11131 this.error(errorObject_1.errorObject.e);
11134 closingSubscription = new Subscription_1.Subscription();
11135 this.closingSubscription = closingSubscription;
11136 this.add(closingSubscription);
11137 this.subscribing = true;
11138 closingSubscription.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
11139 this.subscribing = false;
11142 return BufferWhenSubscriber;
11143 }(OuterSubscriber_1.OuterSubscriber));
11145 },{"../OuterSubscriber":31,"../Subscription":37,"../util/errorObject":224,"../util/subscribeToResult":237,"../util/tryCatch":239}],163:[function(require,module,exports){
11147 var __extends = (this && this.__extends) || function (d, b) {
11148 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11149 function __() { this.constructor = d; }
11150 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11152 var OuterSubscriber_1 = require('../OuterSubscriber');
11153 var subscribeToResult_1 = require('../util/subscribeToResult');
11155 * Catches errors on the observable to be handled by returning a new observable or throwing an error.
11157 * <img src="./img/catch.png" width="100%">
11159 * @example <caption>Continues with a different Observable when there's an error</caption>
11161 * Observable.of(1, 2, 3, 4, 5)
11168 * .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
11169 * .subscribe(x => console.log(x));
11170 * // 1, 2, 3, I, II, III, IV, V
11172 * @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
11174 * Observable.of(1, 2, 3, 4, 5)
11181 * .catch((err, caught) => caught)
11183 * .subscribe(x => console.log(x));
11184 * // 1, 2, 3, 1, 2, 3, ...
11186 * @example <caption>Throws a new error when the source Observable throws an error</caption>
11188 * Observable.of(1, 2, 3, 4, 5)
11196 * throw 'error in source. Details: ' + err;
11199 * x => console.log(x),
11200 * err => console.log(err)
11202 * // 1, 2, 3, error in source. Details: four!
11204 * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
11205 * is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
11206 * is returned by the `selector` will be used to continue the observable chain.
11207 * @return {Observable} An observable that originates from either the source or the observable returned by the
11208 * catch `selector` function.
11211 function catchError(selector) {
11212 return function catchErrorOperatorFunction(source) {
11213 var operator = new CatchOperator(selector);
11214 var caught = source.lift(operator);
11215 return (operator.caught = caught);
11218 exports.catchError = catchError;
11219 var CatchOperator = (function () {
11220 function CatchOperator(selector) {
11221 this.selector = selector;
11223 CatchOperator.prototype.call = function (subscriber, source) {
11224 return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
11226 return CatchOperator;
11229 * We need this JSDoc comment for affecting ESDoc.
11231 * @extends {Ignored}
11233 var CatchSubscriber = (function (_super) {
11234 __extends(CatchSubscriber, _super);
11235 function CatchSubscriber(destination, selector, caught) {
11236 _super.call(this, destination);
11237 this.selector = selector;
11238 this.caught = caught;
11240 // NOTE: overriding `error` instead of `_error` because we don't want
11241 // to have this flag this subscriber as `isStopped`. We can mimic the
11242 // behavior of the RetrySubscriber (from the `retry` operator), where
11243 // we unsubscribe from our source chain, reset our Subscriber flags,
11244 // then subscribe to the selector result.
11245 CatchSubscriber.prototype.error = function (err) {
11246 if (!this.isStopped) {
11247 var result = void 0;
11249 result = this.selector(err, this.caught);
11252 _super.prototype.error.call(this, err2);
11255 this._unsubscribeAndRecycle();
11256 this.add(subscribeToResult_1.subscribeToResult(this, result));
11259 return CatchSubscriber;
11260 }(OuterSubscriber_1.OuterSubscriber));
11262 },{"../OuterSubscriber":31,"../util/subscribeToResult":237}],164:[function(require,module,exports){
11264 var __extends = (this && this.__extends) || function (d, b) {
11265 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11266 function __() { this.constructor = d; }
11267 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11269 var ArrayObservable_1 = require('../observable/ArrayObservable');
11270 var isArray_1 = require('../util/isArray');
11271 var OuterSubscriber_1 = require('../OuterSubscriber');
11272 var subscribeToResult_1 = require('../util/subscribeToResult');
11274 /* tslint:enable:max-line-length */
11276 * Combines multiple Observables to create an Observable whose values are
11277 * calculated from the latest values of each of its input Observables.
11279 * <span class="informal">Whenever any input Observable emits a value, it
11280 * computes a formula using the latest values from all the inputs, then emits
11281 * the output of that formula.</span>
11283 * <img src="./img/combineLatest.png" width="100%">
11285 * `combineLatest` combines the values from this Observable with values from
11286 * Observables passed as arguments. This is done by subscribing to each
11287 * Observable, in order, and collecting an array of each of the most recent
11288 * values any time any of the input Observables emits, then either taking that
11289 * array and passing it as arguments to an optional `project` function and
11290 * emitting the return value of that, or just emitting the array of recent
11291 * values directly if there is no `project` function.
11293 * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
11294 * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
11295 * var height = Rx.Observable.of(1.76, 1.77, 1.78);
11296 * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
11297 * bmi.subscribe(x => console.log('BMI is ' + x));
11299 * // With output to console:
11300 * // BMI is 24.212293388429753
11301 * // BMI is 23.93948099205209
11302 * // BMI is 23.671253629592222
11304 * @see {@link combineAll}
11305 * @see {@link merge}
11306 * @see {@link withLatestFrom}
11308 * @param {ObservableInput} other An input Observable to combine with the source
11309 * Observable. More than one input Observables may be given as argument.
11310 * @param {function} [project] An optional function to project the values from
11311 * the combined latest values into a new value on the output Observable.
11312 * @return {Observable} An Observable of projected values from the most recent
11313 * values from each input Observable, or an array of the most recent values from
11314 * each input Observable.
11315 * @method combineLatest
11316 * @owner Observable
11318 function combineLatest() {
11319 var observables = [];
11320 for (var _i = 0; _i < arguments.length; _i++) {
11321 observables[_i - 0] = arguments[_i];
11323 var project = null;
11324 if (typeof observables[observables.length - 1] === 'function') {
11325 project = observables.pop();
11327 // if the first and only other argument besides the resultSelector is an array
11328 // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
11329 if (observables.length === 1 && isArray_1.isArray(observables[0])) {
11330 observables = observables[0].slice();
11332 return function (source) { return source.lift.call(new ArrayObservable_1.ArrayObservable([source].concat(observables)), new CombineLatestOperator(project)); };
11334 exports.combineLatest = combineLatest;
11335 var CombineLatestOperator = (function () {
11336 function CombineLatestOperator(project) {
11337 this.project = project;
11339 CombineLatestOperator.prototype.call = function (subscriber, source) {
11340 return source.subscribe(new CombineLatestSubscriber(subscriber, this.project));
11342 return CombineLatestOperator;
11344 exports.CombineLatestOperator = CombineLatestOperator;
11346 * We need this JSDoc comment for affecting ESDoc.
11348 * @extends {Ignored}
11350 var CombineLatestSubscriber = (function (_super) {
11351 __extends(CombineLatestSubscriber, _super);
11352 function CombineLatestSubscriber(destination, project) {
11353 _super.call(this, destination);
11354 this.project = project;
11357 this.observables = [];
11359 CombineLatestSubscriber.prototype._next = function (observable) {
11360 this.values.push(none);
11361 this.observables.push(observable);
11363 CombineLatestSubscriber.prototype._complete = function () {
11364 var observables = this.observables;
11365 var len = observables.length;
11367 this.destination.complete();
11371 this.toRespond = len;
11372 for (var i = 0; i < len; i++) {
11373 var observable = observables[i];
11374 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
11378 CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
11379 if ((this.active -= 1) === 0) {
11380 this.destination.complete();
11383 CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11384 var values = this.values;
11385 var oldVal = values[outerIndex];
11386 var toRespond = !this.toRespond
11388 : oldVal === none ? --this.toRespond : this.toRespond;
11389 values[outerIndex] = innerValue;
11390 if (toRespond === 0) {
11391 if (this.project) {
11392 this._tryProject(values);
11395 this.destination.next(values.slice());
11399 CombineLatestSubscriber.prototype._tryProject = function (values) {
11402 result = this.project.apply(this, values);
11405 this.destination.error(err);
11408 this.destination.next(result);
11410 return CombineLatestSubscriber;
11411 }(OuterSubscriber_1.OuterSubscriber));
11412 exports.CombineLatestSubscriber = CombineLatestSubscriber;
11414 },{"../OuterSubscriber":31,"../observable/ArrayObservable":93,"../util/isArray":226,"../util/subscribeToResult":237}],165:[function(require,module,exports){
11416 var concat_1 = require('../observable/concat');
11417 /* tslint:enable:max-line-length */
11419 * Creates an output Observable which sequentially emits all values from every
11420 * given input Observable after the current Observable.
11422 * <span class="informal">Concatenates multiple Observables together by
11423 * sequentially emitting their values, one Observable after the other.</span>
11425 * <img src="./img/concat.png" width="100%">
11427 * Joins this Observable with multiple other Observables by subscribing to them
11428 * one at a time, starting with the source, and merging their results into the
11429 * output Observable. Will wait for each Observable to complete before moving
11432 * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
11433 * var timer = Rx.Observable.interval(1000).take(4);
11434 * var sequence = Rx.Observable.range(1, 10);
11435 * var result = timer.concat(sequence);
11436 * result.subscribe(x => console.log(x));
11439 * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
11441 * @example <caption>Concatenate 3 Observables</caption>
11442 * var timer1 = Rx.Observable.interval(1000).take(10);
11443 * var timer2 = Rx.Observable.interval(2000).take(6);
11444 * var timer3 = Rx.Observable.interval(500).take(10);
11445 * var result = timer1.concat(timer2, timer3);
11446 * result.subscribe(x => console.log(x));
11448 * // results in the following:
11449 * // (Prints to console sequentially)
11450 * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
11451 * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
11452 * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
11454 * @see {@link concatAll}
11455 * @see {@link concatMap}
11456 * @see {@link concatMapTo}
11458 * @param {ObservableInput} other An input Observable to concatenate after the source
11459 * Observable. More than one input Observables may be given as argument.
11460 * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
11461 * Observable subscription on.
11462 * @return {Observable} All values of each passed Observable merged into a
11463 * single Observable, in order, in serial fashion.
11465 * @owner Observable
11467 function concat() {
11468 var observables = [];
11469 for (var _i = 0; _i < arguments.length; _i++) {
11470 observables[_i - 0] = arguments[_i];
11472 return function (source) { return source.lift.call(concat_1.concat.apply(void 0, [source].concat(observables))); };
11474 exports.concat = concat;
11476 },{"../observable/concat":105}],166:[function(require,module,exports){
11478 var mergeAll_1 = require('./mergeAll');
11480 * Converts a higher-order Observable into a first-order Observable by
11481 * concatenating the inner Observables in order.
11483 * <span class="informal">Flattens an Observable-of-Observables by putting one
11484 * inner Observable after the other.</span>
11486 * <img src="./img/concatAll.png" width="100%">
11488 * Joins every Observable emitted by the source (a higher-order Observable), in
11489 * a serial fashion. It subscribes to each inner Observable only after the
11490 * previous inner Observable has completed, and merges all of their values into
11491 * the returned observable.
11493 * __Warning:__ If the source Observable emits Observables quickly and
11494 * endlessly, and the inner Observables it emits generally complete slower than
11495 * the source emits, you can run into memory issues as the incoming Observables
11496 * collect in an unbounded buffer.
11498 * Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set
11501 * @example <caption>For each click event, tick every second from 0 to 3, with no concurrency</caption>
11502 * var clicks = Rx.Observable.fromEvent(document, 'click');
11503 * var higherOrder = clicks.map(ev => Rx.Observable.interval(1000).take(4));
11504 * var firstOrder = higherOrder.concatAll();
11505 * firstOrder.subscribe(x => console.log(x));
11507 * // Results in the following:
11508 * // (results are not concurrent)
11509 * // For every click on the "document" it will emit values 0 to 3 spaced
11510 * // on a 1000ms interval
11511 * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
11513 * @see {@link combineAll}
11514 * @see {@link concat}
11515 * @see {@link concatMap}
11516 * @see {@link concatMapTo}
11517 * @see {@link exhaust}
11518 * @see {@link mergeAll}
11519 * @see {@link switch}
11520 * @see {@link zipAll}
11522 * @return {Observable} An Observable emitting values from all the inner
11523 * Observables concatenated.
11524 * @method concatAll
11525 * @owner Observable
11527 function concatAll() {
11528 return mergeAll_1.mergeAll(1);
11530 exports.concatAll = concatAll;
11532 },{"./mergeAll":180}],167:[function(require,module,exports){
11534 var __extends = (this && this.__extends) || function (d, b) {
11535 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11536 function __() { this.constructor = d; }
11537 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11539 var Subscriber_1 = require('../Subscriber');
11541 * Counts the number of emissions on the source and emits that number when the
11542 * source completes.
11544 * <span class="informal">Tells how many values were emitted, when the source
11545 * completes.</span>
11547 * <img src="./img/count.png" width="100%">
11549 * `count` transforms an Observable that emits values into an Observable that
11550 * emits a single value that represents the number of values emitted by the
11551 * source Observable. If the source Observable terminates with an error, `count`
11552 * will pass this error notification along without emitting a value first. If
11553 * the source Observable does not terminate at all, `count` will neither emit
11554 * a value nor terminate. This operator takes an optional `predicate` function
11555 * as argument, in which case the output emission will represent the number of
11556 * source values that matched `true` with the `predicate`.
11558 * @example <caption>Counts how many seconds have passed before the first click happened</caption>
11559 * var seconds = Rx.Observable.interval(1000);
11560 * var clicks = Rx.Observable.fromEvent(document, 'click');
11561 * var secondsBeforeClick = seconds.takeUntil(clicks);
11562 * var result = secondsBeforeClick.count();
11563 * result.subscribe(x => console.log(x));
11565 * @example <caption>Counts how many odd numbers are there between 1 and 7</caption>
11566 * var numbers = Rx.Observable.range(1, 7);
11567 * var result = numbers.count(i => i % 2 === 1);
11568 * result.subscribe(x => console.log(x));
11575 * @see {@link reduce}
11577 * @param {function(value: T, i: number, source: Observable<T>): boolean} [predicate] A
11578 * boolean function to select what values are to be counted. It is provided with
11580 * - `value`: the value from the source Observable.
11581 * - `index`: the (zero-based) "index" of the value from the source Observable.
11582 * - `source`: the source Observable instance itself.
11583 * @return {Observable} An Observable of one number that represents the count as
11586 * @owner Observable
11588 function count(predicate) {
11589 return function (source) { return source.lift(new CountOperator(predicate, source)); };
11591 exports.count = count;
11592 var CountOperator = (function () {
11593 function CountOperator(predicate, source) {
11594 this.predicate = predicate;
11595 this.source = source;
11597 CountOperator.prototype.call = function (subscriber, source) {
11598 return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source));
11600 return CountOperator;
11603 * We need this JSDoc comment for affecting ESDoc.
11605 * @extends {Ignored}
11607 var CountSubscriber = (function (_super) {
11608 __extends(CountSubscriber, _super);
11609 function CountSubscriber(destination, predicate, source) {
11610 _super.call(this, destination);
11611 this.predicate = predicate;
11612 this.source = source;
11616 CountSubscriber.prototype._next = function (value) {
11617 if (this.predicate) {
11618 this._tryPredicate(value);
11624 CountSubscriber.prototype._tryPredicate = function (value) {
11627 result = this.predicate(value, this.index++, this.source);
11630 this.destination.error(err);
11637 CountSubscriber.prototype._complete = function () {
11638 this.destination.next(this.count);
11639 this.destination.complete();
11641 return CountSubscriber;
11642 }(Subscriber_1.Subscriber));
11644 },{"../Subscriber":36}],168:[function(require,module,exports){
11646 var __extends = (this && this.__extends) || function (d, b) {
11647 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11648 function __() { this.constructor = d; }
11649 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11651 var Subscriber_1 = require('../Subscriber');
11652 var async_1 = require('../scheduler/async');
11654 * Emits a value from the source Observable only after a particular time span
11655 * has passed without another source emission.
11657 * <span class="informal">It's like {@link delay}, but passes only the most
11658 * recent value from each burst of emissions.</span>
11660 * <img src="./img/debounceTime.png" width="100%">
11662 * `debounceTime` delays values emitted by the source Observable, but drops
11663 * previous pending delayed emissions if a new value arrives on the source
11664 * Observable. This operator keeps track of the most recent value from the
11665 * source Observable, and emits that only when `dueTime` enough time has passed
11666 * without any other value appearing on the source Observable. If a new value
11667 * appears before `dueTime` silence occurs, the previous value will be dropped
11668 * and will not be emitted on the output Observable.
11670 * This is a rate-limiting operator, because it is impossible for more than one
11671 * value to be emitted in any time window of duration `dueTime`, but it is also
11672 * a delay-like operator since output emissions do not occur at the same time as
11673 * they did on the source Observable. Optionally takes a {@link IScheduler} for
11676 * @example <caption>Emit the most recent click after a burst of clicks</caption>
11677 * var clicks = Rx.Observable.fromEvent(document, 'click');
11678 * var result = clicks.debounceTime(1000);
11679 * result.subscribe(x => console.log(x));
11681 * @see {@link auditTime}
11682 * @see {@link debounce}
11683 * @see {@link delay}
11684 * @see {@link sampleTime}
11685 * @see {@link throttleTime}
11687 * @param {number} dueTime The timeout duration in milliseconds (or the time
11688 * unit determined internally by the optional `scheduler`) for the window of
11689 * time required to wait for emission silence before emitting the most recent
11691 * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
11692 * managing the timers that handle the timeout for each value.
11693 * @return {Observable} An Observable that delays the emissions of the source
11694 * Observable by the specified `dueTime`, and may drop some values if they occur
11696 * @method debounceTime
11697 * @owner Observable
11699 function debounceTime(dueTime, scheduler) {
11700 if (scheduler === void 0) { scheduler = async_1.async; }
11701 return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); };
11703 exports.debounceTime = debounceTime;
11704 var DebounceTimeOperator = (function () {
11705 function DebounceTimeOperator(dueTime, scheduler) {
11706 this.dueTime = dueTime;
11707 this.scheduler = scheduler;
11709 DebounceTimeOperator.prototype.call = function (subscriber, source) {
11710 return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
11712 return DebounceTimeOperator;
11715 * We need this JSDoc comment for affecting ESDoc.
11717 * @extends {Ignored}
11719 var DebounceTimeSubscriber = (function (_super) {
11720 __extends(DebounceTimeSubscriber, _super);
11721 function DebounceTimeSubscriber(destination, dueTime, scheduler) {
11722 _super.call(this, destination);
11723 this.dueTime = dueTime;
11724 this.scheduler = scheduler;
11725 this.debouncedSubscription = null;
11726 this.lastValue = null;
11727 this.hasValue = false;
11729 DebounceTimeSubscriber.prototype._next = function (value) {
11730 this.clearDebounce();
11731 this.lastValue = value;
11732 this.hasValue = true;
11733 this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
11735 DebounceTimeSubscriber.prototype._complete = function () {
11736 this.debouncedNext();
11737 this.destination.complete();
11739 DebounceTimeSubscriber.prototype.debouncedNext = function () {
11740 this.clearDebounce();
11741 if (this.hasValue) {
11742 this.destination.next(this.lastValue);
11743 this.lastValue = null;
11744 this.hasValue = false;
11747 DebounceTimeSubscriber.prototype.clearDebounce = function () {
11748 var debouncedSubscription = this.debouncedSubscription;
11749 if (debouncedSubscription !== null) {
11750 this.remove(debouncedSubscription);
11751 debouncedSubscription.unsubscribe();
11752 this.debouncedSubscription = null;
11755 return DebounceTimeSubscriber;
11756 }(Subscriber_1.Subscriber));
11757 function dispatchNext(subscriber) {
11758 subscriber.debouncedNext();
11761 },{"../Subscriber":36,"../scheduler/async":212}],169:[function(require,module,exports){
11763 var __extends = (this && this.__extends) || function (d, b) {
11764 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11765 function __() { this.constructor = d; }
11766 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11768 var Subscriber_1 = require('../Subscriber');
11769 /* tslint:enable:max-line-length */
11771 * Emits a given value if the source Observable completes without emitting any
11772 * `next` value, otherwise mirrors the source Observable.
11774 * <span class="informal">If the source Observable turns out to be empty, then
11775 * this operator will emit a default value.</span>
11777 * <img src="./img/defaultIfEmpty.png" width="100%">
11779 * `defaultIfEmpty` emits the values emitted by the source Observable or a
11780 * specified default value if the source Observable is empty (completes without
11781 * having emitted any `next` value).
11783 * @example <caption>If no clicks happen in 5 seconds, then emit "no clicks"</caption>
11784 * var clicks = Rx.Observable.fromEvent(document, 'click');
11785 * var clicksBeforeFive = clicks.takeUntil(Rx.Observable.interval(5000));
11786 * var result = clicksBeforeFive.defaultIfEmpty('no clicks');
11787 * result.subscribe(x => console.log(x));
11789 * @see {@link empty}
11790 * @see {@link last}
11792 * @param {any} [defaultValue=null] The default value used if the source
11793 * Observable is empty.
11794 * @return {Observable} An Observable that emits either the specified
11795 * `defaultValue` if the source Observable emits no items, or the values emitted
11796 * by the source Observable.
11797 * @method defaultIfEmpty
11798 * @owner Observable
11800 function defaultIfEmpty(defaultValue) {
11801 if (defaultValue === void 0) { defaultValue = null; }
11802 return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); };
11804 exports.defaultIfEmpty = defaultIfEmpty;
11805 var DefaultIfEmptyOperator = (function () {
11806 function DefaultIfEmptyOperator(defaultValue) {
11807 this.defaultValue = defaultValue;
11809 DefaultIfEmptyOperator.prototype.call = function (subscriber, source) {
11810 return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));
11812 return DefaultIfEmptyOperator;
11815 * We need this JSDoc comment for affecting ESDoc.
11817 * @extends {Ignored}
11819 var DefaultIfEmptySubscriber = (function (_super) {
11820 __extends(DefaultIfEmptySubscriber, _super);
11821 function DefaultIfEmptySubscriber(destination, defaultValue) {
11822 _super.call(this, destination);
11823 this.defaultValue = defaultValue;
11824 this.isEmpty = true;
11826 DefaultIfEmptySubscriber.prototype._next = function (value) {
11827 this.isEmpty = false;
11828 this.destination.next(value);
11830 DefaultIfEmptySubscriber.prototype._complete = function () {
11831 if (this.isEmpty) {
11832 this.destination.next(this.defaultValue);
11834 this.destination.complete();
11836 return DefaultIfEmptySubscriber;
11837 }(Subscriber_1.Subscriber));
11839 },{"../Subscriber":36}],170:[function(require,module,exports){
11841 var __extends = (this && this.__extends) || function (d, b) {
11842 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11843 function __() { this.constructor = d; }
11844 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11846 var async_1 = require('../scheduler/async');
11847 var isDate_1 = require('../util/isDate');
11848 var Subscriber_1 = require('../Subscriber');
11849 var Notification_1 = require('../Notification');
11851 * Delays the emission of items from the source Observable by a given timeout or
11852 * until a given Date.
11854 * <span class="informal">Time shifts each item by some specified amount of
11855 * milliseconds.</span>
11857 * <img src="./img/delay.png" width="100%">
11859 * If the delay argument is a Number, this operator time shifts the source
11860 * Observable by that amount of time expressed in milliseconds. The relative
11861 * time intervals between the values are preserved.
11863 * If the delay argument is a Date, this operator time shifts the start of the
11864 * Observable execution until the given date occurs.
11866 * @example <caption>Delay each click by one second</caption>
11867 * var clicks = Rx.Observable.fromEvent(document, 'click');
11868 * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
11869 * delayedClicks.subscribe(x => console.log(x));
11871 * @example <caption>Delay all clicks until a future date happens</caption>
11872 * var clicks = Rx.Observable.fromEvent(document, 'click');
11873 * var date = new Date('March 15, 2050 12:00:00'); // in the future
11874 * var delayedClicks = clicks.delay(date); // click emitted only after that date
11875 * delayedClicks.subscribe(x => console.log(x));
11877 * @see {@link debounceTime}
11878 * @see {@link delayWhen}
11880 * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
11881 * a `Date` until which the emission of the source items is delayed.
11882 * @param {Scheduler} [scheduler=async] The IScheduler to use for
11883 * managing the timers that handle the time-shift for each item.
11884 * @return {Observable} An Observable that delays the emissions of the source
11885 * Observable by the specified timeout or Date.
11887 * @owner Observable
11889 function delay(delay, scheduler) {
11890 if (scheduler === void 0) { scheduler = async_1.async; }
11891 var absoluteDelay = isDate_1.isDate(delay);
11892 var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
11893 return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); };
11895 exports.delay = delay;
11896 var DelayOperator = (function () {
11897 function DelayOperator(delay, scheduler) {
11898 this.delay = delay;
11899 this.scheduler = scheduler;
11901 DelayOperator.prototype.call = function (subscriber, source) {
11902 return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
11904 return DelayOperator;
11907 * We need this JSDoc comment for affecting ESDoc.
11909 * @extends {Ignored}
11911 var DelaySubscriber = (function (_super) {
11912 __extends(DelaySubscriber, _super);
11913 function DelaySubscriber(destination, delay, scheduler) {
11914 _super.call(this, destination);
11915 this.delay = delay;
11916 this.scheduler = scheduler;
11918 this.active = false;
11919 this.errored = false;
11921 DelaySubscriber.dispatch = function (state) {
11922 var source = state.source;
11923 var queue = source.queue;
11924 var scheduler = state.scheduler;
11925 var destination = state.destination;
11926 while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
11927 queue.shift().notification.observe(destination);
11929 if (queue.length > 0) {
11930 var delay_1 = Math.max(0, queue[0].time - scheduler.now());
11931 this.schedule(state, delay_1);
11934 source.active = false;
11937 DelaySubscriber.prototype._schedule = function (scheduler) {
11938 this.active = true;
11939 this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
11940 source: this, destination: this.destination, scheduler: scheduler
11943 DelaySubscriber.prototype.scheduleNotification = function (notification) {
11944 if (this.errored === true) {
11947 var scheduler = this.scheduler;
11948 var message = new DelayMessage(scheduler.now() + this.delay, notification);
11949 this.queue.push(message);
11950 if (this.active === false) {
11951 this._schedule(scheduler);
11954 DelaySubscriber.prototype._next = function (value) {
11955 this.scheduleNotification(Notification_1.Notification.createNext(value));
11957 DelaySubscriber.prototype._error = function (err) {
11958 this.errored = true;
11960 this.destination.error(err);
11962 DelaySubscriber.prototype._complete = function () {
11963 this.scheduleNotification(Notification_1.Notification.createComplete());
11965 return DelaySubscriber;
11966 }(Subscriber_1.Subscriber));
11967 var DelayMessage = (function () {
11968 function DelayMessage(time, notification) {
11970 this.notification = notification;
11972 return DelayMessage;
11975 },{"../Notification":28,"../Subscriber":36,"../scheduler/async":212,"../util/isDate":228}],171:[function(require,module,exports){
11977 var __extends = (this && this.__extends) || function (d, b) {
11978 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11979 function __() { this.constructor = d; }
11980 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11982 var OuterSubscriber_1 = require('../OuterSubscriber');
11983 var subscribeToResult_1 = require('../util/subscribeToResult');
11984 var Set_1 = require('../util/Set');
11986 * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
11988 * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
11989 * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
11990 * source observable directly with an equality check against previous values.
11992 * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
11994 * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
11995 * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
11996 * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
11997 * that the internal `Set` can be "flushed", basically clearing it of values.
11999 * @example <caption>A simple example with numbers</caption>
12000 * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
12002 * .subscribe(x => console.log(x)); // 1, 2, 3, 4
12004 * @example <caption>An example using a keySelector function</caption>
12005 * interface Person {
12010 * Observable.of<Person>(
12011 * { age: 4, name: 'Foo'},
12012 * { age: 7, name: 'Bar'},
12013 * { age: 5, name: 'Foo'})
12014 * .distinct((p: Person) => p.name)
12015 * .subscribe(x => console.log(x));
12018 * // { age: 4, name: 'Foo' }
12019 * // { age: 7, name: 'Bar' }
12021 * @see {@link distinctUntilChanged}
12022 * @see {@link distinctUntilKeyChanged}
12024 * @param {function} [keySelector] Optional function to select which value you want to check as distinct.
12025 * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.
12026 * @return {Observable} An Observable that emits items from the source Observable with distinct values.
12028 * @owner Observable
12030 function distinct(keySelector, flushes) {
12031 return function (source) { return source.lift(new DistinctOperator(keySelector, flushes)); };
12033 exports.distinct = distinct;
12034 var DistinctOperator = (function () {
12035 function DistinctOperator(keySelector, flushes) {
12036 this.keySelector = keySelector;
12037 this.flushes = flushes;
12039 DistinctOperator.prototype.call = function (subscriber, source) {
12040 return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
12042 return DistinctOperator;
12045 * We need this JSDoc comment for affecting ESDoc.
12047 * @extends {Ignored}
12049 var DistinctSubscriber = (function (_super) {
12050 __extends(DistinctSubscriber, _super);
12051 function DistinctSubscriber(destination, keySelector, flushes) {
12052 _super.call(this, destination);
12053 this.keySelector = keySelector;
12054 this.values = new Set_1.Set();
12056 this.add(subscribeToResult_1.subscribeToResult(this, flushes));
12059 DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12060 this.values.clear();
12062 DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
12063 this._error(error);
12065 DistinctSubscriber.prototype._next = function (value) {
12066 if (this.keySelector) {
12067 this._useKeySelector(value);
12070 this._finalizeNext(value, value);
12073 DistinctSubscriber.prototype._useKeySelector = function (value) {
12075 var destination = this.destination;
12077 key = this.keySelector(value);
12080 destination.error(err);
12083 this._finalizeNext(key, value);
12085 DistinctSubscriber.prototype._finalizeNext = function (key, value) {
12086 var values = this.values;
12087 if (!values.has(key)) {
12089 this.destination.next(value);
12092 return DistinctSubscriber;
12093 }(OuterSubscriber_1.OuterSubscriber));
12094 exports.DistinctSubscriber = DistinctSubscriber;
12096 },{"../OuterSubscriber":31,"../util/Set":221,"../util/subscribeToResult":237}],172:[function(require,module,exports){
12098 var __extends = (this && this.__extends) || function (d, b) {
12099 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12100 function __() { this.constructor = d; }
12101 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12103 var Subscriber_1 = require('../Subscriber');
12104 var tryCatch_1 = require('../util/tryCatch');
12105 var errorObject_1 = require('../util/errorObject');
12106 /* tslint:enable:max-line-length */
12108 * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
12110 * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.
12112 * If a comparator function is not provided, an equality check is used by default.
12114 * @example <caption>A simple example with numbers</caption>
12115 * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
12116 * .distinctUntilChanged()
12117 * .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
12119 * @example <caption>An example using a compare function</caption>
12120 * interface Person {
12125 * Observable.of<Person>(
12126 * { age: 4, name: 'Foo'},
12127 * { age: 7, name: 'Bar'},
12128 * { age: 5, name: 'Foo'})
12129 * { age: 6, name: 'Foo'})
12130 * .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
12131 * .subscribe(x => console.log(x));
12134 * // { age: 4, name: 'Foo' }
12135 * // { age: 7, name: 'Bar' }
12136 * // { age: 5, name: 'Foo' }
12138 * @see {@link distinct}
12139 * @see {@link distinctUntilKeyChanged}
12141 * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
12142 * @return {Observable} An Observable that emits items from the source Observable with distinct values.
12143 * @method distinctUntilChanged
12144 * @owner Observable
12146 function distinctUntilChanged(compare, keySelector) {
12147 return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); };
12149 exports.distinctUntilChanged = distinctUntilChanged;
12150 var DistinctUntilChangedOperator = (function () {
12151 function DistinctUntilChangedOperator(compare, keySelector) {
12152 this.compare = compare;
12153 this.keySelector = keySelector;
12155 DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
12156 return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
12158 return DistinctUntilChangedOperator;
12161 * We need this JSDoc comment for affecting ESDoc.
12163 * @extends {Ignored}
12165 var DistinctUntilChangedSubscriber = (function (_super) {
12166 __extends(DistinctUntilChangedSubscriber, _super);
12167 function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
12168 _super.call(this, destination);
12169 this.keySelector = keySelector;
12170 this.hasKey = false;
12171 if (typeof compare === 'function') {
12172 this.compare = compare;
12175 DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
12178 DistinctUntilChangedSubscriber.prototype._next = function (value) {
12179 var keySelector = this.keySelector;
12182 key = tryCatch_1.tryCatch(this.keySelector)(value);
12183 if (key === errorObject_1.errorObject) {
12184 return this.destination.error(errorObject_1.errorObject.e);
12187 var result = false;
12189 result = tryCatch_1.tryCatch(this.compare)(this.key, key);
12190 if (result === errorObject_1.errorObject) {
12191 return this.destination.error(errorObject_1.errorObject.e);
12195 this.hasKey = true;
12197 if (Boolean(result) === false) {
12199 this.destination.next(value);
12202 return DistinctUntilChangedSubscriber;
12203 }(Subscriber_1.Subscriber));
12205 },{"../Subscriber":36,"../util/errorObject":224,"../util/tryCatch":239}],173:[function(require,module,exports){
12207 var __extends = (this && this.__extends) || function (d, b) {
12208 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12209 function __() { this.constructor = d; }
12210 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12212 var tryCatch_1 = require('../util/tryCatch');
12213 var errorObject_1 = require('../util/errorObject');
12214 var OuterSubscriber_1 = require('../OuterSubscriber');
12215 var subscribeToResult_1 = require('../util/subscribeToResult');
12216 /* tslint:enable:max-line-length */
12218 * Recursively projects each source value to an Observable which is merged in
12219 * the output Observable.
12221 * <span class="informal">It's similar to {@link mergeMap}, but applies the
12222 * projection function to every source value as well as every output value.
12223 * It's recursive.</span>
12225 * <img src="./img/expand.png" width="100%">
12227 * Returns an Observable that emits items based on applying a function that you
12228 * supply to each item emitted by the source Observable, where that function
12229 * returns an Observable, and then merging those resulting Observables and
12230 * emitting the results of this merger. *Expand* will re-emit on the output
12231 * Observable every source value. Then, each output value is given to the
12232 * `project` function which returns an inner Observable to be merged on the
12233 * output Observable. Those output values resulting from the projection are also
12234 * given to the `project` function to produce new output values. This is how
12235 * *expand* behaves recursively.
12237 * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
12238 * var clicks = Rx.Observable.fromEvent(document, 'click');
12239 * var powersOfTwo = clicks
12241 * .expand(x => Rx.Observable.of(2 * x).delay(1000))
12243 * powersOfTwo.subscribe(x => console.log(x));
12245 * @see {@link mergeMap}
12246 * @see {@link mergeScan}
12248 * @param {function(value: T, index: number) => Observable} project A function
12249 * that, when applied to an item emitted by the source or the output Observable,
12250 * returns an Observable.
12251 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
12252 * Observables being subscribed to concurrently.
12253 * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
12254 * each projected inner Observable.
12255 * @return {Observable} An Observable that emits the source values and also
12256 * result of applying the projection function to each value emitted on the
12257 * output Observable and and merging the results of the Observables obtained
12258 * from this transformation.
12260 * @owner Observable
12262 function expand(project, concurrent, scheduler) {
12263 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12264 if (scheduler === void 0) { scheduler = undefined; }
12265 concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
12266 return function (source) { return source.lift(new ExpandOperator(project, concurrent, scheduler)); };
12268 exports.expand = expand;
12269 var ExpandOperator = (function () {
12270 function ExpandOperator(project, concurrent, scheduler) {
12271 this.project = project;
12272 this.concurrent = concurrent;
12273 this.scheduler = scheduler;
12275 ExpandOperator.prototype.call = function (subscriber, source) {
12276 return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
12278 return ExpandOperator;
12280 exports.ExpandOperator = ExpandOperator;
12282 * We need this JSDoc comment for affecting ESDoc.
12284 * @extends {Ignored}
12286 var ExpandSubscriber = (function (_super) {
12287 __extends(ExpandSubscriber, _super);
12288 function ExpandSubscriber(destination, project, concurrent, scheduler) {
12289 _super.call(this, destination);
12290 this.project = project;
12291 this.concurrent = concurrent;
12292 this.scheduler = scheduler;
12295 this.hasCompleted = false;
12296 if (concurrent < Number.POSITIVE_INFINITY) {
12300 ExpandSubscriber.dispatch = function (arg) {
12301 var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
12302 subscriber.subscribeToProjection(result, value, index);
12304 ExpandSubscriber.prototype._next = function (value) {
12305 var destination = this.destination;
12306 if (destination.closed) {
12310 var index = this.index++;
12311 if (this.active < this.concurrent) {
12312 destination.next(value);
12313 var result = tryCatch_1.tryCatch(this.project)(value, index);
12314 if (result === errorObject_1.errorObject) {
12315 destination.error(errorObject_1.errorObject.e);
12317 else if (!this.scheduler) {
12318 this.subscribeToProjection(result, value, index);
12321 var state = { subscriber: this, result: result, value: value, index: index };
12322 this.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
12326 this.buffer.push(value);
12329 ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
12331 this.add(subscribeToResult_1.subscribeToResult(this, result, value, index));
12333 ExpandSubscriber.prototype._complete = function () {
12334 this.hasCompleted = true;
12335 if (this.hasCompleted && this.active === 0) {
12336 this.destination.complete();
12339 ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12340 this._next(innerValue);
12342 ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
12343 var buffer = this.buffer;
12344 this.remove(innerSub);
12346 if (buffer && buffer.length > 0) {
12347 this._next(buffer.shift());
12349 if (this.hasCompleted && this.active === 0) {
12350 this.destination.complete();
12353 return ExpandSubscriber;
12354 }(OuterSubscriber_1.OuterSubscriber));
12355 exports.ExpandSubscriber = ExpandSubscriber;
12357 },{"../OuterSubscriber":31,"../util/errorObject":224,"../util/subscribeToResult":237,"../util/tryCatch":239}],174:[function(require,module,exports){
12359 var __extends = (this && this.__extends) || function (d, b) {
12360 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12361 function __() { this.constructor = d; }
12362 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12364 var Subscriber_1 = require('../Subscriber');
12365 /* tslint:enable:max-line-length */
12367 * Filter items emitted by the source Observable by only emitting those that
12368 * satisfy a specified predicate.
12370 * <span class="informal">Like
12371 * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
12372 * it only emits a value from the source if it passes a criterion function.</span>
12374 * <img src="./img/filter.png" width="100%">
12376 * Similar to the well-known `Array.prototype.filter` method, this operator
12377 * takes values from the source Observable, passes them through a `predicate`
12378 * function and only emits those values that yielded `true`.
12380 * @example <caption>Emit only click events whose target was a DIV element</caption>
12381 * var clicks = Rx.Observable.fromEvent(document, 'click');
12382 * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
12383 * clicksOnDivs.subscribe(x => console.log(x));
12385 * @see {@link distinct}
12386 * @see {@link distinctUntilChanged}
12387 * @see {@link distinctUntilKeyChanged}
12388 * @see {@link ignoreElements}
12389 * @see {@link partition}
12390 * @see {@link skip}
12392 * @param {function(value: T, index: number): boolean} predicate A function that
12393 * evaluates each value emitted by the source Observable. If it returns `true`,
12394 * the value is emitted, if `false` the value is not passed to the output
12395 * Observable. The `index` parameter is the number `i` for the i-th source
12396 * emission that has happened since the subscription, starting from the number
12398 * @param {any} [thisArg] An optional argument to determine the value of `this`
12399 * in the `predicate` function.
12400 * @return {Observable} An Observable of values from the source that were
12401 * allowed by the `predicate` function.
12403 * @owner Observable
12405 function filter(predicate, thisArg) {
12406 return function filterOperatorFunction(source) {
12407 return source.lift(new FilterOperator(predicate, thisArg));
12410 exports.filter = filter;
12411 var FilterOperator = (function () {
12412 function FilterOperator(predicate, thisArg) {
12413 this.predicate = predicate;
12414 this.thisArg = thisArg;
12416 FilterOperator.prototype.call = function (subscriber, source) {
12417 return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
12419 return FilterOperator;
12422 * We need this JSDoc comment for affecting ESDoc.
12424 * @extends {Ignored}
12426 var FilterSubscriber = (function (_super) {
12427 __extends(FilterSubscriber, _super);
12428 function FilterSubscriber(destination, predicate, thisArg) {
12429 _super.call(this, destination);
12430 this.predicate = predicate;
12431 this.thisArg = thisArg;
12434 // the try catch block below is left specifically for
12435 // optimization and perf reasons. a tryCatcher is not necessary here.
12436 FilterSubscriber.prototype._next = function (value) {
12439 result = this.predicate.call(this.thisArg, value, this.count++);
12442 this.destination.error(err);
12446 this.destination.next(value);
12449 return FilterSubscriber;
12450 }(Subscriber_1.Subscriber));
12452 },{"../Subscriber":36}],175:[function(require,module,exports){
12454 var __extends = (this && this.__extends) || function (d, b) {
12455 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12456 function __() { this.constructor = d; }
12457 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12459 var Subscriber_1 = require('../Subscriber');
12460 var Subscription_1 = require('../Subscription');
12462 * Returns an Observable that mirrors the source Observable, but will call a specified function when
12463 * the source terminates on complete or error.
12464 * @param {function} callback Function to be called when source terminates.
12465 * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.
12467 * @owner Observable
12469 function finalize(callback) {
12470 return function (source) { return source.lift(new FinallyOperator(callback)); };
12472 exports.finalize = finalize;
12473 var FinallyOperator = (function () {
12474 function FinallyOperator(callback) {
12475 this.callback = callback;
12477 FinallyOperator.prototype.call = function (subscriber, source) {
12478 return source.subscribe(new FinallySubscriber(subscriber, this.callback));
12480 return FinallyOperator;
12483 * We need this JSDoc comment for affecting ESDoc.
12485 * @extends {Ignored}
12487 var FinallySubscriber = (function (_super) {
12488 __extends(FinallySubscriber, _super);
12489 function FinallySubscriber(destination, callback) {
12490 _super.call(this, destination);
12491 this.add(new Subscription_1.Subscription(callback));
12493 return FinallySubscriber;
12494 }(Subscriber_1.Subscriber));
12496 },{"../Subscriber":36,"../Subscription":37}],176:[function(require,module,exports){
12498 var __extends = (this && this.__extends) || function (d, b) {
12499 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12500 function __() { this.constructor = d; }
12501 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12503 var Subscriber_1 = require('../Subscriber');
12504 var EmptyError_1 = require('../util/EmptyError');
12506 * Emits only the first value (or the first value that meets some condition)
12507 * emitted by the source Observable.
12509 * <span class="informal">Emits only the first value. Or emits only the first
12510 * value that passes some test.</span>
12512 * <img src="./img/first.png" width="100%">
12514 * If called with no arguments, `first` emits the first value of the source
12515 * Observable, then completes. If called with a `predicate` function, `first`
12516 * emits the first value of the source that matches the specified condition. It
12517 * may also take a `resultSelector` function to produce the output value from
12518 * the input value, and a `defaultValue` to emit in case the source completes
12519 * before it is able to emit a valid value. Throws an error if `defaultValue`
12520 * was not provided and a matching element is not found.
12522 * @example <caption>Emit only the first click that happens on the DOM</caption>
12523 * var clicks = Rx.Observable.fromEvent(document, 'click');
12524 * var result = clicks.first();
12525 * result.subscribe(x => console.log(x));
12527 * @example <caption>Emits the first click that happens on a DIV</caption>
12528 * var clicks = Rx.Observable.fromEvent(document, 'click');
12529 * var result = clicks.first(ev => ev.target.tagName === 'DIV');
12530 * result.subscribe(x => console.log(x));
12532 * @see {@link filter}
12533 * @see {@link find}
12534 * @see {@link take}
12536 * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
12537 * callback if the Observable completes before any `next` notification was sent.
12539 * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
12540 * An optional function called with each item to test for condition matching.
12541 * @param {function(value: T, index: number): R} [resultSelector] A function to
12542 * produce the value on the output Observable based on the values
12543 * and the indices of the source Observable. The arguments passed to this
12545 * - `value`: the value that was emitted on the source.
12546 * - `index`: the "index" of the value from the source.
12547 * @param {R} [defaultValue] The default value emitted in case no valid value
12548 * was found on the source.
12549 * @return {Observable<T|R>} An Observable of the first item that matches the
12552 * @owner Observable
12554 function first(predicate, resultSelector, defaultValue) {
12555 return function (source) { return source.lift(new FirstOperator(predicate, resultSelector, defaultValue, source)); };
12557 exports.first = first;
12558 var FirstOperator = (function () {
12559 function FirstOperator(predicate, resultSelector, defaultValue, source) {
12560 this.predicate = predicate;
12561 this.resultSelector = resultSelector;
12562 this.defaultValue = defaultValue;
12563 this.source = source;
12565 FirstOperator.prototype.call = function (observer, source) {
12566 return source.subscribe(new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
12568 return FirstOperator;
12571 * We need this JSDoc comment for affecting ESDoc.
12573 * @extends {Ignored}
12575 var FirstSubscriber = (function (_super) {
12576 __extends(FirstSubscriber, _super);
12577 function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) {
12578 _super.call(this, destination);
12579 this.predicate = predicate;
12580 this.resultSelector = resultSelector;
12581 this.defaultValue = defaultValue;
12582 this.source = source;
12584 this.hasCompleted = false;
12585 this._emitted = false;
12587 FirstSubscriber.prototype._next = function (value) {
12588 var index = this.index++;
12589 if (this.predicate) {
12590 this._tryPredicate(value, index);
12593 this._emit(value, index);
12596 FirstSubscriber.prototype._tryPredicate = function (value, index) {
12599 result = this.predicate(value, index, this.source);
12602 this.destination.error(err);
12606 this._emit(value, index);
12609 FirstSubscriber.prototype._emit = function (value, index) {
12610 if (this.resultSelector) {
12611 this._tryResultSelector(value, index);
12614 this._emitFinal(value);
12616 FirstSubscriber.prototype._tryResultSelector = function (value, index) {
12619 result = this.resultSelector(value, index);
12622 this.destination.error(err);
12625 this._emitFinal(result);
12627 FirstSubscriber.prototype._emitFinal = function (value) {
12628 var destination = this.destination;
12629 if (!this._emitted) {
12630 this._emitted = true;
12631 destination.next(value);
12632 destination.complete();
12633 this.hasCompleted = true;
12636 FirstSubscriber.prototype._complete = function () {
12637 var destination = this.destination;
12638 if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') {
12639 destination.next(this.defaultValue);
12640 destination.complete();
12642 else if (!this.hasCompleted) {
12643 destination.error(new EmptyError_1.EmptyError);
12646 return FirstSubscriber;
12647 }(Subscriber_1.Subscriber));
12649 },{"../Subscriber":36,"../util/EmptyError":219}],177:[function(require,module,exports){
12651 var __extends = (this && this.__extends) || function (d, b) {
12652 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12653 function __() { this.constructor = d; }
12654 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12656 var Subscriber_1 = require('../Subscriber');
12657 var EmptyError_1 = require('../util/EmptyError');
12658 /* tslint:enable:max-line-length */
12660 * Returns an Observable that emits only the last item emitted by the source Observable.
12661 * It optionally takes a predicate function as a parameter, in which case, rather than emitting
12662 * the last item from the source Observable, the resulting Observable will emit the last item
12663 * from the source Observable that satisfies the predicate.
12665 * <img src="./img/last.png" width="100%">
12667 * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
12668 * callback if the Observable completes before any `next` notification was sent.
12669 * @param {function} predicate - The condition any source emitted item has to satisfy.
12670 * @return {Observable} An Observable that emits only the last item satisfying the given condition
12671 * from the source, or an NoSuchElementException if no such items are emitted.
12672 * @throws - Throws if no items that match the predicate are emitted by the source Observable.
12674 * @owner Observable
12676 function last(predicate, resultSelector, defaultValue) {
12677 return function (source) { return source.lift(new LastOperator(predicate, resultSelector, defaultValue, source)); };
12679 exports.last = last;
12680 var LastOperator = (function () {
12681 function LastOperator(predicate, resultSelector, defaultValue, source) {
12682 this.predicate = predicate;
12683 this.resultSelector = resultSelector;
12684 this.defaultValue = defaultValue;
12685 this.source = source;
12687 LastOperator.prototype.call = function (observer, source) {
12688 return source.subscribe(new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
12690 return LastOperator;
12693 * We need this JSDoc comment for affecting ESDoc.
12695 * @extends {Ignored}
12697 var LastSubscriber = (function (_super) {
12698 __extends(LastSubscriber, _super);
12699 function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) {
12700 _super.call(this, destination);
12701 this.predicate = predicate;
12702 this.resultSelector = resultSelector;
12703 this.defaultValue = defaultValue;
12704 this.source = source;
12705 this.hasValue = false;
12707 if (typeof defaultValue !== 'undefined') {
12708 this.lastValue = defaultValue;
12709 this.hasValue = true;
12712 LastSubscriber.prototype._next = function (value) {
12713 var index = this.index++;
12714 if (this.predicate) {
12715 this._tryPredicate(value, index);
12718 if (this.resultSelector) {
12719 this._tryResultSelector(value, index);
12722 this.lastValue = value;
12723 this.hasValue = true;
12726 LastSubscriber.prototype._tryPredicate = function (value, index) {
12729 result = this.predicate(value, index, this.source);
12732 this.destination.error(err);
12736 if (this.resultSelector) {
12737 this._tryResultSelector(value, index);
12740 this.lastValue = value;
12741 this.hasValue = true;
12744 LastSubscriber.prototype._tryResultSelector = function (value, index) {
12747 result = this.resultSelector(value, index);
12750 this.destination.error(err);
12753 this.lastValue = result;
12754 this.hasValue = true;
12756 LastSubscriber.prototype._complete = function () {
12757 var destination = this.destination;
12758 if (this.hasValue) {
12759 destination.next(this.lastValue);
12760 destination.complete();
12763 destination.error(new EmptyError_1.EmptyError);
12766 return LastSubscriber;
12767 }(Subscriber_1.Subscriber));
12769 },{"../Subscriber":36,"../util/EmptyError":219}],178:[function(require,module,exports){
12771 var __extends = (this && this.__extends) || function (d, b) {
12772 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12773 function __() { this.constructor = d; }
12774 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12776 var Subscriber_1 = require('../Subscriber');
12778 * Applies a given `project` function to each value emitted by the source
12779 * Observable, and emits the resulting values as an Observable.
12781 * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
12782 * it passes each source value through a transformation function to get
12783 * corresponding output values.</span>
12785 * <img src="./img/map.png" width="100%">
12787 * Similar to the well known `Array.prototype.map` function, this operator
12788 * applies a projection to each value and emits that projection in the output
12791 * @example <caption>Map every click to the clientX position of that click</caption>
12792 * var clicks = Rx.Observable.fromEvent(document, 'click');
12793 * var positions = clicks.map(ev => ev.clientX);
12794 * positions.subscribe(x => console.log(x));
12796 * @see {@link mapTo}
12797 * @see {@link pluck}
12799 * @param {function(value: T, index: number): R} project The function to apply
12800 * to each `value` emitted by the source Observable. The `index` parameter is
12801 * the number `i` for the i-th emission that has happened since the
12802 * subscription, starting from the number `0`.
12803 * @param {any} [thisArg] An optional argument to define what `this` is in the
12804 * `project` function.
12805 * @return {Observable<R>} An Observable that emits the values from the source
12806 * Observable transformed by the given `project` function.
12808 * @owner Observable
12810 function map(project, thisArg) {
12811 return function mapOperation(source) {
12812 if (typeof project !== 'function') {
12813 throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
12815 return source.lift(new MapOperator(project, thisArg));
12819 var MapOperator = (function () {
12820 function MapOperator(project, thisArg) {
12821 this.project = project;
12822 this.thisArg = thisArg;
12824 MapOperator.prototype.call = function (subscriber, source) {
12825 return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
12827 return MapOperator;
12829 exports.MapOperator = MapOperator;
12831 * We need this JSDoc comment for affecting ESDoc.
12833 * @extends {Ignored}
12835 var MapSubscriber = (function (_super) {
12836 __extends(MapSubscriber, _super);
12837 function MapSubscriber(destination, project, thisArg) {
12838 _super.call(this, destination);
12839 this.project = project;
12841 this.thisArg = thisArg || this;
12843 // NOTE: This looks unoptimized, but it's actually purposefully NOT
12844 // using try/catch optimizations.
12845 MapSubscriber.prototype._next = function (value) {
12848 result = this.project.call(this.thisArg, value, this.count++);
12851 this.destination.error(err);
12854 this.destination.next(result);
12856 return MapSubscriber;
12857 }(Subscriber_1.Subscriber));
12859 },{"../Subscriber":36}],179:[function(require,module,exports){
12861 var Observable_1 = require('../Observable');
12862 var ArrayObservable_1 = require('../observable/ArrayObservable');
12863 var mergeAll_1 = require('./mergeAll');
12864 var isScheduler_1 = require('../util/isScheduler');
12865 /* tslint:enable:max-line-length */
12867 var observables = [];
12868 for (var _i = 0; _i < arguments.length; _i++) {
12869 observables[_i - 0] = arguments[_i];
12871 return function (source) { return source.lift.call(mergeStatic.apply(void 0, [source].concat(observables))); };
12873 exports.merge = merge;
12874 /* tslint:enable:max-line-length */
12876 * Creates an output Observable which concurrently emits all values from every
12877 * given input Observable.
12879 * <span class="informal">Flattens multiple Observables together by blending
12880 * their values into one Observable.</span>
12882 * <img src="./img/merge.png" width="100%">
12884 * `merge` subscribes to each given input Observable (as arguments), and simply
12885 * forwards (without doing any transformation) all the values from all the input
12886 * Observables to the output Observable. The output Observable only completes
12887 * once all input Observables have completed. Any error delivered by an input
12888 * Observable will be immediately emitted on the output Observable.
12890 * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
12891 * var clicks = Rx.Observable.fromEvent(document, 'click');
12892 * var timer = Rx.Observable.interval(1000);
12893 * var clicksOrTimer = Rx.Observable.merge(clicks, timer);
12894 * clicksOrTimer.subscribe(x => console.log(x));
12896 * // Results in the following:
12897 * // timer will emit ascending values, one every second(1000ms) to console
12898 * // clicks logs MouseEvents to console everytime the "document" is clicked
12899 * // Since the two streams are merged you see these happening
12900 * // as they occur.
12902 * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
12903 * var timer1 = Rx.Observable.interval(1000).take(10);
12904 * var timer2 = Rx.Observable.interval(2000).take(6);
12905 * var timer3 = Rx.Observable.interval(500).take(10);
12906 * var concurrent = 2; // the argument
12907 * var merged = Rx.Observable.merge(timer1, timer2, timer3, concurrent);
12908 * merged.subscribe(x => console.log(x));
12910 * // Results in the following:
12911 * // - First timer1 and timer2 will run concurrently
12912 * // - timer1 will emit a value every 1000ms for 10 iterations
12913 * // - timer2 will emit a value every 2000ms for 6 iterations
12914 * // - after timer1 hits it's max iteration, timer2 will
12915 * // continue, and timer3 will start to run concurrently with timer2
12916 * // - when timer2 hits it's max iteration it terminates, and
12917 * // timer3 will continue to emit a value every 500ms until it is complete
12919 * @see {@link mergeAll}
12920 * @see {@link mergeMap}
12921 * @see {@link mergeMapTo}
12922 * @see {@link mergeScan}
12924 * @param {...ObservableInput} observables Input Observables to merge together.
12925 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
12926 * Observables being subscribed to concurrently.
12927 * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
12928 * concurrency of input Observables.
12929 * @return {Observable} an Observable that emits items that are the result of
12930 * every input Observable.
12933 * @owner Observable
12935 function mergeStatic() {
12936 var observables = [];
12937 for (var _i = 0; _i < arguments.length; _i++) {
12938 observables[_i - 0] = arguments[_i];
12940 var concurrent = Number.POSITIVE_INFINITY;
12941 var scheduler = null;
12942 var last = observables[observables.length - 1];
12943 if (isScheduler_1.isScheduler(last)) {
12944 scheduler = observables.pop();
12945 if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
12946 concurrent = observables.pop();
12949 else if (typeof last === 'number') {
12950 concurrent = observables.pop();
12952 if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
12953 return observables[0];
12955 return mergeAll_1.mergeAll(concurrent)(new ArrayObservable_1.ArrayObservable(observables, scheduler));
12957 exports.mergeStatic = mergeStatic;
12959 },{"../Observable":29,"../observable/ArrayObservable":93,"../util/isScheduler":233,"./mergeAll":180}],180:[function(require,module,exports){
12961 var mergeMap_1 = require('./mergeMap');
12962 var identity_1 = require('../util/identity');
12964 * Converts a higher-order Observable into a first-order Observable which
12965 * concurrently delivers all values that are emitted on the inner Observables.
12967 * <span class="informal">Flattens an Observable-of-Observables.</span>
12969 * <img src="./img/mergeAll.png" width="100%">
12971 * `mergeAll` subscribes to an Observable that emits Observables, also known as
12972 * a higher-order Observable. Each time it observes one of these emitted inner
12973 * Observables, it subscribes to that and delivers all the values from the
12974 * inner Observable on the output Observable. The output Observable only
12975 * completes once all inner Observables have completed. Any error delivered by
12976 * a inner Observable will be immediately emitted on the output Observable.
12978 * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
12979 * var clicks = Rx.Observable.fromEvent(document, 'click');
12980 * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
12981 * var firstOrder = higherOrder.mergeAll();
12982 * firstOrder.subscribe(x => console.log(x));
12984 * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
12985 * var clicks = Rx.Observable.fromEvent(document, 'click');
12986 * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
12987 * var firstOrder = higherOrder.mergeAll(2);
12988 * firstOrder.subscribe(x => console.log(x));
12990 * @see {@link combineAll}
12991 * @see {@link concatAll}
12992 * @see {@link exhaust}
12993 * @see {@link merge}
12994 * @see {@link mergeMap}
12995 * @see {@link mergeMapTo}
12996 * @see {@link mergeScan}
12997 * @see {@link switch}
12998 * @see {@link zipAll}
13000 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
13001 * Observables being subscribed to concurrently.
13002 * @return {Observable} An Observable that emits values coming from all the
13003 * inner Observables emitted by the source Observable.
13005 * @owner Observable
13007 function mergeAll(concurrent) {
13008 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
13009 return mergeMap_1.mergeMap(identity_1.identity, null, concurrent);
13011 exports.mergeAll = mergeAll;
13013 },{"../util/identity":225,"./mergeMap":181}],181:[function(require,module,exports){
13015 var __extends = (this && this.__extends) || function (d, b) {
13016 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13017 function __() { this.constructor = d; }
13018 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13020 var subscribeToResult_1 = require('../util/subscribeToResult');
13021 var OuterSubscriber_1 = require('../OuterSubscriber');
13022 /* tslint:enable:max-line-length */
13024 * Projects each source value to an Observable which is merged in the output
13027 * <span class="informal">Maps each value to an Observable, then flattens all of
13028 * these inner Observables using {@link mergeAll}.</span>
13030 * <img src="./img/mergeMap.png" width="100%">
13032 * Returns an Observable that emits items based on applying a function that you
13033 * supply to each item emitted by the source Observable, where that function
13034 * returns an Observable, and then merging those resulting Observables and
13035 * emitting the results of this merger.
13037 * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
13038 * var letters = Rx.Observable.of('a', 'b', 'c');
13039 * var result = letters.mergeMap(x =>
13040 * Rx.Observable.interval(1000).map(i => x+i)
13042 * result.subscribe(x => console.log(x));
13044 * // Results in the following:
13051 * // continues to list a,b,c with respective ascending integers
13053 * @see {@link concatMap}
13054 * @see {@link exhaustMap}
13055 * @see {@link merge}
13056 * @see {@link mergeAll}
13057 * @see {@link mergeMapTo}
13058 * @see {@link mergeScan}
13059 * @see {@link switchMap}
13061 * @param {function(value: T, ?index: number): ObservableInput} project A function
13062 * that, when applied to an item emitted by the source Observable, returns an
13064 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
13065 * A function to produce the value on the output Observable based on the values
13066 * and the indices of the source (outer) emission and the inner Observable
13067 * emission. The arguments passed to this function are:
13068 * - `outerValue`: the value that came from the source
13069 * - `innerValue`: the value that came from the projected Observable
13070 * - `outerIndex`: the "index" of the value that came from the source
13071 * - `innerIndex`: the "index" of the value from the projected Observable
13072 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
13073 * Observables being subscribed to concurrently.
13074 * @return {Observable} An Observable that emits the result of applying the
13075 * projection function (and the optional `resultSelector`) to each item emitted
13076 * by the source Observable and merging the results of the Observables obtained
13077 * from this transformation.
13079 * @owner Observable
13081 function mergeMap(project, resultSelector, concurrent) {
13082 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
13083 return function mergeMapOperatorFunction(source) {
13084 if (typeof resultSelector === 'number') {
13085 concurrent = resultSelector;
13086 resultSelector = null;
13088 return source.lift(new MergeMapOperator(project, resultSelector, concurrent));
13091 exports.mergeMap = mergeMap;
13092 var MergeMapOperator = (function () {
13093 function MergeMapOperator(project, resultSelector, concurrent) {
13094 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
13095 this.project = project;
13096 this.resultSelector = resultSelector;
13097 this.concurrent = concurrent;
13099 MergeMapOperator.prototype.call = function (observer, source) {
13100 return source.subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent));
13102 return MergeMapOperator;
13104 exports.MergeMapOperator = MergeMapOperator;
13106 * We need this JSDoc comment for affecting ESDoc.
13108 * @extends {Ignored}
13110 var MergeMapSubscriber = (function (_super) {
13111 __extends(MergeMapSubscriber, _super);
13112 function MergeMapSubscriber(destination, project, resultSelector, concurrent) {
13113 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
13114 _super.call(this, destination);
13115 this.project = project;
13116 this.resultSelector = resultSelector;
13117 this.concurrent = concurrent;
13118 this.hasCompleted = false;
13123 MergeMapSubscriber.prototype._next = function (value) {
13124 if (this.active < this.concurrent) {
13125 this._tryNext(value);
13128 this.buffer.push(value);
13131 MergeMapSubscriber.prototype._tryNext = function (value) {
13133 var index = this.index++;
13135 result = this.project(value, index);
13138 this.destination.error(err);
13142 this._innerSub(result, value, index);
13144 MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
13145 this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index));
13147 MergeMapSubscriber.prototype._complete = function () {
13148 this.hasCompleted = true;
13149 if (this.active === 0 && this.buffer.length === 0) {
13150 this.destination.complete();
13153 MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13154 if (this.resultSelector) {
13155 this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex);
13158 this.destination.next(innerValue);
13161 MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
13164 result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
13167 this.destination.error(err);
13170 this.destination.next(result);
13172 MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
13173 var buffer = this.buffer;
13174 this.remove(innerSub);
13176 if (buffer.length > 0) {
13177 this._next(buffer.shift());
13179 else if (this.active === 0 && this.hasCompleted) {
13180 this.destination.complete();
13183 return MergeMapSubscriber;
13184 }(OuterSubscriber_1.OuterSubscriber));
13185 exports.MergeMapSubscriber = MergeMapSubscriber;
13187 },{"../OuterSubscriber":31,"../util/subscribeToResult":237}],182:[function(require,module,exports){
13189 var ConnectableObservable_1 = require('../observable/ConnectableObservable');
13190 /* tslint:enable:max-line-length */
13192 * Returns an Observable that emits the results of invoking a specified selector on items
13193 * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.
13195 * <img src="./img/multicast.png" width="100%">
13197 * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through
13198 * which the source sequence's elements will be multicast to the selector function
13199 * or Subject to push source elements into.
13200 * @param {Function} [selector] - Optional selector function that can use the multicasted source stream
13201 * as many times as needed, without causing multiple subscriptions to the source stream.
13202 * Subscribers to the given source will receive all notifications of the source from the
13203 * time of the subscription forward.
13204 * @return {Observable} An Observable that emits the results of invoking the selector
13205 * on the items emitted by a `ConnectableObservable` that shares a single subscription to
13206 * the underlying stream.
13207 * @method multicast
13208 * @owner Observable
13210 function multicast(subjectOrSubjectFactory, selector) {
13211 return function multicastOperatorFunction(source) {
13212 var subjectFactory;
13213 if (typeof subjectOrSubjectFactory === 'function') {
13214 subjectFactory = subjectOrSubjectFactory;
13217 subjectFactory = function subjectFactory() {
13218 return subjectOrSubjectFactory;
13221 if (typeof selector === 'function') {
13222 return source.lift(new MulticastOperator(subjectFactory, selector));
13224 var connectable = Object.create(source, ConnectableObservable_1.connectableObservableDescriptor);
13225 connectable.source = source;
13226 connectable.subjectFactory = subjectFactory;
13227 return connectable;
13230 exports.multicast = multicast;
13231 var MulticastOperator = (function () {
13232 function MulticastOperator(subjectFactory, selector) {
13233 this.subjectFactory = subjectFactory;
13234 this.selector = selector;
13236 MulticastOperator.prototype.call = function (subscriber, source) {
13237 var selector = this.selector;
13238 var subject = this.subjectFactory();
13239 var subscription = selector(subject).subscribe(subscriber);
13240 subscription.add(source.subscribe(subject));
13241 return subscription;
13243 return MulticastOperator;
13245 exports.MulticastOperator = MulticastOperator;
13247 },{"../observable/ConnectableObservable":94}],183:[function(require,module,exports){
13249 var __extends = (this && this.__extends) || function (d, b) {
13250 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13251 function __() { this.constructor = d; }
13252 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13254 var Subscriber_1 = require('../Subscriber');
13255 var Notification_1 = require('../Notification');
13258 * Re-emits all notifications from source Observable with specified scheduler.
13260 * <span class="informal">Ensure a specific scheduler is used, from outside of an Observable.</span>
13262 * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule
13263 * notifications emitted by the source Observable. It might be useful, if you do not have control over
13264 * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless.
13266 * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable,
13267 * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal
13268 * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits
13269 * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`.
13270 * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split
13271 * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source
13272 * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a
13273 * little bit more, to ensure that they are emitted at expected moments.
13275 * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications
13276 * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn`
13277 * will delay all notifications - including error notifications - while `delay` will pass through error
13278 * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator
13279 * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used
13280 * for notification emissions in general.
13282 * @example <caption>Ensure values in subscribe are called just before browser repaint.</caption>
13283 * const intervals = Rx.Observable.interval(10); // Intervals are scheduled
13284 * // with async scheduler by default...
13287 * .observeOn(Rx.Scheduler.animationFrame) // ...but we will observe on animationFrame
13288 * .subscribe(val => { // scheduler to ensure smooth animation.
13289 * someDiv.style.height = val + 'px';
13292 * @see {@link delay}
13294 * @param {IScheduler} scheduler Scheduler that will be used to reschedule notifications from source Observable.
13295 * @param {number} [delay] Number of milliseconds that states with what delay every notification should be rescheduled.
13296 * @return {Observable<T>} Observable that emits the same notifications as the source Observable,
13297 * but with provided scheduler.
13299 * @method observeOn
13300 * @owner Observable
13302 function observeOn(scheduler, delay) {
13303 if (delay === void 0) { delay = 0; }
13304 return function observeOnOperatorFunction(source) {
13305 return source.lift(new ObserveOnOperator(scheduler, delay));
13308 exports.observeOn = observeOn;
13309 var ObserveOnOperator = (function () {
13310 function ObserveOnOperator(scheduler, delay) {
13311 if (delay === void 0) { delay = 0; }
13312 this.scheduler = scheduler;
13313 this.delay = delay;
13315 ObserveOnOperator.prototype.call = function (subscriber, source) {
13316 return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
13318 return ObserveOnOperator;
13320 exports.ObserveOnOperator = ObserveOnOperator;
13322 * We need this JSDoc comment for affecting ESDoc.
13324 * @extends {Ignored}
13326 var ObserveOnSubscriber = (function (_super) {
13327 __extends(ObserveOnSubscriber, _super);
13328 function ObserveOnSubscriber(destination, scheduler, delay) {
13329 if (delay === void 0) { delay = 0; }
13330 _super.call(this, destination);
13331 this.scheduler = scheduler;
13332 this.delay = delay;
13334 ObserveOnSubscriber.dispatch = function (arg) {
13335 var notification = arg.notification, destination = arg.destination;
13336 notification.observe(destination);
13337 this.unsubscribe();
13339 ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
13340 this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
13342 ObserveOnSubscriber.prototype._next = function (value) {
13343 this.scheduleMessage(Notification_1.Notification.createNext(value));
13345 ObserveOnSubscriber.prototype._error = function (err) {
13346 this.scheduleMessage(Notification_1.Notification.createError(err));
13348 ObserveOnSubscriber.prototype._complete = function () {
13349 this.scheduleMessage(Notification_1.Notification.createComplete());
13351 return ObserveOnSubscriber;
13352 }(Subscriber_1.Subscriber));
13353 exports.ObserveOnSubscriber = ObserveOnSubscriber;
13354 var ObserveOnMessage = (function () {
13355 function ObserveOnMessage(notification, destination) {
13356 this.notification = notification;
13357 this.destination = destination;
13359 return ObserveOnMessage;
13361 exports.ObserveOnMessage = ObserveOnMessage;
13363 },{"../Notification":28,"../Subscriber":36}],184:[function(require,module,exports){
13365 var __extends = (this && this.__extends) || function (d, b) {
13366 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13367 function __() { this.constructor = d; }
13368 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13370 var Subscriber_1 = require('../Subscriber');
13372 * Groups pairs of consecutive emissions together and emits them as an array of
13375 * <span class="informal">Puts the current value and previous value together as
13376 * an array, and emits that.</span>
13378 * <img src="./img/pairwise.png" width="100%">
13380 * The Nth emission from the source Observable will cause the output Observable
13381 * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
13382 * pair. For this reason, `pairwise` emits on the second and subsequent
13383 * emissions from the source Observable, but not on the first emission, because
13384 * there is no previous value in that case.
13386 * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
13387 * var clicks = Rx.Observable.fromEvent(document, 'click');
13388 * var pairs = clicks.pairwise();
13389 * var distance = pairs.map(pair => {
13390 * var x0 = pair[0].clientX;
13391 * var y0 = pair[0].clientY;
13392 * var x1 = pair[1].clientX;
13393 * var y1 = pair[1].clientY;
13394 * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
13396 * distance.subscribe(x => console.log(x));
13398 * @see {@link buffer}
13399 * @see {@link bufferCount}
13401 * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
13402 * consecutive values from the source Observable.
13404 * @owner Observable
13406 function pairwise() {
13407 return function (source) { return source.lift(new PairwiseOperator()); };
13409 exports.pairwise = pairwise;
13410 var PairwiseOperator = (function () {
13411 function PairwiseOperator() {
13413 PairwiseOperator.prototype.call = function (subscriber, source) {
13414 return source.subscribe(new PairwiseSubscriber(subscriber));
13416 return PairwiseOperator;
13419 * We need this JSDoc comment for affecting ESDoc.
13421 * @extends {Ignored}
13423 var PairwiseSubscriber = (function (_super) {
13424 __extends(PairwiseSubscriber, _super);
13425 function PairwiseSubscriber(destination) {
13426 _super.call(this, destination);
13427 this.hasPrev = false;
13429 PairwiseSubscriber.prototype._next = function (value) {
13430 if (this.hasPrev) {
13431 this.destination.next([this.prev, value]);
13434 this.hasPrev = true;
13438 return PairwiseSubscriber;
13439 }(Subscriber_1.Subscriber));
13441 },{"../Subscriber":36}],185:[function(require,module,exports){
13443 var map_1 = require('./map');
13445 * Maps each source value (an object) to its specified nested property.
13447 * <span class="informal">Like {@link map}, but meant only for picking one of
13448 * the nested properties of every emitted object.</span>
13450 * <img src="./img/pluck.png" width="100%">
13452 * Given a list of strings describing a path to an object property, retrieves
13453 * the value of a specified nested property from all values in the source
13454 * Observable. If a property can't be resolved, it will return `undefined` for
13457 * @example <caption>Map every click to the tagName of the clicked target element</caption>
13458 * var clicks = Rx.Observable.fromEvent(document, 'click');
13459 * var tagNames = clicks.pluck('target', 'tagName');
13460 * tagNames.subscribe(x => console.log(x));
13464 * @param {...string} properties The nested properties to pluck from each source
13465 * value (an object).
13466 * @return {Observable} A new Observable of property values from the source values.
13468 * @owner Observable
13471 var properties = [];
13472 for (var _i = 0; _i < arguments.length; _i++) {
13473 properties[_i - 0] = arguments[_i];
13475 var length = properties.length;
13476 if (length === 0) {
13477 throw new Error('list of properties cannot be empty.');
13479 return function (source) { return map_1.map(plucker(properties, length))(source); };
13481 exports.pluck = pluck;
13482 function plucker(props, length) {
13483 var mapper = function (x) {
13484 var currentProp = x;
13485 for (var i = 0; i < length; i++) {
13486 var p = currentProp[props[i]];
13487 if (typeof p !== 'undefined') {
13494 return currentProp;
13499 },{"./map":178}],186:[function(require,module,exports){
13501 var Subject_1 = require('../Subject');
13502 var multicast_1 = require('./multicast');
13503 /* tslint:enable:max-line-length */
13505 * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
13506 * before it begins emitting items to those Observers that have subscribed to it.
13508 * <img src="./img/publish.png" width="100%">
13510 * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
13511 * as needed, without causing multiple subscriptions to the source sequence.
13512 * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
13513 * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
13515 * @owner Observable
13517 function publish(selector) {
13519 multicast_1.multicast(function () { return new Subject_1.Subject(); }, selector) :
13520 multicast_1.multicast(new Subject_1.Subject());
13522 exports.publish = publish;
13524 },{"../Subject":34,"./multicast":182}],187:[function(require,module,exports){
13526 var ReplaySubject_1 = require('../ReplaySubject');
13527 var multicast_1 = require('./multicast');
13528 /* tslint:enable:max-line-length */
13529 function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) {
13530 if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') {
13531 scheduler = selectorOrScheduler;
13533 var selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined;
13534 var subject = new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler);
13535 return function (source) { return multicast_1.multicast(function () { return subject; }, selector)(source); };
13537 exports.publishReplay = publishReplay;
13539 },{"../ReplaySubject":32,"./multicast":182}],188:[function(require,module,exports){
13541 var scan_1 = require('./scan');
13542 var takeLast_1 = require('./takeLast');
13543 var defaultIfEmpty_1 = require('./defaultIfEmpty');
13544 var pipe_1 = require('../util/pipe');
13545 /* tslint:enable:max-line-length */
13547 * Applies an accumulator function over the source Observable, and returns the
13548 * accumulated result when the source completes, given an optional seed value.
13550 * <span class="informal">Combines together all values emitted on the source,
13551 * using an accumulator function that knows how to join a new source value into
13552 * the accumulation from the past.</span>
13554 * <img src="./img/reduce.png" width="100%">
13557 * [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce),
13558 * `reduce` applies an `accumulator` function against an accumulation and each
13559 * value of the source Observable (from the past) to reduce it to a single
13560 * value, emitted on the output Observable. Note that `reduce` will only emit
13561 * one value, only when the source Observable completes. It is equivalent to
13562 * applying operator {@link scan} followed by operator {@link last}.
13564 * Returns an Observable that applies a specified `accumulator` function to each
13565 * item emitted by the source Observable. If a `seed` value is specified, then
13566 * that value will be used as the initial value for the accumulator. If no seed
13567 * value is specified, the first item of the source is used as the seed.
13569 * @example <caption>Count the number of click events that happened in 5 seconds</caption>
13570 * var clicksInFiveSeconds = Rx.Observable.fromEvent(document, 'click')
13571 * .takeUntil(Rx.Observable.interval(5000));
13572 * var ones = clicksInFiveSeconds.mapTo(1);
13574 * var count = ones.reduce((acc, one) => acc + one, seed);
13575 * count.subscribe(x => console.log(x));
13577 * @see {@link count}
13578 * @see {@link expand}
13579 * @see {@link mergeScan}
13580 * @see {@link scan}
13582 * @param {function(acc: R, value: T, index: number): R} accumulator The accumulator function
13583 * called on each source value.
13584 * @param {R} [seed] The initial accumulation value.
13585 * @return {Observable<R>} An Observable that emits a single value that is the
13586 * result of accumulating the values emitted by the source Observable.
13588 * @owner Observable
13590 function reduce(accumulator, seed) {
13591 // providing a seed of `undefined` *should* be valid and trigger
13592 // hasSeed! so don't use `seed !== undefined` checks!
13593 // For this reason, we have to check it here at the original call site
13594 // otherwise inside Operator/Subscriber we won't know if `undefined`
13595 // means they didn't provide anything or if they literally provided `undefined`
13596 if (arguments.length >= 2) {
13597 return function reduceOperatorFunctionWithSeed(source) {
13598 return pipe_1.pipe(scan_1.scan(accumulator, seed), takeLast_1.takeLast(1), defaultIfEmpty_1.defaultIfEmpty(seed))(source);
13601 return function reduceOperatorFunction(source) {
13602 return pipe_1.pipe(scan_1.scan(function (acc, value, index) {
13603 return accumulator(acc, value, index + 1);
13604 }), takeLast_1.takeLast(1))(source);
13607 exports.reduce = reduce;
13609 },{"../util/pipe":235,"./defaultIfEmpty":169,"./scan":192,"./takeLast":200}],189:[function(require,module,exports){
13611 var __extends = (this && this.__extends) || function (d, b) {
13612 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13613 function __() { this.constructor = d; }
13614 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13616 var Subscriber_1 = require('../Subscriber');
13617 function refCount() {
13618 return function refCountOperatorFunction(source) {
13619 return source.lift(new RefCountOperator(source));
13622 exports.refCount = refCount;
13623 var RefCountOperator = (function () {
13624 function RefCountOperator(connectable) {
13625 this.connectable = connectable;
13627 RefCountOperator.prototype.call = function (subscriber, source) {
13628 var connectable = this.connectable;
13629 connectable._refCount++;
13630 var refCounter = new RefCountSubscriber(subscriber, connectable);
13631 var subscription = source.subscribe(refCounter);
13632 if (!refCounter.closed) {
13633 refCounter.connection = connectable.connect();
13635 return subscription;
13637 return RefCountOperator;
13639 var RefCountSubscriber = (function (_super) {
13640 __extends(RefCountSubscriber, _super);
13641 function RefCountSubscriber(destination, connectable) {
13642 _super.call(this, destination);
13643 this.connectable = connectable;
13645 RefCountSubscriber.prototype._unsubscribe = function () {
13646 var connectable = this.connectable;
13647 if (!connectable) {
13648 this.connection = null;
13651 this.connectable = null;
13652 var refCount = connectable._refCount;
13653 if (refCount <= 0) {
13654 this.connection = null;
13657 connectable._refCount = refCount - 1;
13658 if (refCount > 1) {
13659 this.connection = null;
13663 // Compare the local RefCountSubscriber's connection Subscription to the
13664 // connection Subscription on the shared ConnectableObservable. In cases
13665 // where the ConnectableObservable source synchronously emits values, and
13666 // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
13667 // execution continues to here before the RefCountOperator has a chance to
13668 // supply the RefCountSubscriber with the shared connection Subscription.
13671 // Observable.range(0, 10)
13677 // In order to account for this case, RefCountSubscriber should only dispose
13678 // the ConnectableObservable's shared connection Subscription if the
13679 // connection Subscription exists, *and* either:
13680 // a. RefCountSubscriber doesn't have a reference to the shared connection
13681 // Subscription yet, or,
13682 // b. RefCountSubscriber's connection Subscription reference is identical
13683 // to the shared connection Subscription
13685 var connection = this.connection;
13686 var sharedConnection = connectable._connection;
13687 this.connection = null;
13688 if (sharedConnection && (!connection || sharedConnection === connection)) {
13689 sharedConnection.unsubscribe();
13692 return RefCountSubscriber;
13693 }(Subscriber_1.Subscriber));
13695 },{"../Subscriber":36}],190:[function(require,module,exports){
13697 var __extends = (this && this.__extends) || function (d, b) {
13698 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13699 function __() { this.constructor = d; }
13700 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13702 var Subscriber_1 = require('../Subscriber');
13704 * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
13705 * calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given
13706 * as a number parameter) rather than propagating the `error` call.
13708 * <img src="./img/retry.png" width="100%">
13710 * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted
13711 * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second
13712 * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications
13713 * would be: [1, 2, 1, 2, 3, 4, 5, `complete`].
13714 * @param {number} count - Number of retry attempts before failing.
13715 * @return {Observable} The source Observable modified with the retry logic.
13717 * @owner Observable
13719 function retry(count) {
13720 if (count === void 0) { count = -1; }
13721 return function (source) { return source.lift(new RetryOperator(count, source)); };
13723 exports.retry = retry;
13724 var RetryOperator = (function () {
13725 function RetryOperator(count, source) {
13726 this.count = count;
13727 this.source = source;
13729 RetryOperator.prototype.call = function (subscriber, source) {
13730 return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source));
13732 return RetryOperator;
13735 * We need this JSDoc comment for affecting ESDoc.
13737 * @extends {Ignored}
13739 var RetrySubscriber = (function (_super) {
13740 __extends(RetrySubscriber, _super);
13741 function RetrySubscriber(destination, count, source) {
13742 _super.call(this, destination);
13743 this.count = count;
13744 this.source = source;
13746 RetrySubscriber.prototype.error = function (err) {
13747 if (!this.isStopped) {
13748 var _a = this, source = _a.source, count = _a.count;
13750 return _super.prototype.error.call(this, err);
13752 else if (count > -1) {
13753 this.count = count - 1;
13755 source.subscribe(this._unsubscribeAndRecycle());
13758 return RetrySubscriber;
13759 }(Subscriber_1.Subscriber));
13761 },{"../Subscriber":36}],191:[function(require,module,exports){
13763 var __extends = (this && this.__extends) || function (d, b) {
13764 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13765 function __() { this.constructor = d; }
13766 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13768 var OuterSubscriber_1 = require('../OuterSubscriber');
13769 var subscribeToResult_1 = require('../util/subscribeToResult');
13771 * Emits the most recently emitted value from the source Observable whenever
13772 * another Observable, the `notifier`, emits.
13774 * <span class="informal">It's like {@link sampleTime}, but samples whenever
13775 * the `notifier` Observable emits something.</span>
13777 * <img src="./img/sample.png" width="100%">
13779 * Whenever the `notifier` Observable emits a value or completes, `sample`
13780 * looks at the source Observable and emits whichever value it has most recently
13781 * emitted since the previous sampling, unless the source has not emitted
13782 * anything since the previous sampling. The `notifier` is subscribed to as soon
13783 * as the output Observable is subscribed.
13785 * @example <caption>On every click, sample the most recent "seconds" timer</caption>
13786 * var seconds = Rx.Observable.interval(1000);
13787 * var clicks = Rx.Observable.fromEvent(document, 'click');
13788 * var result = seconds.sample(clicks);
13789 * result.subscribe(x => console.log(x));
13791 * @see {@link audit}
13792 * @see {@link debounce}
13793 * @see {@link sampleTime}
13794 * @see {@link throttle}
13796 * @param {Observable<any>} notifier The Observable to use for sampling the
13797 * source Observable.
13798 * @return {Observable<T>} An Observable that emits the results of sampling the
13799 * values emitted by the source Observable whenever the notifier Observable
13800 * emits value or completes.
13802 * @owner Observable
13804 function sample(notifier) {
13805 return function (source) { return source.lift(new SampleOperator(notifier)); };
13807 exports.sample = sample;
13808 var SampleOperator = (function () {
13809 function SampleOperator(notifier) {
13810 this.notifier = notifier;
13812 SampleOperator.prototype.call = function (subscriber, source) {
13813 var sampleSubscriber = new SampleSubscriber(subscriber);
13814 var subscription = source.subscribe(sampleSubscriber);
13815 subscription.add(subscribeToResult_1.subscribeToResult(sampleSubscriber, this.notifier));
13816 return subscription;
13818 return SampleOperator;
13821 * We need this JSDoc comment for affecting ESDoc.
13823 * @extends {Ignored}
13825 var SampleSubscriber = (function (_super) {
13826 __extends(SampleSubscriber, _super);
13827 function SampleSubscriber() {
13828 _super.apply(this, arguments);
13829 this.hasValue = false;
13831 SampleSubscriber.prototype._next = function (value) {
13832 this.value = value;
13833 this.hasValue = true;
13835 SampleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13838 SampleSubscriber.prototype.notifyComplete = function () {
13841 SampleSubscriber.prototype.emitValue = function () {
13842 if (this.hasValue) {
13843 this.hasValue = false;
13844 this.destination.next(this.value);
13847 return SampleSubscriber;
13848 }(OuterSubscriber_1.OuterSubscriber));
13850 },{"../OuterSubscriber":31,"../util/subscribeToResult":237}],192:[function(require,module,exports){
13852 var __extends = (this && this.__extends) || function (d, b) {
13853 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13854 function __() { this.constructor = d; }
13855 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13857 var Subscriber_1 = require('../Subscriber');
13858 /* tslint:enable:max-line-length */
13860 * Applies an accumulator function over the source Observable, and returns each
13861 * intermediate result, with an optional seed value.
13863 * <span class="informal">It's like {@link reduce}, but emits the current
13864 * accumulation whenever the source emits a value.</span>
13866 * <img src="./img/scan.png" width="100%">
13868 * Combines together all values emitted on the source, using an accumulator
13869 * function that knows how to join a new source value into the accumulation from
13870 * the past. Is similar to {@link reduce}, but emits the intermediate
13873 * Returns an Observable that applies a specified `accumulator` function to each
13874 * item emitted by the source Observable. If a `seed` value is specified, then
13875 * that value will be used as the initial value for the accumulator. If no seed
13876 * value is specified, the first item of the source is used as the seed.
13878 * @example <caption>Count the number of click events</caption>
13879 * var clicks = Rx.Observable.fromEvent(document, 'click');
13880 * var ones = clicks.mapTo(1);
13882 * var count = ones.scan((acc, one) => acc + one, seed);
13883 * count.subscribe(x => console.log(x));
13885 * @see {@link expand}
13886 * @see {@link mergeScan}
13887 * @see {@link reduce}
13889 * @param {function(acc: R, value: T, index: number): R} accumulator
13890 * The accumulator function called on each source value.
13891 * @param {T|R} [seed] The initial accumulation value.
13892 * @return {Observable<R>} An observable of the accumulated values.
13894 * @owner Observable
13896 function scan(accumulator, seed) {
13897 var hasSeed = false;
13898 // providing a seed of `undefined` *should* be valid and trigger
13899 // hasSeed! so don't use `seed !== undefined` checks!
13900 // For this reason, we have to check it here at the original call site
13901 // otherwise inside Operator/Subscriber we won't know if `undefined`
13902 // means they didn't provide anything or if they literally provided `undefined`
13903 if (arguments.length >= 2) {
13906 return function scanOperatorFunction(source) {
13907 return source.lift(new ScanOperator(accumulator, seed, hasSeed));
13910 exports.scan = scan;
13911 var ScanOperator = (function () {
13912 function ScanOperator(accumulator, seed, hasSeed) {
13913 if (hasSeed === void 0) { hasSeed = false; }
13914 this.accumulator = accumulator;
13916 this.hasSeed = hasSeed;
13918 ScanOperator.prototype.call = function (subscriber, source) {
13919 return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
13921 return ScanOperator;
13924 * We need this JSDoc comment for affecting ESDoc.
13926 * @extends {Ignored}
13928 var ScanSubscriber = (function (_super) {
13929 __extends(ScanSubscriber, _super);
13930 function ScanSubscriber(destination, accumulator, _seed, hasSeed) {
13931 _super.call(this, destination);
13932 this.accumulator = accumulator;
13933 this._seed = _seed;
13934 this.hasSeed = hasSeed;
13937 Object.defineProperty(ScanSubscriber.prototype, "seed", {
13941 set: function (value) {
13942 this.hasSeed = true;
13943 this._seed = value;
13948 ScanSubscriber.prototype._next = function (value) {
13949 if (!this.hasSeed) {
13951 this.destination.next(value);
13954 return this._tryNext(value);
13957 ScanSubscriber.prototype._tryNext = function (value) {
13958 var index = this.index++;
13961 result = this.accumulator(this.seed, value, index);
13964 this.destination.error(err);
13966 this.seed = result;
13967 this.destination.next(result);
13969 return ScanSubscriber;
13970 }(Subscriber_1.Subscriber));
13972 },{"../Subscriber":36}],193:[function(require,module,exports){
13974 var multicast_1 = require('./multicast');
13975 var refCount_1 = require('./refCount');
13976 var Subject_1 = require('../Subject');
13977 function shareSubjectFactory() {
13978 return new Subject_1.Subject();
13981 * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
13982 * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
13983 * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
13984 * This is an alias for .multicast(() => new Subject()).refCount().
13986 * <img src="./img/share.png" width="100%">
13988 * @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.
13990 * @owner Observable
13993 return function (source) { return refCount_1.refCount()(multicast_1.multicast(shareSubjectFactory)(source)); };
13995 exports.share = share;
13998 },{"../Subject":34,"./multicast":182,"./refCount":189}],194:[function(require,module,exports){
14000 var __extends = (this && this.__extends) || function (d, b) {
14001 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14002 function __() { this.constructor = d; }
14003 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14005 var Subscriber_1 = require('../Subscriber');
14007 * Returns an Observable that skips the first `count` items emitted by the source Observable.
14009 * <img src="./img/skip.png" width="100%">
14011 * @param {Number} count - The number of times, items emitted by source Observable should be skipped.
14012 * @return {Observable} An Observable that skips values emitted by the source Observable.
14015 * @owner Observable
14017 function skip(count) {
14018 return function (source) { return source.lift(new SkipOperator(count)); };
14020 exports.skip = skip;
14021 var SkipOperator = (function () {
14022 function SkipOperator(total) {
14023 this.total = total;
14025 SkipOperator.prototype.call = function (subscriber, source) {
14026 return source.subscribe(new SkipSubscriber(subscriber, this.total));
14028 return SkipOperator;
14031 * We need this JSDoc comment for affecting ESDoc.
14033 * @extends {Ignored}
14035 var SkipSubscriber = (function (_super) {
14036 __extends(SkipSubscriber, _super);
14037 function SkipSubscriber(destination, total) {
14038 _super.call(this, destination);
14039 this.total = total;
14042 SkipSubscriber.prototype._next = function (x) {
14043 if (++this.count > this.total) {
14044 this.destination.next(x);
14047 return SkipSubscriber;
14048 }(Subscriber_1.Subscriber));
14050 },{"../Subscriber":36}],195:[function(require,module,exports){
14052 var __extends = (this && this.__extends) || function (d, b) {
14053 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14054 function __() { this.constructor = d; }
14055 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14057 var OuterSubscriber_1 = require('../OuterSubscriber');
14058 var subscribeToResult_1 = require('../util/subscribeToResult');
14060 * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
14062 * <img src="./img/skipUntil.png" width="100%">
14064 * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to
14065 * be mirrored by the resulting Observable.
14066 * @return {Observable<T>} An Observable that skips items from the source Observable until the second Observable emits
14067 * an item, then emits the remaining items.
14068 * @method skipUntil
14069 * @owner Observable
14071 function skipUntil(notifier) {
14072 return function (source) { return source.lift(new SkipUntilOperator(notifier)); };
14074 exports.skipUntil = skipUntil;
14075 var SkipUntilOperator = (function () {
14076 function SkipUntilOperator(notifier) {
14077 this.notifier = notifier;
14079 SkipUntilOperator.prototype.call = function (subscriber, source) {
14080 return source.subscribe(new SkipUntilSubscriber(subscriber, this.notifier));
14082 return SkipUntilOperator;
14085 * We need this JSDoc comment for affecting ESDoc.
14087 * @extends {Ignored}
14089 var SkipUntilSubscriber = (function (_super) {
14090 __extends(SkipUntilSubscriber, _super);
14091 function SkipUntilSubscriber(destination, notifier) {
14092 _super.call(this, destination);
14093 this.hasValue = false;
14094 this.isInnerStopped = false;
14095 this.add(subscribeToResult_1.subscribeToResult(this, notifier));
14097 SkipUntilSubscriber.prototype._next = function (value) {
14098 if (this.hasValue) {
14099 _super.prototype._next.call(this, value);
14102 SkipUntilSubscriber.prototype._complete = function () {
14103 if (this.isInnerStopped) {
14104 _super.prototype._complete.call(this);
14107 this.unsubscribe();
14110 SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14111 this.hasValue = true;
14113 SkipUntilSubscriber.prototype.notifyComplete = function () {
14114 this.isInnerStopped = true;
14115 if (this.isStopped) {
14116 _super.prototype._complete.call(this);
14119 return SkipUntilSubscriber;
14120 }(OuterSubscriber_1.OuterSubscriber));
14122 },{"../OuterSubscriber":31,"../util/subscribeToResult":237}],196:[function(require,module,exports){
14124 var __extends = (this && this.__extends) || function (d, b) {
14125 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14126 function __() { this.constructor = d; }
14127 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14129 var Subscriber_1 = require('../Subscriber');
14131 * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
14132 * true, but emits all further source items as soon as the condition becomes false.
14134 * <img src="./img/skipWhile.png" width="100%">
14136 * @param {Function} predicate - A function to test each item emitted from the source Observable.
14137 * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the
14138 * specified predicate becomes false.
14139 * @method skipWhile
14140 * @owner Observable
14142 function skipWhile(predicate) {
14143 return function (source) { return source.lift(new SkipWhileOperator(predicate)); };
14145 exports.skipWhile = skipWhile;
14146 var SkipWhileOperator = (function () {
14147 function SkipWhileOperator(predicate) {
14148 this.predicate = predicate;
14150 SkipWhileOperator.prototype.call = function (subscriber, source) {
14151 return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
14153 return SkipWhileOperator;
14156 * We need this JSDoc comment for affecting ESDoc.
14158 * @extends {Ignored}
14160 var SkipWhileSubscriber = (function (_super) {
14161 __extends(SkipWhileSubscriber, _super);
14162 function SkipWhileSubscriber(destination, predicate) {
14163 _super.call(this, destination);
14164 this.predicate = predicate;
14165 this.skipping = true;
14168 SkipWhileSubscriber.prototype._next = function (value) {
14169 var destination = this.destination;
14170 if (this.skipping) {
14171 this.tryCallPredicate(value);
14173 if (!this.skipping) {
14174 destination.next(value);
14177 SkipWhileSubscriber.prototype.tryCallPredicate = function (value) {
14179 var result = this.predicate(value, this.index++);
14180 this.skipping = Boolean(result);
14183 this.destination.error(err);
14186 return SkipWhileSubscriber;
14187 }(Subscriber_1.Subscriber));
14189 },{"../Subscriber":36}],197:[function(require,module,exports){
14191 var ArrayObservable_1 = require('../observable/ArrayObservable');
14192 var ScalarObservable_1 = require('../observable/ScalarObservable');
14193 var EmptyObservable_1 = require('../observable/EmptyObservable');
14194 var concat_1 = require('../observable/concat');
14195 var isScheduler_1 = require('../util/isScheduler');
14196 /* tslint:enable:max-line-length */
14198 * Returns an Observable that emits the items you specify as arguments before it begins to emit
14199 * items emitted by the source Observable.
14201 * <img src="./img/startWith.png" width="100%">
14203 * @param {...T} values - Items you want the modified Observable to emit first.
14204 * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling
14205 * the emissions of the `next` notifications.
14206 * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items
14207 * emitted by the source Observable.
14208 * @method startWith
14209 * @owner Observable
14211 function startWith() {
14213 for (var _i = 0; _i < arguments.length; _i++) {
14214 array[_i - 0] = arguments[_i];
14216 return function (source) {
14217 var scheduler = array[array.length - 1];
14218 if (isScheduler_1.isScheduler(scheduler)) {
14224 var len = array.length;
14226 return concat_1.concat(new ScalarObservable_1.ScalarObservable(array[0], scheduler), source);
14228 else if (len > 1) {
14229 return concat_1.concat(new ArrayObservable_1.ArrayObservable(array, scheduler), source);
14232 return concat_1.concat(new EmptyObservable_1.EmptyObservable(scheduler), source);
14236 exports.startWith = startWith;
14238 },{"../observable/ArrayObservable":93,"../observable/EmptyObservable":96,"../observable/ScalarObservable":102,"../observable/concat":105,"../util/isScheduler":233}],198:[function(require,module,exports){
14240 var __extends = (this && this.__extends) || function (d, b) {
14241 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14242 function __() { this.constructor = d; }
14243 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14245 var OuterSubscriber_1 = require('../OuterSubscriber');
14246 var subscribeToResult_1 = require('../util/subscribeToResult');
14247 /* tslint:enable:max-line-length */
14249 * Projects each source value to an Observable which is merged in the output
14250 * Observable, emitting values only from the most recently projected Observable.
14252 * <span class="informal">Maps each value to an Observable, then flattens all of
14253 * these inner Observables using {@link switch}.</span>
14255 * <img src="./img/switchMap.png" width="100%">
14257 * Returns an Observable that emits items based on applying a function that you
14258 * supply to each item emitted by the source Observable, where that function
14259 * returns an (so-called "inner") Observable. Each time it observes one of these
14260 * inner Observables, the output Observable begins emitting the items emitted by
14261 * that inner Observable. When a new inner Observable is emitted, `switchMap`
14262 * stops emitting items from the earlier-emitted inner Observable and begins
14263 * emitting items from the new one. It continues to behave like this for
14264 * subsequent inner Observables.
14266 * @example <caption>Rerun an interval Observable on every click event</caption>
14267 * var clicks = Rx.Observable.fromEvent(document, 'click');
14268 * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
14269 * result.subscribe(x => console.log(x));
14271 * @see {@link concatMap}
14272 * @see {@link exhaustMap}
14273 * @see {@link mergeMap}
14274 * @see {@link switch}
14275 * @see {@link switchMapTo}
14277 * @param {function(value: T, ?index: number): ObservableInput} project A function
14278 * that, when applied to an item emitted by the source Observable, returns an
14280 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
14281 * A function to produce the value on the output Observable based on the values
14282 * and the indices of the source (outer) emission and the inner Observable
14283 * emission. The arguments passed to this function are:
14284 * - `outerValue`: the value that came from the source
14285 * - `innerValue`: the value that came from the projected Observable
14286 * - `outerIndex`: the "index" of the value that came from the source
14287 * - `innerIndex`: the "index" of the value from the projected Observable
14288 * @return {Observable} An Observable that emits the result of applying the
14289 * projection function (and the optional `resultSelector`) to each item emitted
14290 * by the source Observable and taking only the values from the most recently
14291 * projected inner Observable.
14292 * @method switchMap
14293 * @owner Observable
14295 function switchMap(project, resultSelector) {
14296 return function switchMapOperatorFunction(source) {
14297 return source.lift(new SwitchMapOperator(project, resultSelector));
14300 exports.switchMap = switchMap;
14301 var SwitchMapOperator = (function () {
14302 function SwitchMapOperator(project, resultSelector) {
14303 this.project = project;
14304 this.resultSelector = resultSelector;
14306 SwitchMapOperator.prototype.call = function (subscriber, source) {
14307 return source.subscribe(new SwitchMapSubscriber(subscriber, this.project, this.resultSelector));
14309 return SwitchMapOperator;
14312 * We need this JSDoc comment for affecting ESDoc.
14314 * @extends {Ignored}
14316 var SwitchMapSubscriber = (function (_super) {
14317 __extends(SwitchMapSubscriber, _super);
14318 function SwitchMapSubscriber(destination, project, resultSelector) {
14319 _super.call(this, destination);
14320 this.project = project;
14321 this.resultSelector = resultSelector;
14324 SwitchMapSubscriber.prototype._next = function (value) {
14326 var index = this.index++;
14328 result = this.project(value, index);
14331 this.destination.error(error);
14334 this._innerSub(result, value, index);
14336 SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
14337 var innerSubscription = this.innerSubscription;
14338 if (innerSubscription) {
14339 innerSubscription.unsubscribe();
14341 this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index));
14343 SwitchMapSubscriber.prototype._complete = function () {
14344 var innerSubscription = this.innerSubscription;
14345 if (!innerSubscription || innerSubscription.closed) {
14346 _super.prototype._complete.call(this);
14349 SwitchMapSubscriber.prototype._unsubscribe = function () {
14350 this.innerSubscription = null;
14352 SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
14353 this.remove(innerSub);
14354 this.innerSubscription = null;
14355 if (this.isStopped) {
14356 _super.prototype._complete.call(this);
14359 SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14360 if (this.resultSelector) {
14361 this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex);
14364 this.destination.next(innerValue);
14367 SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
14370 result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
14373 this.destination.error(err);
14376 this.destination.next(result);
14378 return SwitchMapSubscriber;
14379 }(OuterSubscriber_1.OuterSubscriber));
14381 },{"../OuterSubscriber":31,"../util/subscribeToResult":237}],199:[function(require,module,exports){
14383 var __extends = (this && this.__extends) || function (d, b) {
14384 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14385 function __() { this.constructor = d; }
14386 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14388 var Subscriber_1 = require('../Subscriber');
14389 var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError');
14390 var EmptyObservable_1 = require('../observable/EmptyObservable');
14392 * Emits only the first `count` values emitted by the source Observable.
14394 * <span class="informal">Takes the first `count` values from the source, then
14395 * completes.</span>
14397 * <img src="./img/take.png" width="100%">
14399 * `take` returns an Observable that emits only the first `count` values emitted
14400 * by the source Observable. If the source emits fewer than `count` values then
14401 * all of its values are emitted. After that, it completes, regardless if the
14402 * source completes.
14404 * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
14405 * var interval = Rx.Observable.interval(1000);
14406 * var five = interval.take(5);
14407 * five.subscribe(x => console.log(x));
14409 * @see {@link takeLast}
14410 * @see {@link takeUntil}
14411 * @see {@link takeWhile}
14412 * @see {@link skip}
14414 * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
14415 * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
14417 * @param {number} count The maximum number of `next` values to emit.
14418 * @return {Observable<T>} An Observable that emits only the first `count`
14419 * values emitted by the source Observable, or all of the values from the source
14420 * if the source emits fewer than `count` values.
14422 * @owner Observable
14424 function take(count) {
14425 return function (source) {
14427 return new EmptyObservable_1.EmptyObservable();
14430 return source.lift(new TakeOperator(count));
14434 exports.take = take;
14435 var TakeOperator = (function () {
14436 function TakeOperator(total) {
14437 this.total = total;
14438 if (this.total < 0) {
14439 throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
14442 TakeOperator.prototype.call = function (subscriber, source) {
14443 return source.subscribe(new TakeSubscriber(subscriber, this.total));
14445 return TakeOperator;
14448 * We need this JSDoc comment for affecting ESDoc.
14450 * @extends {Ignored}
14452 var TakeSubscriber = (function (_super) {
14453 __extends(TakeSubscriber, _super);
14454 function TakeSubscriber(destination, total) {
14455 _super.call(this, destination);
14456 this.total = total;
14459 TakeSubscriber.prototype._next = function (value) {
14460 var total = this.total;
14461 var count = ++this.count;
14462 if (count <= total) {
14463 this.destination.next(value);
14464 if (count === total) {
14465 this.destination.complete();
14466 this.unsubscribe();
14470 return TakeSubscriber;
14471 }(Subscriber_1.Subscriber));
14473 },{"../Subscriber":36,"../observable/EmptyObservable":96,"../util/ArgumentOutOfRangeError":218}],200:[function(require,module,exports){
14475 var __extends = (this && this.__extends) || function (d, b) {
14476 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14477 function __() { this.constructor = d; }
14478 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14480 var Subscriber_1 = require('../Subscriber');
14481 var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError');
14482 var EmptyObservable_1 = require('../observable/EmptyObservable');
14484 * Emits only the last `count` values emitted by the source Observable.
14486 * <span class="informal">Remembers the latest `count` values, then emits those
14487 * only when the source completes.</span>
14489 * <img src="./img/takeLast.png" width="100%">
14491 * `takeLast` returns an Observable that emits at most the last `count` values
14492 * emitted by the source Observable. If the source emits fewer than `count`
14493 * values then all of its values are emitted. This operator must wait until the
14494 * `complete` notification emission from the source in order to emit the `next`
14495 * values on the output Observable, because otherwise it is impossible to know
14496 * whether or not more values will be emitted on the source. For this reason,
14497 * all values are emitted synchronously, followed by the complete notification.
14499 * @example <caption>Take the last 3 values of an Observable with many values</caption>
14500 * var many = Rx.Observable.range(1, 100);
14501 * var lastThree = many.takeLast(3);
14502 * lastThree.subscribe(x => console.log(x));
14504 * @see {@link take}
14505 * @see {@link takeUntil}
14506 * @see {@link takeWhile}
14507 * @see {@link skip}
14509 * @throws {ArgumentOutOfRangeError} When using `takeLast(i)`, it delivers an
14510 * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
14512 * @param {number} count The maximum number of values to emit from the end of
14513 * the sequence of values emitted by the source Observable.
14514 * @return {Observable<T>} An Observable that emits at most the last count
14515 * values emitted by the source Observable.
14517 * @owner Observable
14519 function takeLast(count) {
14520 return function takeLastOperatorFunction(source) {
14522 return new EmptyObservable_1.EmptyObservable();
14525 return source.lift(new TakeLastOperator(count));
14529 exports.takeLast = takeLast;
14530 var TakeLastOperator = (function () {
14531 function TakeLastOperator(total) {
14532 this.total = total;
14533 if (this.total < 0) {
14534 throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
14537 TakeLastOperator.prototype.call = function (subscriber, source) {
14538 return source.subscribe(new TakeLastSubscriber(subscriber, this.total));
14540 return TakeLastOperator;
14543 * We need this JSDoc comment for affecting ESDoc.
14545 * @extends {Ignored}
14547 var TakeLastSubscriber = (function (_super) {
14548 __extends(TakeLastSubscriber, _super);
14549 function TakeLastSubscriber(destination, total) {
14550 _super.call(this, destination);
14551 this.total = total;
14552 this.ring = new Array();
14555 TakeLastSubscriber.prototype._next = function (value) {
14556 var ring = this.ring;
14557 var total = this.total;
14558 var count = this.count++;
14559 if (ring.length < total) {
14563 var index = count % total;
14564 ring[index] = value;
14567 TakeLastSubscriber.prototype._complete = function () {
14568 var destination = this.destination;
14569 var count = this.count;
14571 var total = this.count >= this.total ? this.total : this.count;
14572 var ring = this.ring;
14573 for (var i = 0; i < total; i++) {
14574 var idx = (count++) % total;
14575 destination.next(ring[idx]);
14578 destination.complete();
14580 return TakeLastSubscriber;
14581 }(Subscriber_1.Subscriber));
14583 },{"../Subscriber":36,"../observable/EmptyObservable":96,"../util/ArgumentOutOfRangeError":218}],201:[function(require,module,exports){
14585 var __extends = (this && this.__extends) || function (d, b) {
14586 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14587 function __() { this.constructor = d; }
14588 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14590 var OuterSubscriber_1 = require('../OuterSubscriber');
14591 var subscribeToResult_1 = require('../util/subscribeToResult');
14593 * Emits the values emitted by the source Observable until a `notifier`
14594 * Observable emits a value.
14596 * <span class="informal">Lets values pass until a second Observable,
14597 * `notifier`, emits something. Then, it completes.</span>
14599 * <img src="./img/takeUntil.png" width="100%">
14601 * `takeUntil` subscribes and begins mirroring the source Observable. It also
14602 * monitors a second Observable, `notifier` that you provide. If the `notifier`
14603 * emits a value or a complete notification, the output Observable stops
14604 * mirroring the source Observable and completes.
14606 * @example <caption>Tick every second until the first click happens</caption>
14607 * var interval = Rx.Observable.interval(1000);
14608 * var clicks = Rx.Observable.fromEvent(document, 'click');
14609 * var result = interval.takeUntil(clicks);
14610 * result.subscribe(x => console.log(x));
14612 * @see {@link take}
14613 * @see {@link takeLast}
14614 * @see {@link takeWhile}
14615 * @see {@link skip}
14617 * @param {Observable} notifier The Observable whose first emitted value will
14618 * cause the output Observable of `takeUntil` to stop emitting values from the
14619 * source Observable.
14620 * @return {Observable<T>} An Observable that emits the values from the source
14621 * Observable until such time as `notifier` emits its first value.
14622 * @method takeUntil
14623 * @owner Observable
14625 function takeUntil(notifier) {
14626 return function (source) { return source.lift(new TakeUntilOperator(notifier)); };
14628 exports.takeUntil = takeUntil;
14629 var TakeUntilOperator = (function () {
14630 function TakeUntilOperator(notifier) {
14631 this.notifier = notifier;
14633 TakeUntilOperator.prototype.call = function (subscriber, source) {
14634 return source.subscribe(new TakeUntilSubscriber(subscriber, this.notifier));
14636 return TakeUntilOperator;
14639 * We need this JSDoc comment for affecting ESDoc.
14641 * @extends {Ignored}
14643 var TakeUntilSubscriber = (function (_super) {
14644 __extends(TakeUntilSubscriber, _super);
14645 function TakeUntilSubscriber(destination, notifier) {
14646 _super.call(this, destination);
14647 this.notifier = notifier;
14648 this.add(subscribeToResult_1.subscribeToResult(this, notifier));
14650 TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14653 TakeUntilSubscriber.prototype.notifyComplete = function () {
14656 return TakeUntilSubscriber;
14657 }(OuterSubscriber_1.OuterSubscriber));
14659 },{"../OuterSubscriber":31,"../util/subscribeToResult":237}],202:[function(require,module,exports){
14661 var __extends = (this && this.__extends) || function (d, b) {
14662 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14663 function __() { this.constructor = d; }
14664 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14666 var Subscriber_1 = require('../Subscriber');
14668 * Emits values emitted by the source Observable so long as each value satisfies
14669 * the given `predicate`, and then completes as soon as this `predicate` is not
14672 * <span class="informal">Takes values from the source only while they pass the
14673 * condition given. When the first value does not satisfy, it completes.</span>
14675 * <img src="./img/takeWhile.png" width="100%">
14677 * `takeWhile` subscribes and begins mirroring the source Observable. Each value
14678 * emitted on the source is given to the `predicate` function which returns a
14679 * boolean, representing a condition to be satisfied by the source values. The
14680 * output Observable emits the source values until such time as the `predicate`
14681 * returns false, at which point `takeWhile` stops mirroring the source
14682 * Observable and completes the output Observable.
14684 * @example <caption>Emit click events only while the clientX property is greater than 200</caption>
14685 * var clicks = Rx.Observable.fromEvent(document, 'click');
14686 * var result = clicks.takeWhile(ev => ev.clientX > 200);
14687 * result.subscribe(x => console.log(x));
14689 * @see {@link take}
14690 * @see {@link takeLast}
14691 * @see {@link takeUntil}
14692 * @see {@link skip}
14694 * @param {function(value: T, index: number): boolean} predicate A function that
14695 * evaluates a value emitted by the source Observable and returns a boolean.
14696 * Also takes the (zero-based) index as the second argument.
14697 * @return {Observable<T>} An Observable that emits the values from the source
14698 * Observable so long as each value satisfies the condition defined by the
14699 * `predicate`, then completes.
14700 * @method takeWhile
14701 * @owner Observable
14703 function takeWhile(predicate) {
14704 return function (source) { return source.lift(new TakeWhileOperator(predicate)); };
14706 exports.takeWhile = takeWhile;
14707 var TakeWhileOperator = (function () {
14708 function TakeWhileOperator(predicate) {
14709 this.predicate = predicate;
14711 TakeWhileOperator.prototype.call = function (subscriber, source) {
14712 return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate));
14714 return TakeWhileOperator;
14717 * We need this JSDoc comment for affecting ESDoc.
14719 * @extends {Ignored}
14721 var TakeWhileSubscriber = (function (_super) {
14722 __extends(TakeWhileSubscriber, _super);
14723 function TakeWhileSubscriber(destination, predicate) {
14724 _super.call(this, destination);
14725 this.predicate = predicate;
14728 TakeWhileSubscriber.prototype._next = function (value) {
14729 var destination = this.destination;
14732 result = this.predicate(value, this.index++);
14735 destination.error(err);
14738 this.nextOrComplete(value, result);
14740 TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) {
14741 var destination = this.destination;
14742 if (Boolean(predicateResult)) {
14743 destination.next(value);
14746 destination.complete();
14749 return TakeWhileSubscriber;
14750 }(Subscriber_1.Subscriber));
14752 },{"../Subscriber":36}],203:[function(require,module,exports){
14754 var __extends = (this && this.__extends) || function (d, b) {
14755 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14756 function __() { this.constructor = d; }
14757 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14759 var Subscriber_1 = require('../Subscriber');
14760 /* tslint:enable:max-line-length */
14762 * Perform a side effect for every emission on the source Observable, but return
14763 * an Observable that is identical to the source.
14765 * <span class="informal">Intercepts each emission on the source and runs a
14766 * function, but returns an output which is identical to the source as long as errors don't occur.</span>
14768 * <img src="./img/do.png" width="100%">
14770 * Returns a mirrored Observable of the source Observable, but modified so that
14771 * the provided Observer is called to perform a side effect for every value,
14772 * error, and completion emitted by the source. Any errors that are thrown in
14773 * the aforementioned Observer or handlers are safely sent down the error path
14774 * of the output Observable.
14776 * This operator is useful for debugging your Observables for the correct values
14777 * or performing other side effects.
14779 * Note: this is different to a `subscribe` on the Observable. If the Observable
14780 * returned by `do` is not subscribed, the side effects specified by the
14781 * Observer will never happen. `do` therefore simply spies on existing
14782 * execution, it does not trigger an execution to happen like `subscribe` does.
14784 * @example <caption>Map every click to the clientX position of that click, while also logging the click event</caption>
14785 * var clicks = Rx.Observable.fromEvent(document, 'click');
14786 * var positions = clicks
14787 * .do(ev => console.log(ev))
14788 * .map(ev => ev.clientX);
14789 * positions.subscribe(x => console.log(x));
14792 * @see {@link subscribe}
14794 * @param {Observer|function} [nextOrObserver] A normal Observer object or a
14795 * callback for `next`.
14796 * @param {function} [error] Callback for errors in the source.
14797 * @param {function} [complete] Callback for the completion of the source.
14798 * @return {Observable} An Observable identical to the source, but runs the
14799 * specified Observer or callback(s) for each item.
14802 function tap(nextOrObserver, error, complete) {
14803 return function tapOperatorFunction(source) {
14804 return source.lift(new DoOperator(nextOrObserver, error, complete));
14808 var DoOperator = (function () {
14809 function DoOperator(nextOrObserver, error, complete) {
14810 this.nextOrObserver = nextOrObserver;
14811 this.error = error;
14812 this.complete = complete;
14814 DoOperator.prototype.call = function (subscriber, source) {
14815 return source.subscribe(new DoSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
14820 * We need this JSDoc comment for affecting ESDoc.
14822 * @extends {Ignored}
14824 var DoSubscriber = (function (_super) {
14825 __extends(DoSubscriber, _super);
14826 function DoSubscriber(destination, nextOrObserver, error, complete) {
14827 _super.call(this, destination);
14828 var safeSubscriber = new Subscriber_1.Subscriber(nextOrObserver, error, complete);
14829 safeSubscriber.syncErrorThrowable = true;
14830 this.add(safeSubscriber);
14831 this.safeSubscriber = safeSubscriber;
14833 DoSubscriber.prototype._next = function (value) {
14834 var safeSubscriber = this.safeSubscriber;
14835 safeSubscriber.next(value);
14836 if (safeSubscriber.syncErrorThrown) {
14837 this.destination.error(safeSubscriber.syncErrorValue);
14840 this.destination.next(value);
14843 DoSubscriber.prototype._error = function (err) {
14844 var safeSubscriber = this.safeSubscriber;
14845 safeSubscriber.error(err);
14846 if (safeSubscriber.syncErrorThrown) {
14847 this.destination.error(safeSubscriber.syncErrorValue);
14850 this.destination.error(err);
14853 DoSubscriber.prototype._complete = function () {
14854 var safeSubscriber = this.safeSubscriber;
14855 safeSubscriber.complete();
14856 if (safeSubscriber.syncErrorThrown) {
14857 this.destination.error(safeSubscriber.syncErrorValue);
14860 this.destination.complete();
14863 return DoSubscriber;
14864 }(Subscriber_1.Subscriber));
14866 },{"../Subscriber":36}],204:[function(require,module,exports){
14868 var __extends = (this && this.__extends) || function (d, b) {
14869 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14870 function __() { this.constructor = d; }
14871 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14873 var async_1 = require('../scheduler/async');
14874 var isDate_1 = require('../util/isDate');
14875 var Subscriber_1 = require('../Subscriber');
14876 var TimeoutError_1 = require('../util/TimeoutError');
14879 * Errors if Observable does not emit a value in given time span.
14881 * <span class="informal">Timeouts on Observable that doesn't emit values fast enough.</span>
14883 * <img src="./img/timeout.png" width="100%">
14885 * `timeout` operator accepts as an argument either a number or a Date.
14887 * If number was provided, it returns an Observable that behaves like a source
14888 * Observable, unless there is a period of time where there is no value emitted.
14889 * So if you provide `100` as argument and first value comes after 50ms from
14890 * the moment of subscription, this value will be simply re-emitted by the resulting
14891 * Observable. If however after that 100ms passes without a second value being emitted,
14892 * stream will end with an error and source Observable will be unsubscribed.
14893 * These checks are performed throughout whole lifecycle of Observable - from the moment
14894 * it was subscribed to, until it completes or errors itself. Thus every value must be
14895 * emitted within specified period since previous value.
14897 * If provided argument was Date, returned Observable behaves differently. It throws
14898 * if Observable did not complete before provided Date. This means that periods between
14899 * emission of particular values do not matter in this case. If Observable did not complete
14900 * before provided Date, source Observable will be unsubscribed. Other than that, resulting
14901 * stream behaves just as source Observable.
14903 * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments)
14904 * when returned Observable will check if source stream emitted value or completed.
14906 * @example <caption>Check if ticks are emitted within certain timespan</caption>
14907 * const seconds = Rx.Observable.interval(1000);
14909 * seconds.timeout(1100) // Let's use bigger timespan to be safe,
14910 * // since `interval` might fire a bit later then scheduled.
14912 * value => console.log(value), // Will emit numbers just as regular `interval` would.
14913 * err => console.log(err) // Will never be called.
14916 * seconds.timeout(900).subscribe(
14917 * value => console.log(value), // Will never be called.
14918 * err => console.log(err) // Will emit error before even first value is emitted,
14919 * // since it did not arrive within 900ms period.
14922 * @example <caption>Use Date to check if Observable completed</caption>
14923 * const seconds = Rx.Observable.interval(1000);
14925 * seconds.timeout(new Date("December 17, 2020 03:24:00"))
14927 * value => console.log(value), // Will emit values as regular `interval` would
14928 * // until December 17, 2020 at 03:24:00.
14929 * err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error,
14930 * // since Observable did not complete by then.
14933 * @see {@link timeoutWith}
14935 * @param {number|Date} due Number specifying period within which Observable must emit values
14936 * or Date specifying before when Observable should complete
14937 * @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur.
14938 * @return {Observable<T>} Observable that mirrors behaviour of source, unless timeout checks fail.
14940 * @owner Observable
14942 function timeout(due, scheduler) {
14943 if (scheduler === void 0) { scheduler = async_1.async; }
14944 var absoluteTimeout = isDate_1.isDate(due);
14945 var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);
14946 return function (source) { return source.lift(new TimeoutOperator(waitFor, absoluteTimeout, scheduler, new TimeoutError_1.TimeoutError())); };
14948 exports.timeout = timeout;
14949 var TimeoutOperator = (function () {
14950 function TimeoutOperator(waitFor, absoluteTimeout, scheduler, errorInstance) {
14951 this.waitFor = waitFor;
14952 this.absoluteTimeout = absoluteTimeout;
14953 this.scheduler = scheduler;
14954 this.errorInstance = errorInstance;
14956 TimeoutOperator.prototype.call = function (subscriber, source) {
14957 return source.subscribe(new TimeoutSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.scheduler, this.errorInstance));
14959 return TimeoutOperator;
14962 * We need this JSDoc comment for affecting ESDoc.
14964 * @extends {Ignored}
14966 var TimeoutSubscriber = (function (_super) {
14967 __extends(TimeoutSubscriber, _super);
14968 function TimeoutSubscriber(destination, absoluteTimeout, waitFor, scheduler, errorInstance) {
14969 _super.call(this, destination);
14970 this.absoluteTimeout = absoluteTimeout;
14971 this.waitFor = waitFor;
14972 this.scheduler = scheduler;
14973 this.errorInstance = errorInstance;
14974 this.action = null;
14975 this.scheduleTimeout();
14977 TimeoutSubscriber.dispatchTimeout = function (subscriber) {
14978 subscriber.error(subscriber.errorInstance);
14980 TimeoutSubscriber.prototype.scheduleTimeout = function () {
14981 var action = this.action;
14983 // Recycle the action if we've already scheduled one. All the production
14984 // Scheduler Actions mutate their state/delay time and return themeselves.
14985 // VirtualActions are immutable, so they create and return a clone. In this
14986 // case, we need to set the action reference to the most recent VirtualAction,
14987 // to ensure that's the one we clone from next time.
14988 this.action = action.schedule(this, this.waitFor);
14991 this.add(this.action = this.scheduler.schedule(TimeoutSubscriber.dispatchTimeout, this.waitFor, this));
14994 TimeoutSubscriber.prototype._next = function (value) {
14995 if (!this.absoluteTimeout) {
14996 this.scheduleTimeout();
14998 _super.prototype._next.call(this, value);
15000 TimeoutSubscriber.prototype._unsubscribe = function () {
15001 this.action = null;
15002 this.scheduler = null;
15003 this.errorInstance = null;
15005 return TimeoutSubscriber;
15006 }(Subscriber_1.Subscriber));
15008 },{"../Subscriber":36,"../scheduler/async":212,"../util/TimeoutError":222,"../util/isDate":228}],205:[function(require,module,exports){
15010 var __extends = (this && this.__extends) || function (d, b) {
15011 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15012 function __() { this.constructor = d; }
15013 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15015 var OuterSubscriber_1 = require('../OuterSubscriber');
15016 var subscribeToResult_1 = require('../util/subscribeToResult');
15017 /* tslint:enable:max-line-length */
15019 * Combines the source Observable with other Observables to create an Observable
15020 * whose values are calculated from the latest values of each, only when the
15023 * <span class="informal">Whenever the source Observable emits a value, it
15024 * computes a formula using that value plus the latest values from other input
15025 * Observables, then emits the output of that formula.</span>
15027 * <img src="./img/withLatestFrom.png" width="100%">
15029 * `withLatestFrom` combines each value from the source Observable (the
15030 * instance) with the latest values from the other input Observables only when
15031 * the source emits a value, optionally using a `project` function to determine
15032 * the value to be emitted on the output Observable. All input Observables must
15033 * emit at least one value before the output Observable will emit a value.
15035 * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
15036 * var clicks = Rx.Observable.fromEvent(document, 'click');
15037 * var timer = Rx.Observable.interval(1000);
15038 * var result = clicks.withLatestFrom(timer);
15039 * result.subscribe(x => console.log(x));
15041 * @see {@link combineLatest}
15043 * @param {ObservableInput} other An input Observable to combine with the source
15044 * Observable. More than one input Observables may be given as argument.
15045 * @param {Function} [project] Projection function for combining values
15046 * together. Receives all values in order of the Observables passed, where the
15047 * first parameter is a value from the source Observable. (e.g.
15048 * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
15049 * passed, arrays will be emitted on the output Observable.
15050 * @return {Observable} An Observable of projected values from the most recent
15051 * values from each input Observable, or an array of the most recent values from
15052 * each input Observable.
15053 * @method withLatestFrom
15054 * @owner Observable
15056 function withLatestFrom() {
15058 for (var _i = 0; _i < arguments.length; _i++) {
15059 args[_i - 0] = arguments[_i];
15061 return function (source) {
15063 if (typeof args[args.length - 1] === 'function') {
15064 project = args.pop();
15066 var observables = args;
15067 return source.lift(new WithLatestFromOperator(observables, project));
15070 exports.withLatestFrom = withLatestFrom;
15071 var WithLatestFromOperator = (function () {
15072 function WithLatestFromOperator(observables, project) {
15073 this.observables = observables;
15074 this.project = project;
15076 WithLatestFromOperator.prototype.call = function (subscriber, source) {
15077 return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
15079 return WithLatestFromOperator;
15082 * We need this JSDoc comment for affecting ESDoc.
15084 * @extends {Ignored}
15086 var WithLatestFromSubscriber = (function (_super) {
15087 __extends(WithLatestFromSubscriber, _super);
15088 function WithLatestFromSubscriber(destination, observables, project) {
15089 _super.call(this, destination);
15090 this.observables = observables;
15091 this.project = project;
15092 this.toRespond = [];
15093 var len = observables.length;
15094 this.values = new Array(len);
15095 for (var i = 0; i < len; i++) {
15096 this.toRespond.push(i);
15098 for (var i = 0; i < len; i++) {
15099 var observable = observables[i];
15100 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
15103 WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
15104 this.values[outerIndex] = innerValue;
15105 var toRespond = this.toRespond;
15106 if (toRespond.length > 0) {
15107 var found = toRespond.indexOf(outerIndex);
15108 if (found !== -1) {
15109 toRespond.splice(found, 1);
15113 WithLatestFromSubscriber.prototype.notifyComplete = function () {
15116 WithLatestFromSubscriber.prototype._next = function (value) {
15117 if (this.toRespond.length === 0) {
15118 var args = [value].concat(this.values);
15119 if (this.project) {
15120 this._tryProject(args);
15123 this.destination.next(args);
15127 WithLatestFromSubscriber.prototype._tryProject = function (args) {
15130 result = this.project.apply(this, args);
15133 this.destination.error(err);
15136 this.destination.next(result);
15138 return WithLatestFromSubscriber;
15139 }(OuterSubscriber_1.OuterSubscriber));
15141 },{"../OuterSubscriber":31,"../util/subscribeToResult":237}],206:[function(require,module,exports){
15143 var __extends = (this && this.__extends) || function (d, b) {
15144 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15145 function __() { this.constructor = d; }
15146 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15148 var ArrayObservable_1 = require('../observable/ArrayObservable');
15149 var isArray_1 = require('../util/isArray');
15150 var Subscriber_1 = require('../Subscriber');
15151 var OuterSubscriber_1 = require('../OuterSubscriber');
15152 var subscribeToResult_1 = require('../util/subscribeToResult');
15153 var iterator_1 = require('../symbol/iterator');
15154 /* tslint:enable:max-line-length */
15156 * @param observables
15157 * @return {Observable<R>}
15159 * @owner Observable
15162 var observables = [];
15163 for (var _i = 0; _i < arguments.length; _i++) {
15164 observables[_i - 0] = arguments[_i];
15166 return function zipOperatorFunction(source) {
15167 return source.lift.call(zipStatic.apply(void 0, [source].concat(observables)));
15171 /* tslint:enable:max-line-length */
15173 * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each
15174 * of its input Observables.
15176 * If the latest parameter is a function, this function is used to compute the created value from the input values.
15177 * Otherwise, an array of the input values is returned.
15179 * @example <caption>Combine age and name from different sources</caption>
15181 * let age$ = Observable.of<number>(27, 25, 29);
15182 * let name$ = Observable.of<string>('Foo', 'Bar', 'Beer');
15183 * let isDev$ = Observable.of<boolean>(true, true, false);
15189 * (age: number, name: string, isDev: boolean) => ({ age, name, isDev }))
15190 * .subscribe(x => console.log(x));
15193 * // { age: 27, name: 'Foo', isDev: true }
15194 * // { age: 25, name: 'Bar', isDev: true }
15195 * // { age: 29, name: 'Beer', isDev: false }
15197 * @param observables
15198 * @return {Observable<R>}
15201 * @owner Observable
15203 function zipStatic() {
15204 var observables = [];
15205 for (var _i = 0; _i < arguments.length; _i++) {
15206 observables[_i - 0] = arguments[_i];
15208 var project = observables[observables.length - 1];
15209 if (typeof project === 'function') {
15212 return new ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project));
15214 exports.zipStatic = zipStatic;
15215 var ZipOperator = (function () {
15216 function ZipOperator(project) {
15217 this.project = project;
15219 ZipOperator.prototype.call = function (subscriber, source) {
15220 return source.subscribe(new ZipSubscriber(subscriber, this.project));
15222 return ZipOperator;
15224 exports.ZipOperator = ZipOperator;
15226 * We need this JSDoc comment for affecting ESDoc.
15228 * @extends {Ignored}
15230 var ZipSubscriber = (function (_super) {
15231 __extends(ZipSubscriber, _super);
15232 function ZipSubscriber(destination, project, values) {
15233 if (values === void 0) { values = Object.create(null); }
15234 _super.call(this, destination);
15235 this.iterators = [];
15237 this.project = (typeof project === 'function') ? project : null;
15238 this.values = values;
15240 ZipSubscriber.prototype._next = function (value) {
15241 var iterators = this.iterators;
15242 if (isArray_1.isArray(value)) {
15243 iterators.push(new StaticArrayIterator(value));
15245 else if (typeof value[iterator_1.iterator] === 'function') {
15246 iterators.push(new StaticIterator(value[iterator_1.iterator]()));
15249 iterators.push(new ZipBufferIterator(this.destination, this, value));
15252 ZipSubscriber.prototype._complete = function () {
15253 var iterators = this.iterators;
15254 var len = iterators.length;
15256 this.destination.complete();
15260 for (var i = 0; i < len; i++) {
15261 var iterator = iterators[i];
15262 if (iterator.stillUnsubscribed) {
15263 this.add(iterator.subscribe(iterator, i));
15266 this.active--; // not an observable
15270 ZipSubscriber.prototype.notifyInactive = function () {
15272 if (this.active === 0) {
15273 this.destination.complete();
15276 ZipSubscriber.prototype.checkIterators = function () {
15277 var iterators = this.iterators;
15278 var len = iterators.length;
15279 var destination = this.destination;
15280 // abort if not all of them have values
15281 for (var i = 0; i < len; i++) {
15282 var iterator = iterators[i];
15283 if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
15287 var shouldComplete = false;
15289 for (var i = 0; i < len; i++) {
15290 var iterator = iterators[i];
15291 var result = iterator.next();
15292 // check to see if it's completed now that you've gotten
15294 if (iterator.hasCompleted()) {
15295 shouldComplete = true;
15298 destination.complete();
15301 args.push(result.value);
15303 if (this.project) {
15304 this._tryProject(args);
15307 destination.next(args);
15309 if (shouldComplete) {
15310 destination.complete();
15313 ZipSubscriber.prototype._tryProject = function (args) {
15316 result = this.project.apply(this, args);
15319 this.destination.error(err);
15322 this.destination.next(result);
15324 return ZipSubscriber;
15325 }(Subscriber_1.Subscriber));
15326 exports.ZipSubscriber = ZipSubscriber;
15327 var StaticIterator = (function () {
15328 function StaticIterator(iterator) {
15329 this.iterator = iterator;
15330 this.nextResult = iterator.next();
15332 StaticIterator.prototype.hasValue = function () {
15335 StaticIterator.prototype.next = function () {
15336 var result = this.nextResult;
15337 this.nextResult = this.iterator.next();
15340 StaticIterator.prototype.hasCompleted = function () {
15341 var nextResult = this.nextResult;
15342 return nextResult && nextResult.done;
15344 return StaticIterator;
15346 var StaticArrayIterator = (function () {
15347 function StaticArrayIterator(array) {
15348 this.array = array;
15351 this.length = array.length;
15353 StaticArrayIterator.prototype[iterator_1.iterator] = function () {
15356 StaticArrayIterator.prototype.next = function (value) {
15357 var i = this.index++;
15358 var array = this.array;
15359 return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
15361 StaticArrayIterator.prototype.hasValue = function () {
15362 return this.array.length > this.index;
15364 StaticArrayIterator.prototype.hasCompleted = function () {
15365 return this.array.length === this.index;
15367 return StaticArrayIterator;
15370 * We need this JSDoc comment for affecting ESDoc.
15372 * @extends {Ignored}
15374 var ZipBufferIterator = (function (_super) {
15375 __extends(ZipBufferIterator, _super);
15376 function ZipBufferIterator(destination, parent, observable) {
15377 _super.call(this, destination);
15378 this.parent = parent;
15379 this.observable = observable;
15380 this.stillUnsubscribed = true;
15382 this.isComplete = false;
15384 ZipBufferIterator.prototype[iterator_1.iterator] = function () {
15387 // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next
15388 // this is legit because `next()` will never be called by a subscription in this case.
15389 ZipBufferIterator.prototype.next = function () {
15390 var buffer = this.buffer;
15391 if (buffer.length === 0 && this.isComplete) {
15392 return { value: null, done: true };
15395 return { value: buffer.shift(), done: false };
15398 ZipBufferIterator.prototype.hasValue = function () {
15399 return this.buffer.length > 0;
15401 ZipBufferIterator.prototype.hasCompleted = function () {
15402 return this.buffer.length === 0 && this.isComplete;
15404 ZipBufferIterator.prototype.notifyComplete = function () {
15405 if (this.buffer.length > 0) {
15406 this.isComplete = true;
15407 this.parent.notifyInactive();
15410 this.destination.complete();
15413 ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
15414 this.buffer.push(innerValue);
15415 this.parent.checkIterators();
15417 ZipBufferIterator.prototype.subscribe = function (value, index) {
15418 return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
15420 return ZipBufferIterator;
15421 }(OuterSubscriber_1.OuterSubscriber));
15423 },{"../OuterSubscriber":31,"../Subscriber":36,"../observable/ArrayObservable":93,"../symbol/iterator":214,"../util/isArray":226,"../util/subscribeToResult":237}],207:[function(require,module,exports){
15425 var __extends = (this && this.__extends) || function (d, b) {
15426 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15427 function __() { this.constructor = d; }
15428 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15430 var Subscription_1 = require('../Subscription');
15432 * A unit of work to be executed in a {@link Scheduler}. An action is typically
15433 * created from within a Scheduler and an RxJS user does not need to concern
15434 * themselves about creating and manipulating an Action.
15437 * class Action<T> extends Subscription {
15438 * new (scheduler: Scheduler, work: (state?: T) => void);
15439 * schedule(state?: T, delay: number = 0): Subscription;
15445 var Action = (function (_super) {
15446 __extends(Action, _super);
15447 function Action(scheduler, work) {
15451 * Schedules this action on its parent Scheduler for execution. May be passed
15452 * some context object, `state`. May happen at some point in the future,
15453 * according to the `delay` parameter, if specified.
15454 * @param {T} [state] Some contextual data that the `work` function uses when
15455 * called by the Scheduler.
15456 * @param {number} [delay] Time to wait before executing the work, where the
15457 * time unit is implicit and defined by the Scheduler.
15460 Action.prototype.schedule = function (state, delay) {
15461 if (delay === void 0) { delay = 0; }
15465 }(Subscription_1.Subscription));
15466 exports.Action = Action;
15468 },{"../Subscription":37}],208:[function(require,module,exports){
15470 var __extends = (this && this.__extends) || function (d, b) {
15471 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15472 function __() { this.constructor = d; }
15473 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15475 var root_1 = require('../util/root');
15476 var Action_1 = require('./Action');
15478 * We need this JSDoc comment for affecting ESDoc.
15480 * @extends {Ignored}
15482 var AsyncAction = (function (_super) {
15483 __extends(AsyncAction, _super);
15484 function AsyncAction(scheduler, work) {
15485 _super.call(this, scheduler, work);
15486 this.scheduler = scheduler;
15488 this.pending = false;
15490 AsyncAction.prototype.schedule = function (state, delay) {
15491 if (delay === void 0) { delay = 0; }
15495 // Always replace the current state with the new state.
15496 this.state = state;
15497 // Set the pending flag indicating that this action has been scheduled, or
15498 // has recursively rescheduled itself.
15499 this.pending = true;
15501 var scheduler = this.scheduler;
15503 // Important implementation note:
15505 // Actions only execute once by default, unless rescheduled from within the
15506 // scheduled callback. This allows us to implement single and repeat
15507 // actions via the same code path, without adding API surface area, as well
15508 // as mimic traditional recursion but across asynchronous boundaries.
15510 // However, JS runtimes and timers distinguish between intervals achieved by
15511 // serial `setTimeout` calls vs. a single `setInterval` call. An interval of
15512 // serial `setTimeout` calls can be individually delayed, which delays
15513 // scheduling the next `setTimeout`, and so on. `setInterval` attempts to
15514 // guarantee the interval callback will be invoked more precisely to the
15515 // interval period, regardless of load.
15517 // Therefore, we use `setInterval` to schedule single and repeat actions.
15518 // If the action reschedules itself with the same delay, the interval is not
15519 // canceled. If the action doesn't reschedule, or reschedules with a
15520 // different delay, the interval will be canceled after scheduled callback
15524 this.id = this.recycleAsyncId(scheduler, id, delay);
15526 this.delay = delay;
15527 // If this action has already an async Id, don't request a new one.
15528 this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
15531 AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
15532 if (delay === void 0) { delay = 0; }
15533 return root_1.root.setInterval(scheduler.flush.bind(scheduler, this), delay);
15535 AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
15536 if (delay === void 0) { delay = 0; }
15537 // If this action is rescheduled with the same delay time, don't clear the interval id.
15538 if (delay !== null && this.delay === delay && this.pending === false) {
15541 // Otherwise, if the action's delay time is different from the current delay,
15542 // or the action has been rescheduled before it's executed, clear the interval id
15543 return root_1.root.clearInterval(id) && undefined || undefined;
15546 * Immediately executes this action and the `work` it contains.
15549 AsyncAction.prototype.execute = function (state, delay) {
15551 return new Error('executing a cancelled action');
15553 this.pending = false;
15554 var error = this._execute(state, delay);
15558 else if (this.pending === false && this.id != null) {
15559 // Dequeue if the action didn't reschedule itself. Don't call
15560 // unsubscribe(), because the action could reschedule later.
15563 // scheduler.schedule(function doWork(counter) {
15564 // /* ... I'm a busy worker bee ... */
15565 // var originalAction = this;
15566 // /* wait 100ms before rescheduling the action */
15567 // setTimeout(function () {
15568 // originalAction.schedule(counter + 1);
15572 this.id = this.recycleAsyncId(this.scheduler, this.id, null);
15575 AsyncAction.prototype._execute = function (state, delay) {
15576 var errored = false;
15577 var errorValue = undefined;
15583 errorValue = !!e && e || new Error(e);
15586 this.unsubscribe();
15590 AsyncAction.prototype._unsubscribe = function () {
15592 var scheduler = this.scheduler;
15593 var actions = scheduler.actions;
15594 var index = actions.indexOf(this);
15597 this.pending = false;
15598 this.scheduler = null;
15599 if (index !== -1) {
15600 actions.splice(index, 1);
15603 this.id = this.recycleAsyncId(scheduler, id, null);
15607 return AsyncAction;
15608 }(Action_1.Action));
15609 exports.AsyncAction = AsyncAction;
15611 },{"../util/root":236,"./Action":207}],209:[function(require,module,exports){
15613 var __extends = (this && this.__extends) || function (d, b) {
15614 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15615 function __() { this.constructor = d; }
15616 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15618 var Scheduler_1 = require('../Scheduler');
15619 var AsyncScheduler = (function (_super) {
15620 __extends(AsyncScheduler, _super);
15621 function AsyncScheduler() {
15622 _super.apply(this, arguments);
15625 * A flag to indicate whether the Scheduler is currently executing a batch of
15629 this.active = false;
15631 * An internal ID used to track the latest asynchronous task such as those
15632 * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
15636 this.scheduled = undefined;
15638 AsyncScheduler.prototype.flush = function (action) {
15639 var actions = this.actions;
15641 actions.push(action);
15645 this.active = true;
15647 if (error = action.execute(action.state, action.delay)) {
15650 } while (action = actions.shift()); // exhaust the scheduler queue
15651 this.active = false;
15653 while (action = actions.shift()) {
15654 action.unsubscribe();
15659 return AsyncScheduler;
15660 }(Scheduler_1.Scheduler));
15661 exports.AsyncScheduler = AsyncScheduler;
15663 },{"../Scheduler":33}],210:[function(require,module,exports){
15665 var __extends = (this && this.__extends) || function (d, b) {
15666 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15667 function __() { this.constructor = d; }
15668 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15670 var AsyncAction_1 = require('./AsyncAction');
15672 * We need this JSDoc comment for affecting ESDoc.
15674 * @extends {Ignored}
15676 var QueueAction = (function (_super) {
15677 __extends(QueueAction, _super);
15678 function QueueAction(scheduler, work) {
15679 _super.call(this, scheduler, work);
15680 this.scheduler = scheduler;
15683 QueueAction.prototype.schedule = function (state, delay) {
15684 if (delay === void 0) { delay = 0; }
15686 return _super.prototype.schedule.call(this, state, delay);
15688 this.delay = delay;
15689 this.state = state;
15690 this.scheduler.flush(this);
15693 QueueAction.prototype.execute = function (state, delay) {
15694 return (delay > 0 || this.closed) ?
15695 _super.prototype.execute.call(this, state, delay) :
15696 this._execute(state, delay);
15698 QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
15699 if (delay === void 0) { delay = 0; }
15700 // If delay exists and is greater than 0, or if the delay is null (the
15701 // action wasn't rescheduled) but was originally scheduled as an async
15702 // action, then recycle as an async action.
15703 if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
15704 return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
15706 // Otherwise flush the scheduler starting with this action.
15707 return scheduler.flush(this);
15709 return QueueAction;
15710 }(AsyncAction_1.AsyncAction));
15711 exports.QueueAction = QueueAction;
15713 },{"./AsyncAction":208}],211:[function(require,module,exports){
15715 var __extends = (this && this.__extends) || function (d, b) {
15716 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15717 function __() { this.constructor = d; }
15718 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15720 var AsyncScheduler_1 = require('./AsyncScheduler');
15721 var QueueScheduler = (function (_super) {
15722 __extends(QueueScheduler, _super);
15723 function QueueScheduler() {
15724 _super.apply(this, arguments);
15726 return QueueScheduler;
15727 }(AsyncScheduler_1.AsyncScheduler));
15728 exports.QueueScheduler = QueueScheduler;
15730 },{"./AsyncScheduler":209}],212:[function(require,module,exports){
15732 var AsyncAction_1 = require('./AsyncAction');
15733 var AsyncScheduler_1 = require('./AsyncScheduler');
15738 * <span class="informal">Schedule task as if you used setTimeout(task, duration)</span>
15740 * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript
15741 * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating
15744 * If you just want to "defer" task, that is to perform it right after currently
15745 * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),
15746 * better choice will be the {@link asap} scheduler.
15748 * @example <caption>Use async scheduler to delay task</caption>
15749 * const task = () => console.log('it works!');
15751 * Rx.Scheduler.async.schedule(task, 2000);
15753 * // After 2 seconds logs:
15757 * @example <caption>Use async scheduler to repeat task in intervals</caption>
15758 * function task(state) {
15759 * console.log(state);
15760 * this.schedule(state + 1, 1000); // `this` references currently executing Action,
15761 * // which we reschedule with new state and delay
15764 * Rx.Scheduler.async.schedule(task, 3000, 0);
15776 exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
15778 },{"./AsyncAction":208,"./AsyncScheduler":209}],213:[function(require,module,exports){
15780 var QueueAction_1 = require('./QueueAction');
15781 var QueueScheduler_1 = require('./QueueScheduler');
15786 * <span class="informal">Put every next task on a queue, instead of executing it immediately</span>
15788 * `queue` scheduler, when used with delay, behaves the same as {@link async} scheduler.
15790 * When used without delay, it schedules given task synchronously - executes it right when
15791 * it is scheduled. However when called recursively, that is when inside the scheduled task,
15792 * another task is scheduled with queue scheduler, instead of executing immediately as well,
15793 * that task will be put on a queue and wait for current one to finish.
15795 * This means that when you execute task with `queue` scheduler, you are sure it will end
15796 * before any other task scheduled with that scheduler will start.
15798 * @examples <caption>Schedule recursively first, then do something</caption>
15800 * Rx.Scheduler.queue.schedule(() => {
15801 * Rx.Scheduler.queue.schedule(() => console.log('second')); // will not happen now, but will be put on a queue
15803 * console.log('first');
15811 * @example <caption>Reschedule itself recursively</caption>
15813 * Rx.Scheduler.queue.schedule(function(state) {
15814 * if (state !== 0) {
15815 * console.log('before', state);
15816 * this.schedule(state - 1); // `this` references currently executing Action,
15817 * // which we reschedule with new state
15818 * console.log('after', state);
15822 * // In scheduler that runs recursively, you would expect:
15830 * // But with queue it logs:
15843 exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
15845 },{"./QueueAction":210,"./QueueScheduler":211}],214:[function(require,module,exports){
15847 var root_1 = require('../util/root');
15848 function symbolIteratorPonyfill(root) {
15849 var Symbol = root.Symbol;
15850 if (typeof Symbol === 'function') {
15851 if (!Symbol.iterator) {
15852 Symbol.iterator = Symbol('iterator polyfill');
15854 return Symbol.iterator;
15857 // [for Mozilla Gecko 27-35:](https://mzl.la/2ewE1zC)
15858 var Set_1 = root.Set;
15859 if (Set_1 && typeof new Set_1()['@@iterator'] === 'function') {
15860 return '@@iterator';
15862 var Map_1 = root.Map;
15863 // required for compatability with es6-shim
15865 var keys = Object.getOwnPropertyNames(Map_1.prototype);
15866 for (var i = 0; i < keys.length; ++i) {
15868 // according to spec, Map.prototype[@@iterator] and Map.orototype.entries must be equal.
15869 if (key !== 'entries' && key !== 'size' && Map_1.prototype[key] === Map_1.prototype['entries']) {
15874 return '@@iterator';
15877 exports.symbolIteratorPonyfill = symbolIteratorPonyfill;
15878 exports.iterator = symbolIteratorPonyfill(root_1.root);
15880 * @deprecated use iterator instead
15882 exports.$$iterator = exports.iterator;
15884 },{"../util/root":236}],215:[function(require,module,exports){
15886 var root_1 = require('../util/root');
15887 function getSymbolObservable(context) {
15889 var Symbol = context.Symbol;
15890 if (typeof Symbol === 'function') {
15891 if (Symbol.observable) {
15892 $$observable = Symbol.observable;
15895 $$observable = Symbol('observable');
15896 Symbol.observable = $$observable;
15900 $$observable = '@@observable';
15902 return $$observable;
15904 exports.getSymbolObservable = getSymbolObservable;
15905 exports.observable = getSymbolObservable(root_1.root);
15907 * @deprecated use observable instead
15909 exports.$$observable = exports.observable;
15911 },{"../util/root":236}],216:[function(require,module,exports){
15913 var root_1 = require('../util/root');
15914 var Symbol = root_1.root.Symbol;
15915 exports.rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ?
15916 Symbol.for('rxSubscriber') : '@@rxSubscriber';
15918 * @deprecated use rxSubscriber instead
15920 exports.$$rxSubscriber = exports.rxSubscriber;
15922 },{"../util/root":236}],217:[function(require,module,exports){
15924 var root_1 = require('./root');
15925 var RequestAnimationFrameDefinition = (function () {
15926 function RequestAnimationFrameDefinition(root) {
15927 if (root.requestAnimationFrame) {
15928 this.cancelAnimationFrame = root.cancelAnimationFrame.bind(root);
15929 this.requestAnimationFrame = root.requestAnimationFrame.bind(root);
15931 else if (root.mozRequestAnimationFrame) {
15932 this.cancelAnimationFrame = root.mozCancelAnimationFrame.bind(root);
15933 this.requestAnimationFrame = root.mozRequestAnimationFrame.bind(root);
15935 else if (root.webkitRequestAnimationFrame) {
15936 this.cancelAnimationFrame = root.webkitCancelAnimationFrame.bind(root);
15937 this.requestAnimationFrame = root.webkitRequestAnimationFrame.bind(root);
15939 else if (root.msRequestAnimationFrame) {
15940 this.cancelAnimationFrame = root.msCancelAnimationFrame.bind(root);
15941 this.requestAnimationFrame = root.msRequestAnimationFrame.bind(root);
15943 else if (root.oRequestAnimationFrame) {
15944 this.cancelAnimationFrame = root.oCancelAnimationFrame.bind(root);
15945 this.requestAnimationFrame = root.oRequestAnimationFrame.bind(root);
15948 this.cancelAnimationFrame = root.clearTimeout.bind(root);
15949 this.requestAnimationFrame = function (cb) { return root.setTimeout(cb, 1000 / 60); };
15952 return RequestAnimationFrameDefinition;
15954 exports.RequestAnimationFrameDefinition = RequestAnimationFrameDefinition;
15955 exports.AnimationFrame = new RequestAnimationFrameDefinition(root_1.root);
15957 },{"./root":236}],218:[function(require,module,exports){
15959 var __extends = (this && this.__extends) || function (d, b) {
15960 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15961 function __() { this.constructor = d; }
15962 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15965 * An error thrown when an element was queried at a certain index of an
15966 * Observable, but no such index or position exists in that sequence.
15968 * @see {@link elementAt}
15969 * @see {@link take}
15970 * @see {@link takeLast}
15972 * @class ArgumentOutOfRangeError
15974 var ArgumentOutOfRangeError = (function (_super) {
15975 __extends(ArgumentOutOfRangeError, _super);
15976 function ArgumentOutOfRangeError() {
15977 var err = _super.call(this, 'argument out of range');
15978 this.name = err.name = 'ArgumentOutOfRangeError';
15979 this.stack = err.stack;
15980 this.message = err.message;
15982 return ArgumentOutOfRangeError;
15984 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError;
15986 },{}],219:[function(require,module,exports){
15988 var __extends = (this && this.__extends) || function (d, b) {
15989 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15990 function __() { this.constructor = d; }
15991 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15994 * An error thrown when an Observable or a sequence was queried but has no
15997 * @see {@link first}
15998 * @see {@link last}
15999 * @see {@link single}
16001 * @class EmptyError
16003 var EmptyError = (function (_super) {
16004 __extends(EmptyError, _super);
16005 function EmptyError() {
16006 var err = _super.call(this, 'no elements in sequence');
16007 this.name = err.name = 'EmptyError';
16008 this.stack = err.stack;
16009 this.message = err.message;
16013 exports.EmptyError = EmptyError;
16015 },{}],220:[function(require,module,exports){
16017 var __extends = (this && this.__extends) || function (d, b) {
16018 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
16019 function __() { this.constructor = d; }
16020 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16023 * An error thrown when an action is invalid because the object has been
16026 * @see {@link Subject}
16027 * @see {@link BehaviorSubject}
16029 * @class ObjectUnsubscribedError
16031 var ObjectUnsubscribedError = (function (_super) {
16032 __extends(ObjectUnsubscribedError, _super);
16033 function ObjectUnsubscribedError() {
16034 var err = _super.call(this, 'object unsubscribed');
16035 this.name = err.name = 'ObjectUnsubscribedError';
16036 this.stack = err.stack;
16037 this.message = err.message;
16039 return ObjectUnsubscribedError;
16041 exports.ObjectUnsubscribedError = ObjectUnsubscribedError;
16043 },{}],221:[function(require,module,exports){
16045 var root_1 = require('./root');
16046 function minimalSetImpl() {
16047 // THIS IS NOT a full impl of Set, this is just the minimum
16048 // bits of functionality we need for this library.
16049 return (function () {
16050 function MinimalSet() {
16053 MinimalSet.prototype.add = function (value) {
16054 if (!this.has(value)) {
16055 this._values.push(value);
16058 MinimalSet.prototype.has = function (value) {
16059 return this._values.indexOf(value) !== -1;
16061 Object.defineProperty(MinimalSet.prototype, "size", {
16063 return this._values.length;
16068 MinimalSet.prototype.clear = function () {
16069 this._values.length = 0;
16074 exports.minimalSetImpl = minimalSetImpl;
16075 exports.Set = root_1.root.Set || minimalSetImpl();
16077 },{"./root":236}],222:[function(require,module,exports){
16079 var __extends = (this && this.__extends) || function (d, b) {
16080 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
16081 function __() { this.constructor = d; }
16082 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16085 * An error thrown when duetime elapses.
16087 * @see {@link timeout}
16089 * @class TimeoutError
16091 var TimeoutError = (function (_super) {
16092 __extends(TimeoutError, _super);
16093 function TimeoutError() {
16094 var err = _super.call(this, 'Timeout has occurred');
16095 this.name = err.name = 'TimeoutError';
16096 this.stack = err.stack;
16097 this.message = err.message;
16099 return TimeoutError;
16101 exports.TimeoutError = TimeoutError;
16103 },{}],223:[function(require,module,exports){
16105 var __extends = (this && this.__extends) || function (d, b) {
16106 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
16107 function __() { this.constructor = d; }
16108 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16111 * An error thrown when one or more errors have occurred during the
16112 * `unsubscribe` of a {@link Subscription}.
16114 var UnsubscriptionError = (function (_super) {
16115 __extends(UnsubscriptionError, _super);
16116 function UnsubscriptionError(errors) {
16118 this.errors = errors;
16119 var err = Error.call(this, errors ?
16120 errors.length + " errors occurred during unsubscription:\n " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n ') : '');
16121 this.name = err.name = 'UnsubscriptionError';
16122 this.stack = err.stack;
16123 this.message = err.message;
16125 return UnsubscriptionError;
16127 exports.UnsubscriptionError = UnsubscriptionError;
16129 },{}],224:[function(require,module,exports){
16131 // typeof any so that it we don't have to cast when comparing a result to the error object
16132 exports.errorObject = { e: {} };
16134 },{}],225:[function(require,module,exports){
16136 function identity(x) {
16139 exports.identity = identity;
16141 },{}],226:[function(require,module,exports){
16143 exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
16145 },{}],227:[function(require,module,exports){
16147 exports.isArrayLike = (function (x) { return x && typeof x.length === 'number'; });
16149 },{}],228:[function(require,module,exports){
16151 function isDate(value) {
16152 return value instanceof Date && !isNaN(+value);
16154 exports.isDate = isDate;
16156 },{}],229:[function(require,module,exports){
16158 function isFunction(x) {
16159 return typeof x === 'function';
16161 exports.isFunction = isFunction;
16163 },{}],230:[function(require,module,exports){
16165 var isArray_1 = require('../util/isArray');
16166 function isNumeric(val) {
16167 // parseFloat NaNs numeric-cast false positives (null|true|false|"")
16168 // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
16169 // subtraction forces infinities to NaN
16170 // adding 1 corrects loss of precision from parseFloat (#15100)
16171 return !isArray_1.isArray(val) && (val - parseFloat(val) + 1) >= 0;
16173 exports.isNumeric = isNumeric;
16176 },{"../util/isArray":226}],231:[function(require,module,exports){
16178 function isObject(x) {
16179 return x != null && typeof x === 'object';
16181 exports.isObject = isObject;
16183 },{}],232:[function(require,module,exports){
16185 function isPromise(value) {
16186 return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
16188 exports.isPromise = isPromise;
16190 },{}],233:[function(require,module,exports){
16192 function isScheduler(value) {
16193 return value && typeof value.schedule === 'function';
16195 exports.isScheduler = isScheduler;
16197 },{}],234:[function(require,module,exports){
16199 /* tslint:disable:no-empty */
16200 function noop() { }
16201 exports.noop = noop;
16203 },{}],235:[function(require,module,exports){
16205 var noop_1 = require('./noop');
16206 /* tslint:enable:max-line-length */
16209 for (var _i = 0; _i < arguments.length; _i++) {
16210 fns[_i - 0] = arguments[_i];
16212 return pipeFromArray(fns);
16214 exports.pipe = pipe;
16216 function pipeFromArray(fns) {
16218 return noop_1.noop;
16220 if (fns.length === 1) {
16223 return function piped(input) {
16224 return fns.reduce(function (prev, fn) { return fn(prev); }, input);
16227 exports.pipeFromArray = pipeFromArray;
16229 },{"./noop":234}],236:[function(require,module,exports){
16230 (function (global){
16232 // CommonJS / Node have global context exposed as "global" variable.
16233 // We don't want to include the whole node.d.ts this this compilation unit so we'll just fake
16234 // the global "global" var for now.
16235 var __window = typeof window !== 'undefined' && window;
16236 var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
16237 self instanceof WorkerGlobalScope && self;
16238 var __global = typeof global !== 'undefined' && global;
16239 var _root = __window || __global || __self;
16240 exports.root = _root;
16241 // Workaround Closure Compiler restriction: The body of a goog.module cannot use throw.
16242 // This is needed when used with angular/tsickle which inserts a goog.module statement.
16246 throw new Error('RxJS could not find any global context (window, self, global)');
16250 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
16252 },{}],237:[function(require,module,exports){
16254 var root_1 = require('./root');
16255 var isArrayLike_1 = require('./isArrayLike');
16256 var isPromise_1 = require('./isPromise');
16257 var isObject_1 = require('./isObject');
16258 var Observable_1 = require('../Observable');
16259 var iterator_1 = require('../symbol/iterator');
16260 var InnerSubscriber_1 = require('../InnerSubscriber');
16261 var observable_1 = require('../symbol/observable');
16262 function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) {
16263 var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex);
16264 if (destination.closed) {
16267 if (result instanceof Observable_1.Observable) {
16268 if (result._isScalar) {
16269 destination.next(result.value);
16270 destination.complete();
16274 destination.syncErrorThrowable = true;
16275 return result.subscribe(destination);
16278 else if (isArrayLike_1.isArrayLike(result)) {
16279 for (var i = 0, len = result.length; i < len && !destination.closed; i++) {
16280 destination.next(result[i]);
16282 if (!destination.closed) {
16283 destination.complete();
16286 else if (isPromise_1.isPromise(result)) {
16287 result.then(function (value) {
16288 if (!destination.closed) {
16289 destination.next(value);
16290 destination.complete();
16292 }, function (err) { return destination.error(err); })
16293 .then(null, function (err) {
16294 // Escaping the Promise trap: globally throw unhandled errors
16295 root_1.root.setTimeout(function () { throw err; });
16297 return destination;
16299 else if (result && typeof result[iterator_1.iterator] === 'function') {
16300 var iterator = result[iterator_1.iterator]();
16302 var item = iterator.next();
16304 destination.complete();
16307 destination.next(item.value);
16308 if (destination.closed) {
16313 else if (result && typeof result[observable_1.observable] === 'function') {
16314 var obs = result[observable_1.observable]();
16315 if (typeof obs.subscribe !== 'function') {
16316 destination.error(new TypeError('Provided object does not correctly implement Symbol.observable'));
16319 return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex));
16323 var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'";
16324 var msg = ("You provided " + value + " where a stream was expected.")
16325 + ' You can provide an Observable, Promise, Array, or Iterable.';
16326 destination.error(new TypeError(msg));
16330 exports.subscribeToResult = subscribeToResult;
16332 },{"../InnerSubscriber":27,"../Observable":29,"../symbol/iterator":214,"../symbol/observable":215,"./isArrayLike":227,"./isObject":231,"./isPromise":232,"./root":236}],238:[function(require,module,exports){
16334 var Subscriber_1 = require('../Subscriber');
16335 var rxSubscriber_1 = require('../symbol/rxSubscriber');
16336 var Observer_1 = require('../Observer');
16337 function toSubscriber(nextOrObserver, error, complete) {
16338 if (nextOrObserver) {
16339 if (nextOrObserver instanceof Subscriber_1.Subscriber) {
16340 return nextOrObserver;
16342 if (nextOrObserver[rxSubscriber_1.rxSubscriber]) {
16343 return nextOrObserver[rxSubscriber_1.rxSubscriber]();
16346 if (!nextOrObserver && !error && !complete) {
16347 return new Subscriber_1.Subscriber(Observer_1.empty);
16349 return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
16351 exports.toSubscriber = toSubscriber;
16353 },{"../Observer":30,"../Subscriber":36,"../symbol/rxSubscriber":216}],239:[function(require,module,exports){
16355 var errorObject_1 = require('./errorObject');
16356 var tryCatchTarget;
16357 function tryCatcher() {
16359 return tryCatchTarget.apply(this, arguments);
16362 errorObject_1.errorObject.e = e;
16363 return errorObject_1.errorObject;
16366 function tryCatch(fn) {
16367 tryCatchTarget = fn;
16370 exports.tryCatch = tryCatch;
16373 },{"./errorObject":224}],240:[function(require,module,exports){
16374 // threejs.org/license
16375 (function(m,ja){"object"===typeof exports&&"undefined"!==typeof module?ja(exports):"function"===typeof define&&define.amd?define(["exports"],ja):ja(m.THREE=m.THREE||{})})(this,function(m){function ja(){}function C(a,b){this.x=a||0;this.y=b||0}function K(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];0<arguments.length&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}function Z(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._w=void 0!==d?d:1}
16376 function p(a,b,c){this.x=a||0;this.y=b||0;this.z=c||0}function ra(){this.elements=[1,0,0,0,1,0,0,0,1];0<arguments.length&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}function ea(a,b,c,d,e,f,g,h,k,l){Object.defineProperty(this,"id",{value:kf++});this.uuid=R.generateUUID();this.name="";this.image=void 0!==a?a:ea.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=void 0!==b?b:ea.DEFAULT_MAPPING;this.wrapS=void 0!==c?c:1001;this.wrapT=void 0!==d?d:1001;this.magFilter=
16377 void 0!==e?e:1006;this.minFilter=void 0!==f?f:1008;this.anisotropy=void 0!==k?k:1;this.format=void 0!==g?g:1023;this.type=void 0!==h?h:1009;this.offset=new C(0,0);this.repeat=new C(1,1);this.center=new C(0,0);this.rotation=0;this.matrixAutoUpdate=!0;this.matrix=new ra;this.generateMipmaps=!0;this.premultiplyAlpha=!1;this.flipY=!0;this.unpackAlignment=4;this.encoding=void 0!==l?l:3E3;this.version=0;this.onUpdate=null}function da(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=void 0!==d?d:1}function Hb(a,
16378 b,c){this.uuid=R.generateUUID();this.width=a;this.height=b;this.scissor=new da(0,0,a,b);this.scissorTest=!1;this.viewport=new da(0,0,a,b);c=c||{};void 0===c.minFilter&&(c.minFilter=1006);this.texture=new ea(void 0,void 0,c.wrapS,c.wrapT,c.magFilter,c.minFilter,c.format,c.type,c.anisotropy,c.encoding);this.depthBuffer=void 0!==c.depthBuffer?c.depthBuffer:!0;this.stencilBuffer=void 0!==c.stencilBuffer?c.stencilBuffer:!0;this.depthTexture=void 0!==c.depthTexture?c.depthTexture:null}function Ib(a,b,c){Hb.call(this,
16379 a,b,c);this.activeMipMapLevel=this.activeCubeFace=0}function fb(a,b,c,d,e,f,g,h,k,l,q,n){ea.call(this,null,f,g,h,k,l,d,e,q,n);this.image={data:a,width:b,height:c};this.magFilter=void 0!==k?k:1003;this.minFilter=void 0!==l?l:1003;this.flipY=this.generateMipmaps=!1;this.unpackAlignment=1}function Ua(a,b,c,d,e,f,g,h,k,l){a=void 0!==a?a:[];ea.call(this,a,void 0!==b?b:301,c,d,e,f,g,h,k,l);this.flipY=!1}function Jb(a,b,c){var d=a[0];if(0>=d||0<d)return a;var e=b*c,f=we[e];void 0===f&&(f=new Float32Array(e),
16380 we[e]=f);if(0!==b)for(d.toArray(f,0),d=1,e=0;d!==b;++d)e+=c,a[d].toArray(f,e);return f}function xe(a,b){var c=ye[b];void 0===c&&(c=new Int32Array(b),ye[b]=c);for(var d=0;d!==b;++d)c[d]=a.allocTextureUnit();return c}function lf(a,b){a.uniform1f(this.addr,b)}function mf(a,b){a.uniform1i(this.addr,b)}function nf(a,b){void 0===b.x?a.uniform2fv(this.addr,b):a.uniform2f(this.addr,b.x,b.y)}function of(a,b){void 0!==b.x?a.uniform3f(this.addr,b.x,b.y,b.z):void 0!==b.r?a.uniform3f(this.addr,b.r,b.g,b.b):a.uniform3fv(this.addr,
16381 b)}function pf(a,b){void 0===b.x?a.uniform4fv(this.addr,b):a.uniform4f(this.addr,b.x,b.y,b.z,b.w)}function qf(a,b){a.uniformMatrix2fv(this.addr,!1,b.elements||b)}function rf(a,b){void 0===b.elements?a.uniformMatrix3fv(this.addr,!1,b):(ze.set(b.elements),a.uniformMatrix3fv(this.addr,!1,ze))}function sf(a,b){void 0===b.elements?a.uniformMatrix4fv(this.addr,!1,b):(Ae.set(b.elements),a.uniformMatrix4fv(this.addr,!1,Ae))}function tf(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTexture2D(b||
16382 Be,d)}function uf(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTextureCube(b||Ce,d)}function De(a,b){a.uniform2iv(this.addr,b)}function Ee(a,b){a.uniform3iv(this.addr,b)}function Fe(a,b){a.uniform4iv(this.addr,b)}function vf(a){switch(a){case 5126:return lf;case 35664:return nf;case 35665:return of;case 35666:return pf;case 35674:return qf;case 35675:return rf;case 35676:return sf;case 35678:case 36198:return tf;case 35680:return uf;case 5124:case 35670:return mf;case 35667:case 35671:return De;
16383 case 35668:case 35672:return Ee;case 35669:case 35673:return Fe}}function wf(a,b){a.uniform1fv(this.addr,b)}function xf(a,b){a.uniform1iv(this.addr,b)}function yf(a,b){a.uniform2fv(this.addr,Jb(b,this.size,2))}function zf(a,b){a.uniform3fv(this.addr,Jb(b,this.size,3))}function Af(a,b){a.uniform4fv(this.addr,Jb(b,this.size,4))}function Bf(a,b){a.uniformMatrix2fv(this.addr,!1,Jb(b,this.size,4))}function Cf(a,b){a.uniformMatrix3fv(this.addr,!1,Jb(b,this.size,9))}function Df(a,b){a.uniformMatrix4fv(this.addr,
16384 !1,Jb(b,this.size,16))}function Ef(a,b,c){var d=b.length,e=xe(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTexture2D(b[a]||Be,e[a])}function Ff(a,b,c){var d=b.length,e=xe(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTextureCube(b[a]||Ce,e[a])}function Gf(a){switch(a){case 5126:return wf;case 35664:return yf;case 35665:return zf;case 35666:return Af;case 35674:return Bf;case 35675:return Cf;case 35676:return Df;case 35678:return Ef;case 35680:return Ff;case 5124:case 35670:return xf;
16385 case 35667:case 35671:return De;case 35668:case 35672:return Ee;case 35669:case 35673:return Fe}}function Hf(a,b,c){this.id=a;this.addr=c;this.setValue=vf(b.type)}function If(a,b,c){this.id=a;this.addr=c;this.size=b.size;this.setValue=Gf(b.type)}function Ge(a){this.id=a;this.seq=[];this.map={}}function gb(a,b,c){this.seq=[];this.map={};this.renderer=c;c=a.getProgramParameter(b,a.ACTIVE_UNIFORMS);for(var d=0;d<c;++d){var e=a.getActiveUniform(b,d),f=a.getUniformLocation(b,e.name),g=this,h=e.name,k=
16386 h.length;for(Od.lastIndex=0;;){var l=Od.exec(h),q=Od.lastIndex,n=l[1],t=l[3];"]"===l[2]&&(n|=0);if(void 0===t||"["===t&&q+2===k){h=g;e=void 0===t?new Hf(n,e,f):new If(n,e,f);h.seq.push(e);h.map[e.id]=e;break}else t=g.map[n],void 0===t&&(t=new Ge(n),n=g,g=t,n.seq.push(g),n.map[g.id]=g),g=t}}}function H(a,b,c){return void 0===b&&void 0===c?this.set(a):this.setRGB(a,b,c)}function kd(a,b){this.min=void 0!==a?a:new C(Infinity,Infinity);this.max=void 0!==b?b:new C(-Infinity,-Infinity)}function Jf(a,b,c,
16387 d,e){var f,g,h,k,l,q,n,t,r,m,v,w,x,z,I,B;this.render=function(a,u,za,la){if(0!==a.length){u=new p;var J=la.w/la.z,ta=.5*la.z,Va=.5*la.w,L=16/la.w,Y=new C(L*J,L),ua=new p(1,1,0),M=new C(1,1),V=new kd;V.min.set(la.x,la.y);V.max.set(la.x+(la.z-16),la.y+(la.w-16));if(void 0===z){var L=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),y=new Uint16Array([0,1,2,0,2,3]);v=b.createBuffer();w=b.createBuffer();b.bindBuffer(b.ARRAY_BUFFER,v);b.bufferData(b.ARRAY_BUFFER,L,b.STATIC_DRAW);b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,
16388 w);b.bufferData(b.ELEMENT_ARRAY_BUFFER,y,b.STATIC_DRAW);I=b.createTexture();B=b.createTexture();c.bindTexture(b.TEXTURE_2D,I);b.texImage2D(b.TEXTURE_2D,0,b.RGB,16,16,0,b.RGB,b.UNSIGNED_BYTE,null);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,b.NEAREST);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,b.NEAREST);c.bindTexture(b.TEXTURE_2D,B);b.texImage2D(b.TEXTURE_2D,0,
16389 b.RGBA,16,16,0,b.RGBA,b.UNSIGNED_BYTE,null);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,b.NEAREST);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,b.NEAREST);var L=x={vertexShader:"uniform lowp int renderType;\nuniform vec3 screenPosition;\nuniform vec2 scale;\nuniform float rotation;\nuniform sampler2D occlusionMap;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\n\tvUV = uv;\n\tvec2 pos = position;\n\tif ( renderType == 2 ) {\n\t\tvec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );\n\t\tvVisibility = visibility.r / 9.0;\n\t\tvVisibility *= 1.0 - visibility.g / 9.0;\n\t\tvVisibility *= visibility.b / 9.0;\n\t\tvVisibility *= 1.0 - visibility.a / 9.0;\n\t\tpos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;\n\t\tpos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;\n\t}\n\tgl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );\n}",
16390 fragmentShader:"uniform lowp int renderType;\nuniform sampler2D map;\nuniform float opacity;\nuniform vec3 color;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\n\tif ( renderType == 0 ) {\n\t\tgl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );\n\t} else if ( renderType == 1 ) {\n\t\tgl_FragColor = texture2D( map, vUV );\n\t} else {\n\t\tvec4 texture = texture2D( map, vUV );\n\t\ttexture.a *= opacity * vVisibility;\n\t\tgl_FragColor = texture;\n\t\tgl_FragColor.rgb *= color;\n\t}\n}"},y=b.createProgram(),
16391 A=b.createShader(b.FRAGMENT_SHADER),aa=b.createShader(b.VERTEX_SHADER),D="precision "+e.precision+" float;\n";b.shaderSource(A,D+L.fragmentShader);b.shaderSource(aa,D+L.vertexShader);b.compileShader(A);b.compileShader(aa);b.attachShader(y,A);b.attachShader(y,aa);b.linkProgram(y);z=y;r=b.getAttribLocation(z,"position");m=b.getAttribLocation(z,"uv");f=b.getUniformLocation(z,"renderType");g=b.getUniformLocation(z,"map");h=b.getUniformLocation(z,"occlusionMap");k=b.getUniformLocation(z,"opacity");l=b.getUniformLocation(z,
16392 "color");q=b.getUniformLocation(z,"scale");n=b.getUniformLocation(z,"rotation");t=b.getUniformLocation(z,"screenPosition")}c.useProgram(z);c.initAttributes();c.enableAttribute(r);c.enableAttribute(m);c.disableUnusedAttributes();b.uniform1i(h,0);b.uniform1i(g,1);b.bindBuffer(b.ARRAY_BUFFER,v);b.vertexAttribPointer(r,2,b.FLOAT,!1,16,0);b.vertexAttribPointer(m,2,b.FLOAT,!1,16,8);b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,w);c.disable(b.CULL_FACE);c.buffers.depth.setMask(!1);y=0;for(A=a.length;y<A;y++)if(L=
16393 16/la.w,Y.set(L*J,L),aa=a[y],u.set(aa.matrixWorld.elements[12],aa.matrixWorld.elements[13],aa.matrixWorld.elements[14]),u.applyMatrix4(za.matrixWorldInverse),u.applyMatrix4(za.projectionMatrix),ua.copy(u),M.x=la.x+ua.x*ta+ta-8,M.y=la.y+ua.y*Va+Va-8,!0===V.containsPoint(M)){c.activeTexture(b.TEXTURE0);c.bindTexture(b.TEXTURE_2D,null);c.activeTexture(b.TEXTURE1);c.bindTexture(b.TEXTURE_2D,I);b.copyTexImage2D(b.TEXTURE_2D,0,b.RGB,M.x,M.y,16,16,0);b.uniform1i(f,0);b.uniform2f(q,Y.x,Y.y);b.uniform3f(t,
16394 ua.x,ua.y,ua.z);c.disable(b.BLEND);c.enable(b.DEPTH_TEST);b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0);c.activeTexture(b.TEXTURE0);c.bindTexture(b.TEXTURE_2D,B);b.copyTexImage2D(b.TEXTURE_2D,0,b.RGBA,M.x,M.y,16,16,0);b.uniform1i(f,1);c.disable(b.DEPTH_TEST);c.activeTexture(b.TEXTURE1);c.bindTexture(b.TEXTURE_2D,I);b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0);aa.positionScreen.copy(ua);aa.customUpdateCallback?aa.customUpdateCallback(aa):aa.updateLensFlares();b.uniform1i(f,2);c.enable(b.BLEND);
16395 for(var D=0,H=aa.lensFlares.length;D<H;D++){var E=aa.lensFlares[D];.001<E.opacity&&.001<E.scale&&(ua.x=E.x,ua.y=E.y,ua.z=E.z,L=E.size*E.scale/la.w,Y.x=L*J,Y.y=L,b.uniform3f(t,ua.x,ua.y,ua.z),b.uniform2f(q,Y.x,Y.y),b.uniform1f(n,E.rotation),b.uniform1f(k,E.opacity),b.uniform3f(l,E.color.r,E.color.g,E.color.b),c.setBlending(E.blending,E.blendEquation,E.blendSrc,E.blendDst),d.setTexture2D(E.texture,1),b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0))}}c.enable(b.CULL_FACE);c.enable(b.DEPTH_TEST);c.buffers.depth.setMask(!0);
16396 c.reset()}}}function tc(a,b,c,d,e,f,g,h,k){ea.call(this,a,b,c,d,e,f,g,h,k);this.needsUpdate=!0}function Kf(a,b,c,d,e){var f,g,h,k,l,q,n,t,r,m,v,w,x,z,I,B,J;function ta(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:b.id-a.id}var za,la,ha,He,Va=new p,L=new Z,C=new p;this.render=function(u,p,V){if(0!==u.length){if(void 0===ha){var M=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),y=new Uint16Array([0,1,2,0,2,3]);za=b.createBuffer();la=b.createBuffer();
16397 b.bindBuffer(b.ARRAY_BUFFER,za);b.bufferData(b.ARRAY_BUFFER,M,b.STATIC_DRAW);b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,la);b.bufferData(b.ELEMENT_ARRAY_BUFFER,y,b.STATIC_DRAW);M=b.createProgram();y=b.createShader(b.VERTEX_SHADER);var Y=b.createShader(b.FRAGMENT_SHADER);b.shaderSource(y,["precision "+e.precision+" float;","#define SHADER_NAME SpriteMaterial\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform float rotation;\nuniform vec2 scale;\nuniform vec2 uvOffset;\nuniform vec2 uvScale;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvarying float fogDepth;\nvoid main() {\n\tvUV = uvOffset + uv * uvScale;\n\tvec2 alignedPosition = position * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tvec4 mvPosition;\n\tmvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\tfogDepth = - mvPosition.z;\n}"].join("\n"));
16398 b.shaderSource(Y,["precision "+e.precision+" float;","#define SHADER_NAME SpriteMaterial\nuniform vec3 color;\nuniform sampler2D map;\nuniform float opacity;\nuniform int fogType;\nuniform vec3 fogColor;\nuniform float fogDensity;\nuniform float fogNear;\nuniform float fogFar;\nuniform float alphaTest;\nvarying vec2 vUV;\nvarying float fogDepth;\nvoid main() {\n\tvec4 texture = texture2D( map, vUV );\n\tgl_FragColor = vec4( color * texture.xyz, texture.a * opacity );\n\tif ( gl_FragColor.a < alphaTest ) discard;\n\tif ( fogType > 0 ) {\n\t\tfloat fogFactor = 0.0;\n\t\tif ( fogType == 1 ) {\n\t\t\tfogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t\t} else {\n\t\t\tconst float LOG2 = 1.442695;\n\t\t\tfogFactor = exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 );\n\t\t\tfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n\t\t}\n\t\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n\t}\n}"].join("\n"));
16399 b.compileShader(y);b.compileShader(Y);b.attachShader(M,y);b.attachShader(M,Y);b.linkProgram(M);ha=M;B=b.getAttribLocation(ha,"position");J=b.getAttribLocation(ha,"uv");f=b.getUniformLocation(ha,"uvOffset");g=b.getUniformLocation(ha,"uvScale");h=b.getUniformLocation(ha,"rotation");k=b.getUniformLocation(ha,"scale");l=b.getUniformLocation(ha,"color");q=b.getUniformLocation(ha,"map");n=b.getUniformLocation(ha,"opacity");t=b.getUniformLocation(ha,"modelViewMatrix");r=b.getUniformLocation(ha,"projectionMatrix");
16400 m=b.getUniformLocation(ha,"fogType");v=b.getUniformLocation(ha,"fogDensity");w=b.getUniformLocation(ha,"fogNear");x=b.getUniformLocation(ha,"fogFar");z=b.getUniformLocation(ha,"fogColor");b.getUniformLocation(ha,"fogDepth");I=b.getUniformLocation(ha,"alphaTest");M=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");M.width=8;M.height=8;y=M.getContext("2d");y.fillStyle="white";y.fillRect(0,0,8,8);He=new tc(M)}c.useProgram(ha);c.initAttributes();c.enableAttribute(B);c.enableAttribute(J);
16401 c.disableUnusedAttributes();c.disable(b.CULL_FACE);c.enable(b.BLEND);b.bindBuffer(b.ARRAY_BUFFER,za);b.vertexAttribPointer(B,2,b.FLOAT,!1,16,0);b.vertexAttribPointer(J,2,b.FLOAT,!1,16,8);b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,la);b.uniformMatrix4fv(r,!1,V.projectionMatrix.elements);c.activeTexture(b.TEXTURE0);b.uniform1i(q,0);y=M=0;(Y=p.fog)?(b.uniform3f(z,Y.color.r,Y.color.g,Y.color.b),Y.isFog?(b.uniform1f(w,Y.near),b.uniform1f(x,Y.far),b.uniform1i(m,1),y=M=1):Y.isFogExp2&&(b.uniform1f(v,Y.density),
16402 b.uniform1i(m,2),y=M=2)):(b.uniform1i(m,0),y=M=0);for(var A=0,ua=u.length;A<ua;A++)Y=u[A],Y.modelViewMatrix.multiplyMatrices(V.matrixWorldInverse,Y.matrixWorld),Y.z=-Y.modelViewMatrix.elements[14];u.sort(ta);for(var E=[],A=0,ua=u.length;A<ua;A++){Y=u[A];var G=Y.material;if(!1!==G.visible){Y.onBeforeRender(a,p,V,void 0,G,void 0);b.uniform1f(I,G.alphaTest);b.uniformMatrix4fv(t,!1,Y.modelViewMatrix.elements);Y.matrixWorld.decompose(Va,L,C);E[0]=C.x;E[1]=C.y;var D=0;p.fog&&G.fog&&(D=y);M!==D&&(b.uniform1i(m,
16403 D),M=D);null!==G.map?(b.uniform2f(f,G.map.offset.x,G.map.offset.y),b.uniform2f(g,G.map.repeat.x,G.map.repeat.y)):(b.uniform2f(f,0,0),b.uniform2f(g,1,1));b.uniform1f(n,G.opacity);b.uniform3f(l,G.color.r,G.color.g,G.color.b);b.uniform1f(h,G.rotation);b.uniform2fv(k,E);c.setBlending(G.blending,G.blendEquation,G.blendSrc,G.blendDst,G.blendEquationAlpha,G.blendSrcAlpha,G.blendDstAlpha,G.premultipliedAlpha);c.buffers.depth.setTest(G.depthTest);c.buffers.depth.setMask(G.depthWrite);c.buffers.color.setMask(G.colorWrite);
16404 d.setTexture2D(G.map||He,0);b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0);Y.onAfterRender(a,p,V,void 0,G,void 0)}}c.enable(b.CULL_FACE);c.reset()}}}function Q(){Object.defineProperty(this,"id",{value:Lf++});this.uuid=R.generateUUID();this.name="";this.type="Material";this.lights=this.fog=!0;this.blending=1;this.side=0;this.flatShading=!1;this.vertexColors=0;this.opacity=1;this.transparent=!1;this.blendSrc=204;this.blendDst=205;this.blendEquation=100;this.blendEquationAlpha=this.blendDstAlpha=this.blendSrcAlpha=
16405 null;this.depthFunc=3;this.depthWrite=this.depthTest=!0;this.clippingPlanes=null;this.clipShadows=this.clipIntersection=!1;this.colorWrite=!0;this.precision=null;this.polygonOffset=!1;this.polygonOffsetUnits=this.polygonOffsetFactor=0;this.dithering=!1;this.alphaTest=0;this.premultipliedAlpha=!1;this.overdraw=0;this.visible=!0;this.userData={};this.needsUpdate=!0}function Wa(a){Q.call(this);this.type="MeshDepthMaterial";this.depthPacking=3200;this.morphTargets=this.skinning=!1;this.displacementMap=
16406 this.alphaMap=this.map=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.lights=this.fog=!1;this.setValues(a)}function Xa(a){Q.call(this);this.type="MeshDistanceMaterial";this.referencePosition=new p;this.nearDistance=1;this.farDistance=1E3;this.morphTargets=this.skinning=!1;this.displacementMap=this.alphaMap=this.map=null;this.displacementScale=1;this.displacementBias=0;this.lights=this.fog=!1;this.setValues(a)}function Oa(a,b){this.min=void 0!==
16407 a?a:new p(Infinity,Infinity,Infinity);this.max=void 0!==b?b:new p(-Infinity,-Infinity,-Infinity)}function Da(a,b){this.center=void 0!==a?a:new p;this.radius=void 0!==b?b:0}function Aa(a,b){this.normal=void 0!==a?a:new p(1,0,0);this.constant=void 0!==b?b:0}function ld(a,b,c,d,e,f){this.planes=[void 0!==a?a:new Aa,void 0!==b?b:new Aa,void 0!==c?c:new Aa,void 0!==d?d:new Aa,void 0!==e?e:new Aa,void 0!==f?f:new Aa]}function Ie(a,b,c){function d(b,c,d,e,f,g){var h=b.geometry;var k=n;var l=b.customDepthMaterial;
16408 d&&(k=t,l=b.customDistanceMaterial);l?k=l:(l=!1,c.morphTargets&&(h&&h.isBufferGeometry?l=h.morphAttributes&&h.morphAttributes.position&&0<h.morphAttributes.position.length:h&&h.isGeometry&&(l=h.morphTargets&&0<h.morphTargets.length)),b.isSkinnedMesh&&!1===c.skinning&&console.warn("THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:",b),b=b.isSkinnedMesh&&c.skinning,h=0,l&&(h|=1),b&&(h|=2),k=k[h]);a.localClippingEnabled&&!0===c.clipShadows&&0!==c.clippingPlanes.length&&(h=
16409 k.uuid,l=c.uuid,b=r[h],void 0===b&&(b={},r[h]=b),h=b[l],void 0===h&&(h=k.clone(),b[l]=h),k=h);k.visible=c.visible;k.wireframe=c.wireframe;l=c.side;B.renderSingleSided&&2==l&&(l=0);B.renderReverseSided&&(0===l?l=1:1===l&&(l=0));k.side=l;k.clipShadows=c.clipShadows;k.clippingPlanes=c.clippingPlanes;k.clipIntersection=c.clipIntersection;k.wireframeLinewidth=c.wireframeLinewidth;k.linewidth=c.linewidth;d&&k.isMeshDistanceMaterial&&(k.referencePosition.copy(e),k.nearDistance=f,k.farDistance=g);return k}
16410 function e(c,g,h,k){var l;if(!1!==c.visible){if(c.layers.test(g.layers)&&(c.isMesh||c.isLine||c.isPoints)&&c.castShadow&&(!c.frustumCulled||f.intersectsObject(c))){c.modelViewMatrix.multiplyMatrices(h.matrixWorldInverse,c.matrixWorld);var n=b.update(c),t=c.material;if(Array.isArray(t))for(var r=n.groups,m=0,z=r.length;m<z;m++){var u=r[m];(l=t[u.materialIndex])&&l.visible&&(l=d(c,l,k,q,h.near,h.far),a.renderBufferDirect(h,null,n,l,c,u))}else t.visible&&(l=d(c,t,k,q,h.near,h.far),a.renderBufferDirect(h,
16411 null,n,l,c,null))}c=c.children;n=0;for(t=c.length;n<t;n++)e(c[n],g,h,k)}}var f=new ld,g=new K,h=new C,k=new C(c,c),l=new p,q=new p,n=Array(4),t=Array(4),r={},m=[new p(1,0,0),new p(-1,0,0),new p(0,0,1),new p(0,0,-1),new p(0,1,0),new p(0,-1,0)],v=[new p(0,1,0),new p(0,1,0),new p(0,1,0),new p(0,1,0),new p(0,0,1),new p(0,0,-1)],w=[new da,new da,new da,new da,new da,new da];for(c=0;4!==c;++c){var x=0!==(c&1),z=0!==(c&2),I=new Wa({depthPacking:3201,morphTargets:x,skinning:z});n[c]=I;x=new Xa({morphTargets:x,
16412 skinning:z});t[c]=x}var B=this;this.enabled=!1;this.autoUpdate=!0;this.needsUpdate=!1;this.type=1;this.renderSingleSided=this.renderReverseSided=!0;this.render=function(b,c,d){if(!1!==B.enabled&&(!1!==B.autoUpdate||!1!==B.needsUpdate)&&0!==b.length){var n=a.state;n.disable(a.context.BLEND);n.buffers.color.setClear(1,1,1,1);n.buffers.depth.setTest(!0);n.setScissorTest(!1);for(var t,r=0,z=b.length;r<z;r++){var u=b[r];t=u.shadow;var I=u&&u.isPointLight;if(void 0===t)console.warn("THREE.WebGLShadowMap:",
16413 u,"has no shadow.");else{var p=t.camera;h.copy(t.mapSize);h.min(k);if(I){var x=h.x,J=h.y;w[0].set(2*x,J,x,J);w[1].set(0,J,x,J);w[2].set(3*x,J,x,J);w[3].set(x,J,x,J);w[4].set(3*x,0,x,J);w[5].set(x,0,x,J);h.x*=4;h.y*=2}null===t.map&&(t.map=new Hb(h.x,h.y,{minFilter:1003,magFilter:1003,format:1023}),t.map.texture.name=u.name+".shadowMap",p.updateProjectionMatrix());t.isSpotLightShadow&&t.update(u);x=t.map;J=t.matrix;q.setFromMatrixPosition(u.matrixWorld);p.position.copy(q);I?(t=6,J.makeTranslation(-q.x,
16414 -q.y,-q.z)):(t=1,l.setFromMatrixPosition(u.target.matrixWorld),p.lookAt(l),p.updateMatrixWorld(),J.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),J.multiply(p.projectionMatrix),J.multiply(p.matrixWorldInverse));a.setRenderTarget(x);a.clear();for(u=0;u<t;u++)I&&(l.copy(p.position),l.add(m[u]),p.up.copy(v[u]),p.lookAt(l),p.updateMatrixWorld(),n.viewport(w[u])),g.multiplyMatrices(p.projectionMatrix,p.matrixWorldInverse),f.setFromMatrix(g),e(c,d,p,I)}}B.needsUpdate=!1}}}function Mf(a){var b={};return{get:function(a){a.isInterleavedBufferAttribute&&
16415 (a=a.data);return b[a.uuid]},remove:function(c){c.isInterleavedBufferAttribute&&(c=c.data);var d=b[c.uuid];d&&(a.deleteBuffer(d.buffer),delete b[c.uuid])},update:function(c,d){c.isInterleavedBufferAttribute&&(c=c.data);var e=b[c.uuid];if(void 0===e){var e=c.uuid,f=c.array,g=c.dynamic?a.DYNAMIC_DRAW:a.STATIC_DRAW,h=a.createBuffer();a.bindBuffer(d,h);a.bufferData(d,f,g);c.onUploadCallback();d=a.FLOAT;f instanceof Float32Array?d=a.FLOAT:f instanceof Float64Array?console.warn("THREE.WebGLAttributes: Unsupported data buffer format: Float64Array."):
16416 f instanceof Uint16Array?d=a.UNSIGNED_SHORT:f instanceof Int16Array?d=a.SHORT:f instanceof Uint32Array?d=a.UNSIGNED_INT:f instanceof Int32Array?d=a.INT:f instanceof Int8Array?d=a.BYTE:f instanceof Uint8Array&&(d=a.UNSIGNED_BYTE);b[e]={buffer:h,type:d,bytesPerElement:f.BYTES_PER_ELEMENT,version:c.version}}else e.version<c.version&&(f=c,h=f.array,g=f.updateRange,a.bindBuffer(d,e.buffer),!1===f.dynamic?a.bufferData(d,h,a.STATIC_DRAW):-1===g.count?a.bufferSubData(d,0,h):0===g.count?console.error("THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually."):
16417 (a.bufferSubData(d,g.offset*h.BYTES_PER_ELEMENT,h.subarray(g.offset,g.offset+g.count)),g.count=-1),e.version=c.version)}}}function Ya(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._order=d||Ya.DefaultOrder}function Pd(){this.mask=1}function A(){Object.defineProperty(this,"id",{value:Nf++});this.uuid=R.generateUUID();this.name="";this.type="Object3D";this.parent=null;this.children=[];this.up=A.DefaultUp.clone();var a=new p,b=new Ya,c=new Z,d=new p(1,1,1);b.onChange(function(){c.setFromEuler(b,
16418 !1)});c.onChange(function(){b.setFromQuaternion(c,void 0,!1)});Object.defineProperties(this,{position:{enumerable:!0,value:a},rotation:{enumerable:!0,value:b},quaternion:{enumerable:!0,value:c},scale:{enumerable:!0,value:d},modelViewMatrix:{value:new K},normalMatrix:{value:new ra}});this.matrix=new K;this.matrixWorld=new K;this.matrixAutoUpdate=A.DefaultMatrixAutoUpdate;this.matrixWorldNeedsUpdate=!1;this.layers=new Pd;this.visible=!0;this.receiveShadow=this.castShadow=!1;this.frustumCulled=!0;this.renderOrder=
16419 0;this.userData={}}function La(){A.call(this);this.type="Camera";this.matrixWorldInverse=new K;this.projectionMatrix=new K}function Kb(a,b,c,d,e,f){La.call(this);this.type="OrthographicCamera";this.zoom=1;this.view=null;this.left=a;this.right=b;this.top=c;this.bottom=d;this.near=void 0!==e?e:.1;this.far=void 0!==f?f:2E3;this.updateProjectionMatrix()}function Pa(a,b,c,d,e,f){this.a=a;this.b=b;this.c=c;this.normal=d&&d.isVector3?d:new p;this.vertexNormals=Array.isArray(d)?d:[];this.color=e&&e.isColor?
16420 e:new H;this.vertexColors=Array.isArray(e)?e:[];this.materialIndex=void 0!==f?f:0}function N(){Object.defineProperty(this,"id",{value:Of+=2});this.uuid=R.generateUUID();this.name="";this.type="Geometry";this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.lineDistancesNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=
16421 this.uvsNeedUpdate=this.verticesNeedUpdate=this.elementsNeedUpdate=!1}function P(a,b,c){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.uuid=R.generateUUID();this.name="";this.array=a;this.itemSize=b;this.count=void 0!==a?a.length/b:0;this.normalized=!0===c;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function uc(a,b,c){P.call(this,new Int8Array(a),b,c)}function vc(a,b,c){P.call(this,new Uint8Array(a),
16422 b,c)}function wc(a,b,c){P.call(this,new Uint8ClampedArray(a),b,c)}function xc(a,b,c){P.call(this,new Int16Array(a),b,c)}function hb(a,b,c){P.call(this,new Uint16Array(a),b,c)}function yc(a,b,c){P.call(this,new Int32Array(a),b,c)}function ib(a,b,c){P.call(this,new Uint32Array(a),b,c)}function y(a,b,c){P.call(this,new Float32Array(a),b,c)}function zc(a,b,c){P.call(this,new Float64Array(a),b,c)}function Je(){this.indices=[];this.vertices=[];this.normals=[];this.colors=[];this.uvs=[];this.uvs2=[];this.groups=
16423 [];this.morphTargets={};this.skinWeights=[];this.skinIndices=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.uvsNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.verticesNeedUpdate=!1}function Qd(a){if(0===a.length)return-Infinity;for(var b=a[0],c=1,d=a.length;c<d;++c)a[c]>b&&(b=a[c]);return b}function D(){Object.defineProperty(this,"id",{value:Pf+=2});this.uuid=R.generateUUID();this.name="";this.type="BufferGeometry";this.index=null;this.attributes={};this.morphAttributes=
16424 {};this.groups=[];this.boundingSphere=this.boundingBox=null;this.drawRange={start:0,count:Infinity}}function Lb(a,b,c,d,e,f){N.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};this.fromBufferGeometry(new jb(a,b,c,d,e,f));this.mergeVertices()}function jb(a,b,c,d,e,f){function g(a,b,c,d,e,f,g,m,ta,za,la){var z=f/ta,u=g/za,v=f/2,w=g/2,I=m/2;g=ta+1;var B=za+1,x=f=0,J,y,C=new p;for(y=0;y<B;y++){var A=y*u-w;for(J=0;J<g;J++)C[a]=
16425 (J*z-v)*d,C[b]=A*e,C[c]=I,l.push(C.x,C.y,C.z),C[a]=0,C[b]=0,C[c]=0<m?1:-1,q.push(C.x,C.y,C.z),n.push(J/ta),n.push(1-y/za),f+=1}for(y=0;y<za;y++)for(J=0;J<ta;J++)a=t+J+g*(y+1),b=t+(J+1)+g*(y+1),c=t+(J+1)+g*y,k.push(t+J+g*y,a,c),k.push(a,b,c),x+=6;h.addGroup(r,x,la);r+=x;t+=f}D.call(this);this.type="BoxBufferGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};var h=this;a=a||1;b=b||1;c=c||1;d=Math.floor(d)||1;e=Math.floor(e)||1;f=Math.floor(f)||1;var k=
16426 [],l=[],q=[],n=[],t=0,r=0;g("z","y","x",-1,-1,c,b,a,f,e,0);g("z","y","x",1,-1,c,b,-a,f,e,1);g("x","z","y",1,1,a,c,b,d,f,2);g("x","z","y",1,-1,a,c,-b,d,f,3);g("x","y","z",1,-1,a,b,c,d,e,4);g("x","y","z",-1,-1,a,b,-c,d,e,5);this.setIndex(k);this.addAttribute("position",new y(l,3));this.addAttribute("normal",new y(q,3));this.addAttribute("uv",new y(n,2))}function Ac(a,b,c,d){N.call(this);this.type="PlaneGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};this.fromBufferGeometry(new kb(a,
16427 b,c,d));this.mergeVertices()}function kb(a,b,c,d){D.call(this);this.type="PlaneBufferGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};a=a||1;b=b||1;var e=a/2,f=b/2;c=Math.floor(c)||1;d=Math.floor(d)||1;var g=c+1,h=d+1,k=a/c,l=b/d,q=[],n=[],t=[],r=[];for(a=0;a<h;a++){var m=a*l-f;for(b=0;b<g;b++)n.push(b*k-e,-m,0),t.push(0,0,1),r.push(b/c),r.push(1-a/d)}for(a=0;a<d;a++)for(b=0;b<c;b++)e=b+g*(a+1),f=b+1+g*(a+1),h=b+1+g*a,q.push(b+g*a,e,h),q.push(e,f,h);this.setIndex(q);this.addAttribute("position",
16428 new y(n,3));this.addAttribute("normal",new y(t,3));this.addAttribute("uv",new y(r,2))}function va(a){Q.call(this);this.type="MeshBasicMaterial";this.color=new H(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.lights=this.morphTargets=this.skinning=
16429 !1;this.setValues(a)}function oa(a){Q.call(this);this.type="ShaderMaterial";this.defines={};this.uniforms={};this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";this.linewidth=1;this.wireframe=!1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.skinning=this.clipping=this.lights=this.fog=!1;this.extensions={derivatives:!1,fragDepth:!1,
16430 drawBuffers:!1,shaderTextureLOD:!1};this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv2:[0,0]};this.index0AttributeName=void 0;void 0!==a&&(void 0!==a.attributes&&console.error("THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead."),this.setValues(a))}function lb(a,b){this.origin=void 0!==a?a:new p;this.direction=void 0!==b?b:new p}function Mb(a,b){this.start=void 0!==a?a:new p;this.end=void 0!==b?b:new p}function Qa(a,b,c){this.a=void 0!==a?a:new p;this.b=void 0!==
16431 b?b:new p;this.c=void 0!==c?c:new p}function pa(a,b){A.call(this);this.type="Mesh";this.geometry=void 0!==a?a:new D;this.material=void 0!==b?b:new va({color:16777215*Math.random()});this.drawMode=0;this.updateMorphTargets()}function Qf(a,b,c,d){function e(a,c){b.buffers.color.setClear(a.r,a.g,a.b,c,d)}var f=new H(0),g=0,h,k,l;return{getClearColor:function(){return f},setClearColor:function(a,b){f.set(a);g=void 0!==b?b:1;e(f,g)},getClearAlpha:function(){return g},setClearAlpha:function(a){g=a;e(f,
16432 g)},render:function(b,d,t,r){d=d.background;null===d?e(f,g):d&&d.isColor&&(e(d,1),r=!0);(a.autoClear||r)&&a.clear(a.autoClearColor,a.autoClearDepth,a.autoClearStencil);d&&d.isCubeTexture?(void 0===l&&(l=new pa(new jb(1,1,1),new oa({uniforms:mb.cube.uniforms,vertexShader:mb.cube.vertexShader,fragmentShader:mb.cube.fragmentShader,side:1,depthTest:!0,depthWrite:!1,fog:!1})),l.geometry.removeAttribute("normal"),l.geometry.removeAttribute("uv"),l.onBeforeRender=function(a,b,c){this.matrixWorld.copyPosition(c.matrixWorld)},
16433 c.update(l.geometry)),l.material.uniforms.tCube.value=d,b.push(l,l.geometry,l.material,0,null)):d&&d.isTexture&&(void 0===h&&(h=new Kb(-1,1,1,-1,0,1),k=new pa(new kb(2,2),new va({depthTest:!1,depthWrite:!1,fog:!1})),c.update(k.geometry)),k.material.map=d,a.renderBufferDirect(h,null,k.geometry,k.material,k,null))}}}function Rf(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.program&&b.program&&a.program!==b.program?a.program.id-b.program.id:a.material.id!==b.material.id?a.material.id-
16434 b.material.id:a.z!==b.z?a.z-b.z:a.id-b.id}function Sf(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:a.id-b.id}function Tf(){var a=[],b=0,c=[],d=[];return{opaque:c,transparent:d,init:function(){b=0;c.length=0;d.length=0},push:function(e,f,g,h,k){var l=a[b];void 0===l?(l={id:e.id,object:e,geometry:f,material:g,program:g.program,renderOrder:e.renderOrder,z:h,group:k},a[b]=l):(l.id=e.id,l.object=e,l.geometry=f,l.material=g,l.program=g.program,l.renderOrder=e.renderOrder,
16435 l.z=h,l.group=k);(!0===g.transparent?d:c).push(l);b++},sort:function(){1<c.length&&c.sort(Rf);1<d.length&&d.sort(Sf)}}}function Uf(){var a={};return{get:function(b,c){b=b.id+","+c.id;c=a[b];void 0===c&&(c=new Tf,a[b]=c);return c},dispose:function(){a={}}}}function Vf(a,b){return Math.abs(b[1])-Math.abs(a[1])}function Wf(a){var b={},c=new Float32Array(8);return{update:function(d,e,f,g){var h=d.morphTargetInfluences,k=h.length;d=b[e.id];if(void 0===d){d=[];for(var l=0;l<k;l++)d[l]=[l,0];b[e.id]=d}var q=
16436 f.morphTargets&&e.morphAttributes.position;f=f.morphNormals&&e.morphAttributes.normal;for(l=0;l<k;l++){var n=d[l];0!==n[1]&&(q&&e.removeAttribute("morphTarget"+l),f&&e.removeAttribute("morphNormal"+l))}for(l=0;l<k;l++)n=d[l],n[0]=l,n[1]=h[l];d.sort(Vf);for(l=0;8>l;l++){if(n=d[l])if(h=n[0],n=n[1]){q&&e.addAttribute("morphTarget"+l,q[h]);f&&e.addAttribute("morphNormal"+l,f[h]);c[l]=n;continue}c[l]=0}g.getUniforms().setValue(a,"morphTargetInfluences",c)}}}function Xf(a,b,c){var d,e,f;this.setMode=function(a){d=
16437 a};this.setIndex=function(a){e=a.type;f=a.bytesPerElement};this.render=function(b,h){a.drawElements(d,h,e,b*f);c.calls++;c.vertices+=h;d===a.TRIANGLES?c.faces+=h/3:d===a.POINTS&&(c.points+=h)};this.renderInstances=function(g,h,k){var l=b.get("ANGLE_instanced_arrays");null===l?console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):(l.drawElementsInstancedANGLE(d,k,e,h*f,g.maxInstancedCount),c.calls++,c.vertices+=
16438 k*g.maxInstancedCount,d===a.TRIANGLES?c.faces+=g.maxInstancedCount*k/3:d===a.POINTS&&(c.points+=g.maxInstancedCount*k))}}function Yf(a,b,c){var d;this.setMode=function(a){d=a};this.render=function(b,f){a.drawArrays(d,b,f);c.calls++;c.vertices+=f;d===a.TRIANGLES?c.faces+=f/3:d===a.POINTS&&(c.points+=f)};this.renderInstances=function(e,f,g){var h=b.get("ANGLE_instanced_arrays");if(null===h)console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");
16439 else{var k=e.attributes.position;k.isInterleavedBufferAttribute?(g=k.data.count,h.drawArraysInstancedANGLE(d,0,g,e.maxInstancedCount)):h.drawArraysInstancedANGLE(d,f,g,e.maxInstancedCount);c.calls++;c.vertices+=g*e.maxInstancedCount;d===a.TRIANGLES?c.faces+=e.maxInstancedCount*g/3:d===a.POINTS&&(c.points+=e.maxInstancedCount*g)}}}function Zf(a,b,c){function d(a){a=a.target;var g=e[a.id];null!==g.index&&b.remove(g.index);for(var k in g.attributes)b.remove(g.attributes[k]);a.removeEventListener("dispose",
16440 d);delete e[a.id];if(k=f[a.id])b.remove(k),delete f[a.id];if(k=f[g.id])b.remove(k),delete f[g.id];c.geometries--}var e={},f={};return{get:function(a,b){var f=e[b.id];if(f)return f;b.addEventListener("dispose",d);b.isBufferGeometry?f=b:b.isGeometry&&(void 0===b._bufferGeometry&&(b._bufferGeometry=(new D).setFromObject(a)),f=b._bufferGeometry);e[b.id]=f;c.geometries++;return f},update:function(c){var d=c.index,e=c.attributes;null!==d&&b.update(d,a.ELEMENT_ARRAY_BUFFER);for(var f in e)b.update(e[f],
16441 a.ARRAY_BUFFER);c=c.morphAttributes;for(f in c)for(var d=c[f],e=0,g=d.length;e<g;e++)b.update(d[e],a.ARRAY_BUFFER)},getWireframeAttribute:function(c){var d=f[c.id];if(d)return d;d=[];var e=c.index;var g=c.attributes;if(null!==e){var q=e.array;for(var n=0,t=q.length;n<t;n+=3){var r=q[n+0];g=q[n+1];e=q[n+2];d.push(r,g,g,e,e,r)}}else for(q=g.position.array,n=0,t=q.length/3-1;n<t;n+=3)r=n+0,g=n+1,e=n+2,d.push(r,g,g,e,e,r);d=new (65535<Qd(d)?ib:hb)(d,1);b.update(d,a.ELEMENT_ARRAY_BUFFER);return f[c.id]=
16442 d}}}function $f(){var a={};return{get:function(b){if(void 0!==a[b.id])return a[b.id];switch(b.type){case "DirectionalLight":var c={direction:new p,color:new H,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "SpotLight":c={position:new p,direction:new p,color:new H,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "PointLight":c={position:new p,color:new H,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C,
16443 shadowCameraNear:1,shadowCameraFar:1E3};break;case "HemisphereLight":c={direction:new p,skyColor:new H,groundColor:new H};break;case "RectAreaLight":c={color:new H,position:new p,halfWidth:new p,halfHeight:new p}}return a[b.id]=c}}}function ag(){var a=new $f,b={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]},c=new p,d=new K,e=new K;return{setup:function(f,
16444 g,h){for(var k,l=0,q=0,n=0,t=0,r=0,m=0,v=0,w=0,p=h.matrixWorldInverse,z=0,I=f.length;z<I;z++){var B=f[z];k=B.color;var J=B.intensity,ta=B.distance,za=B.shadow&&B.shadow.map?B.shadow.map.texture:null;if(B.isAmbientLight)l+=k.r*J,q+=k.g*J,n+=k.b*J;else if(B.isDirectionalLight){h=a.get(B);h.color.copy(B.color).multiplyScalar(B.intensity);h.direction.setFromMatrixPosition(B.matrixWorld);c.setFromMatrixPosition(B.target.matrixWorld);h.direction.sub(c);h.direction.transformDirection(p);if(h.shadow=B.castShadow)k=
16445 B.shadow,h.shadowBias=k.bias,h.shadowRadius=k.radius,h.shadowMapSize=k.mapSize;b.directionalShadowMap[t]=za;b.directionalShadowMatrix[t]=B.shadow.matrix;b.directional[t]=h;t++}else if(B.isSpotLight){h=a.get(B);h.position.setFromMatrixPosition(B.matrixWorld);h.position.applyMatrix4(p);h.color.copy(k).multiplyScalar(J);h.distance=ta;h.direction.setFromMatrixPosition(B.matrixWorld);c.setFromMatrixPosition(B.target.matrixWorld);h.direction.sub(c);h.direction.transformDirection(p);h.coneCos=Math.cos(B.angle);
16446 h.penumbraCos=Math.cos(B.angle*(1-B.penumbra));h.decay=0===B.distance?0:B.decay;if(h.shadow=B.castShadow)k=B.shadow,h.shadowBias=k.bias,h.shadowRadius=k.radius,h.shadowMapSize=k.mapSize;b.spotShadowMap[m]=za;b.spotShadowMatrix[m]=B.shadow.matrix;b.spot[m]=h;m++}else if(B.isRectAreaLight)h=a.get(B),h.color.copy(k).multiplyScalar(J/(B.width*B.height)),h.position.setFromMatrixPosition(B.matrixWorld),h.position.applyMatrix4(p),e.identity(),d.copy(B.matrixWorld),d.premultiply(p),e.extractRotation(d),h.halfWidth.set(.5*
16447 B.width,0,0),h.halfHeight.set(0,.5*B.height,0),h.halfWidth.applyMatrix4(e),h.halfHeight.applyMatrix4(e),b.rectArea[v]=h,v++;else if(B.isPointLight){h=a.get(B);h.position.setFromMatrixPosition(B.matrixWorld);h.position.applyMatrix4(p);h.color.copy(B.color).multiplyScalar(B.intensity);h.distance=B.distance;h.decay=0===B.distance?0:B.decay;if(h.shadow=B.castShadow)k=B.shadow,h.shadowBias=k.bias,h.shadowRadius=k.radius,h.shadowMapSize=k.mapSize,h.shadowCameraNear=k.camera.near,h.shadowCameraFar=k.camera.far;
16448 b.pointShadowMap[r]=za;b.pointShadowMatrix[r]=B.shadow.matrix;b.point[r]=h;r++}else B.isHemisphereLight&&(h=a.get(B),h.direction.setFromMatrixPosition(B.matrixWorld),h.direction.transformDirection(p),h.direction.normalize(),h.skyColor.copy(B.color).multiplyScalar(J),h.groundColor.copy(B.groundColor).multiplyScalar(J),b.hemi[w]=h,w++)}b.ambient[0]=l;b.ambient[1]=q;b.ambient[2]=n;b.directional.length=t;b.spot.length=m;b.rectArea.length=v;b.point.length=r;b.hemi.length=w;b.hash=t+","+r+","+m+","+v+","+
16449 w+","+g.length},state:b}}function bg(a,b){var c={};return{update:function(d){var e=b.frame,f=d.geometry,g=a.get(d,f);c[g.id]!==e&&(f.isGeometry&&g.updateFromObject(d),a.update(g),c[g.id]=e);return g},clear:function(){c={}}}}function cg(a){a=a.split("\n");for(var b=0;b<a.length;b++)a[b]=b+1+": "+a[b];return a.join("\n")}function Ke(a,b,c){var d=a.createShader(b);a.shaderSource(d,c);a.compileShader(d);!1===a.getShaderParameter(d,a.COMPILE_STATUS)&&console.error("THREE.WebGLShader: Shader couldn't compile.");
16450 ""!==a.getShaderInfoLog(d)&&console.warn("THREE.WebGLShader: gl.getShaderInfoLog()",b===a.VERTEX_SHADER?"vertex":"fragment",a.getShaderInfoLog(d),cg(c));return d}function Le(a){switch(a){case 3E3:return["Linear","( value )"];case 3001:return["sRGB","( value )"];case 3002:return["RGBE","( value )"];case 3004:return["RGBM","( value, 7.0 )"];case 3005:return["RGBM","( value, 16.0 )"];case 3006:return["RGBD","( value, 256.0 )"];case 3007:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw Error("unsupported encoding: "+
16451 a);}}function Rd(a,b){b=Le(b);return"vec4 "+a+"( vec4 value ) { return "+b[0]+"ToLinear"+b[1]+"; }"}function dg(a,b){b=Le(b);return"vec4 "+a+"( vec4 value ) { return LinearTo"+b[0]+b[1]+"; }"}function eg(a,b){switch(b){case 1:b="Linear";break;case 2:b="Reinhard";break;case 3:b="Uncharted2";break;case 4:b="OptimizedCineon";break;default:throw Error("unsupported toneMapping: "+b);}return"vec3 "+a+"( vec3 color ) { return "+b+"ToneMapping( color ); }"}function fg(a,b,c){a=a||{};return[a.derivatives||
16452 b.envMapCubeUV||b.bumpMap||b.normalMap||b.flatShading?"#extension GL_OES_standard_derivatives : enable":"",(a.fragDepth||b.logarithmicDepthBuffer)&&c.get("EXT_frag_depth")?"#extension GL_EXT_frag_depth : enable":"",a.drawBuffers&&c.get("WEBGL_draw_buffers")?"#extension GL_EXT_draw_buffers : require":"",(a.shaderTextureLOD||b.envMap)&&c.get("EXT_shader_texture_lod")?"#extension GL_EXT_shader_texture_lod : enable":""].filter(Bc).join("\n")}function gg(a){var b=[],c;for(c in a){var d=a[c];!1!==d&&b.push("#define "+
16453 c+" "+d)}return b.join("\n")}function Bc(a){return""!==a}function Me(a,b){return a.replace(/NUM_DIR_LIGHTS/g,b.numDirLights).replace(/NUM_SPOT_LIGHTS/g,b.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g,b.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,b.numPointLights).replace(/NUM_HEMI_LIGHTS/g,b.numHemiLights)}function Sd(a){return a.replace(/^[ \t]*#include +<([\w\d.]+)>/gm,function(a,c){a=W[c];if(void 0===a)throw Error("Can not resolve #include <"+c+">");return Sd(a)})}function Ne(a){return a.replace(/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,
16454 function(a,c,d,e){a="";for(c=parseInt(c);c<parseInt(d);c++)a+=e.replace(/\[ i \]/g,"[ "+c+" ]");return a})}function hg(a,b,c,d,e,f){var g=a.context,h=d.defines,k=e.vertexShader,l=e.fragmentShader,q="SHADOWMAP_TYPE_BASIC";1===f.shadowMapType?q="SHADOWMAP_TYPE_PCF":2===f.shadowMapType&&(q="SHADOWMAP_TYPE_PCF_SOFT");var n="ENVMAP_TYPE_CUBE",t="ENVMAP_MODE_REFLECTION",r="ENVMAP_BLENDING_MULTIPLY";if(f.envMap){switch(d.envMap.mapping){case 301:case 302:n="ENVMAP_TYPE_CUBE";break;case 306:case 307:n="ENVMAP_TYPE_CUBE_UV";
16455 break;case 303:case 304:n="ENVMAP_TYPE_EQUIREC";break;case 305:n="ENVMAP_TYPE_SPHERE"}switch(d.envMap.mapping){case 302:case 304:t="ENVMAP_MODE_REFRACTION"}switch(d.combine){case 0:r="ENVMAP_BLENDING_MULTIPLY";break;case 1:r="ENVMAP_BLENDING_MIX";break;case 2:r="ENVMAP_BLENDING_ADD"}}var m=0<a.gammaFactor?a.gammaFactor:1,v=fg(d.extensions,f,b),w=gg(h),p=g.createProgram();d.isRawShaderMaterial?(h=[w].filter(Bc).join("\n"),0<h.length&&(h+="\n"),b=[v,w].filter(Bc).join("\n"),0<b.length&&(b+="\n")):(h=
16456 ["precision "+f.precision+" float;","precision "+f.precision+" int;","#define SHADER_NAME "+e.name,w,f.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+m,"#define MAX_BONES "+f.maxBones,f.useFog&&f.fog?"#define USE_FOG":"",f.useFog&&f.fogExp?"#define FOG_EXP2":"",f.map?"#define USE_MAP":"",f.envMap?"#define USE_ENVMAP":"",f.envMap?"#define "+t:"",f.lightMap?"#define USE_LIGHTMAP":"",f.aoMap?"#define USE_AOMAP":"",f.emissiveMap?"#define USE_EMISSIVEMAP":"",f.bumpMap?"#define USE_BUMPMAP":
16457 "",f.normalMap?"#define USE_NORMALMAP":"",f.displacementMap&&f.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",f.specularMap?"#define USE_SPECULARMAP":"",f.roughnessMap?"#define USE_ROUGHNESSMAP":"",f.metalnessMap?"#define USE_METALNESSMAP":"",f.alphaMap?"#define USE_ALPHAMAP":"",f.vertexColors?"#define USE_COLOR":"",f.flatShading?"#define FLAT_SHADED":"",f.skinning?"#define USE_SKINNING":"",f.useVertexTexture?"#define BONE_TEXTURE":"",f.morphTargets?"#define USE_MORPHTARGETS":"",f.morphNormals&&
16458 !1===f.flatShading?"#define USE_MORPHNORMALS":"",f.doubleSided?"#define DOUBLE_SIDED":"",f.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+f.numClippingPlanes,f.shadowMapEnabled?"#define USE_SHADOWMAP":"",f.shadowMapEnabled?"#define "+q:"",f.sizeAttenuation?"#define USE_SIZEATTENUATION":"",f.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",f.logarithmicDepthBuffer&&b.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;",
16459 "uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;",
16460 "\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(Bc).join("\n"),b=[v,"precision "+f.precision+" float;","precision "+f.precision+" int;","#define SHADER_NAME "+e.name,w,f.alphaTest?"#define ALPHATEST "+f.alphaTest:
16461 "","#define GAMMA_FACTOR "+m,f.useFog&&f.fog?"#define USE_FOG":"",f.useFog&&f.fogExp?"#define FOG_EXP2":"",f.map?"#define USE_MAP":"",f.envMap?"#define USE_ENVMAP":"",f.envMap?"#define "+n:"",f.envMap?"#define "+t:"",f.envMap?"#define "+r:"",f.lightMap?"#define USE_LIGHTMAP":"",f.aoMap?"#define USE_AOMAP":"",f.emissiveMap?"#define USE_EMISSIVEMAP":"",f.bumpMap?"#define USE_BUMPMAP":"",f.normalMap?"#define USE_NORMALMAP":"",f.specularMap?"#define USE_SPECULARMAP":"",f.roughnessMap?"#define USE_ROUGHNESSMAP":
16462 "",f.metalnessMap?"#define USE_METALNESSMAP":"",f.alphaMap?"#define USE_ALPHAMAP":"",f.vertexColors?"#define USE_COLOR":"",f.gradientMap?"#define USE_GRADIENTMAP":"",f.flatShading?"#define FLAT_SHADED":"",f.doubleSided?"#define DOUBLE_SIDED":"",f.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+f.numClippingPlanes,"#define UNION_CLIPPING_PLANES "+(f.numClippingPlanes-f.numClipIntersection),f.shadowMapEnabled?"#define USE_SHADOWMAP":"",f.shadowMapEnabled?"#define "+q:"",f.premultipliedAlpha?
16463 "#define PREMULTIPLIED_ALPHA":"",f.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",f.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",f.logarithmicDepthBuffer&&b.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",f.envMap&&b.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",0!==f.toneMapping?"#define TONE_MAPPING":"",0!==f.toneMapping?W.tonemapping_pars_fragment:"",0!==f.toneMapping?eg("toneMapping",f.toneMapping):
16464 "",f.dithering?"#define DITHERING":"",f.outputEncoding||f.mapEncoding||f.envMapEncoding||f.emissiveMapEncoding?W.encodings_pars_fragment:"",f.mapEncoding?Rd("mapTexelToLinear",f.mapEncoding):"",f.envMapEncoding?Rd("envMapTexelToLinear",f.envMapEncoding):"",f.emissiveMapEncoding?Rd("emissiveMapTexelToLinear",f.emissiveMapEncoding):"",f.outputEncoding?dg("linearToOutputTexel",f.outputEncoding):"",f.depthPacking?"#define DEPTH_PACKING "+d.depthPacking:"","\n"].filter(Bc).join("\n"));k=Sd(k);k=Me(k,f);
16465 l=Sd(l);l=Me(l,f);d.isShaderMaterial||(k=Ne(k),l=Ne(l));l=b+l;k=Ke(g,g.VERTEX_SHADER,h+k);l=Ke(g,g.FRAGMENT_SHADER,l);g.attachShader(p,k);g.attachShader(p,l);void 0!==d.index0AttributeName?g.bindAttribLocation(p,0,d.index0AttributeName):!0===f.morphTargets&&g.bindAttribLocation(p,0,"position");g.linkProgram(p);f=g.getProgramInfoLog(p);e=g.getShaderInfoLog(k);q=g.getShaderInfoLog(l);t=n=!0;if(!1===g.getProgramParameter(p,g.LINK_STATUS))n=!1,console.error("THREE.WebGLProgram: shader error: ",g.getError(),
16466 "gl.VALIDATE_STATUS",g.getProgramParameter(p,g.VALIDATE_STATUS),"gl.getProgramInfoLog",f,e,q);else if(""!==f)console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",f);else if(""===e||""===q)t=!1;t&&(this.diagnostics={runnable:n,material:d,programLog:f,vertexShader:{log:e,prefix:h},fragmentShader:{log:q,prefix:b}});g.deleteShader(k);g.deleteShader(l);var z;this.getUniforms=function(){void 0===z&&(z=new gb(g,p,a));return z};var I;this.getAttributes=function(){if(void 0===I){for(var a={},b=g.getProgramParameter(p,
16467 g.ACTIVE_ATTRIBUTES),c=0;c<b;c++){var d=g.getActiveAttrib(p,c).name;a[d]=g.getAttribLocation(p,d)}I=a}return I};this.destroy=function(){g.deleteProgram(p);this.program=void 0};Object.defineProperties(this,{uniforms:{get:function(){console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms().");return this.getUniforms()}},attributes:{get:function(){console.warn("THREE.WebGLProgram: .attributes is now .getAttributes().");return this.getAttributes()}}});this.id=ig++;this.code=c;this.usedTimes=1;
16468 this.program=p;this.vertexShader=k;this.fragmentShader=l;return this}function jg(a,b,c){function d(a,b){if(a)a.isTexture?c=a.encoding:a.isWebGLRenderTarget&&(console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead."),c=a.texture.encoding);else var c=3E3;3E3===c&&b&&(c=3007);return c}var e=[],f={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",
16469 MeshPhongMaterial:"phong",MeshToonMaterial:"phong",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow"},g="precision supportsVertexTextures map mapEncoding envMap envMapMode envMapEncoding lightMap aoMap emissiveMap emissiveMapEncoding bumpMap normalMap displacementMap specularMap roughnessMap metalnessMap gradientMap alphaMap combine vertexColors fog useFog fogExp flatShading sizeAttenuation logarithmicDepthBuffer skinning maxBones useVertexTexture morphTargets morphNormals maxMorphTargets maxMorphNormals premultipliedAlpha numDirLights numPointLights numSpotLights numHemiLights numRectAreaLights shadowMapEnabled shadowMapType toneMapping physicallyCorrectLights alphaTest doubleSided flipSided numClippingPlanes numClipIntersection depthPacking dithering".split(" ");
16470 this.getParameters=function(b,e,g,q,n,t,r){var h=f[b.type];if(r.isSkinnedMesh){var l=r.skeleton.bones;if(c.floatVertexTextures)l=1024;else{var k=Math.min(Math.floor((c.maxVertexUniforms-20)/4),l.length);k<l.length?(console.warn("THREE.WebGLRenderer: Skeleton has "+l.length+" bones. This GPU supports "+k+"."),l=0):l=k}}else l=0;k=c.precision;null!==b.precision&&(k=c.getMaxPrecision(b.precision),k!==b.precision&&console.warn("THREE.WebGLProgram.getParameters:",b.precision,"not supported, using",k,"instead."));
16471 var m=a.getRenderTarget();return{shaderID:h,precision:k,supportsVertexTextures:c.vertexTextures,outputEncoding:d(m?m.texture:null,a.gammaOutput),map:!!b.map,mapEncoding:d(b.map,a.gammaInput),envMap:!!b.envMap,envMapMode:b.envMap&&b.envMap.mapping,envMapEncoding:d(b.envMap,a.gammaInput),envMapCubeUV:!!b.envMap&&(306===b.envMap.mapping||307===b.envMap.mapping),lightMap:!!b.lightMap,aoMap:!!b.aoMap,emissiveMap:!!b.emissiveMap,emissiveMapEncoding:d(b.emissiveMap,a.gammaInput),bumpMap:!!b.bumpMap,normalMap:!!b.normalMap,
16472 displacementMap:!!b.displacementMap,roughnessMap:!!b.roughnessMap,metalnessMap:!!b.metalnessMap,specularMap:!!b.specularMap,alphaMap:!!b.alphaMap,gradientMap:!!b.gradientMap,combine:b.combine,vertexColors:b.vertexColors,fog:!!q,useFog:b.fog,fogExp:q&&q.isFogExp2,flatShading:b.flatShading,sizeAttenuation:b.sizeAttenuation,logarithmicDepthBuffer:c.logarithmicDepthBuffer,skinning:b.skinning&&0<l,maxBones:l,useVertexTexture:c.floatVertexTextures,morphTargets:b.morphTargets,morphNormals:b.morphNormals,
16473 maxMorphTargets:a.maxMorphTargets,maxMorphNormals:a.maxMorphNormals,numDirLights:e.directional.length,numPointLights:e.point.length,numSpotLights:e.spot.length,numRectAreaLights:e.rectArea.length,numHemiLights:e.hemi.length,numClippingPlanes:n,numClipIntersection:t,dithering:b.dithering,shadowMapEnabled:a.shadowMap.enabled&&r.receiveShadow&&0<g.length,shadowMapType:a.shadowMap.type,toneMapping:a.toneMapping,physicallyCorrectLights:a.physicallyCorrectLights,premultipliedAlpha:b.premultipliedAlpha,
16474 alphaTest:b.alphaTest,doubleSided:2===b.side,flipSided:1===b.side,depthPacking:void 0!==b.depthPacking?b.depthPacking:!1}};this.getProgramCode=function(b,c){var d=[];c.shaderID?d.push(c.shaderID):(d.push(b.fragmentShader),d.push(b.vertexShader));if(void 0!==b.defines)for(var e in b.defines)d.push(e),d.push(b.defines[e]);for(e=0;e<g.length;e++)d.push(c[g[e]]);d.push(b.onBeforeCompile.toString());d.push(a.gammaOutput);return d.join()};this.acquireProgram=function(c,d,f,g){for(var h,l=0,k=e.length;l<
16475 k;l++){var q=e[l];if(q.code===g){h=q;++h.usedTimes;break}}void 0===h&&(h=new hg(a,b,g,c,d,f),e.push(h));return h};this.releaseProgram=function(a){if(0===--a.usedTimes){var b=e.indexOf(a);e[b]=e[e.length-1];e.pop();a.destroy()}};this.programs=e}function kg(a,b,c,d,e,f,g){function h(a,b){if(a.width>b||a.height>b){b/=Math.max(a.width,a.height);var c=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");c.width=Math.floor(a.width*b);c.height=Math.floor(a.height*b);c.getContext("2d").drawImage(a,
16476 0,0,a.width,a.height,0,0,c.width,c.height);console.warn("THREE.WebGLRenderer: image is too big ("+a.width+"x"+a.height+"). Resized to "+c.width+"x"+c.height,a);return c}return a}function k(a){return R.isPowerOfTwo(a.width)&&R.isPowerOfTwo(a.height)}function l(a,b){return a.generateMipmaps&&b&&1003!==a.minFilter&&1006!==a.minFilter}function q(b){return 1003===b||1004===b||1005===b?a.NEAREST:a.LINEAR}function n(b){b=b.target;b.removeEventListener("dispose",n);a:{var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube);
16477 else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d.remove(b)}g.textures--}function t(b){b=b.target;b.removeEventListener("dispose",t);var c=d.get(b),e=d.get(b.texture);if(b){void 0!==e.__webglTexture&&a.deleteTexture(e.__webglTexture);b.depthTexture&&b.depthTexture.dispose();if(b.isWebGLRenderTargetCube)for(e=0;6>e;e++)a.deleteFramebuffer(c.__webglFramebuffer[e]),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer[e]);else a.deleteFramebuffer(c.__webglFramebuffer),
16478 c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d.remove(b.texture);d.remove(b)}g.textures--}function r(b,q){var t=d.get(b);if(0<b.version&&t.__version!==b.version){var r=b.image;if(void 0===r)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",b);else if(!1===r.complete)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",b);else{void 0===t.__webglInit&&(t.__webglInit=!0,b.addEventListener("dispose",n),t.__webglTexture=
16479 a.createTexture(),g.textures++);c.activeTexture(a.TEXTURE0+q);c.bindTexture(a.TEXTURE_2D,t.__webglTexture);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha);a.pixelStorei(a.UNPACK_ALIGNMENT,b.unpackAlignment);var u=h(b.image,e.maxTextureSize);(1001!==b.wrapS||1001!==b.wrapT||1003!==b.minFilter&&1006!==b.minFilter)&&!1===k(u)&&(q=u,q instanceof HTMLImageElement||q instanceof HTMLCanvasElement||q instanceof ImageBitmap?(r=document.createElementNS("http://www.w3.org/1999/xhtml",
16480 "canvas"),r.width=R.floorPowerOfTwo(q.width),r.height=R.floorPowerOfTwo(q.height),r.getContext("2d").drawImage(q,0,0,r.width,r.height),console.warn("THREE.WebGLRenderer: image is not power of two ("+q.width+"x"+q.height+"). Resized to "+r.width+"x"+r.height,q),u=r):u=q);q=k(u);var r=f.convert(b.format),z=f.convert(b.type);m(a.TEXTURE_2D,b,q);var p=b.mipmaps;if(b.isDepthTexture){p=a.DEPTH_COMPONENT;if(1015===b.type){if(!x)throw Error("Float Depth Texture only supported in WebGL2.0");p=a.DEPTH_COMPONENT32F}else x&&
16481 (p=a.DEPTH_COMPONENT16);1026===b.format&&p===a.DEPTH_COMPONENT&&1012!==b.type&&1014!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),b.type=1012,z=f.convert(b.type));1027===b.format&&(p=a.DEPTH_STENCIL,1020!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),b.type=1020,z=f.convert(b.type)));c.texImage2D(a.TEXTURE_2D,0,p,u.width,u.height,0,r,z,null)}else if(b.isDataTexture)if(0<
16482 p.length&&q){for(var v=0,w=p.length;v<w;v++)u=p[v],c.texImage2D(a.TEXTURE_2D,v,r,u.width,u.height,0,r,z,u.data);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,r,u.width,u.height,0,r,z,u.data);else if(b.isCompressedTexture)for(v=0,w=p.length;v<w;v++)u=p[v],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(r)?c.compressedTexImage2D(a.TEXTURE_2D,v,r,u.width,u.height,0,u.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):
16483 c.texImage2D(a.TEXTURE_2D,v,r,u.width,u.height,0,r,z,u.data);else if(0<p.length&&q){v=0;for(w=p.length;v<w;v++)u=p[v],c.texImage2D(a.TEXTURE_2D,v,r,r,z,u);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,r,r,z,u);l(b,q)&&a.generateMipmap(a.TEXTURE_2D);t.__version=b.version;if(b.onUpdate)b.onUpdate(b);return}}c.activeTexture(a.TEXTURE0+q);c.bindTexture(a.TEXTURE_2D,t.__webglTexture)}function m(c,g,h){h?(a.texParameteri(c,a.TEXTURE_WRAP_S,f.convert(g.wrapS)),a.texParameteri(c,a.TEXTURE_WRAP_T,
16484 f.convert(g.wrapT)),a.texParameteri(c,a.TEXTURE_MAG_FILTER,f.convert(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,f.convert(g.minFilter))):(a.texParameteri(c,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(c,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),1001===g.wrapS&&1001===g.wrapT||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.",g),a.texParameteri(c,a.TEXTURE_MAG_FILTER,q(g.magFilter)),a.texParameteri(c,
16485 a.TEXTURE_MIN_FILTER,q(g.minFilter)),1003!==g.minFilter&&1006!==g.minFilter&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.",g));!(h=b.get("EXT_texture_filter_anisotropic"))||1015===g.type&&null===b.get("OES_texture_float_linear")||1016===g.type&&null===b.get("OES_texture_half_float_linear")||!(1<g.anisotropy||d.get(g).__currentAnisotropy)||(a.texParameterf(c,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(g.anisotropy,
16486 e.getMaxAnisotropy())),d.get(g).__currentAnisotropy=g.anisotropy)}function p(b,e,g,h){var l=f.convert(e.texture.format),k=f.convert(e.texture.type);c.texImage2D(h,0,l,e.width,e.height,0,l,k,null);a.bindFramebuffer(a.FRAMEBUFFER,b);a.framebufferTexture2D(a.FRAMEBUFFER,g,h,d.get(e.texture).__webglTexture,0);a.bindFramebuffer(a.FRAMEBUFFER,null)}function w(b,c){a.bindRenderbuffer(a.RENDERBUFFER,b);c.depthBuffer&&!c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_COMPONENT16,c.width,c.height),
16487 a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,b)):c.depthBuffer&&c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_STENCIL,c.width,c.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,b)):a.renderbufferStorage(a.RENDERBUFFER,a.RGBA4,c.width,c.height);a.bindRenderbuffer(a.RENDERBUFFER,null)}var x="undefined"!==typeof WebGL2RenderingContext&&a instanceof window.WebGL2RenderingContext;this.setTexture2D=r;this.setTextureCube=
16488 function(b,q){var t=d.get(b);if(6===b.image.length)if(0<b.version&&t.__version!==b.version){t.__image__webglTextureCube||(b.addEventListener("dispose",n),t.__image__webglTextureCube=a.createTexture(),g.textures++);c.activeTexture(a.TEXTURE0+q);c.bindTexture(a.TEXTURE_CUBE_MAP,t.__image__webglTextureCube);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);q=b&&b.isCompressedTexture;for(var r=b.image[0]&&b.image[0].isDataTexture,u=[],p=0;6>p;p++)u[p]=q||r?r?b.image[p].image:b.image[p]:h(b.image[p],e.maxCubemapSize);
16489 var v=k(u[0]),w=f.convert(b.format),z=f.convert(b.type);m(a.TEXTURE_CUBE_MAP,b,v);for(p=0;6>p;p++)if(q)for(var x,I=u[p].mipmaps,y=0,C=I.length;y<C;y++)x=I[y],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(w)?c.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+p,y,w,x.width,x.height,0,x.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+p,y,w,x.width,x.height,
16490 0,w,z,x.data);else r?c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+p,0,w,u[p].width,u[p].height,0,w,z,u[p].data):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+p,0,w,w,z,u[p]);l(b,v)&&a.generateMipmap(a.TEXTURE_CUBE_MAP);t.__version=b.version;if(b.onUpdate)b.onUpdate(b)}else c.activeTexture(a.TEXTURE0+q),c.bindTexture(a.TEXTURE_CUBE_MAP,t.__image__webglTextureCube)};this.setTextureCubeDynamic=function(b,e){c.activeTexture(a.TEXTURE0+e);c.bindTexture(a.TEXTURE_CUBE_MAP,d.get(b).__webglTexture)};this.setupRenderTarget=
16491 function(b){var e=d.get(b),f=d.get(b.texture);b.addEventListener("dispose",t);f.__webglTexture=a.createTexture();g.textures++;var h=!0===b.isWebGLRenderTargetCube,n=k(b);if(h){e.__webglFramebuffer=[];for(var q=0;6>q;q++)e.__webglFramebuffer[q]=a.createFramebuffer()}else e.__webglFramebuffer=a.createFramebuffer();if(h){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);m(a.TEXTURE_CUBE_MAP,b.texture,n);for(q=0;6>q;q++)p(e.__webglFramebuffer[q],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+q);
16492 l(b.texture,n)&&a.generateMipmap(a.TEXTURE_CUBE_MAP);c.bindTexture(a.TEXTURE_CUBE_MAP,null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),m(a.TEXTURE_2D,b.texture,n),p(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),l(b.texture,n)&&a.generateMipmap(a.TEXTURE_2D),c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=!0===b.isWebGLRenderTargetCube;if(b.depthTexture){if(f)throw Error("target.depthTexture not supported in Cube render targets");if(b&&b.isWebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported");
16493 a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer);if(!b.depthTexture||!b.depthTexture.isDepthTexture)throw Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");d.get(b.depthTexture).__webglTexture&&b.depthTexture.image.width===b.width&&b.depthTexture.image.height===b.height||(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0);r(b.depthTexture,0);e=d.get(b.depthTexture).__webglTexture;if(1026===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,
16494 a.DEPTH_ATTACHMENT,a.TEXTURE_2D,e,0);else if(1027===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.TEXTURE_2D,e,0);else throw Error("Unknown depthTexture format");}else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),w(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),w(e.__webglDepthbuffer,
16495 b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap=function(b){var e=b.texture,f=k(b);l(e,f)&&(b=b.isWebGLRenderTargetCube?a.TEXTURE_CUBE_MAP:a.TEXTURE_2D,e=d.get(e).__webglTexture,c.bindTexture(b,e),a.generateMipmap(b),c.bindTexture(b,null))}}function lg(){var a={};return{get:function(b){b=b.uuid;var c=a[b];void 0===c&&(c={},a[b]=c);return c},remove:function(b){delete a[b.uuid]},clear:function(){a={}}}}function mg(a,b,c){function d(b,c,d){var e=new Uint8Array(4),f=a.createTexture();
16496 a.bindTexture(b,f);a.texParameteri(b,a.TEXTURE_MIN_FILTER,a.NEAREST);a.texParameteri(b,a.TEXTURE_MAG_FILTER,a.NEAREST);for(b=0;b<d;b++)a.texImage2D(c+b,0,a.RGBA,1,1,0,a.RGBA,a.UNSIGNED_BYTE,e);return f}function e(b){!0!==z[b]&&(a.enable(b),z[b]=!0)}function f(b){!1!==z[b]&&(a.disable(b),z[b]=!1)}function g(b,d,g,h,l,k,n,q){0!==b?e(a.BLEND):f(a.BLEND);if(5!==b){if(b!==J||q!==L)switch(b){case 2:q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,a.ONE,a.ONE,a.ONE)):(a.blendEquation(a.FUNC_ADD),
16497 a.blendFunc(a.SRC_ALPHA,a.ONE));break;case 3:q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.ZERO,a.ONE_MINUS_SRC_COLOR,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.ONE_MINUS_SRC_COLOR));break;case 4:q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.SRC_COLOR,a.ZERO,a.SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.SRC_COLOR));break;default:q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,
16498 a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA))}E=A=ha=C=y=ta=null}else{l=l||d;k=k||g;n=n||h;if(d!==ta||l!==ha)a.blendEquationSeparate(c.convert(d),c.convert(l)),ta=d,ha=l;if(g!==y||h!==C||k!==A||n!==E)a.blendFuncSeparate(c.convert(g),c.convert(h),c.convert(k),c.convert(n)),y=g,C=h,A=k,E=n}J=b;L=q}function h(b){D!==b&&(b?a.frontFace(a.CW):a.frontFace(a.CCW),D=b)}
16499 function k(b){0!==b?(e(a.CULL_FACE),b!==H&&(1===b?a.cullFace(a.BACK):2===b?a.cullFace(a.FRONT):a.cullFace(a.FRONT_AND_BACK))):f(a.CULL_FACE);H=b}function l(b,c,d){if(b){if(e(a.POLYGON_OFFSET_FILL),V!==c||K!==d)a.polygonOffset(c,d),V=c,K=d}else f(a.POLYGON_OFFSET_FILL)}function q(b){void 0===b&&(b=a.TEXTURE0+N-1);R!==b&&(a.activeTexture(b),R=b)}var n=new function(){var b=!1,c=new da,d=null,e=new da(0,0,0,0);return{setMask:function(c){d===c||b||(a.colorMask(c,c,c,c),d=c)},setLocked:function(a){b=a},
16500 setClear:function(b,d,f,g,h){!0===h&&(b*=g,d*=g,f*=g);c.set(b,d,f,g);!1===e.equals(c)&&(a.clearColor(b,d,f,g),e.copy(c))},reset:function(){b=!1;d=null;e.set(-1,0,0,0)}}},t=new function(){var b=!1,c=null,d=null,g=null;return{setTest:function(b){b?e(a.DEPTH_TEST):f(a.DEPTH_TEST)},setMask:function(d){c===d||b||(a.depthMask(d),c=d)},setFunc:function(b){if(d!==b){if(b)switch(b){case 0:a.depthFunc(a.NEVER);break;case 1:a.depthFunc(a.ALWAYS);break;case 2:a.depthFunc(a.LESS);break;case 3:a.depthFunc(a.LEQUAL);
16501 break;case 4:a.depthFunc(a.EQUAL);break;case 5:a.depthFunc(a.GEQUAL);break;case 6:a.depthFunc(a.GREATER);break;case 7:a.depthFunc(a.NOTEQUAL);break;default:a.depthFunc(a.LEQUAL)}else a.depthFunc(a.LEQUAL);d=b}},setLocked:function(a){b=a},setClear:function(b){g!==b&&(a.clearDepth(b),g=b)},reset:function(){b=!1;g=d=c=null}}},r=new function(){var b=!1,c=null,d=null,g=null,h=null,l=null,k=null,n=null,q=null;return{setTest:function(b){b?e(a.STENCIL_TEST):f(a.STENCIL_TEST)},setMask:function(d){c===d||b||
16502 (a.stencilMask(d),c=d)},setFunc:function(b,c,e){if(d!==b||g!==c||h!==e)a.stencilFunc(b,c,e),d=b,g=c,h=e},setOp:function(b,c,d){if(l!==b||k!==c||n!==d)a.stencilOp(b,c,d),l=b,k=c,n=d},setLocked:function(a){b=a},setClear:function(b){q!==b&&(a.clearStencil(b),q=b)},reset:function(){b=!1;q=n=k=l=h=g=d=c=null}}},m=a.getParameter(a.MAX_VERTEX_ATTRIBS),p=new Uint8Array(m),w=new Uint8Array(m),x=new Uint8Array(m),z={},I=null,B=null,J=null,ta=null,y=null,C=null,ha=null,A=null,E=null,L=!1,D=null,H=null,M=null,
16503 V=null,K=null,N=a.getParameter(a.MAX_COMBINED_TEXTURE_IMAGE_UNITS),m=parseFloat(/^WebGL\ ([0-9])/.exec(a.getParameter(a.VERSION))[1]),aa=1<=parseFloat(m),R=null,P={},Q=new da,G=new da,X={};X[a.TEXTURE_2D]=d(a.TEXTURE_2D,a.TEXTURE_2D,1);X[a.TEXTURE_CUBE_MAP]=d(a.TEXTURE_CUBE_MAP,a.TEXTURE_CUBE_MAP_POSITIVE_X,6);n.setClear(0,0,0,1);t.setClear(1);r.setClear(0);e(a.DEPTH_TEST);t.setFunc(3);h(!1);k(1);e(a.CULL_FACE);e(a.BLEND);g(1);return{buffers:{color:n,depth:t,stencil:r},initAttributes:function(){for(var a=
16504 0,b=p.length;a<b;a++)p[a]=0},enableAttribute:function(c){p[c]=1;0===w[c]&&(a.enableVertexAttribArray(c),w[c]=1);0!==x[c]&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,0),x[c]=0)},enableAttributeAndDivisor:function(c,d){p[c]=1;0===w[c]&&(a.enableVertexAttribArray(c),w[c]=1);x[c]!==d&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,d),x[c]=d)},disableUnusedAttributes:function(){for(var b=0,c=w.length;b!==c;++b)w[b]!==p[b]&&(a.disableVertexAttribArray(b),w[b]=0)},enable:e,
16505 disable:f,getCompressedTextureFormats:function(){if(null===I&&(I=[],b.get("WEBGL_compressed_texture_pvrtc")||b.get("WEBGL_compressed_texture_s3tc")||b.get("WEBGL_compressed_texture_etc1")))for(var c=a.getParameter(a.COMPRESSED_TEXTURE_FORMATS),d=0;d<c.length;d++)I.push(c[d]);return I},useProgram:function(b){return B!==b?(a.useProgram(b),B=b,!0):!1},setBlending:g,setMaterial:function(b){2===b.side?f(a.CULL_FACE):e(a.CULL_FACE);h(1===b.side);!0===b.transparent?g(b.blending,b.blendEquation,b.blendSrc,
16506 b.blendDst,b.blendEquationAlpha,b.blendSrcAlpha,b.blendDstAlpha,b.premultipliedAlpha):g(0);t.setFunc(b.depthFunc);t.setTest(b.depthTest);t.setMask(b.depthWrite);n.setMask(b.colorWrite);l(b.polygonOffset,b.polygonOffsetFactor,b.polygonOffsetUnits)},setFlipSided:h,setCullFace:k,setLineWidth:function(b){b!==M&&(aa&&a.lineWidth(b),M=b)},setPolygonOffset:l,setScissorTest:function(b){b?e(a.SCISSOR_TEST):f(a.SCISSOR_TEST)},activeTexture:q,bindTexture:function(b,c){null===R&&q();var d=P[R];void 0===d&&(d=
16507 {type:void 0,texture:void 0},P[R]=d);if(d.type!==b||d.texture!==c)a.bindTexture(b,c||X[b]),d.type=b,d.texture=c},compressedTexImage2D:function(){try{a.compressedTexImage2D.apply(a,arguments)}catch(fa){console.error("THREE.WebGLState:",fa)}},texImage2D:function(){try{a.texImage2D.apply(a,arguments)}catch(fa){console.error("THREE.WebGLState:",fa)}},scissor:function(b){!1===Q.equals(b)&&(a.scissor(b.x,b.y,b.z,b.w),Q.copy(b))},viewport:function(b){!1===G.equals(b)&&(a.viewport(b.x,b.y,b.z,b.w),G.copy(b))},
16508 reset:function(){for(var b=0;b<w.length;b++)1===w[b]&&(a.disableVertexAttribArray(b),w[b]=0);z={};R=I=null;P={};H=D=J=B=null;n.reset();t.reset();r.reset()}}}function ng(a,b,c){function d(b){if("highp"===b){if(0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.HIGH_FLOAT).precision&&0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.HIGH_FLOAT).precision)return"highp";b="mediump"}return"mediump"===b&&0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.MEDIUM_FLOAT).precision&&0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,
16509 a.MEDIUM_FLOAT).precision?"mediump":"lowp"}var e,f=void 0!==c.precision?c.precision:"highp",g=d(f);g!==f&&(console.warn("THREE.WebGLRenderer:",f,"not supported, using",g,"instead."),f=g);c=!0===c.logarithmicDepthBuffer;var g=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS),h=a.getParameter(a.MAX_VERTEX_TEXTURE_IMAGE_UNITS),k=a.getParameter(a.MAX_TEXTURE_SIZE),l=a.getParameter(a.MAX_CUBE_MAP_TEXTURE_SIZE),q=a.getParameter(a.MAX_VERTEX_ATTRIBS),n=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS),t=a.getParameter(a.MAX_VARYING_VECTORS),
16510 r=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS),m=0<h,p=!!b.get("OES_texture_float");return{getMaxAnisotropy:function(){if(void 0!==e)return e;var c=b.get("EXT_texture_filter_anisotropic");return e=null!==c?a.getParameter(c.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0},getMaxPrecision:d,precision:f,logarithmicDepthBuffer:c,maxTextures:g,maxVertexTextures:h,maxTextureSize:k,maxCubemapSize:l,maxAttributes:q,maxVertexUniforms:n,maxVaryings:t,maxFragmentUniforms:r,vertexTextures:m,floatFragmentTextures:p,floatVertexTextures:m&&
16511 p}}function U(a,b,c,d){La.call(this);this.type="PerspectiveCamera";this.fov=void 0!==a?a:50;this.zoom=1;this.near=void 0!==c?c:.1;this.far=void 0!==d?d:2E3;this.focus=10;this.aspect=void 0!==b?b:1;this.view=null;this.filmGauge=35;this.filmOffset=0;this.updateProjectionMatrix()}function nd(a){U.call(this);this.cameras=a||[]}function og(a){function b(){if(null!==d&&d.isPresenting){var b=d.getEyeParameters("left"),e=b.renderWidth,b=b.renderHeight;t=a.getPixelRatio();n=a.getSize();a.setDrawingBufferSize(2*
16512 e,b,1)}else c.enabled&&a.setDrawingBufferSize(n.width,n.height,t)}var c=this,d=null,e=null;"undefined"!==typeof window&&"VRFrameData"in window&&(e=new window.VRFrameData);var f=new K,g=new K,h=new K,k=new U;k.bounds=new da(0,0,.5,1);k.layers.enable(1);var l=new U;l.bounds=new da(.5,0,.5,1);l.layers.enable(2);var q=new nd([k,l]);q.layers.enable(1);q.layers.enable(2);var n,t;"undefined"!==typeof window&&window.addEventListener("vrdisplaypresentchange",b,!1);this.standing=this.enabled=!1;this.getDevice=
16513 function(){return d};this.setDevice=function(a){void 0!==a&&(d=a)};this.getCamera=function(a){if(null===d)return a;d.depthNear=a.near;d.depthFar=a.far;d.getFrameData(e);var b=e.pose;null!==b.position?a.position.fromArray(b.position):a.position.set(0,0,0);null!==b.orientation&&a.quaternion.fromArray(b.orientation);a.updateMatrixWorld();b=d.stageParameters;this.standing&&b&&(g.fromArray(b.sittingToStandingTransform),h.getInverse(g),a.matrixWorld.multiply(g),a.matrixWorldInverse.multiply(h));if(!1===
16514 d.isPresenting)return a;k.near=a.near;l.near=a.near;k.far=a.far;l.far=a.far;q.matrixWorld.copy(a.matrixWorld);q.matrixWorldInverse.copy(a.matrixWorldInverse);k.matrixWorldInverse.fromArray(e.leftViewMatrix);l.matrixWorldInverse.fromArray(e.rightViewMatrix);this.standing&&b&&(k.matrixWorldInverse.multiply(h),l.matrixWorldInverse.multiply(h));a=a.parent;null!==a&&(f.getInverse(a.matrixWorld),k.matrixWorldInverse.multiply(f),l.matrixWorldInverse.multiply(f));k.matrixWorld.getInverse(k.matrixWorldInverse);
16515 l.matrixWorld.getInverse(l.matrixWorldInverse);k.projectionMatrix.fromArray(e.leftProjectionMatrix);l.projectionMatrix.fromArray(e.rightProjectionMatrix);q.projectionMatrix.copy(k.projectionMatrix);a=d.getLayers();a.length&&(a=a[0],null!==a.leftBounds&&4===a.leftBounds.length&&k.bounds.fromArray(a.leftBounds),null!==a.rightBounds&&4===a.rightBounds.length&&l.bounds.fromArray(a.rightBounds));return q};this.getStandingMatrix=function(){return g};this.submitFrame=function(){d&&d.isPresenting&&d.submitFrame()};
16516 this.dispose=function(){"undefined"!==typeof window&&window.removeEventListener("vrdisplaypresentchange",b)}}function pg(a){var b={};return{get:function(c){if(void 0!==b[c])return b[c];switch(c){case "WEBGL_depth_texture":var d=a.getExtension("WEBGL_depth_texture")||a.getExtension("MOZ_WEBGL_depth_texture")||a.getExtension("WEBKIT_WEBGL_depth_texture");break;case "EXT_texture_filter_anisotropic":d=a.getExtension("EXT_texture_filter_anisotropic")||a.getExtension("MOZ_EXT_texture_filter_anisotropic")||
16517 a.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case "WEBGL_compressed_texture_s3tc":d=a.getExtension("WEBGL_compressed_texture_s3tc")||a.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case "WEBGL_compressed_texture_pvrtc":d=a.getExtension("WEBGL_compressed_texture_pvrtc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case "WEBGL_compressed_texture_etc1":d=a.getExtension("WEBGL_compressed_texture_etc1");
16518 break;default:d=a.getExtension(c)}null===d&&console.warn("THREE.WebGLRenderer: "+c+" extension not supported.");return b[c]=d}}}function qg(){function a(){l.value!==d&&(l.value=d,l.needsUpdate=0<e);c.numPlanes=e;c.numIntersection=0}function b(a,b,d,e){var f=null!==a?a.length:0,g=null;if(0!==f){g=l.value;if(!0!==e||null===g){e=d+4*f;b=b.matrixWorldInverse;k.getNormalMatrix(b);if(null===g||g.length<e)g=new Float32Array(e);for(e=0;e!==f;++e,d+=4)h.copy(a[e]).applyMatrix4(b,k),h.normal.toArray(g,d),g[d+
16519 3]=h.constant}l.value=g;l.needsUpdate=!0}c.numPlanes=f;return g}var c=this,d=null,e=0,f=!1,g=!1,h=new Aa,k=new ra,l={value:null,needsUpdate:!1};this.uniform=l;this.numIntersection=this.numPlanes=0;this.init=function(a,c,g){var h=0!==a.length||c||0!==e||f;f=c;d=b(a,g,0);e=a.length;return h};this.beginShadows=function(){g=!0;b(null)};this.endShadows=function(){g=!1;a()};this.setState=function(c,h,k,r,m,p){if(!f||null===c||0===c.length||g&&!k)g?b(null):a();else{k=g?0:e;var n=4*k,q=m.clippingState||null;
16520 l.value=q;q=b(c,r,n,p);for(c=0;c!==n;++c)q[c]=d[c];m.clippingState=q;this.numIntersection=h?this.numPlanes:0;this.numPlanes+=k}}}function Pe(a,b){return{convert:function(c){if(1E3===c)return a.REPEAT;if(1001===c)return a.CLAMP_TO_EDGE;if(1002===c)return a.MIRRORED_REPEAT;if(1003===c)return a.NEAREST;if(1004===c)return a.NEAREST_MIPMAP_NEAREST;if(1005===c)return a.NEAREST_MIPMAP_LINEAR;if(1006===c)return a.LINEAR;if(1007===c)return a.LINEAR_MIPMAP_NEAREST;if(1008===c)return a.LINEAR_MIPMAP_LINEAR;
16521 if(1009===c)return a.UNSIGNED_BYTE;if(1017===c)return a.UNSIGNED_SHORT_4_4_4_4;if(1018===c)return a.UNSIGNED_SHORT_5_5_5_1;if(1019===c)return a.UNSIGNED_SHORT_5_6_5;if(1010===c)return a.BYTE;if(1011===c)return a.SHORT;if(1012===c)return a.UNSIGNED_SHORT;if(1013===c)return a.INT;if(1014===c)return a.UNSIGNED_INT;if(1015===c)return a.FLOAT;if(1016===c){var d=b.get("OES_texture_half_float");if(null!==d)return d.HALF_FLOAT_OES}if(1021===c)return a.ALPHA;if(1022===c)return a.RGB;if(1023===c)return a.RGBA;
16522 if(1024===c)return a.LUMINANCE;if(1025===c)return a.LUMINANCE_ALPHA;if(1026===c)return a.DEPTH_COMPONENT;if(1027===c)return a.DEPTH_STENCIL;if(100===c)return a.FUNC_ADD;if(101===c)return a.FUNC_SUBTRACT;if(102===c)return a.FUNC_REVERSE_SUBTRACT;if(200===c)return a.ZERO;if(201===c)return a.ONE;if(202===c)return a.SRC_COLOR;if(203===c)return a.ONE_MINUS_SRC_COLOR;if(204===c)return a.SRC_ALPHA;if(205===c)return a.ONE_MINUS_SRC_ALPHA;if(206===c)return a.DST_ALPHA;if(207===c)return a.ONE_MINUS_DST_ALPHA;
16523 if(208===c)return a.DST_COLOR;if(209===c)return a.ONE_MINUS_DST_COLOR;if(210===c)return a.SRC_ALPHA_SATURATE;if(2001===c||2002===c||2003===c||2004===c)if(d=b.get("WEBGL_compressed_texture_s3tc"),null!==d){if(2001===c)return d.COMPRESSED_RGB_S3TC_DXT1_EXT;if(2002===c)return d.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(2003===c)return d.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(2004===c)return d.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(2100===c||2101===c||2102===c||2103===c)if(d=b.get("WEBGL_compressed_texture_pvrtc"),null!==
16524 d){if(2100===c)return d.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(2101===c)return d.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(2102===c)return d.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(2103===c)return d.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(2151===c&&(d=b.get("WEBGL_compressed_texture_etc1"),null!==d))return d.COMPRESSED_RGB_ETC1_WEBGL;if(103===c||104===c)if(d=b.get("EXT_blend_minmax"),null!==d){if(103===c)return d.MIN_EXT;if(104===c)return d.MAX_EXT}return 1020===c&&(d=b.get("WEBGL_depth_texture"),null!==d)?d.UNSIGNED_INT_24_8_WEBGL:
16525 0}}}function Wd(a){function b(){ia=new pg(F);ia.get("WEBGL_depth_texture");ia.get("OES_texture_float");ia.get("OES_texture_float_linear");ia.get("OES_texture_half_float");ia.get("OES_texture_half_float_linear");ia.get("OES_standard_derivatives");ia.get("OES_element_index_uint");ia.get("ANGLE_instanced_arrays");oa=new Pe(F,ia);Z=new ng(F,ia,a);ba=new mg(F,ia,oa);ba.scissor(S.copy(ea).multiplyScalar(O));ba.viewport(Q.copy(ca).multiplyScalar(O));U=new lg;T=new kg(F,ia,ba,U,Z,oa,Vd);na=new Mf(F);pa=new Zf(F,
16526 na,Vd);ra=new bg(pa,Ra);va=new Wf(F);ma=new jg(L,ia,Z);sa=new ag;qa=new Uf;ja=new Qf(L,ba,pa,J);wa=new Yf(F,ia,Ra);xa=new Xf(F,ia,Ra);ya=new Jf(L,F,ba,T,Z);Aa=new Kf(L,F,ba,T,Z);L.info.programs=ma.programs;L.context=F;L.capabilities=Z;L.extensions=ia;L.properties=U;L.renderLists=qa;L.state=ba}function c(a){a.preventDefault();console.log("THREE.WebGLRenderer: Context Lost.");Y=!0}function d(){console.log("THREE.WebGLRenderer: Context Restored.");Y=!1;b()}function e(a){a=a.target;a.removeEventListener("dispose",
16527 e);f(a);U.remove(a)}function f(a){var b=U.get(a).program;a.program=void 0;void 0!==b&&ma.releaseProgram(b)}function g(a,b,c){a.render(function(a){L.renderBufferImmediate(a,b,c)})}function h(a){null!==Ba&&Ba(a);(a=ka.getDevice())&&a.isPresenting?a.requestAnimationFrame(h):window.requestAnimationFrame(h)}function k(a,b,c){if(!1!==a.visible){if(a.layers.test(b.layers))if(a.isLight)y.push(a),a.castShadow&&C.push(a);else if(a.isSprite)a.frustumCulled&&!Td.intersectsSprite(a)||D.push(a);else if(a.isLensFlare)Va.push(a);
16528 else if(a.isImmediateRenderObject)c&&Nb.setFromMatrixPosition(a.matrixWorld).applyMatrix4(md),A.push(a,null,a.material,Nb.z,null);else if(a.isMesh||a.isLine||a.isPoints)if(a.isSkinnedMesh&&a.skeleton.update(),!a.frustumCulled||Td.intersectsObject(a)){c&&Nb.setFromMatrixPosition(a.matrixWorld).applyMatrix4(md);var d=ra.update(a),e=a.material;if(Array.isArray(e))for(var f=d.groups,g=0,h=f.length;g<h;g++){var l=f[g],n=e[l.materialIndex];n&&n.visible&&A.push(a,d,n,Nb.z,l)}else e.visible&&A.push(a,d,e,
16529 Nb.z,null)}a=a.children;g=0;for(h=a.length;g<h;g++)k(a[g],b,c)}}function l(a,b,c,d){for(var e=0,f=a.length;e<f;e++){var g=a[e],h=g.object,l=g.geometry,k=void 0===d?g.material:d,g=g.group;if(c.isArrayCamera){aa=c;for(var n=c.cameras,t=0,r=n.length;t<r;t++){var m=n[t];if(h.layers.test(m.layers)){var u=m.bounds;ba.viewport(Q.set(u.x*X,u.y*fa,u.z*X,u.w*fa).multiplyScalar(O));q(h,b,m,l,k,g)}}}else aa=null,q(h,b,c,l,k,g)}}function q(a,b,c,d,e,f){a.onBeforeRender(L,b,c,d,e,f);a.modelViewMatrix.multiplyMatrices(c.matrixWorldInverse,
16530 a.matrixWorld);a.normalMatrix.getNormalMatrix(a.modelViewMatrix);if(a.isImmediateRenderObject){ba.setMaterial(e);var h=t(c,b.fog,e,a);N="";g(a,h,e)}else L.renderBufferDirect(c,b.fog,d,e,a,f);a.onAfterRender(L,b,c,d,e,f)}function n(a,b,c){var d=U.get(a);c=ma.getParameters(a,sa.state,C,b,Fa.numPlanes,Fa.numIntersection,c);var g=ma.getProgramCode(a,c),h=d.program,l=!0;if(void 0===h)a.addEventListener("dispose",e);else if(h.code!==g)f(a);else{if(void 0!==c.shaderID)return;l=!1}l&&(c.shaderID?(h=mb[c.shaderID],
16531 d.shader={name:a.type,uniforms:Ea.clone(h.uniforms),vertexShader:h.vertexShader,fragmentShader:h.fragmentShader}):d.shader={name:a.type,uniforms:a.uniforms,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader},a.onBeforeCompile(d.shader),h=ma.acquireProgram(a,d.shader,c,g),d.program=h,a.program=h);c=h.getAttributes();if(a.morphTargets)for(g=a.numSupportedMorphTargets=0;g<L.maxMorphTargets;g++)0<=c["morphTarget"+g]&&a.numSupportedMorphTargets++;if(a.morphNormals)for(g=a.numSupportedMorphNormals=
16532 0;g<L.maxMorphNormals;g++)0<=c["morphNormal"+g]&&a.numSupportedMorphNormals++;c=d.shader.uniforms;if(!a.isShaderMaterial&&!a.isRawShaderMaterial||!0===a.clipping)d.numClippingPlanes=Fa.numPlanes,d.numIntersection=Fa.numIntersection,c.clippingPlanes=Fa.uniform;d.fog=b;d.lightsHash=sa.state.hash;a.lights&&(c.ambientLightColor.value=sa.state.ambient,c.directionalLights.value=sa.state.directional,c.spotLights.value=sa.state.spot,c.rectAreaLights.value=sa.state.rectArea,c.pointLights.value=sa.state.point,
16533 c.hemisphereLights.value=sa.state.hemi,c.directionalShadowMap.value=sa.state.directionalShadowMap,c.directionalShadowMatrix.value=sa.state.directionalShadowMatrix,c.spotShadowMap.value=sa.state.spotShadowMap,c.spotShadowMatrix.value=sa.state.spotShadowMatrix,c.pointShadowMap.value=sa.state.pointShadowMap,c.pointShadowMatrix.value=sa.state.pointShadowMatrix);a=d.program.getUniforms();a=gb.seqWithValue(a.seq,c);d.uniformsList=a}function t(a,b,c,d){G=0;var e=U.get(c);ga&&(Ud||a!==P)&&Fa.setState(c.clippingPlanes,
16534 c.clipIntersection,c.clipShadows,a,e,a===P&&c.id===V);!1===c.needsUpdate&&(void 0===e.program?c.needsUpdate=!0:c.fog&&e.fog!==b?c.needsUpdate=!0:c.lights&&e.lightsHash!==sa.state.hash?c.needsUpdate=!0:void 0===e.numClippingPlanes||e.numClippingPlanes===Fa.numPlanes&&e.numIntersection===Fa.numIntersection||(c.needsUpdate=!0));c.needsUpdate&&(n(c,b,d),c.needsUpdate=!1);var f=!1,g=!1,h=!1,l=e.program,k=l.getUniforms(),q=e.shader.uniforms;ba.useProgram(l.program)&&(h=g=f=!0);c.id!==V&&(V=c.id,g=!0);if(f||
16535 a!==P){k.setValue(F,"projectionMatrix",a.projectionMatrix);Z.logarithmicDepthBuffer&&k.setValue(F,"logDepthBufFC",2/(Math.log(a.far+1)/Math.LN2));P!==(aa||a)&&(P=aa||a,h=g=!0);if(c.isShaderMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.envMap)f=k.map.cameraPosition,void 0!==f&&f.setValue(F,Nb.setFromMatrixPosition(a.matrixWorld));(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial||c.isMeshStandardMaterial||c.isShaderMaterial||c.skinning)&&k.setValue(F,"viewMatrix",
16536 a.matrixWorldInverse)}if(c.skinning&&(k.setOptional(F,d,"bindMatrix"),k.setOptional(F,d,"bindMatrixInverse"),a=d.skeleton))if(f=a.bones,Z.floatVertexTextures){if(void 0===a.boneTexture){var f=Math.sqrt(4*f.length),f=R.ceilPowerOfTwo(f),f=Math.max(f,4),t=new Float32Array(f*f*4);t.set(a.boneMatrices);var u=new fb(t,f,f,1023,1015);a.boneMatrices=t;a.boneTexture=u;a.boneTextureSize=f}k.setValue(F,"boneTexture",a.boneTexture);k.setValue(F,"boneTextureSize",a.boneTextureSize)}else k.setOptional(F,a,"boneMatrices");
16537 g&&(k.setValue(F,"toneMappingExposure",L.toneMappingExposure),k.setValue(F,"toneMappingWhitePoint",L.toneMappingWhitePoint),c.lights&&(g=h,q.ambientLightColor.needsUpdate=g,q.directionalLights.needsUpdate=g,q.pointLights.needsUpdate=g,q.spotLights.needsUpdate=g,q.rectAreaLights.needsUpdate=g,q.hemisphereLights.needsUpdate=g),b&&c.fog&&(q.fogColor.value=b.color,b.isFog?(q.fogNear.value=b.near,q.fogFar.value=b.far):b.isFogExp2&&(q.fogDensity.value=b.density)),c.isMeshBasicMaterial?r(q,c):c.isMeshLambertMaterial?
16538 (r(q,c),c.emissiveMap&&(q.emissiveMap.value=c.emissiveMap)):c.isMeshPhongMaterial?(r(q,c),c.isMeshToonMaterial?(m(q,c),c.gradientMap&&(q.gradientMap.value=c.gradientMap)):m(q,c)):c.isMeshStandardMaterial?(r(q,c),c.isMeshPhysicalMaterial&&(q.clearCoat.value=c.clearCoat,q.clearCoatRoughness.value=c.clearCoatRoughness),q.roughness.value=c.roughness,q.metalness.value=c.metalness,c.roughnessMap&&(q.roughnessMap.value=c.roughnessMap),c.metalnessMap&&(q.metalnessMap.value=c.metalnessMap),c.emissiveMap&&
16539 (q.emissiveMap.value=c.emissiveMap),c.bumpMap&&(q.bumpMap.value=c.bumpMap,q.bumpScale.value=c.bumpScale),c.normalMap&&(q.normalMap.value=c.normalMap,q.normalScale.value.copy(c.normalScale)),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias),c.envMap&&(q.envMapIntensity.value=c.envMapIntensity)):c.isMeshDepthMaterial?(r(q,c),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=
16540 c.displacementScale,q.displacementBias.value=c.displacementBias)):c.isMeshDistanceMaterial?(r(q,c),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias),q.referencePosition.value.copy(c.referencePosition),q.nearDistance.value=c.nearDistance,q.farDistance.value=c.farDistance):c.isMeshNormalMaterial?(r(q,c),c.bumpMap&&(q.bumpMap.value=c.bumpMap,q.bumpScale.value=c.bumpScale),c.normalMap&&(q.normalMap.value=
16541 c.normalMap,q.normalScale.value.copy(c.normalScale)),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias)):c.isLineBasicMaterial?(q.diffuse.value=c.color,q.opacity.value=c.opacity,c.isLineDashedMaterial&&(q.dashSize.value=c.dashSize,q.totalSize.value=c.dashSize+c.gapSize,q.scale.value=c.scale)):c.isPointsMaterial?(q.diffuse.value=c.color,q.opacity.value=c.opacity,q.size.value=c.size*O,q.scale.value=
16542 .5*fa,q.map.value=c.map,null!==c.map&&(!0===c.map.matrixAutoUpdate&&(b=c.map.offset,g=c.map.repeat,h=c.map.center,c.map.matrix.setUvTransform(b.x,b.y,g.x,g.y,c.map.rotation,h.x,h.y)),q.uvTransform.value.copy(c.map.matrix))):c.isShadowMaterial&&(q.color.value=c.color,q.opacity.value=c.opacity),void 0!==q.ltcMat&&(q.ltcMat.value=E.LTC_MAT_TEXTURE),void 0!==q.ltcMag&&(q.ltcMag.value=E.LTC_MAG_TEXTURE),gb.upload(F,e.uniformsList,q,L));k.setValue(F,"modelViewMatrix",d.modelViewMatrix);k.setValue(F,"normalMatrix",
16543 d.normalMatrix);k.setValue(F,"modelMatrix",d.matrixWorld);return l}function r(a,b){a.opacity.value=b.opacity;b.color&&(a.diffuse.value=b.color);b.emissive&&a.emissive.value.copy(b.emissive).multiplyScalar(b.emissiveIntensity);b.map&&(a.map.value=b.map);b.alphaMap&&(a.alphaMap.value=b.alphaMap);b.specularMap&&(a.specularMap.value=b.specularMap);b.envMap&&(a.envMap.value=b.envMap,a.flipEnvMap.value=b.envMap&&b.envMap.isCubeTexture?-1:1,a.reflectivity.value=b.reflectivity,a.refractionRatio.value=b.refractionRatio);
16544 b.lightMap&&(a.lightMap.value=b.lightMap,a.lightMapIntensity.value=b.lightMapIntensity);b.aoMap&&(a.aoMap.value=b.aoMap,a.aoMapIntensity.value=b.aoMapIntensity);if(b.map)var c=b.map;else b.specularMap?c=b.specularMap:b.displacementMap?c=b.displacementMap:b.normalMap?c=b.normalMap:b.bumpMap?c=b.bumpMap:b.roughnessMap?c=b.roughnessMap:b.metalnessMap?c=b.metalnessMap:b.alphaMap?c=b.alphaMap:b.emissiveMap&&(c=b.emissiveMap);if(void 0!==c){c.isWebGLRenderTarget&&(c=c.texture);if(!0===c.matrixAutoUpdate){b=
16545 c.offset;var d=c.repeat,e=c.center;c.matrix.setUvTransform(b.x,b.y,d.x,d.y,c.rotation,e.x,e.y)}a.uvTransform.value.copy(c.matrix)}}function m(a,b){a.specular.value=b.specular;a.shininess.value=Math.max(b.shininess,1E-4);b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap);b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale);b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale));b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=
16546 b.displacementScale,a.displacementBias.value=b.displacementBias)}console.log("THREE.WebGLRenderer","88");a=a||{};var v=void 0!==a.canvas?a.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),w=void 0!==a.context?a.context:null,x=void 0!==a.alpha?a.alpha:!1,z=void 0!==a.depth?a.depth:!0,I=void 0!==a.stencil?a.stencil:!0,B=void 0!==a.antialias?a.antialias:!1,J=void 0!==a.premultipliedAlpha?a.premultipliedAlpha:!0,ta=void 0!==a.preserveDrawingBuffer?a.preserveDrawingBuffer:!1,y=
16547 [],C=[],A=null,D=[],Va=[];this.domElement=v;this.context=null;this.sortObjects=this.autoClearStencil=this.autoClearDepth=this.autoClearColor=this.autoClear=!0;this.clippingPlanes=[];this.localClippingEnabled=!1;this.gammaFactor=2;this.physicallyCorrectLights=this.gammaOutput=this.gammaInput=!1;this.toneMappingWhitePoint=this.toneMappingExposure=this.toneMapping=1;this.maxMorphTargets=8;this.maxMorphNormals=4;var L=this,Y=!1,H=null,M=null,V=-1,N="",P=null,aa=null,Q=new da,S=new da,W=null,G=0,X=v.width,
16548 fa=v.height,O=1,ca=new da(0,0,X,fa),ea=new da(0,0,X,fa),Oe=!1,Td=new ld,Fa=new qg,ga=!1,Ud=!1,md=new K,Nb=new p,Vd={geometries:0,textures:0},Ra={frame:0,calls:0,vertices:0,faces:0,points:0};this.info={render:Ra,memory:Vd,programs:null};try{x={alpha:x,depth:z,stencil:I,antialias:B,premultipliedAlpha:J,preserveDrawingBuffer:ta};var F=w||v.getContext("webgl",x)||v.getContext("experimental-webgl",x);if(null===F){if(null!==v.getContext("webgl"))throw"Error creating WebGL context with your selected attributes.";
16549 throw"Error creating WebGL context.";}void 0===F.getShaderPrecisionFormat&&(F.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}});v.addEventListener("webglcontextlost",c,!1);v.addEventListener("webglcontextrestored",d,!1)}catch(rg){console.error("THREE.WebGLRenderer: "+rg)}var ia,Z,ba,U,T,na,pa,ra,sa,ma,qa,ja,va,wa,xa,ya,Aa,oa;b();var ka=new og(L);this.vr=ka;var Ca=new Ie(L,ra,Z.maxTextureSize);this.shadowMap=Ca;this.getContext=function(){return F};this.getContextAttributes=
16550 function(){return F.getContextAttributes()};this.forceContextLoss=function(){var a=ia.get("WEBGL_lose_context");a&&a.loseContext()};this.forceContextRestore=function(){var a=ia.get("WEBGL_lose_context");a&&a.restoreContext()};this.getPixelRatio=function(){return O};this.setPixelRatio=function(a){void 0!==a&&(O=a,this.setSize(X,fa,!1))};this.getSize=function(){return{width:X,height:fa}};this.setSize=function(a,b,c){var d=ka.getDevice();d&&d.isPresenting?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):
16551 (X=a,fa=b,v.width=a*O,v.height=b*O,!1!==c&&(v.style.width=a+"px",v.style.height=b+"px"),this.setViewport(0,0,a,b))};this.getDrawingBufferSize=function(){return{width:X*O,height:fa*O}};this.setDrawingBufferSize=function(a,b,c){X=a;fa=b;O=c;v.width=a*c;v.height=b*c;this.setViewport(0,0,a,b)};this.setViewport=function(a,b,c,d){ca.set(a,fa-b-d,c,d);ba.viewport(Q.copy(ca).multiplyScalar(O))};this.setScissor=function(a,b,c,d){ea.set(a,fa-b-d,c,d);ba.scissor(S.copy(ea).multiplyScalar(O))};this.setScissorTest=
16552 function(a){ba.setScissorTest(Oe=a)};this.getClearColor=function(){return ja.getClearColor()};this.setClearColor=function(){ja.setClearColor.apply(ja,arguments)};this.getClearAlpha=function(){return ja.getClearAlpha()};this.setClearAlpha=function(){ja.setClearAlpha.apply(ja,arguments)};this.clear=function(a,b,c){var d=0;if(void 0===a||a)d|=F.COLOR_BUFFER_BIT;if(void 0===b||b)d|=F.DEPTH_BUFFER_BIT;if(void 0===c||c)d|=F.STENCIL_BUFFER_BIT;F.clear(d)};this.clearColor=function(){this.clear(!0,!1,!1)};
16553 this.clearDepth=function(){this.clear(!1,!0,!1)};this.clearStencil=function(){this.clear(!1,!1,!0)};this.clearTarget=function(a,b,c,d){this.setRenderTarget(a);this.clear(b,c,d)};this.dispose=function(){v.removeEventListener("webglcontextlost",c,!1);v.removeEventListener("webglcontextrestored",d,!1);qa.dispose();ka.dispose()};this.renderBufferImmediate=function(a,b,c){ba.initAttributes();var d=U.get(a);a.hasPositions&&!d.position&&(d.position=F.createBuffer());a.hasNormals&&!d.normal&&(d.normal=F.createBuffer());
16554 a.hasUvs&&!d.uv&&(d.uv=F.createBuffer());a.hasColors&&!d.color&&(d.color=F.createBuffer());b=b.getAttributes();a.hasPositions&&(F.bindBuffer(F.ARRAY_BUFFER,d.position),F.bufferData(F.ARRAY_BUFFER,a.positionArray,F.DYNAMIC_DRAW),ba.enableAttribute(b.position),F.vertexAttribPointer(b.position,3,F.FLOAT,!1,0,0));if(a.hasNormals){F.bindBuffer(F.ARRAY_BUFFER,d.normal);if(!c.isMeshPhongMaterial&&!c.isMeshStandardMaterial&&!c.isMeshNormalMaterial&&!0===c.flatShading)for(var e=0,f=3*a.count;e<f;e+=9){var g=
16555 a.normalArray,h=(g[e+0]+g[e+3]+g[e+6])/3,l=(g[e+1]+g[e+4]+g[e+7])/3,k=(g[e+2]+g[e+5]+g[e+8])/3;g[e+0]=h;g[e+1]=l;g[e+2]=k;g[e+3]=h;g[e+4]=l;g[e+5]=k;g[e+6]=h;g[e+7]=l;g[e+8]=k}F.bufferData(F.ARRAY_BUFFER,a.normalArray,F.DYNAMIC_DRAW);ba.enableAttribute(b.normal);F.vertexAttribPointer(b.normal,3,F.FLOAT,!1,0,0)}a.hasUvs&&c.map&&(F.bindBuffer(F.ARRAY_BUFFER,d.uv),F.bufferData(F.ARRAY_BUFFER,a.uvArray,F.DYNAMIC_DRAW),ba.enableAttribute(b.uv),F.vertexAttribPointer(b.uv,2,F.FLOAT,!1,0,0));a.hasColors&&
16556 0!==c.vertexColors&&(F.bindBuffer(F.ARRAY_BUFFER,d.color),F.bufferData(F.ARRAY_BUFFER,a.colorArray,F.DYNAMIC_DRAW),ba.enableAttribute(b.color),F.vertexAttribPointer(b.color,3,F.FLOAT,!1,0,0));ba.disableUnusedAttributes();F.drawArrays(F.TRIANGLES,0,a.count);a.count=0};this.renderBufferDirect=function(a,b,c,d,e,f){ba.setMaterial(d);var g=t(a,b,d,e);a=c.id+"_"+g.id+"_"+(!0===d.wireframe);var h=!1;a!==N&&(N=a,h=!0);e.morphTargetInfluences&&(va.update(e,c,d,g),h=!0);var l=c.index,k=c.attributes.position;
16557 b=1;!0===d.wireframe&&(l=pa.getWireframeAttribute(c),b=2);a=wa;if(null!==l){var n=na.get(l);a=xa;a.setIndex(n)}if(h){h=void 0;if(c&&c.isInstancedBufferGeometry&&null===ia.get("ANGLE_instanced_arrays"))console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");else{void 0===h&&(h=0);ba.initAttributes();var q=c.attributes,g=g.getAttributes(),r=d.defaultAttributeValues;for(J in g){var m=g[J];if(0<=m){var u=
16558 q[J];if(void 0!==u){var p=u.normalized,v=u.itemSize,w=na.get(u);if(void 0!==w){var z=w.buffer,x=w.type,w=w.bytesPerElement;if(u.isInterleavedBufferAttribute){var B=u.data,I=B.stride,u=u.offset;B&&B.isInstancedInterleavedBuffer?(ba.enableAttributeAndDivisor(m,B.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=B.meshPerAttribute*B.count)):ba.enableAttribute(m);F.bindBuffer(F.ARRAY_BUFFER,z);F.vertexAttribPointer(m,v,x,p,I*w,(h*I+u)*w)}else u.isInstancedBufferAttribute?(ba.enableAttributeAndDivisor(m,
16559 u.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=u.meshPerAttribute*u.count)):ba.enableAttribute(m),F.bindBuffer(F.ARRAY_BUFFER,z),F.vertexAttribPointer(m,v,x,p,0,h*v*w)}}else if(void 0!==r&&(p=r[J],void 0!==p))switch(p.length){case 2:F.vertexAttrib2fv(m,p);break;case 3:F.vertexAttrib3fv(m,p);break;case 4:F.vertexAttrib4fv(m,p);break;default:F.vertexAttrib1fv(m,p)}}}ba.disableUnusedAttributes()}null!==l&&F.bindBuffer(F.ELEMENT_ARRAY_BUFFER,n.buffer)}n=0;null!==l?n=l.count:void 0!==
16560 k&&(n=k.count);l=c.drawRange.start*b;k=null!==f?f.start*b:0;var J=Math.max(l,k);f=Math.max(0,Math.min(n,l+c.drawRange.count*b,k+(null!==f?f.count*b:Infinity))-1-J+1);if(0!==f){if(e.isMesh)if(!0===d.wireframe)ba.setLineWidth(d.wireframeLinewidth*(null===H?O:1)),a.setMode(F.LINES);else switch(e.drawMode){case 0:a.setMode(F.TRIANGLES);break;case 1:a.setMode(F.TRIANGLE_STRIP);break;case 2:a.setMode(F.TRIANGLE_FAN)}else e.isLine?(d=d.linewidth,void 0===d&&(d=1),ba.setLineWidth(d*(null===H?O:1)),e.isLineSegments?
16561 a.setMode(F.LINES):e.isLineLoop?a.setMode(F.LINE_LOOP):a.setMode(F.LINE_STRIP)):e.isPoints&&a.setMode(F.POINTS);c&&c.isInstancedBufferGeometry?0<c.maxInstancedCount&&a.renderInstances(c,J,f):a.render(J,f)}};this.compile=function(a,b){y.length=0;C.length=0;a.traverse(function(a){a.isLight&&(y.push(a),a.castShadow&&C.push(a))});sa.setup(y,C,b);a.traverse(function(b){if(b.material)if(Array.isArray(b.material))for(var c=0;c<b.material.length;c++)n(b.material[c],a.fog,b);else n(b.material,a.fog,b)})};
16562 var Da=!1,Ba=null;this.animate=function(a){Ba=a;Da||((a=ka.getDevice())&&a.isPresenting?a.requestAnimationFrame(h):window.requestAnimationFrame(h),Da=!0)};this.render=function(a,b,c,d){if(!b||!b.isCamera)console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");else if(!Y){N="";V=-1;P=null;!0===a.autoUpdate&&a.updateMatrixWorld();null===b.parent&&b.updateMatrixWorld();ka.enabled&&(b=ka.getCamera(b));md.multiplyMatrices(b.projectionMatrix,b.matrixWorldInverse);Td.setFromMatrix(md);
16563 y.length=0;C.length=0;D.length=0;Va.length=0;Ud=this.localClippingEnabled;ga=Fa.init(this.clippingPlanes,Ud,b);A=qa.get(a,b);A.init();k(a,b,L.sortObjects);!0===L.sortObjects&&A.sort();ga&&Fa.beginShadows();Ca.render(C,a,b);sa.setup(y,C,b);ga&&Fa.endShadows();Ra.frame++;Ra.calls=0;Ra.vertices=0;Ra.faces=0;Ra.points=0;void 0===c&&(c=null);this.setRenderTarget(c);ja.render(A,a,b,d);d=A.opaque;var e=A.transparent;if(a.overrideMaterial){var f=a.overrideMaterial;d.length&&l(d,a,b,f);e.length&&l(e,a,b,f)}else d.length&&
16564 l(d,a,b),e.length&&l(e,a,b);Aa.render(D,a,b);ya.render(Va,a,b,Q);c&&T.updateRenderTargetMipmap(c);ba.buffers.depth.setTest(!0);ba.buffers.depth.setMask(!0);ba.buffers.color.setMask(!0);ba.setPolygonOffset(!1);ka.enabled&&ka.submitFrame()}};this.setFaceCulling=function(a,b){ba.setCullFace(a);ba.setFlipSided(0===b)};this.allocTextureUnit=function(){var a=G;a>=Z.maxTextures&&console.warn("THREE.WebGLRenderer: Trying to use "+a+" texture units while this GPU supports only "+Z.maxTextures);G+=1;return a};
16565 this.setTexture2D=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTarget&&(a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);T.setTexture2D(b,c)}}();this.setTexture=function(){var a=!1;return function(b,c){a||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),a=!0);T.setTexture2D(b,c)}}();this.setTextureCube=function(){var a=!1;return function(b,c){b&&
16566 b.isWebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);b&&b.isCubeTexture||Array.isArray(b.image)&&6===b.image.length?T.setTextureCube(b,c):T.setTextureCubeDynamic(b,c)}}();this.getRenderTarget=function(){return H};this.setRenderTarget=function(a){(H=a)&&void 0===U.get(a).__webglFramebuffer&&T.setupRenderTarget(a);var b=null,c=!1;a?(b=U.get(a).__webglFramebuffer,a.isWebGLRenderTargetCube&&
16567 (b=b[a.activeCubeFace],c=!0),Q.copy(a.viewport),S.copy(a.scissor),W=a.scissorTest):(Q.copy(ca).multiplyScalar(O),S.copy(ea).multiplyScalar(O),W=Oe);M!==b&&(F.bindFramebuffer(F.FRAMEBUFFER,b),M=b);ba.viewport(Q);ba.scissor(S);ba.setScissorTest(W);c&&(c=U.get(a.texture),F.framebufferTexture2D(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,c.__webglTexture,a.activeMipMapLevel))};this.readRenderTargetPixels=function(a,b,c,d,e,f){if(a&&a.isWebGLRenderTarget){var g=U.get(a).__webglFramebuffer;
16568 if(g){var h=!1;g!==M&&(F.bindFramebuffer(F.FRAMEBUFFER,g),h=!0);try{var l=a.texture,k=l.format,n=l.type;1023!==k&&oa.convert(k)!==F.getParameter(F.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===n||oa.convert(n)===F.getParameter(F.IMPLEMENTATION_COLOR_READ_TYPE)||1015===n&&(ia.get("OES_texture_float")||ia.get("WEBGL_color_buffer_float"))||1016===n&&ia.get("EXT_color_buffer_half_float")?
16569 F.checkFramebufferStatus(F.FRAMEBUFFER)===F.FRAMEBUFFER_COMPLETE?0<=b&&b<=a.width-d&&0<=c&&c<=a.height-e&&F.readPixels(b,c,d,e,oa.convert(k),oa.convert(n),f):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."):console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.")}finally{h&&F.bindFramebuffer(F.FRAMEBUFFER,M)}}}else console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.")}}
16570 function Ob(a,b){this.name="";this.color=new H(a);this.density=void 0!==b?b:2.5E-4}function Pb(a,b,c){this.name="";this.color=new H(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function od(){A.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function Xd(a,b,c,d,e){A.call(this);this.lensFlares=[];this.positionScreen=new p;this.customUpdateCallback=void 0;void 0!==a&&this.add(a,b,c,d,e)}function Za(a){Q.call(this);this.type="SpriteMaterial";
16571 this.color=new H(16777215);this.map=null;this.rotation=0;this.lights=this.fog=!1;this.setValues(a)}function Cc(a){A.call(this);this.type="Sprite";this.material=void 0!==a?a:new Za}function Dc(){A.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function Ec(a,b){a=a||[];this.bones=a.slice(0);this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===b)this.calculateInverses();else if(this.bones.length===b.length)this.boneInverses=b.slice(0);else for(console.warn("THREE.Skeleton boneInverses is the wrong length."),
16572 this.boneInverses=[],a=0,b=this.bones.length;a<b;a++)this.boneInverses.push(new K)}function pd(){A.call(this);this.type="Bone"}function qd(a,b){pa.call(this,a,b);this.type="SkinnedMesh";this.bindMode="attached";this.bindMatrix=new K;this.bindMatrixInverse=new K;a=this.initBones();a=new Ec(a);this.bind(a,this.matrixWorld);this.normalizeSkinWeights()}function O(a){Q.call(this);this.type="LineBasicMaterial";this.color=new H(16777215);this.linewidth=1;this.linejoin=this.linecap="round";this.lights=!1;
16573 this.setValues(a)}function ma(a,b,c){if(1===c)return console.warn("THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead."),new ca(a,b);A.call(this);this.type="Line";this.geometry=void 0!==a?a:new D;this.material=void 0!==b?b:new O({color:16777215*Math.random()})}function ca(a,b){ma.call(this,a,b);this.type="LineSegments"}function rd(a,b){ma.call(this,a,b);this.type="LineLoop"}function Ba(a){Q.call(this);this.type="PointsMaterial";this.color=new H(16777215);
16574 this.map=null;this.size=1;this.sizeAttenuation=!0;this.lights=!1;this.setValues(a)}function Qb(a,b){A.call(this);this.type="Points";this.geometry=void 0!==a?a:new D;this.material=void 0!==b?b:new Ba({color:16777215*Math.random()})}function Fc(){A.call(this);this.type="Group"}function sd(a,b,c,d,e,f,g,h,k){function l(){var a=q.image;a.readyState>=a.HAVE_CURRENT_DATA&&(q.needsUpdate=!0);requestAnimationFrame(l)}ea.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1;var q=this;requestAnimationFrame(l)}
16575 function Rb(a,b,c,d,e,f,g,h,k,l,q,n){ea.call(this,null,f,g,h,k,l,d,e,q,n);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1}function Gc(a,b,c,d,e,f,g,h,k,l){l=void 0!==l?l:1026;if(1026!==l&&1027!==l)throw Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===c&&1026===l&&(c=1012);void 0===c&&1027===l&&(c=1020);ea.call(this,null,d,e,f,g,h,l,c,k);this.image={width:a,height:b};this.magFilter=void 0!==g?g:1003;this.minFilter=void 0!==
16576 h?h:1003;this.generateMipmaps=this.flipY=!1}function Sb(a){D.call(this);this.type="WireframeGeometry";var b=[],c,d,e,f=[0,0],g={},h=["a","b","c"];if(a&&a.isGeometry){var k=a.faces;var l=0;for(d=k.length;l<d;l++){var q=k[l];for(c=0;3>c;c++){var n=q[h[c]];var t=q[h[(c+1)%3]];f[0]=Math.min(n,t);f[1]=Math.max(n,t);n=f[0]+","+f[1];void 0===g[n]&&(g[n]={index1:f[0],index2:f[1]})}}for(n in g)l=g[n],h=a.vertices[l.index1],b.push(h.x,h.y,h.z),h=a.vertices[l.index2],b.push(h.x,h.y,h.z)}else if(a&&a.isBufferGeometry){var h=
16577 new p;if(null!==a.index){k=a.attributes.position;q=a.index;var r=a.groups;0===r.length&&(r=[{start:0,count:q.count,materialIndex:0}]);a=0;for(e=r.length;a<e;++a)for(l=r[a],c=l.start,d=l.count,l=c,d=c+d;l<d;l+=3)for(c=0;3>c;c++)n=q.getX(l+c),t=q.getX(l+(c+1)%3),f[0]=Math.min(n,t),f[1]=Math.max(n,t),n=f[0]+","+f[1],void 0===g[n]&&(g[n]={index1:f[0],index2:f[1]});for(n in g)l=g[n],h.fromBufferAttribute(k,l.index1),b.push(h.x,h.y,h.z),h.fromBufferAttribute(k,l.index2),b.push(h.x,h.y,h.z)}else for(k=a.attributes.position,
16578 l=0,d=k.count/3;l<d;l++)for(c=0;3>c;c++)g=3*l+c,h.fromBufferAttribute(k,g),b.push(h.x,h.y,h.z),g=3*l+(c+1)%3,h.fromBufferAttribute(k,g),b.push(h.x,h.y,h.z)}this.addAttribute("position",new y(b,3))}function Hc(a,b,c){N.call(this);this.type="ParametricGeometry";this.parameters={func:a,slices:b,stacks:c};this.fromBufferGeometry(new Tb(a,b,c));this.mergeVertices()}function Tb(a,b,c){D.call(this);this.type="ParametricBufferGeometry";this.parameters={func:a,slices:b,stacks:c};var d=[],e=[],f=[],g=[],h=
16579 new p,k=new p,l=new p,q=new p,n=new p,t,r,m=b+1;for(t=0;t<=c;t++){var v=t/c;for(r=0;r<=b;r++){var w=r/b,k=a(w,v,k);e.push(k.x,k.y,k.z);0<=w-1E-5?(l=a(w-1E-5,v,l),q.subVectors(k,l)):(l=a(w+1E-5,v,l),q.subVectors(l,k));0<=v-1E-5?(l=a(w,v-1E-5,l),n.subVectors(k,l)):(l=a(w,v+1E-5,l),n.subVectors(l,k));h.crossVectors(q,n).normalize();f.push(h.x,h.y,h.z);g.push(w,v)}}for(t=0;t<c;t++)for(r=0;r<b;r++)a=t*m+r+1,h=(t+1)*m+r+1,k=(t+1)*m+r,d.push(t*m+r,a,k),d.push(a,h,k);this.setIndex(d);this.addAttribute("position",
16580 new y(e,3));this.addAttribute("normal",new y(f,3));this.addAttribute("uv",new y(g,2))}function Ic(a,b,c,d){N.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};this.fromBufferGeometry(new qa(a,b,c,d));this.mergeVertices()}function qa(a,b,c,d){function e(a){h.push(a.x,a.y,a.z)}function f(b,c){b*=3;c.x=a[b+0];c.y=a[b+1];c.z=a[b+2]}function g(a,b,c,d){0>d&&1===a.x&&(k[b]=a.x-1);0===c.x&&0===c.z&&(k[b]=d/2/Math.PI+.5)}D.call(this);this.type="PolyhedronBufferGeometry";
16581 this.parameters={vertices:a,indices:b,radius:c,detail:d};c=c||1;d=d||0;var h=[],k=[];(function(a){for(var c=new p,d=new p,g=new p,h=0;h<b.length;h+=3){f(b[h+0],c);f(b[h+1],d);f(b[h+2],g);var k,l,m=c,x=d,z=g,I=Math.pow(2,a),B=[];for(l=0;l<=I;l++){B[l]=[];var J=m.clone().lerp(z,l/I),y=x.clone().lerp(z,l/I),C=I-l;for(k=0;k<=C;k++)B[l][k]=0===k&&l===I?J:J.clone().lerp(y,k/C)}for(l=0;l<I;l++)for(k=0;k<2*(I-l)-1;k++)m=Math.floor(k/2),0===k%2?(e(B[l][m+1]),e(B[l+1][m]),e(B[l][m])):(e(B[l][m+1]),e(B[l+1][m+
16582 1]),e(B[l+1][m]))}})(d);(function(a){for(var b=new p,c=0;c<h.length;c+=3)b.x=h[c+0],b.y=h[c+1],b.z=h[c+2],b.normalize().multiplyScalar(a),h[c+0]=b.x,h[c+1]=b.y,h[c+2]=b.z})(c);(function(){for(var a=new p,b=0;b<h.length;b+=3)a.x=h[b+0],a.y=h[b+1],a.z=h[b+2],k.push(Math.atan2(a.z,-a.x)/2/Math.PI+.5,1-(Math.atan2(-a.y,Math.sqrt(a.x*a.x+a.z*a.z))/Math.PI+.5));for(var a=new p,b=new p,c=new p,d=new p,e=new C,f=new C,m=new C,w=0,x=0;w<h.length;w+=9,x+=6){a.set(h[w+0],h[w+1],h[w+2]);b.set(h[w+3],h[w+4],h[w+
16583 5]);c.set(h[w+6],h[w+7],h[w+8]);e.set(k[x+0],k[x+1]);f.set(k[x+2],k[x+3]);m.set(k[x+4],k[x+5]);d.copy(a).add(b).add(c).divideScalar(3);var z=Math.atan2(d.z,-d.x);g(e,x+0,a,z);g(f,x+2,b,z);g(m,x+4,c,z)}for(a=0;a<k.length;a+=6)b=k[a+0],c=k[a+2],d=k[a+4],e=Math.min(b,c,d),.9<Math.max(b,c,d)&&.1>e&&(.2>b&&(k[a+0]+=1),.2>c&&(k[a+2]+=1),.2>d&&(k[a+4]+=1))})();this.addAttribute("position",new y(h,3));this.addAttribute("normal",new y(h.slice(),3));this.addAttribute("uv",new y(k,2));0===d?this.computeVertexNormals():
16584 this.normalizeNormals()}function Jc(a,b){N.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Ub(a,b));this.mergeVertices()}function Ub(a,b){qa.call(this,[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],a,b);this.type="TetrahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Kc(a,b){N.call(this);this.type="OctahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new nb(a,b));this.mergeVertices()}
16585 function nb(a,b){qa.call(this,[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],a,b);this.type="OctahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Lc(a,b){N.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Vb(a,b));this.mergeVertices()}function Vb(a,b){var c=(1+Math.sqrt(5))/2;qa.call(this,[-1,c,0,1,c,0,-1,-c,0,1,-c,0,0,-1,c,0,1,c,0,-1,-c,0,1,-c,c,0,-1,c,0,1,-c,0,-1,-c,0,1],[0,11,
16586 5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],a,b);this.type="IcosahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Mc(a,b){N.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Wb(a,b));this.mergeVertices()}function Wb(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;qa.call(this,[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-d,-c,0,-d,c,0,
16587 d,-c,0,d,c,-d,-c,0,-d,c,0,d,-c,0,d,c,0,-c,0,-d,c,0,-d,-c,0,d,c,0,d],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],a,b);this.type="DodecahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Nc(a,b,c,d,e,f){N.call(this);this.type="TubeGeometry";this.parameters={path:a,
16588 tubularSegments:b,radius:c,radialSegments:d,closed:e};void 0!==f&&console.warn("THREE.TubeGeometry: taper has been removed.");a=new Xb(a,b,c,d,e);this.tangents=a.tangents;this.normals=a.normals;this.binormals=a.binormals;this.fromBufferGeometry(a);this.mergeVertices()}function Xb(a,b,c,d,e){function f(e){q=a.getPointAt(e/b,q);var f=g.normals[e];e=g.binormals[e];for(t=0;t<=d;t++){var l=t/d*Math.PI*2,n=Math.sin(l),l=-Math.cos(l);k.x=l*f.x+n*e.x;k.y=l*f.y+n*e.y;k.z=l*f.z+n*e.z;k.normalize();u.push(k.x,
16589 k.y,k.z);h.x=q.x+c*k.x;h.y=q.y+c*k.y;h.z=q.z+c*k.z;m.push(h.x,h.y,h.z)}}D.call(this);this.type="TubeBufferGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};b=b||64;c=c||1;d=d||8;e=e||!1;var g=a.computeFrenetFrames(b,e);this.tangents=g.tangents;this.normals=g.normals;this.binormals=g.binormals;var h=new p,k=new p,l=new C,q=new p,n,t,m=[],u=[],v=[],w=[];for(n=0;n<b;n++)f(n);f(!1===e?b:0);for(n=0;n<=b;n++)for(t=0;t<=d;t++)l.x=n/b,l.y=t/d,v.push(l.x,l.y);(function(){for(t=
16590 1;t<=b;t++)for(n=1;n<=d;n++){var a=(d+1)*t+(n-1),c=(d+1)*t+n,e=(d+1)*(t-1)+n;w.push((d+1)*(t-1)+(n-1),a,e);w.push(a,c,e)}})();this.setIndex(w);this.addAttribute("position",new y(m,3));this.addAttribute("normal",new y(u,3));this.addAttribute("uv",new y(v,2))}function Oc(a,b,c,d,e,f,g){N.call(this);this.type="TorusKnotGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};void 0!==g&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.");
16591 this.fromBufferGeometry(new Yb(a,b,c,d,e,f));this.mergeVertices()}function Yb(a,b,c,d,e,f){function g(a,b,c,d,e){var f=Math.sin(a);b=c/b*a;c=Math.cos(b);e.x=d*(2+c)*.5*Math.cos(a);e.y=d*(2+c)*f*.5;e.z=d*Math.sin(b)*.5}D.call(this);this.type="TorusKnotBufferGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};a=a||1;b=b||.4;c=Math.floor(c)||64;d=Math.floor(d)||8;e=e||2;f=f||3;var h=[],k=[],l=[],q=[],n,t=new p,m=new p,u=new p,v=new p,w=new p,x=new p,z=new p;for(n=0;n<=
16592 c;++n){var I=n/c*e*Math.PI*2;g(I,e,f,a,u);g(I+.01,e,f,a,v);x.subVectors(v,u);z.addVectors(v,u);w.crossVectors(x,z);z.crossVectors(w,x);w.normalize();z.normalize();for(I=0;I<=d;++I){var B=I/d*Math.PI*2,J=-b*Math.cos(B),B=b*Math.sin(B);t.x=u.x+(J*z.x+B*w.x);t.y=u.y+(J*z.y+B*w.y);t.z=u.z+(J*z.z+B*w.z);k.push(t.x,t.y,t.z);m.subVectors(t,u).normalize();l.push(m.x,m.y,m.z);q.push(n/c);q.push(I/d)}}for(I=1;I<=c;I++)for(n=1;n<=d;n++)a=(d+1)*I+(n-1),b=(d+1)*I+n,e=(d+1)*(I-1)+n,h.push((d+1)*(I-1)+(n-1),a,e),
16593 h.push(a,b,e);this.setIndex(h);this.addAttribute("position",new y(k,3));this.addAttribute("normal",new y(l,3));this.addAttribute("uv",new y(q,2))}function Pc(a,b,c,d,e){N.call(this);this.type="TorusGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};this.fromBufferGeometry(new Zb(a,b,c,d,e));this.mergeVertices()}function Zb(a,b,c,d,e){D.call(this);this.type="TorusBufferGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};a=a||1;b=b||
16594 .4;c=Math.floor(c)||8;d=Math.floor(d)||6;e=e||2*Math.PI;var f=[],g=[],h=[],k=[],l=new p,q=new p,n=new p,t,m;for(t=0;t<=c;t++)for(m=0;m<=d;m++){var u=m/d*e,v=t/c*Math.PI*2;q.x=(a+b*Math.cos(v))*Math.cos(u);q.y=(a+b*Math.cos(v))*Math.sin(u);q.z=b*Math.sin(v);g.push(q.x,q.y,q.z);l.x=a*Math.cos(u);l.y=a*Math.sin(u);n.subVectors(q,l).normalize();h.push(n.x,n.y,n.z);k.push(m/d);k.push(t/c)}for(t=1;t<=c;t++)for(m=1;m<=d;m++)a=(d+1)*(t-1)+m-1,b=(d+1)*(t-1)+m,e=(d+1)*t+m,f.push((d+1)*t+m-1,a,e),f.push(a,b,
16595 e);this.setIndex(f);this.addAttribute("position",new y(g,3));this.addAttribute("normal",new y(h,3));this.addAttribute("uv",new y(k,2))}function $a(a,b){N.call(this);this.type="ExtrudeGeometry";this.parameters={shapes:a,options:b};this.fromBufferGeometry(new Ga(a,b));this.mergeVertices()}function Ga(a,b){"undefined"!==typeof a&&(D.call(this),this.type="ExtrudeBufferGeometry",a=Array.isArray(a)?a:[a],this.addShapeList(a,b),this.computeVertexNormals())}function Qc(a,b){N.call(this);this.type="TextGeometry";
16596 this.parameters={text:a,parameters:b};this.fromBufferGeometry(new $b(a,b));this.mergeVertices()}function $b(a,b){b=b||{};var c=b.font;if(!c||!c.isFont)return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),new N;a=c.generateShapes(a,b.size,b.curveSegments);b.amount=void 0!==b.height?b.height:50;void 0===b.bevelThickness&&(b.bevelThickness=10);void 0===b.bevelSize&&(b.bevelSize=8);void 0===b.bevelEnabled&&(b.bevelEnabled=!1);Ga.call(this,a,b);this.type="TextBufferGeometry"}
16597 function Rc(a,b,c,d,e,f,g){N.call(this);this.type="SphereGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};this.fromBufferGeometry(new ob(a,b,c,d,e,f,g));this.mergeVertices()}function ob(a,b,c,d,e,f,g){D.call(this);this.type="SphereBufferGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};a=a||1;b=Math.max(3,Math.floor(b)||8);c=Math.max(2,Math.floor(c)||6);d=void 0!==
16598 d?d:0;e=void 0!==e?e:2*Math.PI;f=void 0!==f?f:0;g=void 0!==g?g:Math.PI;var h=f+g,k,l,q=0,n=[],t=new p,m=new p,u=[],v=[],w=[],x=[];for(l=0;l<=c;l++){var z=[],I=l/c;for(k=0;k<=b;k++){var B=k/b;t.x=-a*Math.cos(d+B*e)*Math.sin(f+I*g);t.y=a*Math.cos(f+I*g);t.z=a*Math.sin(d+B*e)*Math.sin(f+I*g);v.push(t.x,t.y,t.z);m.set(t.x,t.y,t.z).normalize();w.push(m.x,m.y,m.z);x.push(B,1-I);z.push(q++)}n.push(z)}for(l=0;l<c;l++)for(k=0;k<b;k++)a=n[l][k+1],d=n[l][k],e=n[l+1][k],g=n[l+1][k+1],(0!==l||0<f)&&u.push(a,d,
16599 g),(l!==c-1||h<Math.PI)&&u.push(d,e,g);this.setIndex(u);this.addAttribute("position",new y(v,3));this.addAttribute("normal",new y(w,3));this.addAttribute("uv",new y(x,2))}function Sc(a,b,c,d,e,f){N.call(this);this.type="RingGeometry";this.parameters={innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};this.fromBufferGeometry(new ac(a,b,c,d,e,f));this.mergeVertices()}function ac(a,b,c,d,e,f){D.call(this);this.type="RingBufferGeometry";this.parameters={innerRadius:a,
16600 outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};a=a||.5;b=b||1;e=void 0!==e?e:0;f=void 0!==f?f:2*Math.PI;c=void 0!==c?Math.max(3,c):8;d=void 0!==d?Math.max(1,d):1;var g=[],h=[],k=[],l=[],q=a,n=(b-a)/d,t=new p,m=new C,u,v;for(u=0;u<=d;u++){for(v=0;v<=c;v++)a=e+v/c*f,t.x=q*Math.cos(a),t.y=q*Math.sin(a),h.push(t.x,t.y,t.z),k.push(0,0,1),m.x=(t.x/b+1)/2,m.y=(t.y/b+1)/2,l.push(m.x,m.y);q+=n}for(u=0;u<d;u++)for(b=u*(c+1),v=0;v<c;v++)a=v+b,e=a+c+1,f=a+c+2,q=a+1,g.push(a,e,q),g.push(e,
16601 f,q);this.setIndex(g);this.addAttribute("position",new y(h,3));this.addAttribute("normal",new y(k,3));this.addAttribute("uv",new y(l,2))}function Tc(a,b,c,d){N.call(this);this.type="LatheGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};this.fromBufferGeometry(new bc(a,b,c,d));this.mergeVertices()}function bc(a,b,c,d){D.call(this);this.type="LatheBufferGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};b=Math.floor(b)||12;c=c||0;d=d||2*Math.PI;d=R.clamp(d,
16602 0,2*Math.PI);var e=[],f=[],g=[],h=1/b,k=new p,l=new C,q;for(q=0;q<=b;q++){var n=c+q*h*d;var t=Math.sin(n),m=Math.cos(n);for(n=0;n<=a.length-1;n++)k.x=a[n].x*t,k.y=a[n].y,k.z=a[n].x*m,f.push(k.x,k.y,k.z),l.x=q/b,l.y=n/(a.length-1),g.push(l.x,l.y)}for(q=0;q<b;q++)for(n=0;n<a.length-1;n++)c=n+q*a.length,h=c+a.length,k=c+a.length+1,l=c+1,e.push(c,h,l),e.push(h,k,l);this.setIndex(e);this.addAttribute("position",new y(f,3));this.addAttribute("uv",new y(g,2));this.computeVertexNormals();if(d===2*Math.PI)for(d=
16603 this.attributes.normal.array,e=new p,f=new p,g=new p,c=b*a.length*3,n=q=0;q<a.length;q++,n+=3)e.x=d[n+0],e.y=d[n+1],e.z=d[n+2],f.x=d[c+n+0],f.y=d[c+n+1],f.z=d[c+n+2],g.addVectors(e,f).normalize(),d[n+0]=d[c+n+0]=g.x,d[n+1]=d[c+n+1]=g.y,d[n+2]=d[c+n+2]=g.z}function cc(a,b){N.call(this);this.type="ShapeGeometry";"object"===typeof b&&(console.warn("THREE.ShapeGeometry: Options parameter has been removed."),b=b.curveSegments);this.parameters={shapes:a,curveSegments:b};this.fromBufferGeometry(new dc(a,
16604 b));this.mergeVertices()}function dc(a,b){function c(a){var c,h=e.length/3;a=a.extractPoints(b);var l=a.shape,q=a.holes;if(!1===Ha.isClockWise(l))for(l=l.reverse(),a=0,c=q.length;a<c;a++){var m=q[a];!0===Ha.isClockWise(m)&&(q[a]=m.reverse())}var p=Ha.triangulateShape(l,q);a=0;for(c=q.length;a<c;a++)m=q[a],l=l.concat(m);a=0;for(c=l.length;a<c;a++)m=l[a],e.push(m.x,m.y,0),f.push(0,0,1),g.push(m.x,m.y);a=0;for(c=p.length;a<c;a++)l=p[a],d.push(l[0]+h,l[1]+h,l[2]+h),k+=3}D.call(this);this.type="ShapeBufferGeometry";
16605 this.parameters={shapes:a,curveSegments:b};b=b||12;var d=[],e=[],f=[],g=[],h=0,k=0;if(!1===Array.isArray(a))c(a);else for(var l=0;l<a.length;l++)c(a[l]),this.addGroup(h,k,l),h+=k,k=0;this.setIndex(d);this.addAttribute("position",new y(e,3));this.addAttribute("normal",new y(f,3));this.addAttribute("uv",new y(g,2))}function ec(a,b){D.call(this);this.type="EdgesGeometry";this.parameters={thresholdAngle:b};var c=[];b=Math.cos(R.DEG2RAD*(void 0!==b?b:1));var d=[0,0],e={},f=["a","b","c"];if(a.isBufferGeometry){var g=
16606 new N;g.fromBufferGeometry(a)}else g=a.clone();g.mergeVertices();g.computeFaceNormals();a=g.vertices;g=g.faces;for(var h=0,k=g.length;h<k;h++)for(var l=g[h],q=0;3>q;q++){var n=l[f[q]];var t=l[f[(q+1)%3]];d[0]=Math.min(n,t);d[1]=Math.max(n,t);n=d[0]+","+d[1];void 0===e[n]?e[n]={index1:d[0],index2:d[1],face1:h,face2:void 0}:e[n].face2=h}for(n in e)if(d=e[n],void 0===d.face2||g[d.face1].normal.dot(g[d.face2].normal)<=b)f=a[d.index1],c.push(f.x,f.y,f.z),f=a[d.index2],c.push(f.x,f.y,f.z);this.addAttribute("position",
16607 new y(c,3))}function pb(a,b,c,d,e,f,g,h){N.call(this);this.type="CylinderGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};this.fromBufferGeometry(new Sa(a,b,c,d,e,f,g,h));this.mergeVertices()}function Sa(a,b,c,d,e,f,g,h){function k(c){var e,f=new C,k=new p,r=0,v=!0===c?a:b,z=!0===c?1:-1;var y=u;for(e=1;e<=d;e++)n.push(0,w*z,0),t.push(0,z,0),m.push(.5,.5),u++;var A=u;for(e=0;e<=d;e++){var D=e/d*h+g,L=Math.cos(D),
16608 D=Math.sin(D);k.x=v*D;k.y=w*z;k.z=v*L;n.push(k.x,k.y,k.z);t.push(0,z,0);f.x=.5*L+.5;f.y=.5*D*z+.5;m.push(f.x,f.y);u++}for(e=0;e<d;e++)f=y+e,k=A+e,!0===c?q.push(k,k+1,f):q.push(k+1,k,f),r+=3;l.addGroup(x,r,!0===c?1:2);x+=r}D.call(this);this.type="CylinderBufferGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};var l=this;a=void 0!==a?a:1;b=void 0!==b?b:1;c=c||1;d=Math.floor(d)||8;e=Math.floor(e)||1;f=void 0!==f?f:
16609 !1;g=void 0!==g?g:0;h=void 0!==h?h:2*Math.PI;var q=[],n=[],t=[],m=[],u=0,v=[],w=c/2,x=0;(function(){var f,k,r=new p,J=new p,y=0,C=(b-a)/c;for(k=0;k<=e;k++){var A=[],D=k/e,E=D*(b-a)+a;for(f=0;f<=d;f++){var H=f/d,L=H*h+g,Y=Math.sin(L),L=Math.cos(L);J.x=E*Y;J.y=-D*c+w;J.z=E*L;n.push(J.x,J.y,J.z);r.set(Y,C,L).normalize();t.push(r.x,r.y,r.z);m.push(H,1-D);A.push(u++)}v.push(A)}for(f=0;f<d;f++)for(k=0;k<e;k++)r=v[k+1][f],J=v[k+1][f+1],C=v[k][f+1],q.push(v[k][f],r,C),q.push(r,J,C),y+=6;l.addGroup(x,y,0);
16610 x+=y})();!1===f&&(0<a&&k(!0),0<b&&k(!1));this.setIndex(q);this.addAttribute("position",new y(n,3));this.addAttribute("normal",new y(t,3));this.addAttribute("uv",new y(m,2))}function Uc(a,b,c,d,e,f,g){pb.call(this,0,a,b,c,d,e,f,g);this.type="ConeGeometry";this.parameters={radius:a,height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Vc(a,b,c,d,e,f,g){Sa.call(this,0,a,b,c,d,e,f,g);this.type="ConeBufferGeometry";this.parameters={radius:a,height:b,radialSegments:c,
16611 heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Wc(a,b,c,d){N.call(this);this.type="CircleGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};this.fromBufferGeometry(new fc(a,b,c,d));this.mergeVertices()}function fc(a,b,c,d){D.call(this);this.type="CircleBufferGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};a=a||1;b=void 0!==b?Math.max(3,b):8;c=void 0!==c?c:0;d=void 0!==d?d:2*Math.PI;var e=[],f=[],g=[],h=[],k,l=new p,q=new C;f.push(0,
16612 0,0);g.push(0,0,1);h.push(.5,.5);var n=0;for(k=3;n<=b;n++,k+=3){var t=c+n/b*d;l.x=a*Math.cos(t);l.y=a*Math.sin(t);f.push(l.x,l.y,l.z);g.push(0,0,1);q.x=(f[k]/a+1)/2;q.y=(f[k+1]/a+1)/2;h.push(q.x,q.y)}for(k=1;k<=b;k++)e.push(k,k+1,0);this.setIndex(e);this.addAttribute("position",new y(f,3));this.addAttribute("normal",new y(g,3));this.addAttribute("uv",new y(h,2))}function gc(a){Q.call(this);this.type="ShadowMaterial";this.color=new H(0);this.opacity=1;this.transparent=this.lights=!0;this.setValues(a)}
16613 function hc(a){oa.call(this,a);this.type="RawShaderMaterial"}function Ma(a){Q.call(this);this.defines={STANDARD:""};this.type="MeshStandardMaterial";this.color=new H(16777215);this.metalness=this.roughness=.5;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new H(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=
16614 0;this.envMap=this.alphaMap=this.metalnessMap=this.roughnessMap=null;this.envMapIntensity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function qb(a){Ma.call(this);this.defines={PHYSICAL:""};this.type="MeshPhysicalMaterial";this.reflectivity=.5;this.clearCoatRoughness=this.clearCoat=0;this.setValues(a)}function Ia(a){Q.call(this);this.type="MeshPhongMaterial";
16615 this.color=new H(16777215);this.specular=new H(1118481);this.shininess=30;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new H(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=
16616 !1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function rb(a){Ia.call(this);this.defines={TOON:""};this.type="MeshToonMaterial";this.gradientMap=null;this.setValues(a)}function sb(a){Q.call(this);this.type="MeshNormalMaterial";this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=
16617 !1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.skinning=this.lights=this.fog=!1;this.setValues(a)}function tb(a){Q.call(this);this.type="MeshLambertMaterial";this.color=new H(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new H(0);this.emissiveIntensity=1;this.envMap=this.alphaMap=this.specularMap=this.emissiveMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=
16618 1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function ub(a){O.call(this);this.type="LineDashedMaterial";this.scale=1;this.dashSize=3;this.gapSize=1;this.setValues(a)}function Yd(a,b,c){var d=this,e=!1,f=0,g=0,h=void 0;this.onStart=void 0;this.onLoad=a;this.onProgress=b;this.onError=c;this.itemStart=function(a){g++;if(!1===e&&void 0!==d.onStart)d.onStart(a,f,g);e=!0};this.itemEnd=function(a){f++;if(void 0!==d.onProgress)d.onProgress(a,
16619 f,g);if(f===g&&(e=!1,void 0!==d.onLoad))d.onLoad()};this.itemError=function(a){if(void 0!==d.onError)d.onError(a)};this.resolveURL=function(a){return h?h(a):a};this.setURLModifier=function(a){h=a}}function Ja(a){this.manager=void 0!==a?a:wa}function Qe(a){this.manager=void 0!==a?a:wa;this._parser=null}function Zd(a){this.manager=void 0!==a?a:wa;this._parser=null}function Xc(a){this.manager=void 0!==a?a:wa}function $d(a){this.manager=void 0!==a?a:wa}function td(a){this.manager=void 0!==a?a:wa}function ga(a,
16620 b){A.call(this);this.type="Light";this.color=new H(a);this.intensity=void 0!==b?b:1;this.receiveShadow=void 0}function ud(a,b,c){ga.call(this,a,c);this.type="HemisphereLight";this.castShadow=void 0;this.position.copy(A.DefaultUp);this.updateMatrix();this.groundColor=new H(b)}function vb(a){this.camera=a;this.bias=0;this.radius=1;this.mapSize=new C(512,512);this.map=null;this.matrix=new K}function vd(){vb.call(this,new U(50,1,.5,500))}function wd(a,b,c,d,e,f){ga.call(this,a,b);this.type="SpotLight";
16621 this.position.copy(A.DefaultUp);this.updateMatrix();this.target=new A;Object.defineProperty(this,"power",{get:function(){return this.intensity*Math.PI},set:function(a){this.intensity=a/Math.PI}});this.distance=void 0!==c?c:0;this.angle=void 0!==d?d:Math.PI/3;this.penumbra=void 0!==e?e:0;this.decay=void 0!==f?f:1;this.shadow=new vd}function xd(a,b,c,d){ga.call(this,a,b);this.type="PointLight";Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(a){this.intensity=
16622 a/(4*Math.PI)}});this.distance=void 0!==c?c:0;this.decay=void 0!==d?d:1;this.shadow=new vb(new U(90,1,.5,500))}function yd(){vb.call(this,new Kb(-5,5,5,-5,.5,500))}function zd(a,b){ga.call(this,a,b);this.type="DirectionalLight";this.position.copy(A.DefaultUp);this.updateMatrix();this.target=new A;this.shadow=new yd}function Ad(a,b){ga.call(this,a,b);this.type="AmbientLight";this.castShadow=void 0}function Bd(a,b,c,d){ga.call(this,a,b);this.type="RectAreaLight";this.position.set(0,1,0);this.updateMatrix();
16623 this.width=void 0!==c?c:10;this.height=void 0!==d?d:10}function xa(a,b,c,d){this.parameterPositions=a;this._cachedIndex=0;this.resultBuffer=void 0!==d?d:new b.constructor(c);this.sampleValues=b;this.valueSize=c}function Cd(a,b,c,d){xa.call(this,a,b,c,d);this._offsetNext=this._weightNext=this._offsetPrev=this._weightPrev=-0}function Yc(a,b,c,d){xa.call(this,a,b,c,d)}function Dd(a,b,c,d){xa.call(this,a,b,c,d)}function wb(a,b,c,d){if(void 0===a)throw Error("track name is undefined");if(void 0===b||0===
16624 b.length)throw Error("no keyframes in track named "+a);this.name=a;this.times=T.convertArray(b,this.TimeBufferType);this.values=T.convertArray(c,this.ValueBufferType);this.setInterpolation(d||this.DefaultInterpolation);this.validate();this.optimize()}function ic(a,b,c,d){wb.call(this,a,b,c,d)}function Ed(a,b,c,d){xa.call(this,a,b,c,d)}function Zc(a,b,c,d){wb.call(this,a,b,c,d)}function jc(a,b,c,d){wb.call(this,a,b,c,d)}function Fd(a,b,c,d){wb.call(this,a,b,c,d)}function Gd(a,b,c){wb.call(this,a,b,
16625 c)}function Hd(a,b,c,d){wb.call(this,a,b,c,d)}function xb(a,b,c,d){wb.apply(this,a,b,c,d)}function ka(a,b,c){this.name=a;this.tracks=c;this.duration=void 0!==b?b:-1;this.uuid=R.generateUUID();0>this.duration&&this.resetDuration();this.optimize()}function Id(a){this.manager=void 0!==a?a:wa;this.textures={}}function ae(a){this.manager=void 0!==a?a:wa}function kc(){this.onLoadStart=function(){};this.onLoadProgress=function(){};this.onLoadComplete=function(){}}function be(a){"boolean"===typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),
16626 a=void 0);this.manager=void 0!==a?a:wa;this.withCredentials=!1}function Re(a){this.manager=void 0!==a?a:wa;this.texturePath=""}function Se(a,b,c,d,e){b=.5*(d-b);e=.5*(e-c);var f=a*a;return(2*c-2*d+b+e)*a*f+(-3*c+3*d-2*b-e)*f+b*a+c}function yb(a,b,c,d){var e=1-a;return e*e*b+2*(1-a)*a*c+a*a*d}function zb(a,b,c,d,e){var f=1-a,g=1-a;return f*f*f*b+3*g*g*a*c+3*(1-a)*a*a*d+a*a*a*e}function S(){this.type="Curve";this.arcLengthDivisions=200}function Ka(a,b){S.call(this);this.type="LineCurve";this.v1=a||
16627 new C;this.v2=b||new C}function Ab(){S.call(this);this.type="CurvePath";this.curves=[];this.autoClose=!1}function Na(a,b,c,d,e,f,g,h){S.call(this);this.type="EllipseCurve";this.aX=a||0;this.aY=b||0;this.xRadius=c||1;this.yRadius=d||1;this.aStartAngle=e||0;this.aEndAngle=f||2*Math.PI;this.aClockwise=g||!1;this.aRotation=h||0}function ab(a){S.call(this);this.type="SplineCurve";this.points=a||[]}function bb(a,b,c,d){S.call(this);this.type="CubicBezierCurve";this.v0=a||new C;this.v1=b||new C;this.v2=
16628 c||new C;this.v3=d||new C}function cb(a,b,c){S.call(this);this.type="QuadraticBezierCurve";this.v0=a||new C;this.v1=b||new C;this.v2=c||new C}function Bb(a){Ab.call(this);this.type="Path";this.currentPoint=new C;a&&this.setFromPoints(a)}function Cb(a){Bb.call(this,a);this.type="Shape";this.holes=[]}function ce(){this.type="ShapePath";this.subPaths=[];this.currentPath=null}function de(a){this.type="Font";this.data=a}function Te(a){this.manager=void 0!==a?a:wa}function ee(a){this.manager=void 0!==a?
16629 a:wa}function Ue(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new U;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new U;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=!1}function $c(a,b,c){A.call(this);this.type="CubeCamera";var d=new U(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new p(1,0,0));this.add(d);var e=new U(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new p(-1,0,0));this.add(e);var f=new U(90,1,a,b);f.up.set(0,0,1);f.lookAt(new p(0,1,0));
16630 this.add(f);var g=new U(90,1,a,b);g.up.set(0,0,-1);g.lookAt(new p(0,-1,0));this.add(g);var h=new U(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new p(0,0,1));this.add(h);var k=new U(90,1,a,b);k.up.set(0,-1,0);k.lookAt(new p(0,0,-1));this.add(k);this.renderTarget=new Ib(c,c,{format:1022,magFilter:1006,minFilter:1006});this.renderTarget.texture.name="CubeCamera";this.update=function(a,b){null===this.parent&&this.updateMatrixWorld();var c=this.renderTarget,l=c.texture.generateMipmaps;c.texture.generateMipmaps=
16631 !1;c.activeCubeFace=0;a.render(b,d,c);c.activeCubeFace=1;a.render(b,e,c);c.activeCubeFace=2;a.render(b,f,c);c.activeCubeFace=3;a.render(b,g,c);c.activeCubeFace=4;a.render(b,h,c);c.texture.generateMipmaps=l;c.activeCubeFace=5;a.render(b,k,c);a.setRenderTarget(null)};this.clear=function(a,b,c,d){for(var e=this.renderTarget,f=0;6>f;f++)e.activeCubeFace=f,a.setRenderTarget(e),a.clear(b,c,d);a.setRenderTarget(null)}}function fe(){A.call(this);this.type="AudioListener";this.context=ge.getContext();this.gain=
16632 this.context.createGain();this.gain.connect(this.context.destination);this.filter=null}function lc(a){A.call(this);this.type="Audio";this.context=a.context;this.gain=this.context.createGain();this.gain.connect(a.getInput());this.autoplay=!1;this.buffer=null;this.loop=!1;this.offset=this.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";this.filters=[]}function he(a){lc.call(this,a);this.panner=this.context.createPanner();this.panner.connect(this.gain)}
16633 function ie(a,b){this.analyser=a.context.createAnalyser();this.analyser.fftSize=void 0!==b?b:2048;this.data=new Uint8Array(this.analyser.frequencyBinCount);a.getOutput().connect(this.analyser)}function je(a,b,c){this.binding=a;this.valueSize=c;a=Float64Array;switch(b){case "quaternion":b=this._slerp;break;case "string":case "bool":a=Array;b=this._select;break;default:b=this._lerp}this.buffer=new a(4*c);this._mixBufferRegion=b;this.referenceCount=this.useCount=this.cumulativeWeight=0}function Ve(a,
16634 b,c){c=c||na.parseTrackName(b);this._targetGroup=a;this._bindings=a.subscribe_(b,c)}function na(a,b,c){this.path=b;this.parsedPath=c||na.parseTrackName(b);this.node=na.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function We(){this.uuid=R.generateUUID();this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var a={};this._indicesByUUID=a;for(var b=0,c=arguments.length;b!==c;++b)a[arguments[b].uuid]=b;this._paths=[];this._parsedPaths=[];this._bindings=[];this._bindingsIndicesByPath=
16635 {};var d=this;this.stats={objects:{get total(){return d._objects.length},get inUse(){return this.total-d.nCachedObjects_}},get bindingsPerObject(){return d._bindings.length}}}function Xe(a,b,c){this._mixer=a;this._clip=b;this._localRoot=c||null;a=b.tracks;b=a.length;c=Array(b);for(var d={endingStart:2400,endingEnd:2400},e=0;e!==b;++e){var f=a[e].createInterpolant(null);c[e]=f;f.settings=d}this._interpolantSettings=d;this._interpolants=c;this._propertyBindings=Array(b);this._weightInterpolant=this._timeScaleInterpolant=
16636 this._byClipCacheIndex=this._cacheIndex=null;this.loop=2201;this._loopCount=-1;this._startTime=null;this.time=0;this._effectiveWeight=this.weight=this._effectiveTimeScale=this.timeScale=1;this.repetitions=Infinity;this.paused=!1;this.enabled=!0;this.clampWhenFinished=!1;this.zeroSlopeAtEnd=this.zeroSlopeAtStart=!0}function Ye(a){this._root=a;this._initMemoryManager();this.time=this._accuIndex=0;this.timeScale=1}function Jd(a,b){"string"===typeof a&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),
16637 a=b);this.value=a}function ke(){D.call(this);this.type="InstancedBufferGeometry";this.maxInstancedCount=void 0}function le(a,b,c,d){this.uuid=R.generateUUID();this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0===d}function mc(a,b){this.uuid=R.generateUUID();this.array=a;this.stride=b;this.count=void 0!==a?a.length/b:0;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function me(a,b,c){mc.call(this,a,b);this.meshPerAttribute=c||1}function ne(a,
16638 b,c){P.call(this,a,b);this.meshPerAttribute=c||1}function Ze(a,b,c,d){this.ray=new lb(a,b);this.near=c||0;this.far=d||Infinity;this.params={Mesh:{},Line:{},LOD:{},Points:{threshold:1},Sprite:{}};Object.defineProperties(this.params,{PointCloud:{get:function(){console.warn("THREE.Raycaster: params.PointCloud has been renamed to params.Points.");return this.Points}}})}function $e(a,b){return a.distance-b.distance}function oe(a,b,c,d){if(!1!==a.visible&&(a.raycast(b,c),!0===d)){a=a.children;d=0;for(var e=
16639 a.length;d<e;d++)oe(a[d],b,c,!0)}}function af(a){this.autoStart=void 0!==a?a:!0;this.elapsedTime=this.oldTime=this.startTime=0;this.running=!1}function bf(a,b,c){this.radius=void 0!==a?a:1;this.phi=void 0!==b?b:0;this.theta=void 0!==c?c:0;return this}function cf(a,b,c){this.radius=void 0!==a?a:1;this.theta=void 0!==b?b:0;this.y=void 0!==c?c:0;return this}function ad(a){A.call(this);this.material=a;this.render=function(){}}function bd(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c:
16640 16711680;d=void 0!==d?d:1;b=0;(c=this.object.geometry)&&c.isGeometry?b=3*c.faces.length:c&&c.isBufferGeometry&&(b=c.attributes.normal.count);c=new D;b=new y(6*b,3);c.addAttribute("position",b);ca.call(this,c,new O({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function nc(a,b){A.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=b;a=new D;b=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(var c=0,
16641 d=1;32>c;c++,d++){var e=c/32*Math.PI*2,f=d/32*Math.PI*2;b.push(Math.cos(e),Math.sin(e),1,Math.cos(f),Math.sin(f),1)}a.addAttribute("position",new y(b,3));b=new O({fog:!1});this.cone=new ca(a,b);this.add(this.cone);this.update()}function df(a){var b=[];a&&a.isBone&&b.push(a);for(var c=0;c<a.children.length;c++)b.push.apply(b,df(a.children[c]));return b}function oc(a){for(var b=df(a),c=new D,d=[],e=[],f=new H(0,0,1),g=new H(0,1,0),h=0;h<b.length;h++){var k=b[h];k.parent&&k.parent.isBone&&(d.push(0,
16642 0,0),d.push(0,0,0),e.push(f.r,f.g,f.b),e.push(g.r,g.g,g.b))}c.addAttribute("position",new y(d,3));c.addAttribute("color",new y(e,3));d=new O({vertexColors:2,depthTest:!1,depthWrite:!1,transparent:!0});ca.call(this,c,d);this.root=a;this.bones=b;this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1}function pc(a,b,c){this.light=a;this.light.updateMatrixWorld();this.color=c;a=new ob(b,4,2);b=new va({wireframe:!0,fog:!1});pa.call(this,a,b);this.matrix=this.light.matrixWorld;this.matrixAutoUpdate=!1;this.update()}
16643 function qc(a,b){A.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=b;a=new O({fog:!1});b=new D;b.addAttribute("position",new P(new Float32Array(15),3));this.line=new ma(b,a);this.add(this.line);this.update()}function rc(a,b,c){A.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=c;a=new nb(b);a.rotateY(.5*Math.PI);this.material=new va({wireframe:!0,fog:!1});void 0===
16644 this.color&&(this.material.vertexColors=2);b=a.getAttribute("position");b=new Float32Array(3*b.count);a.addAttribute("color",new P(b,3));this.add(new pa(a,this.material));this.update()}function cd(a,b,c,d){a=a||10;b=b||10;c=new H(void 0!==c?c:4473924);d=new H(void 0!==d?d:8947848);var e=b/2,f=a/b,g=a/2;a=[];for(var h=[],k=0,l=0,q=-g;k<=b;k++,q+=f){a.push(-g,0,q,g,0,q);a.push(q,0,-g,q,0,g);var n=k===e?c:d;n.toArray(h,l);l+=3;n.toArray(h,l);l+=3;n.toArray(h,l);l+=3;n.toArray(h,l);l+=3}b=new D;b.addAttribute("position",
16645 new y(a,3));b.addAttribute("color",new y(h,3));c=new O({vertexColors:2});ca.call(this,b,c)}function Kd(a,b,c,d,e,f){a=a||10;b=b||16;c=c||8;d=d||64;e=new H(void 0!==e?e:4473924);f=new H(void 0!==f?f:8947848);var g=[],h=[],k;for(k=0;k<=b;k++){var l=k/b*2*Math.PI;var q=Math.sin(l)*a;l=Math.cos(l)*a;g.push(0,0,0);g.push(q,0,l);var n=k&1?e:f;h.push(n.r,n.g,n.b);h.push(n.r,n.g,n.b)}for(k=0;k<=c;k++){n=k&1?e:f;var t=a-a/c*k;for(b=0;b<d;b++)l=b/d*2*Math.PI,q=Math.sin(l)*t,l=Math.cos(l)*t,g.push(q,0,l),h.push(n.r,
16646 n.g,n.b),l=(b+1)/d*2*Math.PI,q=Math.sin(l)*t,l=Math.cos(l)*t,g.push(q,0,l),h.push(n.r,n.g,n.b)}a=new D;a.addAttribute("position",new y(g,3));a.addAttribute("color",new y(h,3));g=new O({vertexColors:2});ca.call(this,a,g)}function dd(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c:16776960;d=void 0!==d?d:1;b=0;(c=this.object.geometry)&&c.isGeometry?b=c.faces.length:console.warn("THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.");c=new D;
16647 b=new y(6*b,3);c.addAttribute("position",b);ca.call(this,c,new O({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function sc(a,b,c){A.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=c;void 0===b&&(b=1);a=new D;a.addAttribute("position",new y([-b,b,0,b,b,0,b,-b,0,-b,-b,0,-b,b,0],3));b=new O({fog:!1});this.lightPlane=new ma(a,b);this.add(this.lightPlane);a=new D;a.addAttribute("position",new y([0,0,0,0,0,1],3));this.targetLine=
16648 new ma(a,b);this.add(this.targetLine);this.update()}function ed(a){function b(a,b,d){c(a,d);c(b,d)}function c(a,b){f.push(0,0,0);g.push(b.r,b.g,b.b);void 0===h[a]&&(h[a]=[]);h[a].push(f.length/3-1)}var d=new D,e=new O({color:16777215,vertexColors:1}),f=[],g=[],h={},k=new H(16755200),l=new H(16711680),q=new H(43775),n=new H(16777215),t=new H(3355443);b("n1","n2",k);b("n2","n4",k);b("n4","n3",k);b("n3","n1",k);b("f1","f2",k);b("f2","f4",k);b("f4","f3",k);b("f3","f1",k);b("n1","f1",k);b("n2","f2",k);
16649 b("n3","f3",k);b("n4","f4",k);b("p","n1",l);b("p","n2",l);b("p","n3",l);b("p","n4",l);b("u1","u2",q);b("u2","u3",q);b("u3","u1",q);b("c","t",n);b("p","c",t);b("cn1","cn2",t);b("cn3","cn4",t);b("cf1","cf2",t);b("cf3","cf4",t);d.addAttribute("position",new y(f,3));d.addAttribute("color",new y(g,3));ca.call(this,d,e);this.camera=a;this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.pointMap=h;this.update()}function Db(a,b){this.object=
16650 a;void 0===b&&(b=16776960);a=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]);var c=new Float32Array(24),d=new D;d.setIndex(new P(a,1));d.addAttribute("position",new P(c,3));ca.call(this,d,new O({color:b}));this.matrixAutoUpdate=!1;this.update()}function fd(a,b){this.type="Box3Helper";this.box=a;a=void 0!==b?b:16776960;b=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]);var c=new D;c.setIndex(new P(b,1));c.addAttribute("position",new y([1,1,1,-1,1,1,-1,-1,1,1,-1,
16651 1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],3));ca.call(this,c,new O({color:a}));this.geometry.computeBoundingSphere()}function gd(a,b,c){this.type="PlaneHelper";this.plane=a;this.size=void 0===b?1:b;a=void 0!==c?c:16776960;b=new D;b.addAttribute("position",new y([1,-1,1,-1,1,1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,0,0,1,0,0,0],3));b.computeBoundingSphere();ma.call(this,b,new O({color:a}));b=new D;b.addAttribute("position",new y([1,1,1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,1],3));b.computeBoundingSphere();
16652 this.add(new pa(b,new va({color:a,opacity:.2,transparent:!0,depthWrite:!1})))}function Eb(a,b,c,d,e,f){A.call(this);void 0===d&&(d=16776960);void 0===c&&(c=1);void 0===e&&(e=.2*c);void 0===f&&(f=.2*e);void 0===Ld&&(Ld=new D,Ld.addAttribute("position",new y([0,0,0,0,1,0],3)),pe=new Sa(0,.5,1,5,1),pe.translate(0,-.5,0));this.position.copy(b);this.line=new ma(Ld,new O({color:d}));this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new pa(pe,new va({color:d}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);
16653 this.setDirection(a);this.setLength(c,e,f)}function hd(a){a=a||1;var b=[0,0,0,a,0,0,0,0,0,0,a,0,0,0,0,0,0,a];a=new D;a.addAttribute("position",new y(b,3));a.addAttribute("color",new y([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));b=new O({vertexColors:2});ca.call(this,a,b)}function qe(){var a=0,b=0,c=0,d=0;return{initCatmullRom:function(e,f,g,h,k){e=k*(g-e);h=k*(h-f);a=f;b=e;c=-3*f+3*g-2*e-h;d=2*f-2*g+e+h},initNonuniformCatmullRom:function(e,f,g,h,k,l,q){e=((f-e)/k-(g-e)/(k+l)+(g-f)/l)*l;h=((g-f)/
16654 l-(h-f)/(l+q)+(h-g)/q)*l;a=f;b=e;c=-3*f+3*g-2*e-h;d=2*f-2*g+e+h},calc:function(e){var f=e*e;return a+b*e+c*f+d*f*e}}}function ya(a,b,c,d){S.call(this);this.type="CatmullRomCurve3";this.points=a||[];this.closed=b||!1;this.curveType=c||"centripetal";this.tension=d||.5}function Fb(a,b,c,d){S.call(this);this.type="CubicBezierCurve3";this.v0=a||new p;this.v1=b||new p;this.v2=c||new p;this.v3=d||new p}function Gb(a,b,c){S.call(this);this.type="QuadraticBezierCurve3";this.v0=a||new p;this.v1=b||new p;this.v2=
16655 c||new p}function db(a,b){S.call(this);this.type="LineCurve3";this.v1=a||new p;this.v2=b||new p}function id(a,b,c,d,e,f){Na.call(this,a,b,c,c,d,e,f);this.type="ArcCurve"}function ef(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");ya.call(this,a);this.type="catmullrom";this.closed=!0}function ff(a){console.warn("THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");ya.call(this,a);this.type="catmullrom"}function re(a){console.warn("THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.");
16656 ya.call(this,a);this.type="catmullrom"}void 0===Number.EPSILON&&(Number.EPSILON=Math.pow(2,-52));void 0===Number.isInteger&&(Number.isInteger=function(a){return"number"===typeof a&&isFinite(a)&&Math.floor(a)===a});void 0===Math.sign&&(Math.sign=function(a){return 0>a?-1:0<a?1:+a});!1==="name"in Function.prototype&&Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1]}});void 0===Object.assign&&function(){Object.assign=function(a){if(void 0===
16657 a||null===a)throw new TypeError("Cannot convert undefined or null to object");for(var b=Object(a),c=1;c<arguments.length;c++){var d=arguments[c];if(void 0!==d&&null!==d)for(var e in d)Object.prototype.hasOwnProperty.call(d,e)&&(b[e]=d[e])}return b}}();Object.assign(ja.prototype,{addEventListener:function(a,b){void 0===this._listeners&&(this._listeners={});var c=this._listeners;void 0===c[a]&&(c[a]=[]);-1===c[a].indexOf(b)&&c[a].push(b)},hasEventListener:function(a,b){if(void 0===this._listeners)return!1;
16658 var c=this._listeners;return void 0!==c[a]&&-1!==c[a].indexOf(b)},removeEventListener:function(a,b){void 0!==this._listeners&&(a=this._listeners[a],void 0!==a&&(b=a.indexOf(b),-1!==b&&a.splice(b,1)))},dispatchEvent:function(a){if(void 0!==this._listeners){var b=this._listeners[a.type];if(void 0!==b){a.target=this;for(var b=b.slice(0),c=0,d=b.length;c<d;c++)b[c].call(this,a)}}}});var R={DEG2RAD:Math.PI/180,RAD2DEG:180/Math.PI,generateUUID:function(){var a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),
16659 b=0,c;return function(){for(var d="",e=0;36>e;e++)8===e||13===e||18===e||23===e?d+="-":14===e?d+="4":(2>=b&&(b=33554432+16777216*Math.random()|0),c=b&15,b>>=4,d+=a[19===e?c&3|8:c]);return d}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a,b){return(a%b+b)%b},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},lerp:function(a,b,c){return(1-c)*a+c*b},smoothstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*(3-2*a)},smootherstep:function(a,
16660 b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*a*(a*(6*a-15)+10)},randInt:function(a,b){return a+Math.floor(Math.random()*(b-a+1))},randFloat:function(a,b){return a+Math.random()*(b-a)},randFloatSpread:function(a){return a*(.5-Math.random())},degToRad:function(a){return a*R.DEG2RAD},radToDeg:function(a){return a*R.RAD2DEG},isPowerOfTwo:function(a){return 0===(a&a-1)&&0!==a},ceilPowerOfTwo:function(a){return Math.pow(2,Math.ceil(Math.log(a)/Math.LN2))},floorPowerOfTwo:function(a){return Math.pow(2,
16661 Math.floor(Math.log(a)/Math.LN2))}};Object.defineProperties(C.prototype,{width:{get:function(){return this.x},set:function(a){this.x=a}},height:{get:function(){return this.y},set:function(a){this.y=a}}});Object.assign(C.prototype,{isVector2:!0,set:function(a,b){this.x=a;this.y=b;return this},setScalar:function(a){this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;
16662 default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this},
16663 addScalar:function(a){this.x+=a;this.y+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;return this},subScalar:function(a){this.x-=a;this.y-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;
16664 return this},multiply:function(a){this.x*=a.x;this.y*=a.y;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;return this},divide:function(a){this.x/=a.x;this.y/=a.y;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},applyMatrix3:function(a){var b=this.x,c=this.y;a=a.elements;this.x=a[0]*b+a[3]*c+a[6];this.y=a[1]*b+a[4]*c+a[7];return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=
16665 Math.max(this.y,a.y);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));return this},clampScalar:function(){var a=new C,b=new C;return function(c,d){a.set(c,c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this},ceil:function(){this.x=Math.ceil(this.x);
16666 this.y=Math.ceil(this.y);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);return this},negate:function(){this.x=-this.x;this.y=-this.y;return this},dot:function(a){return this.x*a.x+this.y*a.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},manhattanLength:function(){return Math.abs(this.x)+
16667 Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length()||1)},angle:function(){var a=Math.atan2(this.y,this.x);0>a&&(a+=2*Math.PI);return a},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x;a=this.y-a.y;return b*b+a*a},manhattanDistanceTo:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=
16668 (a.y-this.y)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);
16669 return this},rotateAround:function(a,b){var c=Math.cos(b);b=Math.sin(b);var d=this.x-a.x,e=this.y-a.y;this.x=d*c-e*b+a.x;this.y=d*b+e*c+a.y;return this}});Object.assign(K.prototype,{isMatrix4:!0,set:function(a,b,c,d,e,f,g,h,k,l,q,n,t,m,p,v){var r=this.elements;r[0]=a;r[4]=b;r[8]=c;r[12]=d;r[1]=e;r[5]=f;r[9]=g;r[13]=h;r[2]=k;r[6]=l;r[10]=q;r[14]=n;r[3]=t;r[7]=m;r[11]=p;r[15]=v;return this},identity:function(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this},clone:function(){return(new K).fromArray(this.elements)},
16670 copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];b[11]=a[11];b[12]=a[12];b[13]=a[13];b[14]=a[14];b[15]=a[15];return this},copyPosition:function(a){var b=this.elements;a=a.elements;b[12]=a[12];b[13]=a[13];b[14]=a[14];return this},extractBasis:function(a,b,c){a.setFromMatrixColumn(this,0);b.setFromMatrixColumn(this,1);c.setFromMatrixColumn(this,2);return this},makeBasis:function(a,b,c){this.set(a.x,
16671 b.x,c.x,0,a.y,b.y,c.y,0,a.z,b.z,c.z,0,0,0,0,1);return this},extractRotation:function(){var a=new p;return function(b){var c=this.elements,d=b.elements,e=1/a.setFromMatrixColumn(b,0).length(),f=1/a.setFromMatrixColumn(b,1).length();b=1/a.setFromMatrixColumn(b,2).length();c[0]=d[0]*e;c[1]=d[1]*e;c[2]=d[2]*e;c[4]=d[4]*f;c[5]=d[5]*f;c[6]=d[6]*f;c[8]=d[8]*b;c[9]=d[9]*b;c[10]=d[10]*b;return this}}(),makeRotationFromEuler:function(a){a&&a.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");
16672 var b=this.elements,c=a.x,d=a.y,e=a.z,f=Math.cos(c),c=Math.sin(c),g=Math.cos(d),d=Math.sin(d),h=Math.cos(e),e=Math.sin(e);if("XYZ"===a.order){var k=f*h;var l=f*e;var q=c*h;a=c*e;b[0]=g*h;b[4]=-g*e;b[8]=d;b[1]=l+q*d;b[5]=k-a*d;b[9]=-c*g;b[2]=a-k*d;b[6]=q+l*d;b[10]=f*g}else"YXZ"===a.order?(k=g*h,l=g*e,q=d*h,a=d*e,b[0]=k+a*c,b[4]=q*c-l,b[8]=f*d,b[1]=f*e,b[5]=f*h,b[9]=-c,b[2]=l*c-q,b[6]=a+k*c,b[10]=f*g):"ZXY"===a.order?(k=g*h,l=g*e,q=d*h,a=d*e,b[0]=k-a*c,b[4]=-f*e,b[8]=q+l*c,b[1]=l+q*c,b[5]=f*h,b[9]=
16673 a-k*c,b[2]=-f*d,b[6]=c,b[10]=f*g):"ZYX"===a.order?(k=f*h,l=f*e,q=c*h,a=c*e,b[0]=g*h,b[4]=q*d-l,b[8]=k*d+a,b[1]=g*e,b[5]=a*d+k,b[9]=l*d-q,b[2]=-d,b[6]=c*g,b[10]=f*g):"YZX"===a.order?(k=f*g,l=f*d,q=c*g,a=c*d,b[0]=g*h,b[4]=a-k*e,b[8]=q*e+l,b[1]=e,b[5]=f*h,b[9]=-c*h,b[2]=-d*h,b[6]=l*e+q,b[10]=k-a*e):"XZY"===a.order&&(k=f*g,l=f*d,q=c*g,a=c*d,b[0]=g*h,b[4]=-e,b[8]=d*h,b[1]=k*e+a,b[5]=f*h,b[9]=l*e-q,b[2]=q*e-l,b[6]=c*h,b[10]=a*e+k);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},makeRotationFromQuaternion:function(a){var b=
16674 this.elements,c=a._x,d=a._y,e=a._z,f=a._w,g=c+c,h=d+d,k=e+e;a=c*g;var l=c*h,c=c*k,q=d*h,d=d*k,e=e*k,g=f*g,h=f*h,f=f*k;b[0]=1-(q+e);b[4]=l-f;b[8]=c+h;b[1]=l+f;b[5]=1-(a+e);b[9]=d-g;b[2]=c-h;b[6]=d+g;b[10]=1-(a+q);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},lookAt:function(){var a=new p,b=new p,c=new p;return function(d,e,f){var g=this.elements;c.subVectors(d,e);0===c.lengthSq()&&(c.z=1);c.normalize();a.crossVectors(f,c);0===a.lengthSq()&&(1===Math.abs(f.z)?c.x+=1E-4:c.z+=1E-4,
16675 c.normalize(),a.crossVectors(f,c));a.normalize();b.crossVectors(c,a);g[0]=a.x;g[4]=b.x;g[8]=c.x;g[1]=a.y;g[5]=b.y;g[9]=c.y;g[2]=a.z;g[6]=b.z;g[10]=c.z;return this}}(),multiply:function(a,b){return void 0!==b?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(a,b)):this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements;
16676 b=this.elements;a=c[0];var e=c[4],f=c[8],g=c[12],h=c[1],k=c[5],l=c[9],q=c[13],n=c[2],m=c[6],r=c[10],p=c[14],v=c[3],w=c[7],x=c[11],c=c[15],z=d[0],I=d[4],B=d[8],J=d[12],y=d[1],C=d[5],A=d[9],D=d[13],E=d[2],H=d[6],L=d[10],Y=d[14],N=d[3],M=d[7],V=d[11],d=d[15];b[0]=a*z+e*y+f*E+g*N;b[4]=a*I+e*C+f*H+g*M;b[8]=a*B+e*A+f*L+g*V;b[12]=a*J+e*D+f*Y+g*d;b[1]=h*z+k*y+l*E+q*N;b[5]=h*I+k*C+l*H+q*M;b[9]=h*B+k*A+l*L+q*V;b[13]=h*J+k*D+l*Y+q*d;b[2]=n*z+m*y+r*E+p*N;b[6]=n*I+m*C+r*H+p*M;b[10]=n*B+m*A+r*L+p*V;b[14]=n*J+m*
16677 D+r*Y+p*d;b[3]=v*z+w*y+x*E+c*N;b[7]=v*I+w*C+x*H+c*M;b[11]=v*B+w*A+x*L+c*V;b[15]=v*J+w*D+x*Y+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[4]*=a;b[8]*=a;b[12]*=a;b[1]*=a;b[5]*=a;b[9]*=a;b[13]*=a;b[2]*=a;b[6]*=a;b[10]*=a;b[14]*=a;b[3]*=a;b[7]*=a;b[11]*=a;b[15]*=a;return this},applyToBufferAttribute:function(){var a=new p;return function(b){for(var c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix4(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),determinant:function(){var a=
16678 this.elements,b=a[0],c=a[4],d=a[8],e=a[12],f=a[1],g=a[5],h=a[9],k=a[13],l=a[2],q=a[6],n=a[10],m=a[14];return a[3]*(+e*h*q-d*k*q-e*g*n+c*k*n+d*g*m-c*h*m)+a[7]*(+b*h*m-b*k*n+e*f*n-d*f*m+d*k*l-e*h*l)+a[11]*(+b*k*q-b*g*m-e*f*q+c*f*m+e*g*l-c*k*l)+a[15]*(-d*g*l-b*h*q+b*g*n+d*f*q-c*f*n+c*h*l)},transpose:function(){var a=this.elements;var b=a[1];a[1]=a[4];a[4]=b;b=a[2];a[2]=a[8];a[8]=b;b=a[6];a[6]=a[9];a[9]=b;b=a[3];a[3]=a[12];a[12]=b;b=a[7];a[7]=a[13];a[13]=b;b=a[11];a[11]=a[14];a[14]=b;return this},setPosition:function(a){var b=
16679 this.elements;b[12]=a.x;b[13]=a.y;b[14]=a.z;return this},getInverse:function(a,b){var c=this.elements,d=a.elements;a=d[0];var e=d[1],f=d[2],g=d[3],h=d[4],k=d[5],l=d[6],q=d[7],n=d[8],m=d[9],r=d[10],p=d[11],v=d[12],w=d[13],x=d[14],d=d[15],z=m*x*q-w*r*q+w*l*p-k*x*p-m*l*d+k*r*d,I=v*r*q-n*x*q-v*l*p+h*x*p+n*l*d-h*r*d,B=n*w*q-v*m*q+v*k*p-h*w*p-n*k*d+h*m*d,J=v*m*l-n*w*l-v*k*r+h*w*r+n*k*x-h*m*x,y=a*z+e*I+f*B+g*J;if(0===y){if(!0===b)throw Error("THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0");
16680 console.warn("THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0");return this.identity()}b=1/y;c[0]=z*b;c[1]=(w*r*g-m*x*g-w*f*p+e*x*p+m*f*d-e*r*d)*b;c[2]=(k*x*g-w*l*g+w*f*q-e*x*q-k*f*d+e*l*d)*b;c[3]=(m*l*g-k*r*g-m*f*q+e*r*q+k*f*p-e*l*p)*b;c[4]=I*b;c[5]=(n*x*g-v*r*g+v*f*p-a*x*p-n*f*d+a*r*d)*b;c[6]=(v*l*g-h*x*g-v*f*q+a*x*q+h*f*d-a*l*d)*b;c[7]=(h*r*g-n*l*g+n*f*q-a*r*q-h*f*p+a*l*p)*b;c[8]=B*b;c[9]=(v*m*g-n*w*g-v*e*p+a*w*p+n*e*d-a*m*d)*b;c[10]=(h*w*g-v*k*g+v*e*q-a*w*q-h*e*d+a*k*d)*b;c[11]=
16681 (n*k*g-h*m*g-n*e*q+a*m*q+h*e*p-a*k*p)*b;c[12]=J*b;c[13]=(n*w*f-v*m*f+v*e*r-a*w*r-n*e*x+a*m*x)*b;c[14]=(v*k*f-h*w*f-v*e*l+a*w*l+h*e*x-a*k*x)*b;c[15]=(h*m*f-n*k*f+n*e*l-a*m*l-h*e*r+a*k*r)*b;return this},scale:function(a){var b=this.elements,c=a.x,d=a.y;a=a.z;b[0]*=c;b[4]*=d;b[8]*=a;b[1]*=c;b[5]*=d;b[9]*=a;b[2]*=c;b[6]*=d;b[10]*=a;b[3]*=c;b[7]*=d;b[11]*=a;return this},getMaxScaleOnAxis:function(){var a=this.elements;return Math.sqrt(Math.max(a[0]*a[0]+a[1]*a[1]+a[2]*a[2],a[4]*a[4]+a[5]*a[5]+a[6]*a[6],
16682 a[8]*a[8]+a[9]*a[9]+a[10]*a[10]))},makeTranslation:function(a,b,c){this.set(1,0,0,a,0,1,0,b,0,0,1,c,0,0,0,1);return this},makeRotationX:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(1,0,0,0,0,b,-a,0,0,a,b,0,0,0,0,1);return this},makeRotationY:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,0,a,0,0,1,0,0,-a,0,b,0,0,0,0,1);return this},makeRotationZ:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,-a,0,0,a,b,0,0,0,0,1,0,0,0,0,1);return this},makeRotationAxis:function(a,b){var c=
16683 Math.cos(b);b=Math.sin(b);var d=1-c,e=a.x,f=a.y;a=a.z;var g=d*e,h=d*f;this.set(g*e+c,g*f-b*a,g*a+b*f,0,g*f+b*a,h*f+c,h*a-b*e,0,g*a-b*f,h*a+b*e,d*a*a+c,0,0,0,0,1);return this},makeScale:function(a,b,c){this.set(a,0,0,0,0,b,0,0,0,0,c,0,0,0,0,1);return this},makeShear:function(a,b,c){this.set(1,b,c,0,a,1,c,0,a,b,1,0,0,0,0,1);return this},compose:function(a,b,c){this.makeRotationFromQuaternion(b);this.scale(c);this.setPosition(a);return this},decompose:function(){var a=new p,b=new K;return function(c,
16684 d,e){var f=this.elements,g=a.set(f[0],f[1],f[2]).length(),h=a.set(f[4],f[5],f[6]).length(),k=a.set(f[8],f[9],f[10]).length();0>this.determinant()&&(g=-g);c.x=f[12];c.y=f[13];c.z=f[14];b.copy(this);c=1/g;var f=1/h,l=1/k;b.elements[0]*=c;b.elements[1]*=c;b.elements[2]*=c;b.elements[4]*=f;b.elements[5]*=f;b.elements[6]*=f;b.elements[8]*=l;b.elements[9]*=l;b.elements[10]*=l;d.setFromRotationMatrix(b);e.x=g;e.y=h;e.z=k;return this}}(),makePerspective:function(a,b,c,d,e,f){void 0===f&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");
16685 var g=this.elements;g[0]=2*e/(b-a);g[4]=0;g[8]=(b+a)/(b-a);g[12]=0;g[1]=0;g[5]=2*e/(c-d);g[9]=(c+d)/(c-d);g[13]=0;g[2]=0;g[6]=0;g[10]=-(f+e)/(f-e);g[14]=-2*f*e/(f-e);g[3]=0;g[7]=0;g[11]=-1;g[15]=0;return this},makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=1/(b-a),k=1/(c-d),l=1/(f-e);g[0]=2*h;g[4]=0;g[8]=0;g[12]=-((b+a)*h);g[1]=0;g[5]=2*k;g[9]=0;g[13]=-((c+d)*k);g[2]=0;g[6]=0;g[10]=-2*l;g[14]=-((f+e)*l);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b=this.elements;
16686 a=a.elements;for(var c=0;16>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;16>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];a[b+9]=c[9];a[b+10]=c[10];a[b+11]=c[11];a[b+12]=c[12];a[b+13]=c[13];a[b+14]=c[14];a[b+15]=c[15];return a}});Object.assign(Z,{slerp:function(a,b,c,d){return c.copy(a).slerp(b,
16687 d)},slerpFlat:function(a,b,c,d,e,f,g){var h=c[d+0],k=c[d+1],l=c[d+2];c=c[d+3];d=e[f+0];var q=e[f+1],n=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==q||l!==n){f=1-g;var m=h*d+k*q+l*n+c*e,r=0<=m?1:-1,p=1-m*m;p>Number.EPSILON&&(p=Math.sqrt(p),m=Math.atan2(p,m*r),f=Math.sin(f*m)/p,g=Math.sin(g*m)/p);r*=g;h=h*f+d*r;k=k*f+q*r;l=l*f+n*r;c=c*f+e*r;f===1-g&&(g=1/Math.sqrt(h*h+k*k+l*l+c*c),h*=g,k*=g,l*=g,c*=g)}a[b]=h;a[b+1]=k;a[b+2]=l;a[b+3]=c}});Object.defineProperties(Z.prototype,{x:{get:function(){return this._x},
16688 set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},w:{get:function(){return this._w},set:function(a){this._w=a;this.onChangeCallback()}}});Object.assign(Z.prototype,{set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._w=d;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,
16689 this._w)},copy:function(a){this._x=a.x;this._y=a.y;this._z=a.z;this._w=a.w;this.onChangeCallback();return this},setFromEuler:function(a,b){if(!a||!a.isEuler)throw Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var c=a._x,d=a._y,e=a._z;a=a.order;var f=Math.cos,g=Math.sin,h=f(c/2),k=f(d/2),f=f(e/2),c=g(c/2),d=g(d/2),e=g(e/2);"XYZ"===a?(this._x=c*k*f+h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f-c*d*e):"YXZ"===a?(this._x=c*k*f+
16690 h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f+c*d*e):"ZXY"===a?(this._x=c*k*f-h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f-c*d*e):"ZYX"===a?(this._x=c*k*f-h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f+c*d*e):"YZX"===a?(this._x=c*k*f+h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f-c*d*e):"XZY"===a&&(this._x=c*k*f-h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f+c*d*e);if(!1!==b)this.onChangeCallback();return this},setFromAxisAngle:function(a,
16691 b){b/=2;var c=Math.sin(b);this._x=a.x*c;this._y=a.y*c;this._z=a.z*c;this._w=Math.cos(b);this.onChangeCallback();return this},setFromRotationMatrix:function(a){var b=a.elements,c=b[0];a=b[4];var d=b[8],e=b[1],f=b[5],g=b[9],h=b[2],k=b[6],b=b[10],l=c+f+b;0<l?(c=.5/Math.sqrt(l+1),this._w=.25/c,this._x=(k-g)*c,this._y=(d-h)*c,this._z=(e-a)*c):c>f&&c>b?(c=2*Math.sqrt(1+c-f-b),this._w=(k-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y=
16692 .25*c,this._z=(g+k)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+h)/c,this._y=(g+k)/c,this._z=.25*c);this.onChangeCallback();return this},setFromUnitVectors:function(){var a=new p,b;return function(c,d){void 0===a&&(a=new p);b=c.dot(d)+1;1E-6>b?(b=0,Math.abs(c.x)>Math.abs(c.z)?a.set(-c.y,c.x,0):a.set(0,-c.z,c.y)):a.crossVectors(c,d);this._x=a.x;this._y=a.y;this._z=a.z;this._w=b;return this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){this._x*=
16693 -1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(a){return this._x*a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this},
16694 multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z;a=a._w;var f=b._x,g=b._y,h=b._z;b=b._w;this._x=c*b+a*f+d*h-e*g;this._y=d*b+a*g+e*f-c*h;this._z=e*b+a*h+c*g-d*f;this._w=a*b-c*f-d*g-e*h;this.onChangeCallback();
16695 return this},slerp:function(a,b){if(0===b)return this;if(1===b)return this.copy(a);var c=this._x,d=this._y,e=this._z,f=this._w,g=f*a._w+c*a._x+d*a._y+e*a._z;0>g?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a);if(1<=g)return this._w=f,this._x=c,this._y=d,this._z=e,this;a=Math.sqrt(1-g*g);if(.001>Math.abs(a))return this._w=.5*(f+this._w),this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var h=Math.atan2(a,g),g=Math.sin((1-b)*h)/a;b=Math.sin(b*h)/a;
16696 this._w=f*g+this._w*b;this._x=c*g+this._x*b;this._y=d*g+this._y*b;this._z=e*g+this._z*b;this.onChangeCallback();return this},equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+1];this._z=a[b+2];this._w=a[b+3];this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback=
16697 a;return this},onChangeCallback:function(){}});Object.assign(p.prototype,{isVector3:!0,set:function(a,b,c){this.x=a;this.y=b;this.z=c;return this},setScalar:function(a){this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;
16698 case 1:return this.y;case 2:return this.z;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},
16699 addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=
16700 a.z-b.z;return this},multiply:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(a,b);this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;return this},multiplyVectors:function(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},applyEuler:function(){var a=new Z;return function(b){b&&b.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");
16701 return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a=new Z;return function(b,c){return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[3]*c+a[6]*d;this.y=a[1]*b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;var e=1/(a[3]*b+a[7]*c+a[11]*d+a[15]);this.x=(a[0]*b+a[4]*c+a[8]*d+a[12])*e;this.y=(a[1]*b+a[5]*c+a[9]*
16702 d+a[13])*e;this.z=(a[2]*b+a[6]*c+a[10]*d+a[14])*e;return this},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a=a.w;var h=a*b+f*d-g*c,k=a*c+g*b-e*d,l=a*d+e*c-f*b,b=-e*b-f*c-g*d;this.x=h*a+b*-e+k*-g-l*-f;this.y=k*a+b*-f+l*-e-h*-g;this.z=l*a+b*-g+h*-f-k*-e;return this},project:function(){var a=new K;return function(b){a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyMatrix4(a)}}(),unproject:function(){var a=new K;return function(b){a.multiplyMatrices(b.matrixWorld,
16703 a.getInverse(b.projectionMatrix));return this.applyMatrix4(a)}}(),transformDirection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d;this.y=a[1]*b+a[5]*c+a[9]*d;this.z=a[2]*b+a[6]*c+a[10]*d;return this.normalize()},divide:function(a){this.x/=a.x;this.y/=a.y;this.z/=a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);return this},max:function(a){this.x=
16704 Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));return this},clampScalar:function(){var a=new p,b=new p;return function(c,d){a.set(c,c,c);b.set(d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=
16705 Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x=
16706 -this.x;this.y=-this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-
16707 this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){return void 0!==b?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(a,b)):this.crossVectors(this,a)},crossVectors:function(a,b){var c=a.x,d=a.y;a=a.z;var e=b.x,f=b.y;b=b.z;this.x=d*b-a*f;this.y=a*e-c*b;this.z=c*f-d*e;return this},projectOnVector:function(a){var b=
16708 a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a=new p;return function(b){a.copy(this).projectOnVector(b);return this.sub(a)}}(),reflect:function(){var a=new p;return function(b){return this.sub(a.copy(b).multiplyScalar(2*this.dot(b)))}}(),angleTo:function(a){a=this.dot(a)/Math.sqrt(this.lengthSq()*a.lengthSq());return Math.acos(R.clamp(a,-1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-
16709 a.x,c=this.y-a.y;a=this.z-a.z;return b*b+c*c+a*a},manhattanDistanceTo:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)*a.radius;this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)*a.radius;this.z=b*Math.cos(a.theta);return this},setFromCylindrical:function(a){this.x=a.radius*Math.sin(a.theta);this.y=a.y;this.z=a.radius*Math.cos(a.theta);return this},setFromMatrixPosition:function(a){a=a.elements;this.x=a[12];this.y=
16710 a[13];this.z=a[14];return this},setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),c=this.setFromMatrixColumn(a,1).length();a=this.setFromMatrixColumn(a,2).length();this.x=b;this.y=c;this.z=a;return this},setFromMatrixColumn:function(a,b){return this.fromArray(a.elements,4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=
16711 []);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);return this}});Object.assign(ra.prototype,{isMatrix3:!0,set:function(a,b,c,d,e,f,g,h,k){var l=this.elements;l[0]=a;l[1]=d;l[2]=g;l[3]=b;l[4]=e;l[5]=h;l[6]=c;l[7]=f;l[8]=k;return this},identity:function(){this.set(1,0,0,0,1,0,0,0,1);return this},clone:function(){return(new this.constructor).fromArray(this.elements)},
16712 copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];return this},setFromMatrix4:function(a){a=a.elements;this.set(a[0],a[4],a[8],a[1],a[5],a[9],a[2],a[6],a[10]);return this},applyToBufferAttribute:function(){var a=new p;return function(b){for(var c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix3(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),multiply:function(a){return this.multiplyMatrices(this,
16713 a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements;b=this.elements;a=c[0];var e=c[3],f=c[6],g=c[1],h=c[4],k=c[7],l=c[2],q=c[5],c=c[8],n=d[0],m=d[3],r=d[6],p=d[1],v=d[4],w=d[7],x=d[2],z=d[5],d=d[8];b[0]=a*n+e*p+f*x;b[3]=a*m+e*v+f*z;b[6]=a*r+e*w+f*d;b[1]=g*n+h*p+k*x;b[4]=g*m+h*v+k*z;b[7]=g*r+h*w+k*d;b[2]=l*n+q*p+c*x;b[5]=l*m+q*v+c*z;b[8]=l*r+q*w+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[3]*=a;
16714 b[6]*=a;b[1]*=a;b[4]*=a;b[7]*=a;b[2]*=a;b[5]*=a;b[8]*=a;return this},determinant:function(){var a=this.elements,b=a[0],c=a[1],d=a[2],e=a[3],f=a[4],g=a[5],h=a[6],k=a[7],a=a[8];return b*f*a-b*g*k-c*e*a+c*g*h+d*e*k-d*f*h},getInverse:function(a,b){a&&a.isMatrix4&&console.error("THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument.");var c=a.elements;a=this.elements;var d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],q=c[7],c=c[8],n=c*h-k*q,m=k*l-c*g,r=q*g-h*l,p=d*n+e*m+f*r;if(0===p){if(!0===
16715 b)throw Error("THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0");console.warn("THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0");return this.identity()}b=1/p;a[0]=n*b;a[1]=(f*q-c*e)*b;a[2]=(k*e-f*h)*b;a[3]=m*b;a[4]=(c*d-f*l)*b;a[5]=(f*g-k*d)*b;a[6]=r*b;a[7]=(e*l-q*d)*b;a[8]=(h*d-e*g)*b;return this},transpose:function(){var a=this.elements;var b=a[1];a[1]=a[3];a[3]=b;b=a[2];a[2]=a[6];a[6]=b;b=a[5];a[5]=a[7];a[7]=b;return this},getNormalMatrix:function(a){return this.setFromMatrix4(a).getInverse(this).transpose()},
16716 transposeIntoArray:function(a){var b=this.elements;a[0]=b[0];a[1]=b[3];a[2]=b[6];a[3]=b[1];a[4]=b[4];a[5]=b[7];a[6]=b[2];a[7]=b[5];a[8]=b[8];return this},setUvTransform:function(a,b,c,d,e,f,g){var h=Math.cos(e);e=Math.sin(e);this.set(c*h,c*e,-c*(h*f+e*g)+f+a,-d*e,d*h,-d*(-e*f+h*g)+g+b,0,0,1)},scale:function(a,b){var c=this.elements;c[0]*=a;c[3]*=a;c[6]*=a;c[1]*=b;c[4]*=b;c[7]*=b;return this},rotate:function(a){var b=Math.cos(a);a=Math.sin(a);var c=this.elements,d=c[0],e=c[3],f=c[6],g=c[1],h=c[4],
16717 k=c[7];c[0]=b*d+a*g;c[3]=b*e+a*h;c[6]=b*f+a*k;c[1]=-a*d+b*g;c[4]=-a*e+b*h;c[7]=-a*f+b*k;return this},translate:function(a,b){var c=this.elements;c[0]+=a*c[2];c[3]+=a*c[5];c[6]+=a*c[8];c[1]+=b*c[2];c[4]+=b*c[5];c[7]+=b*c[8];return this},equals:function(a){var b=this.elements;a=a.elements;for(var c=0;9>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;9>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=
16718 this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];return a}});var kf=0;ea.DEFAULT_IMAGE=void 0;ea.DEFAULT_MAPPING=300;Object.defineProperty(ea.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(ea.prototype,ja.prototype,{constructor:ea,isTexture:!0,clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.image=a.image;this.mipmaps=a.mipmaps.slice(0);this.mapping=
16719 a.mapping;this.wrapS=a.wrapS;this.wrapT=a.wrapT;this.magFilter=a.magFilter;this.minFilter=a.minFilter;this.anisotropy=a.anisotropy;this.format=a.format;this.type=a.type;this.offset.copy(a.offset);this.repeat.copy(a.repeat);this.center.copy(a.center);this.rotation=a.rotation;this.matrixAutoUpdate=a.matrixAutoUpdate;this.matrix.copy(a.matrix);this.generateMipmaps=a.generateMipmaps;this.premultiplyAlpha=a.premultiplyAlpha;this.flipY=a.flipY;this.unpackAlignment=a.unpackAlignment;this.encoding=a.encoding;
16720 return this},toJSON:function(a){var b=void 0===a||"string"===typeof a;if(!b&&void 0!==a.textures[this.uuid])return a.textures[this.uuid];var c={metadata:{version:4.5,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};
16721 if(void 0!==this.image){var d=this.image;void 0===d.uuid&&(d.uuid=R.generateUUID());if(!b&&void 0===a.images[d.uuid]){var e=a.images,f=d.uuid,g=d.uuid;if(d instanceof HTMLCanvasElement)var h=d;else{h=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");h.width=d.width;h.height=d.height;var k=h.getContext("2d");d instanceof ImageData?k.putImageData(d,0,0):k.drawImage(d,0,0,d.width,d.height)}h=2048<h.width||2048<h.height?h.toDataURL("image/jpeg",.6):h.toDataURL("image/png");e[f]={uuid:g,
16722 url:h}}c.image=d.uuid}b||(a.textures[this.uuid]=c);return c},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(a){if(300===this.mapping){a.applyMatrix3(this.matrix);if(0>a.x||1<a.x)switch(this.wrapS){case 1E3:a.x-=Math.floor(a.x);break;case 1001:a.x=0>a.x?0:1;break;case 1002:a.x=1===Math.abs(Math.floor(a.x)%2)?Math.ceil(a.x)-a.x:a.x-Math.floor(a.x)}if(0>a.y||1<a.y)switch(this.wrapT){case 1E3:a.y-=Math.floor(a.y);break;case 1001:a.y=0>a.y?0:1;break;case 1002:a.y=1===Math.abs(Math.floor(a.y)%
16723 2)?Math.ceil(a.y)-a.y:a.y-Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}});Object.assign(da.prototype,{isVector4:!0,set:function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.w=d;return this},setScalar:function(a){this.w=this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;
16724 case 3:this.w=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z,this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),
16725 this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,
16726 b);this.x-=a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;this.w-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;this.w*=a;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12]*e;this.y=a[1]*b+a[5]*c+a[9]*d+a[13]*e;this.z=a[2]*b+a[6]*c+a[10]*d+a[14]*
16727 e;this.w=a[3]*b+a[7]*c+a[11]*d+a[15]*e;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},setAxisAngleFromQuaternion:function(a){this.w=2*Math.acos(a.w);var b=Math.sqrt(1-a.w*a.w);1E-4>b?(this.x=1,this.z=this.y=0):(this.x=a.x/b,this.y=a.y/b,this.z=a.z/b);return this},setAxisAngleFromRotationMatrix:function(a){a=a.elements;var b=a[0];var c=a[4];var d=a[8],e=a[1],f=a[5],g=a[9];var h=a[2];var k=a[6];var l=a[10];if(.01>Math.abs(c-e)&&.01>Math.abs(d-h)&&.01>Math.abs(g-k)){if(.1>Math.abs(c+
16728 e)&&.1>Math.abs(d+h)&&.1>Math.abs(g+k)&&.1>Math.abs(b+f+l-3))return this.set(1,0,0,0),this;a=Math.PI;b=(b+1)/2;f=(f+1)/2;l=(l+1)/2;c=(c+e)/4;d=(d+h)/4;g=(g+k)/4;b>f&&b>l?.01>b?(k=0,c=h=.707106781):(k=Math.sqrt(b),h=c/k,c=d/k):f>l?.01>f?(k=.707106781,h=0,c=.707106781):(h=Math.sqrt(f),k=c/h,c=g/h):.01>l?(h=k=.707106781,c=0):(c=Math.sqrt(l),k=d/c,h=g/c);this.set(k,h,c,a);return this}a=Math.sqrt((k-g)*(k-g)+(d-h)*(d-h)+(e-c)*(e-c));.001>Math.abs(a)&&(a=1);this.x=(k-g)/a;this.y=(d-h)/a;this.z=(e-c)/a;
16729 this.w=Math.acos((b+f+l-1)/2);return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);this.w=Math.min(this.w,a.w);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);this.w=Math.max(this.w,a.w);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));this.w=Math.max(a.w,Math.min(b.w,
16730 this.w));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new da,b=new da);a.set(c,c,c,c);b.set(d,d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);this.w=Math.floor(this.w);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);
16731 this.w=Math.ceil(this.w);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);this.w=Math.round(this.w);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);this.w=0>this.w?Math.ceil(this.w):Math.floor(this.w);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this},
16732 dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z+this.w*a.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=
16733 (a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;this.w+=(a.w-this.w)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];this.w=a[b+3];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;a[b+3]=this.w;return a},fromBufferAttribute:function(a,
16734 b,c){void 0!==c&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);this.w=a.getW(b);return this}});Object.assign(Hb.prototype,ja.prototype,{isWebGLRenderTarget:!0,setSize:function(a,b){if(this.width!==a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0,0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=
16735 a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone();this.depthBuffer=a.depthBuffer;this.stencilBuffer=a.stencilBuffer;this.depthTexture=a.depthTexture;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Ib.prototype=Object.create(Hb.prototype);Ib.prototype.constructor=Ib;Ib.prototype.isWebGLRenderTargetCube=!0;fb.prototype=Object.create(ea.prototype);fb.prototype.constructor=fb;fb.prototype.isDataTexture=!0;Ua.prototype=Object.create(ea.prototype);Ua.prototype.constructor=
16736 Ua;Ua.prototype.isCubeTexture=!0;Object.defineProperty(Ua.prototype,"images",{get:function(){return this.image},set:function(a){this.image=a}});var Be=new ea,Ce=new Ua,we=[],ye=[],Ae=new Float32Array(16),ze=new Float32Array(9);Ge.prototype.setValue=function(a,b){for(var c=this.seq,d=0,e=c.length;d!==e;++d){var f=c[d];f.setValue(a,b[f.id])}};var Od=/([\w\d_]+)(\])?(\[|\.)?/g;gb.prototype.setValue=function(a,b,c){b=this.map[b];void 0!==b&&b.setValue(a,c,this.renderer)};gb.prototype.setOptional=function(a,
16737 b,c){b=b[c];void 0!==b&&this.setValue(a,c,b)};gb.upload=function(a,b,c,d){for(var e=0,f=b.length;e!==f;++e){var g=b[e],h=c[g.id];!1!==h.needsUpdate&&g.setValue(a,h.value,d)}};gb.seqWithValue=function(a,b){for(var c=[],d=0,e=a.length;d!==e;++d){var f=a[d];f.id in b&&c.push(f)}return c};var sg={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,
16738 cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,
16739 deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,
16740 lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,
16741 mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,
16742 royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};Object.assign(H.prototype,{isColor:!0,r:1,g:1,b:1,set:function(a){a&&
16743 a.isColor?this.copy(a):"number"===typeof a?this.setHex(a):"string"===typeof a&&this.setStyle(a);return this},setScalar:function(a){this.b=this.g=this.r=a;return this},setHex:function(a){a=Math.floor(a);this.r=(a>>16&255)/255;this.g=(a>>8&255)/255;this.b=(a&255)/255;return this},setRGB:function(a,b,c){this.r=a;this.g=b;this.b=c;return this},setHSL:function(){function a(a,c,d){0>d&&(d+=1);1<d&&--d;return d<1/6?a+6*(c-a)*d:.5>d?c:d<2/3?a+6*(c-a)*(2/3-d):a}return function(b,c,d){b=R.euclideanModulo(b,
16744 1);c=R.clamp(c,0,1);d=R.clamp(d,0,1);0===c?this.r=this.g=this.b=d:(c=.5>=d?d*(1+c):d+c-d*c,d=2*d-c,this.r=a(d,c,b+1/3),this.g=a(d,c,b),this.b=a(d,c,b-1/3));return this}}(),setStyle:function(a){function b(b){void 0!==b&&1>parseFloat(b)&&console.warn("THREE.Color: Alpha component of "+a+" will be ignored.")}var c;if(c=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(a)){var d=c[2];switch(c[1]){case "rgb":case "rgba":if(c=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(255,
16745 parseInt(c[1],10))/255,this.g=Math.min(255,parseInt(c[2],10))/255,this.b=Math.min(255,parseInt(c[3],10))/255,b(c[5]),this;if(c=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(100,parseInt(c[1],10))/100,this.g=Math.min(100,parseInt(c[2],10))/100,this.b=Math.min(100,parseInt(c[3],10))/100,b(c[5]),this;break;case "hsl":case "hsla":if(c=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d)){var d=parseFloat(c[1])/360,
16746 e=parseInt(c[2],10)/100,f=parseInt(c[3],10)/100;b(c[5]);return this.setHSL(d,e,f)}}}else if(c=/^\#([A-Fa-f0-9]+)$/.exec(a)){c=c[1];d=c.length;if(3===d)return this.r=parseInt(c.charAt(0)+c.charAt(0),16)/255,this.g=parseInt(c.charAt(1)+c.charAt(1),16)/255,this.b=parseInt(c.charAt(2)+c.charAt(2),16)/255,this;if(6===d)return this.r=parseInt(c.charAt(0)+c.charAt(1),16)/255,this.g=parseInt(c.charAt(2)+c.charAt(3),16)/255,this.b=parseInt(c.charAt(4)+c.charAt(5),16)/255,this}a&&0<a.length&&(c=sg[a],void 0!==
16747 c?this.setHex(c):console.warn("THREE.Color: Unknown color "+a));return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(a){this.r=a.r;this.g=a.g;this.b=a.b;return this},copyGammaToLinear:function(a,b){void 0===b&&(b=2);this.r=Math.pow(a.r,b);this.g=Math.pow(a.g,b);this.b=Math.pow(a.b,b);return this},copyLinearToGamma:function(a,b){void 0===b&&(b=2);b=0<b?1/b:1;this.r=Math.pow(a.r,b);this.g=Math.pow(a.g,b);this.b=Math.pow(a.b,b);return this},convertGammaToLinear:function(){var a=
16748 this.r,b=this.g,c=this.b;this.r=a*a;this.g=b*b;this.b=c*c;return this},convertLinearToGamma:function(){this.r=Math.sqrt(this.r);this.g=Math.sqrt(this.g);this.b=Math.sqrt(this.b);return this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(a){a=a||{h:0,s:0,l:0};var b=this.r,c=this.g,d=this.b,e=Math.max(b,c,d),f=Math.min(b,c,d),g,h=(f+e)/2;if(f===e)f=g=0;else{var k=e-f,f=.5>=h?k/(e+f):
16749 k/(2-e-f);switch(e){case b:g=(c-d)/k+(c<d?6:0);break;case c:g=(d-b)/k+2;break;case d:g=(b-c)/k+4}g/=6}a.h=g;a.s=f;a.l=h;return a},getStyle:function(){return"rgb("+(255*this.r|0)+","+(255*this.g|0)+","+(255*this.b|0)+")"},offsetHSL:function(a,b,c){var d=this.getHSL();d.h+=a;d.s+=b;d.l+=c;this.setHSL(d.h,d.s,d.l);return this},add:function(a){this.r+=a.r;this.g+=a.g;this.b+=a.b;return this},addColors:function(a,b){this.r=a.r+b.r;this.g=a.g+b.g;this.b=a.b+b.b;return this},addScalar:function(a){this.r+=
16750 a;this.g+=a;this.b+=a;return this},sub:function(a){this.r=Math.max(0,this.r-a.r);this.g=Math.max(0,this.g-a.g);this.b=Math.max(0,this.b-a.b);return this},multiply:function(a){this.r*=a.r;this.g*=a.g;this.b*=a.b;return this},multiplyScalar:function(a){this.r*=a;this.g*=a;this.b*=a;return this},lerp:function(a,b){this.r+=(a.r-this.r)*b;this.g+=(a.g-this.g)*b;this.b+=(a.b-this.b)*b;return this},equals:function(a){return a.r===this.r&&a.g===this.g&&a.b===this.b},fromArray:function(a,b){void 0===b&&(b=
16751 0);this.r=a[b];this.g=a[b+1];this.b=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.r;a[b+1]=this.g;a[b+2]=this.b;return a},toJSON:function(){return this.getHex()}});var E={common:{diffuse:{value:new H(15658734)},opacity:{value:1},map:{value:null},uvTransform:{value:new ra},alphaMap:{value:null}},specularmap:{specularMap:{value:null}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},
16752 aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new C(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:2.5E-4},fogNear:{value:1},
16753 fogFar:{value:2E3},fogColor:{value:new H(16777215)}},lights:{ambientLightColor:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},
16754 pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}}},points:{diffuse:{value:new H(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},uvTransform:{value:new ra}}},
16755 Ea={merge:function(a){for(var b={},c=0;c<a.length;c++){var d=this.clone(a[c]),e;for(e in d)b[e]=d[e]}return b},clone:function(a){var b={},c;for(c in a){b[c]={};for(var d in a[c]){var e=a[c][d];e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture)?b[c][d]=e.clone():Array.isArray(e)?b[c][d]=e.slice():b[c][d]=e}}return b}},W={alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n",
16756 alphatest_fragment:"#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n",
16757 aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",begin_vertex:"\nvec3 transformed = vec3( position );\n",beginnormal_vertex:"\nvec3 objectNormal = vec3( normal );\n",bsdfs:"float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.86267 + (0.49788 + 0.01436 * y ) * y;\n\tfloat b = 3.45068 + (4.18814 + y) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt( 1.0 - x * x ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tvec3 result = vec3( LTC_ClippedSphereFormFactor( vectorFormFactor ) );\n\treturn result;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n",
16758 bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n",
16759 clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n",
16760 clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n",
16761 color_fragment:"#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n",color_pars_vertex:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif",color_vertex:"#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif",common:"#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\n",
16762 cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n",
16763 defaultnormal_vertex:"vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n",
16764 emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n",encodings_fragment:" gl_FragColor = linearToOutputTexel( gl_FragColor );\n",encodings_pars_fragment:"\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n\tXp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract(Le);\n\tvResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n",
16765 envmap_fragment:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n",
16766 envmap_pars_fragment:"#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n",
16767 envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n",envmap_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n",
16768 fog_vertex:"\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n varying float fogDepth;\n#endif\n",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif\n",
16769 gradientmap_pars_fragment:"#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif\n",lightmap_fragment:"#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n",
16770 lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_vertex:"vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n",
16771 lights_pars:"uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n",
16772 lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n",lights_phong_pars_fragment:"varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n",
16773 lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n",
16774 lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tfloat norm = texture2D( ltcMag, uv ).a;\n\t\tvec4 t = texture2D( ltcMat, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( 1, 0, t.y ),\n\t\t\tvec3( 0, t.z, 0 ),\n\t\t\tvec3( t.w, 0, t.x )\n\t\t);\n\t\treflectedLight.directSpecular += lightColor * material.specularColor * norm * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n",
16775 lights_template:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n",
16776 logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\tgl_Position.z *= gl_Position.w;\n\t#endif\n#endif\n",
16777 map_fragment:"#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n",map_particle_fragment:"#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n",map_particle_pars_fragment:"#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif\n",
16778 metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n",
16779 morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n",
16780 normal_fragment:"#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n",
16781 normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n",
16782 packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n",
16783 premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n",project_vertex:"vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n",dithering_fragment:"#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n",dithering_pars_fragment:"#if defined( DITHERING )\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif\n",
16784 roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n",
16785 shadowmap_pars_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n",
16786 shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n",
16787 shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n",
16788 skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n",
16789 skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif\n",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n",
16790 specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n",tonemapping_pars_fragment:"#ifndef saturate\n\t#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n",
16791 uv_pars_fragment:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\n",
16792 uv_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif",
16793 uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n",
16794 cube_vert:"varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}\n",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n",
16795 depth_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n",
16796 distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}\n",
16797 distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}\n",
16798 equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n",equirect_vert:"varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n",
16799 linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
16800 linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}\n",
16801 meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
16802 meshbasic_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}\n",
16803 meshlambert_frag:"uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
16804 meshlambert_vert:"#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
16805 meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
16806 meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
16807 meshphysical_frag:"#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
16808 meshphysical_vert:"#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
16809 normal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n",
16810 normal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n",
16811 points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
16812 points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
16813 shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <fog_fragment>\n}\n",shadow_vert:"#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n"},
16814 mb={basic:{uniforms:Ea.merge([E.common,E.specularmap,E.envmap,E.aomap,E.lightmap,E.fog]),vertexShader:W.meshbasic_vert,fragmentShader:W.meshbasic_frag},lambert:{uniforms:Ea.merge([E.common,E.specularmap,E.envmap,E.aomap,E.lightmap,E.emissivemap,E.fog,E.lights,{emissive:{value:new H(0)}}]),vertexShader:W.meshlambert_vert,fragmentShader:W.meshlambert_frag},phong:{uniforms:Ea.merge([E.common,E.specularmap,E.envmap,E.aomap,E.lightmap,E.emissivemap,E.bumpmap,E.normalmap,E.displacementmap,E.gradientmap,
16815 E.fog,E.lights,{emissive:{value:new H(0)},specular:{value:new H(1118481)},shininess:{value:30}}]),vertexShader:W.meshphong_vert,fragmentShader:W.meshphong_frag},standard:{uniforms:Ea.merge([E.common,E.envmap,E.aomap,E.lightmap,E.emissivemap,E.bumpmap,E.normalmap,E.displacementmap,E.roughnessmap,E.metalnessmap,E.fog,E.lights,{emissive:{value:new H(0)},roughness:{value:.5},metalness:{value:.5},envMapIntensity:{value:1}}]),vertexShader:W.meshphysical_vert,fragmentShader:W.meshphysical_frag},points:{uniforms:Ea.merge([E.points,
16816 E.fog]),vertexShader:W.points_vert,fragmentShader:W.points_frag},dashed:{uniforms:Ea.merge([E.common,E.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:W.linedashed_vert,fragmentShader:W.linedashed_frag},depth:{uniforms:Ea.merge([E.common,E.displacementmap]),vertexShader:W.depth_vert,fragmentShader:W.depth_frag},normal:{uniforms:Ea.merge([E.common,E.bumpmap,E.normalmap,E.displacementmap,{opacity:{value:1}}]),vertexShader:W.normal_vert,fragmentShader:W.normal_frag},cube:{uniforms:{tCube:{value:null},
16817 tFlip:{value:-1},opacity:{value:1}},vertexShader:W.cube_vert,fragmentShader:W.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:W.equirect_vert,fragmentShader:W.equirect_frag},distanceRGBA:{uniforms:Ea.merge([E.common,E.displacementmap,{referencePosition:{value:new p},nearDistance:{value:1},farDistance:{value:1E3}}]),vertexShader:W.distanceRGBA_vert,fragmentShader:W.distanceRGBA_frag},shadow:{uniforms:Ea.merge([E.lights,E.fog,{color:{value:new H(0)},opacity:{value:1}}]),vertexShader:W.shadow_vert,
16818 fragmentShader:W.shadow_frag}};mb.physical={uniforms:Ea.merge([mb.standard.uniforms,{clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:W.meshphysical_vert,fragmentShader:W.meshphysical_frag};Object.assign(kd.prototype,{set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new C;return function(b,c){c=a.copy(c).multiplyScalar(.5);
16819 this.min.copy(b).sub(c);this.max.copy(b).add(c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},makeEmpty:function(){this.min.x=this.min.y=Infinity;this.max.x=this.max.y=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y},getCenter:function(a){a=a||new C;return this.isEmpty()?a.set(0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=
16820 a||new C;return this.isEmpty()?a.set(0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=
16821 this.max.y},getParameter:function(a,b){return(b||new C).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(a){return a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y?!1:!0},clampPoint:function(a,b){return(b||new C).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new C;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);
16822 this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});tc.prototype=Object.create(ea.prototype);tc.prototype.constructor=tc;var Lf=0;Object.assign(Q.prototype,ja.prototype,{isMaterial:!0,onBeforeCompile:function(){},setValues:function(a){if(void 0!==a)for(var b in a){var c=a[b];if(void 0===c)console.warn("THREE.Material: '"+
16823 b+"' parameter is undefined.");else if("shading"===b)console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=1===c?!0:!1;else{var d=this[b];void 0===d?console.warn("THREE."+this.type+": '"+b+"' is not a property of this material."):d&&d.isColor?d.set(c):d&&d.isVector3&&c&&c.isVector3?d.copy(c):this[b]="overdraw"===b?Number(c):c}}},toJSON:function(a){function b(a){var b=[],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var c=
16824 void 0===a||"string"===typeof a;c&&(a={textures:{},images:{}});var d={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};d.uuid=this.uuid;d.type=this.type;""!==this.name&&(d.name=this.name);this.color&&this.color.isColor&&(d.color=this.color.getHex());void 0!==this.roughness&&(d.roughness=this.roughness);void 0!==this.metalness&&(d.metalness=this.metalness);this.emissive&&this.emissive.isColor&&(d.emissive=this.emissive.getHex());1!==this.emissiveIntensity&&(d.emissiveIntensity=this.emissiveIntensity);
16825 this.specular&&this.specular.isColor&&(d.specular=this.specular.getHex());void 0!==this.shininess&&(d.shininess=this.shininess);void 0!==this.clearCoat&&(d.clearCoat=this.clearCoat);void 0!==this.clearCoatRoughness&&(d.clearCoatRoughness=this.clearCoatRoughness);this.map&&this.map.isTexture&&(d.map=this.map.toJSON(a).uuid);this.alphaMap&&this.alphaMap.isTexture&&(d.alphaMap=this.alphaMap.toJSON(a).uuid);this.lightMap&&this.lightMap.isTexture&&(d.lightMap=this.lightMap.toJSON(a).uuid);this.bumpMap&&
16826 this.bumpMap.isTexture&&(d.bumpMap=this.bumpMap.toJSON(a).uuid,d.bumpScale=this.bumpScale);this.normalMap&&this.normalMap.isTexture&&(d.normalMap=this.normalMap.toJSON(a).uuid,d.normalScale=this.normalScale.toArray());this.displacementMap&&this.displacementMap.isTexture&&(d.displacementMap=this.displacementMap.toJSON(a).uuid,d.displacementScale=this.displacementScale,d.displacementBias=this.displacementBias);this.roughnessMap&&this.roughnessMap.isTexture&&(d.roughnessMap=this.roughnessMap.toJSON(a).uuid);
16827 this.metalnessMap&&this.metalnessMap.isTexture&&(d.metalnessMap=this.metalnessMap.toJSON(a).uuid);this.emissiveMap&&this.emissiveMap.isTexture&&(d.emissiveMap=this.emissiveMap.toJSON(a).uuid);this.specularMap&&this.specularMap.isTexture&&(d.specularMap=this.specularMap.toJSON(a).uuid);this.envMap&&this.envMap.isTexture&&(d.envMap=this.envMap.toJSON(a).uuid,d.reflectivity=this.reflectivity);this.gradientMap&&this.gradientMap.isTexture&&(d.gradientMap=this.gradientMap.toJSON(a).uuid);void 0!==this.size&&
16828 (d.size=this.size);void 0!==this.sizeAttenuation&&(d.sizeAttenuation=this.sizeAttenuation);1!==this.blending&&(d.blending=this.blending);!0===this.flatShading&&(d.flatShading=this.flatShading);0!==this.side&&(d.side=this.side);0!==this.vertexColors&&(d.vertexColors=this.vertexColors);1>this.opacity&&(d.opacity=this.opacity);!0===this.transparent&&(d.transparent=this.transparent);d.depthFunc=this.depthFunc;d.depthTest=this.depthTest;d.depthWrite=this.depthWrite;0!==this.rotation&&(d.rotation=this.rotation);
16829 1!==this.linewidth&&(d.linewidth=this.linewidth);void 0!==this.dashSize&&(d.dashSize=this.dashSize);void 0!==this.gapSize&&(d.gapSize=this.gapSize);void 0!==this.scale&&(d.scale=this.scale);!0===this.dithering&&(d.dithering=!0);0<this.alphaTest&&(d.alphaTest=this.alphaTest);!0===this.premultipliedAlpha&&(d.premultipliedAlpha=this.premultipliedAlpha);!0===this.wireframe&&(d.wireframe=this.wireframe);1<this.wireframeLinewidth&&(d.wireframeLinewidth=this.wireframeLinewidth);"round"!==this.wireframeLinecap&&
16830 (d.wireframeLinecap=this.wireframeLinecap);"round"!==this.wireframeLinejoin&&(d.wireframeLinejoin=this.wireframeLinejoin);!0===this.morphTargets&&(d.morphTargets=!0);!0===this.skinning&&(d.skinning=!0);!1===this.visible&&(d.visible=!1);"{}"!==JSON.stringify(this.userData)&&(d.userData=this.userData);c&&(c=b(a.textures),a=b(a.images),0<c.length&&(d.textures=c),0<a.length&&(d.images=a));return d},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.fog=a.fog;
16831 this.lights=a.lights;this.blending=a.blending;this.side=a.side;this.flatShading=a.flatShading;this.vertexColors=a.vertexColors;this.opacity=a.opacity;this.transparent=a.transparent;this.blendSrc=a.blendSrc;this.blendDst=a.blendDst;this.blendEquation=a.blendEquation;this.blendSrcAlpha=a.blendSrcAlpha;this.blendDstAlpha=a.blendDstAlpha;this.blendEquationAlpha=a.blendEquationAlpha;this.depthFunc=a.depthFunc;this.depthTest=a.depthTest;this.depthWrite=a.depthWrite;this.colorWrite=a.colorWrite;this.precision=
16832 a.precision;this.polygonOffset=a.polygonOffset;this.polygonOffsetFactor=a.polygonOffsetFactor;this.polygonOffsetUnits=a.polygonOffsetUnits;this.dithering=a.dithering;this.alphaTest=a.alphaTest;this.premultipliedAlpha=a.premultipliedAlpha;this.overdraw=a.overdraw;this.visible=a.visible;this.userData=JSON.parse(JSON.stringify(a.userData));this.clipShadows=a.clipShadows;this.clipIntersection=a.clipIntersection;a=a.clippingPlanes;var b=null;if(null!==a)for(var c=a.length,b=Array(c),d=0;d!==c;++d)b[d]=
16833 a[d].clone();this.clippingPlanes=b;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Wa.prototype=Object.create(Q.prototype);Wa.prototype.constructor=Wa;Wa.prototype.isMeshDepthMaterial=!0;Wa.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.depthPacking=a.depthPacking;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.map=a.map;this.alphaMap=a.alphaMap;this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=
16834 a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;return this};Xa.prototype=Object.create(Q.prototype);Xa.prototype.constructor=Xa;Xa.prototype.isMeshDistanceMaterial=!0;Xa.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.referencePosition.copy(a.referencePosition);this.nearDistance=a.nearDistance;this.farDistance=a.farDistance;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.map=a.map;this.alphaMap=a.alphaMap;this.displacementMap=
16835 a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;return this};Object.assign(Oa.prototype,{isBox3:!0,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromArray:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.length;h<k;h+=3){var l=a[h],q=a[h+1],n=a[h+2];l<b&&(b=l);q<c&&(c=q);n<d&&(d=n);l>e&&(e=l);q>f&&(f=q);n>g&&(g=n)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromBufferAttribute:function(a){for(var b=
16836 Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.count;h<k;h++){var l=a.getX(h),q=a.getY(h),n=a.getZ(h);l<b&&(b=l);q<c&&(c=q);n<d&&(d=n);l>e&&(e=l);q>f&&(f=q);n>g&&(g=n)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new p;return function(b,c){c=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(c);this.max.copy(b).add(c);
16837 return this}}(),setFromObject:function(a){this.makeEmpty();return this.expandByObject(a)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},makeEmpty:function(){this.min.x=this.min.y=this.min.z=Infinity;this.max.x=this.max.y=this.max.z=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z},getCenter:function(a){a=a||new p;return this.isEmpty()?a.set(0,0,0):
16838 a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=a||new p;return this.isEmpty()?a.set(0,0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},expandByObject:function(){function a(a){var f=a.geometry;if(void 0!==f)if(f.isGeometry)for(f=f.vertices,c=0,d=f.length;c<d;c++)e.copy(f[c]),
16839 e.applyMatrix4(a.matrixWorld),b.expandByPoint(e);else if(f.isBufferGeometry&&(f=f.attributes.position,void 0!==f))for(c=0,d=f.count;c<d;c++)e.fromBufferAttribute(f,c).applyMatrix4(a.matrixWorld),b.expandByPoint(e)}var b,c,d,e=new p;return function(c){b=this;c.updateMatrixWorld(!0);c.traverse(a);return this}}(),containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y||a.z<this.min.z||a.z>this.max.z?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=
16840 this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y&&this.min.z<=a.min.z&&a.max.z<=this.max.z},getParameter:function(a,b){return(b||new p).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y),(a.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(a){return a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y||a.max.z<this.min.z||a.min.z>this.max.z?!1:!0},intersectsSphere:function(){var a=new p;return function(b){this.clampPoint(b.center,
16841 a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){if(0<a.normal.x){var b=a.normal.x*this.min.x;var c=a.normal.x*this.max.x}else b=a.normal.x*this.max.x,c=a.normal.x*this.min.x;0<a.normal.y?(b+=a.normal.y*this.min.y,c+=a.normal.y*this.max.y):(b+=a.normal.y*this.max.y,c+=a.normal.y*this.min.y);0<a.normal.z?(b+=a.normal.z*this.min.z,c+=a.normal.z*this.max.z):(b+=a.normal.z*this.max.z,c+=a.normal.z*this.min.z);return b<=a.constant&&c>=a.constant},clampPoint:function(a,
16842 b){return(b||new p).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new p;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),getBoundingSphere:function(){var a=new p;return function(b){b=b||new Da;this.getCenter(b.center);b.radius=.5*this.getSize(a).length();return b}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);this.isEmpty()&&this.makeEmpty();return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},applyMatrix4:function(){var a=
16843 [new p,new p,new p,new p,new p,new p,new p,new p];return function(b){if(this.isEmpty())return this;a[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(b);a[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(b);a[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(b);a[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(b);a[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(b);a[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(b);a[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(b);
16844 a[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(b);this.setFromPoints(a);return this}}(),translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});Object.assign(Da.prototype,{set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a=new Oa;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).getCenter(d);for(var e=c=0,f=b.length;e<f;e++)c=Math.max(c,
16845 d.distanceToSquared(b[e]));this.radius=Math.sqrt(c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.center.copy(a.center);this.radius=a.radius;return this},empty:function(){return 0>=this.radius},containsPoint:function(a){return a.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(a){return a.distanceTo(this.center)-this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;return a.center.distanceToSquared(this.center)<=
16846 b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(a.distanceToPoint(this.center))<=this.radius},clampPoint:function(a,b){var c=this.center.distanceToSquared(a);b=b||new p;b.copy(a);c>this.radius*this.radius&&(b.sub(this.center).normalize(),b.multiplyScalar(this.radius).add(this.center));return b},getBoundingBox:function(a){a=a||new Oa;a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a);
16847 this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&&a.radius===this.radius}});Object.assign(Aa.prototype,{set:function(a,b){this.normal.copy(a);this.constant=b;return this},setComponents:function(a,b,c,d){this.normal.set(a,b,c);this.constant=d;return this},setFromNormalAndCoplanarPoint:function(a,b){this.normal.copy(a);this.constant=-b.dot(this.normal);return this},setFromCoplanarPoints:function(){var a=
16848 new p,b=new p;return function(c,d,e){d=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();this.setFromNormalAndCoplanarPoint(d,c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.normal.copy(a.normal);this.constant=a.constant;return this},normalize:function(){var a=1/this.normal.length();this.normal.multiplyScalar(a);this.constant*=a;return this},negate:function(){this.constant*=-1;this.normal.negate();return this},distanceToPoint:function(a){return this.normal.dot(a)+
16849 this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a,b){return(b||new p).copy(this.normal).multiplyScalar(-this.distanceToPoint(a)).add(a)},intersectLine:function(){var a=new p;return function(b,c){c=c||new p;var d=b.delta(a),e=this.normal.dot(d);if(0===e){if(0===this.distanceToPoint(b.start))return c.copy(b.start)}else if(e=-(b.start.dot(this.normal)+this.constant)/e,!(0>e||1<e))return c.copy(d).multiplyScalar(e).add(b.start)}}(),intersectsLine:function(a){var b=
16850 this.distanceToPoint(a.start);a=this.distanceToPoint(a.end);return 0>b&&0<a||0>a&&0<b},intersectsBox:function(a){return a.intersectsPlane(this)},intersectsSphere:function(a){return a.intersectsPlane(this)},coplanarPoint:function(a){return(a||new p).copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var a=new p,b=new ra;return function(c,d){d=d||b.getNormalMatrix(c);c=this.coplanarPoint(a).applyMatrix4(c);d=this.normal.applyMatrix3(d).normalize();this.constant=-c.dot(d);return this}}(),
16851 translate:function(a){this.constant-=a.dot(this.normal);return this},equals:function(a){return a.normal.equals(this.normal)&&a.constant===this.constant}});Object.assign(ld.prototype,{set:function(a,b,c,d,e,f){var g=this.planes;g[0].copy(a);g[1].copy(b);g[2].copy(c);g[3].copy(d);g[4].copy(e);g[5].copy(f);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){for(var b=this.planes,c=0;6>c;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes,
16852 c=a.elements;a=c[0];var d=c[1],e=c[2],f=c[3],g=c[4],h=c[5],k=c[6],l=c[7],q=c[8],n=c[9],m=c[10],r=c[11],p=c[12],v=c[13],w=c[14],c=c[15];b[0].setComponents(f-a,l-g,r-q,c-p).normalize();b[1].setComponents(f+a,l+g,r+q,c+p).normalize();b[2].setComponents(f+d,l+h,r+n,c+v).normalize();b[3].setComponents(f-d,l-h,r-n,c-v).normalize();b[4].setComponents(f-e,l-k,r-m,c-w).normalize();b[5].setComponents(f+e,l+k,r+m,c+w).normalize();return this},intersectsObject:function(){var a=new Da;return function(b){var c=
16853 b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSprite:function(){var a=new Da;return function(b){a.center.set(0,0,0);a.radius=.7071067811865476;a.applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSphere:function(a){var b=this.planes,c=a.center;a=-a.radius;for(var d=0;6>d;d++)if(b[d].distanceToPoint(c)<a)return!1;return!0},intersectsBox:function(){var a=new p,b=
16854 new p;return function(c){for(var d=this.planes,e=0;6>e;e++){var f=d[e];a.x=0<f.normal.x?c.min.x:c.max.x;b.x=0<f.normal.x?c.max.x:c.min.x;a.y=0<f.normal.y?c.min.y:c.max.y;b.y=0<f.normal.y?c.max.y:c.min.y;a.z=0<f.normal.z?c.min.z:c.max.z;b.z=0<f.normal.z?c.max.z:c.min.z;var g=f.distanceToPoint(a),f=f.distanceToPoint(b);if(0>g&&0>f)return!1}return!0}}(),containsPoint:function(a){for(var b=this.planes,c=0;6>c;c++)if(0>b[c].distanceToPoint(a))return!1;return!0}});Ya.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" ");
16855 Ya.DefaultOrder="XYZ";Object.defineProperties(Ya.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},order:{get:function(){return this._order},set:function(a){this._order=a;this.onChangeCallback()}}});Object.assign(Ya.prototype,{isEuler:!0,set:function(a,b,c,d){this._x=a;this._y=b;this._z=
16856 c;this._order=d||this._order;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._order)},copy:function(a){this._x=a._x;this._y=a._y;this._z=a._z;this._order=a._order;this.onChangeCallback();return this},setFromRotationMatrix:function(a,b,c){var d=R.clamp,e=a.elements;a=e[0];var f=e[4],g=e[8],h=e[1],k=e[5],l=e[9],q=e[2],n=e[6],e=e[10];b=b||this._order;"XYZ"===b?(this._y=Math.asin(d(g,-1,1)),.99999>Math.abs(g)?(this._x=Math.atan2(-l,e),this._z=
16857 Math.atan2(-f,a)):(this._x=Math.atan2(n,k),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(l,-1,1)),.99999>Math.abs(l)?(this._y=Math.atan2(g,e),this._z=Math.atan2(h,k)):(this._y=Math.atan2(-q,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(n,-1,1)),.99999>Math.abs(n)?(this._y=Math.atan2(-q,e),this._z=Math.atan2(-f,k)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(q,-1,1)),.99999>Math.abs(q)?(this._x=Math.atan2(n,e),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-f,k))):"YZX"===
16858 b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-l,k),this._y=Math.atan2(-q,a)):(this._x=0,this._y=Math.atan2(g,e))):"XZY"===b?(this._z=Math.asin(-d(f,-1,1)),.99999>Math.abs(f)?(this._x=Math.atan2(n,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-l,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order=b;if(!1!==c)this.onChangeCallback();return this},setFromQuaternion:function(){var a=new K;return function(b,c,d){a.makeRotationFromQuaternion(b);
16859 return this.setFromRotationMatrix(a,c,d)}}(),setFromVector3:function(a,b){return this.set(a.x,a.y,a.z,b||this._order)},reorder:function(){var a=new Z;return function(b){a.setFromEuler(this);return this.setFromQuaternion(a,b)}}(),equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._order===this._order},fromArray:function(a){this._x=a[0];this._y=a[1];this._z=a[2];void 0!==a[3]&&(this._order=a[3]);this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===
16860 b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._order;return a},toVector3:function(a){return a?a.set(this._x,this._y,this._z):new p(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(Pd.prototype,{set:function(a){this.mask=1<<a|0},enable:function(a){this.mask=this.mask|1<<a|0},toggle:function(a){this.mask^=1<<a|0},disable:function(a){this.mask&=~(1<<a|0)},test:function(a){return 0!==(this.mask&a.mask)}});
16861 var Nf=0;A.DefaultUp=new p(0,1,0);A.DefaultMatrixAutoUpdate=!0;Object.assign(A.prototype,ja.prototype,{isObject3D:!0,onBeforeRender:function(){},onAfterRender:function(){},applyMatrix:function(a){this.matrix.multiplyMatrices(a,this.matrix);this.matrix.decompose(this.position,this.quaternion,this.scale)},applyQuaternion:function(a){this.quaternion.premultiply(a);return this},setRotationFromAxisAngle:function(a,b){this.quaternion.setFromAxisAngle(a,b)},setRotationFromEuler:function(a){this.quaternion.setFromEuler(a,
16862 !0)},setRotationFromMatrix:function(a){this.quaternion.setFromRotationMatrix(a)},setRotationFromQuaternion:function(a){this.quaternion.copy(a)},rotateOnAxis:function(){var a=new Z;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.multiply(a);return this}}(),rotateOnWorldAxis:function(){var a=new Z;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.premultiply(a);return this}}(),rotateX:function(){var a=new p(1,0,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateY:function(){var a=
16863 new p(0,1,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateZ:function(){var a=new p(0,0,1);return function(b){return this.rotateOnAxis(a,b)}}(),translateOnAxis:function(){var a=new p;return function(b,c){a.copy(b).applyQuaternion(this.quaternion);this.position.add(a.multiplyScalar(c));return this}}(),translateX:function(){var a=new p(1,0,0);return function(b){return this.translateOnAxis(a,b)}}(),translateY:function(){var a=new p(0,1,0);return function(b){return this.translateOnAxis(a,
16864 b)}}(),translateZ:function(){var a=new p(0,0,1);return function(b){return this.translateOnAxis(a,b)}}(),localToWorld:function(a){return a.applyMatrix4(this.matrixWorld)},worldToLocal:function(){var a=new K;return function(b){return b.applyMatrix4(a.getInverse(this.matrixWorld))}}(),lookAt:function(){var a=new K,b=new p;return function(c,d,e){c.isVector3?b.copy(c):b.set(c,d,e);this.isCamera?a.lookAt(this.position,b,this.up):a.lookAt(b,this.position,this.up);this.quaternion.setFromRotationMatrix(a)}}(),
16865 add:function(a){if(1<arguments.length){for(var b=0;b<arguments.length;b++)this.add(arguments[b]);return this}if(a===this)return console.error("THREE.Object3D.add: object can't be added as a child of itself.",a),this;a&&a.isObject3D?(null!==a.parent&&a.parent.remove(a),a.parent=this,a.dispatchEvent({type:"added"}),this.children.push(a)):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",a);return this},remove:function(a){if(1<arguments.length){for(var b=0;b<arguments.length;b++)this.remove(arguments[b]);
16866 return this}b=this.children.indexOf(a);-1!==b&&(a.parent=null,a.dispatchEvent({type:"removed"}),this.children.splice(b,1));return this},getObjectById:function(a){return this.getObjectByProperty("id",a)},getObjectByName:function(a){return this.getObjectByProperty("name",a)},getObjectByProperty:function(a,b){if(this[a]===b)return this;for(var c=0,d=this.children.length;c<d;c++){var e=this.children[c].getObjectByProperty(a,b);if(void 0!==e)return e}},getWorldPosition:function(a){a=a||new p;this.updateMatrixWorld(!0);
16867 return a.setFromMatrixPosition(this.matrixWorld)},getWorldQuaternion:function(){var a=new p,b=new p;return function(c){c=c||new Z;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,c,b);return c}}(),getWorldRotation:function(){var a=new Z;return function(b){b=b||new Ya;this.getWorldQuaternion(a);return b.setFromQuaternion(a,this.rotation.order,!1)}}(),getWorldScale:function(){var a=new p,b=new Z;return function(c){c=c||new p;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,b,c);return c}}(),
16868 getWorldDirection:function(){var a=new Z;return function(b){b=b||new p;this.getWorldQuaternion(a);return b.set(0,0,1).applyQuaternion(a)}}(),raycast:function(){},traverse:function(a){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverse(a)},traverseVisible:function(a){if(!1!==this.visible){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverseVisible(a)}},traverseAncestors:function(a){var b=this.parent;null!==b&&(a(b),b.traverseAncestors(a))},updateMatrix:function(){this.matrix.compose(this.position,
16869 this.quaternion,this.scale);this.matrixWorldNeedsUpdate=!0},updateMatrixWorld:function(a){this.matrixAutoUpdate&&this.updateMatrix();if(this.matrixWorldNeedsUpdate||a)null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,a=!0;for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].updateMatrixWorld(a)},toJSON:function(a){function b(b,c){void 0===b[c.uuid]&&(b[c.uuid]=c.toJSON(a));return c.uuid}function c(a){var b=
16870 [],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var d=void 0===a||"string"===typeof a,e={};d&&(a={geometries:{},materials:{},textures:{},images:{}},e.metadata={version:4.5,type:"Object",generator:"Object3D.toJSON"});var f={};f.uuid=this.uuid;f.type=this.type;""!==this.name&&(f.name=this.name);!0===this.castShadow&&(f.castShadow=!0);!0===this.receiveShadow&&(f.receiveShadow=!0);!1===this.visible&&(f.visible=!1);"{}"!==JSON.stringify(this.userData)&&(f.userData=this.userData);f.matrix=
16871 this.matrix.toArray();void 0!==this.geometry&&(f.geometry=b(a.geometries,this.geometry));if(void 0!==this.material)if(Array.isArray(this.material)){for(var g=[],h=0,k=this.material.length;h<k;h++)g.push(b(a.materials,this.material[h]));f.material=g}else f.material=b(a.materials,this.material);if(0<this.children.length)for(f.children=[],h=0;h<this.children.length;h++)f.children.push(this.children[h].toJSON(a).object);d&&(d=c(a.geometries),g=c(a.materials),h=c(a.textures),k=c(a.images),0<d.length&&
16872 (e.geometries=d),0<g.length&&(e.materials=g),0<h.length&&(e.textures=h),0<k.length&&(e.images=k));e.object=f;return e},clone:function(a){return(new this.constructor).copy(this,a)},copy:function(a,b){void 0===b&&(b=!0);this.name=a.name;this.up.copy(a.up);this.position.copy(a.position);this.quaternion.copy(a.quaternion);this.scale.copy(a.scale);this.matrix.copy(a.matrix);this.matrixWorld.copy(a.matrixWorld);this.matrixAutoUpdate=a.matrixAutoUpdate;this.matrixWorldNeedsUpdate=a.matrixWorldNeedsUpdate;
16873 this.layers.mask=a.layers.mask;this.visible=a.visible;this.castShadow=a.castShadow;this.receiveShadow=a.receiveShadow;this.frustumCulled=a.frustumCulled;this.renderOrder=a.renderOrder;this.userData=JSON.parse(JSON.stringify(a.userData));if(!0===b)for(b=0;b<a.children.length;b++)this.add(a.children[b].clone());return this}});La.prototype=Object.assign(Object.create(A.prototype),{constructor:La,isCamera:!0,copy:function(a,b){A.prototype.copy.call(this,a,b);this.matrixWorldInverse.copy(a.matrixWorldInverse);
16874 this.projectionMatrix.copy(a.projectionMatrix);return this},getWorldDirection:function(){var a=new Z;return function(b){b=b||new p;this.getWorldQuaternion(a);return b.set(0,0,-1).applyQuaternion(a)}}(),updateMatrixWorld:function(a){A.prototype.updateMatrixWorld.call(this,a);this.matrixWorldInverse.getInverse(this.matrixWorld)},clone:function(){return(new this.constructor).copy(this)}});Kb.prototype=Object.assign(Object.create(La.prototype),{constructor:Kb,isOrthographicCamera:!0,copy:function(a,b){La.prototype.copy.call(this,
16875 a,b);this.left=a.left;this.right=a.right;this.top=a.top;this.bottom=a.bottom;this.near=a.near;this.far=a.far;this.zoom=a.zoom;this.view=null===a.view?null:Object.assign({},a.view);return this},setViewOffset:function(a,b,c,d,e,f){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1});this.view.enabled=!0;this.view.fullWidth=a;this.view.fullHeight=b;this.view.offsetX=c;this.view.offsetY=d;this.view.width=e;this.view.height=f;this.updateProjectionMatrix()},
16876 clearViewOffset:function(){null!==this.view&&(this.view.enabled=!1);this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=(this.right-this.left)/(2*this.zoom),b=(this.top-this.bottom)/(2*this.zoom),c=(this.right+this.left)/2,d=(this.top+this.bottom)/2,e=c-a,c=c+a,a=d+b,b=d-b;if(null!==this.view&&this.view.enabled)var c=this.zoom/(this.view.width/this.view.fullWidth),b=this.zoom/(this.view.height/this.view.fullHeight),f=(this.right-this.left)/this.view.width,d=(this.top-this.bottom)/
16877 this.view.height,e=e+this.view.offsetX/c*f,c=e+this.view.width/c*f,a=a-this.view.offsetY/b*d,b=a-this.view.height/b*d;this.projectionMatrix.makeOrthographic(e,c,a,b,this.near,this.far)},toJSON:function(a){a=A.prototype.toJSON.call(this,a);a.object.zoom=this.zoom;a.object.left=this.left;a.object.right=this.right;a.object.top=this.top;a.object.bottom=this.bottom;a.object.near=this.near;a.object.far=this.far;null!==this.view&&(a.object.view=Object.assign({},this.view));return a}});Object.assign(Pa.prototype,
16878 {clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a=a.a;this.b=a.b;this.c=a.c;this.normal.copy(a.normal);this.color.copy(a.color);this.materialIndex=a.materialIndex;for(var b=0,c=a.vertexNormals.length;b<c;b++)this.vertexNormals[b]=a.vertexNormals[b].clone();b=0;for(c=a.vertexColors.length;b<c;b++)this.vertexColors[b]=a.vertexColors[b].clone();return this}});var Of=0;Object.assign(N.prototype,ja.prototype,{isGeometry:!0,applyMatrix:function(a){for(var b=(new ra).getNormalMatrix(a),
16879 c=0,d=this.vertices.length;c<d;c++)this.vertices[c].applyMatrix4(a);c=0;for(d=this.faces.length;c<d;c++){a=this.faces[c];a.normal.applyMatrix3(b).normalize();for(var e=0,f=a.vertexNormals.length;e<f;e++)a.vertexNormals[e].applyMatrix3(b).normalize()}null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();this.normalsNeedUpdate=this.verticesNeedUpdate=!0;return this},rotateX:function(){var a=new K;return function(b){a.makeRotationX(b);this.applyMatrix(a);
16880 return this}}(),rotateY:function(){var a=new K;return function(b){a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new K;return function(b){a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a=new K;return function(b,c,d){a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=new K;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new A;return function(b){a.lookAt(b);
16881 a.updateMatrix();this.applyMatrix(a.matrix)}}(),fromBufferGeometry:function(a){function b(a,b,d,e){var f=void 0!==g?[q[a].clone(),q[b].clone(),q[d].clone()]:[],t=void 0!==h?[c.colors[a].clone(),c.colors[b].clone(),c.colors[d].clone()]:[];e=new Pa(a,b,d,f,t,e);c.faces.push(e);void 0!==k&&c.faceVertexUvs[0].push([n[a].clone(),n[b].clone(),n[d].clone()]);void 0!==l&&c.faceVertexUvs[1].push([m[a].clone(),m[b].clone(),m[d].clone()])}var c=this,d=null!==a.index?a.index.array:void 0,e=a.attributes,f=e.position.array,
16882 g=void 0!==e.normal?e.normal.array:void 0,h=void 0!==e.color?e.color.array:void 0,k=void 0!==e.uv?e.uv.array:void 0,l=void 0!==e.uv2?e.uv2.array:void 0;void 0!==l&&(this.faceVertexUvs[1]=[]);for(var q=[],n=[],m=[],r=e=0;e<f.length;e+=3,r+=2)c.vertices.push(new p(f[e],f[e+1],f[e+2])),void 0!==g&&q.push(new p(g[e],g[e+1],g[e+2])),void 0!==h&&c.colors.push(new H(h[e],h[e+1],h[e+2])),void 0!==k&&n.push(new C(k[r],k[r+1])),void 0!==l&&m.push(new C(l[r],l[r+1]));var u=a.groups;if(0<u.length)for(e=0;e<u.length;e++)for(var f=
16883 u[e],v=f.start,w=f.count,r=v,v=v+w;r<v;r+=3)void 0!==d?b(d[r],d[r+1],d[r+2],f.materialIndex):b(r,r+1,r+2,f.materialIndex);else if(void 0!==d)for(e=0;e<d.length;e+=3)b(d[e],d[e+1],d[e+2]);else for(e=0;e<f.length/3;e+=3)b(e,e+1,e+2);this.computeFaceNormals();null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone());null!==a.boundingSphere&&(this.boundingSphere=a.boundingSphere.clone());return this},center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();this.translate(a.x,
16884 a.y,a.z);return a},normalize:function(){this.computeBoundingSphere();var a=this.boundingSphere.center,b=this.boundingSphere.radius,b=0===b?1:1/b,c=new K;c.set(b,0,0,-b*a.x,0,b,0,-b*a.y,0,0,b,-b*a.z,0,0,0,1);this.applyMatrix(c);return this},computeFaceNormals:function(){for(var a=new p,b=new p,c=0,d=this.faces.length;c<d;c++){var e=this.faces[c],f=this.vertices[e.a],g=this.vertices[e.b];a.subVectors(this.vertices[e.c],g);b.subVectors(f,g);a.cross(b);a.normalize();e.normal.copy(a)}},computeVertexNormals:function(a){void 0===
16885 a&&(a=!0);var b;var c=Array(this.vertices.length);var d=0;for(b=this.vertices.length;d<b;d++)c[d]=new p;if(a){var e=new p,f=new p;a=0;for(d=this.faces.length;a<d;a++){b=this.faces[a];var g=this.vertices[b.a];var h=this.vertices[b.b];var k=this.vertices[b.c];e.subVectors(k,h);f.subVectors(g,h);e.cross(f);c[b.a].add(e);c[b.b].add(e);c[b.c].add(e)}}else for(this.computeFaceNormals(),a=0,d=this.faces.length;a<d;a++)b=this.faces[a],c[b.a].add(b.normal),c[b.b].add(b.normal),c[b.c].add(b.normal);d=0;for(b=
16886 this.vertices.length;d<b;d++)c[d].normalize();a=0;for(d=this.faces.length;a<d;a++)b=this.faces[a],g=b.vertexNormals,3===g.length?(g[0].copy(c[b.a]),g[1].copy(c[b.b]),g[2].copy(c[b.c])):(g[0]=c[b.a].clone(),g[1]=c[b.b].clone(),g[2]=c[b.c].clone());0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeFlatVertexNormals:function(){var a;this.computeFaceNormals();var b=0;for(a=this.faces.length;b<a;b++){var c=this.faces[b];var d=c.vertexNormals;3===d.length?(d[0].copy(c.normal),d[1].copy(c.normal),
16887 d[2].copy(c.normal)):(d[0]=c.normal.clone(),d[1]=c.normal.clone(),d[2]=c.normal.clone())}0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var a,b;var c=0;for(b=this.faces.length;c<b;c++){var d=this.faces[c];d.__originalFaceNormal?d.__originalFaceNormal.copy(d.normal):d.__originalFaceNormal=d.normal.clone();d.__originalVertexNormals||(d.__originalVertexNormals=[]);var e=0;for(a=d.vertexNormals.length;e<a;e++)d.__originalVertexNormals[e]?d.__originalVertexNormals[e].copy(d.vertexNormals[e]):
16888 d.__originalVertexNormals[e]=d.vertexNormals[e].clone()}var f=new N;f.faces=this.faces;e=0;for(a=this.morphTargets.length;e<a;e++){if(!this.morphNormals[e]){this.morphNormals[e]={};this.morphNormals[e].faceNormals=[];this.morphNormals[e].vertexNormals=[];d=this.morphNormals[e].faceNormals;var g=this.morphNormals[e].vertexNormals;c=0;for(b=this.faces.length;c<b;c++){var h=new p;var k={a:new p,b:new p,c:new p};d.push(h);g.push(k)}}g=this.morphNormals[e];f.vertices=this.morphTargets[e].vertices;f.computeFaceNormals();
16889 f.computeVertexNormals();c=0;for(b=this.faces.length;c<b;c++)d=this.faces[c],h=g.faceNormals[c],k=g.vertexNormals[c],h.copy(d.normal),k.a.copy(d.vertexNormals[0]),k.b.copy(d.vertexNormals[1]),k.c.copy(d.vertexNormals[2])}c=0;for(b=this.faces.length;c<b;c++)d=this.faces[c],d.normal=d.__originalFaceNormal,d.vertexNormals=d.__originalVertexNormals},computeLineDistances:function(){for(var a=0,b=this.vertices,c=0,d=b.length;c<d;c++)0<c&&(a+=b[c].distanceTo(b[c-1])),this.lineDistances[c]=a},computeBoundingBox:function(){null===
16890 this.boundingBox&&(this.boundingBox=new Oa);this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new Da);this.boundingSphere.setFromPoints(this.vertices)},merge:function(a,b,c){if(a&&a.isGeometry){var d,e=this.vertices.length,f=this.vertices,g=a.vertices,h=this.faces,k=a.faces,l=this.faceVertexUvs[0],q=a.faceVertexUvs[0],n=this.colors,m=a.colors;void 0===c&&(c=0);void 0!==b&&(d=(new ra).getNormalMatrix(b));a=0;for(var r=g.length;a<
16891 r;a++){var p=g[a].clone();void 0!==b&&p.applyMatrix4(b);f.push(p)}a=0;for(r=m.length;a<r;a++)n.push(m[a].clone());a=0;for(r=k.length;a<r;a++){var g=k[a],v=g.vertexNormals,m=g.vertexColors,n=new Pa(g.a+e,g.b+e,g.c+e);n.normal.copy(g.normal);void 0!==d&&n.normal.applyMatrix3(d).normalize();b=0;for(f=v.length;b<f;b++)p=v[b].clone(),void 0!==d&&p.applyMatrix3(d).normalize(),n.vertexNormals.push(p);n.color.copy(g.color);b=0;for(f=m.length;b<f;b++)p=m[b],n.vertexColors.push(p.clone());n.materialIndex=g.materialIndex+
16892 c;h.push(n)}a=0;for(r=q.length;a<r;a++)if(c=q[a],d=[],void 0!==c){b=0;for(f=c.length;b<f;b++)d.push(c[b].clone());l.push(d)}}else console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",a)},mergeMesh:function(a){a&&a.isMesh?(a.matrixAutoUpdate&&a.updateMatrix(),this.merge(a.geometry,a.matrix)):console.error("THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.",a)},mergeVertices:function(){var a={},b=[],c=[],d=Math.pow(10,4),e;var f=0;for(e=this.vertices.length;f<
16893 e;f++){var g=this.vertices[f];g=Math.round(g.x*d)+"_"+Math.round(g.y*d)+"_"+Math.round(g.z*d);void 0===a[g]?(a[g]=f,b.push(this.vertices[f]),c[f]=b.length-1):c[f]=c[a[g]]}a=[];f=0;for(e=this.faces.length;f<e;f++)for(d=this.faces[f],d.a=c[d.a],d.b=c[d.b],d.c=c[d.c],d=[d.a,d.b,d.c],g=0;3>g;g++)if(d[g]===d[(g+1)%3]){a.push(f);break}for(f=a.length-1;0<=f;f--)for(d=a[f],this.faces.splice(d,1),c=0,e=this.faceVertexUvs.length;c<e;c++)this.faceVertexUvs[c].splice(d,1);f=this.vertices.length-b.length;this.vertices=
16894 b;return f},setFromPoints:function(a){this.vertices=[];for(var b=0,c=a.length;b<c;b++){var d=a[b];this.vertices.push(new p(d.x,d.y,d.z||0))}return this},sortFacesByMaterialIndex:function(){for(var a=this.faces,b=a.length,c=0;c<b;c++)a[c]._id=c;a.sort(function(a,b){return a.materialIndex-b.materialIndex});var d=this.faceVertexUvs[0],e=this.faceVertexUvs[1],f,g;d&&d.length===b&&(f=[]);e&&e.length===b&&(g=[]);for(c=0;c<b;c++){var h=a[c]._id;f&&f.push(d[h]);g&&g.push(e[h])}f&&(this.faceVertexUvs[0]=f);
16895 g&&(this.faceVertexUvs[1]=g)},toJSON:function(){function a(a,b,c){return c?a|1<<b:a&~(1<<b)}function b(a){var b=a.x.toString()+a.y.toString()+a.z.toString();if(void 0!==l[b])return l[b];l[b]=k.length/3;k.push(a.x,a.y,a.z);return l[b]}function c(a){var b=a.r.toString()+a.g.toString()+a.b.toString();if(void 0!==n[b])return n[b];n[b]=q.length;q.push(a.getHex());return n[b]}function d(a){var b=a.x.toString()+a.y.toString();if(void 0!==p[b])return p[b];p[b]=m.length/2;m.push(a.x,a.y);return p[b]}var e=
16896 {metadata:{version:4.5,type:"Geometry",generator:"Geometry.toJSON"}};e.uuid=this.uuid;e.type=this.type;""!==this.name&&(e.name=this.name);if(void 0!==this.parameters){var f=this.parameters,g;for(g in f)void 0!==f[g]&&(e[g]=f[g]);return e}f=[];for(g=0;g<this.vertices.length;g++){var h=this.vertices[g];f.push(h.x,h.y,h.z)}var h=[],k=[],l={},q=[],n={},m=[],p={};for(g=0;g<this.faces.length;g++){var u=this.faces[g],v=void 0!==this.faceVertexUvs[0][g],w=0<u.normal.length(),x=0<u.vertexNormals.length,z=
16897 1!==u.color.r||1!==u.color.g||1!==u.color.b,I=0<u.vertexColors.length,B=0,B=a(B,0,0),B=a(B,1,!0),B=a(B,2,!1),B=a(B,3,v),B=a(B,4,w),B=a(B,5,x),B=a(B,6,z),B=a(B,7,I);h.push(B);h.push(u.a,u.b,u.c);h.push(u.materialIndex);v&&(v=this.faceVertexUvs[0][g],h.push(d(v[0]),d(v[1]),d(v[2])));w&&h.push(b(u.normal));x&&(w=u.vertexNormals,h.push(b(w[0]),b(w[1]),b(w[2])));z&&h.push(c(u.color));I&&(u=u.vertexColors,h.push(c(u[0]),c(u[1]),c(u[2])))}e.data={};e.data.vertices=f;e.data.normals=k;0<q.length&&(e.data.colors=
16898 q);0<m.length&&(e.data.uvs=[m]);e.data.faces=h;return e},clone:function(){return(new N).copy(this)},copy:function(a){var b,c,d;this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingSphere=this.boundingBox=null;this.name=a.name;var e=a.vertices;var f=0;for(b=e.length;f<b;f++)this.vertices.push(e[f].clone());e=a.colors;f=0;for(b=e.length;f<b;f++)this.colors.push(e[f].clone());
16899 e=a.faces;f=0;for(b=e.length;f<b;f++)this.faces.push(e[f].clone());f=0;for(b=a.faceVertexUvs.length;f<b;f++){var g=a.faceVertexUvs[f];void 0===this.faceVertexUvs[f]&&(this.faceVertexUvs[f]=[]);e=0;for(c=g.length;e<c;e++){var h=g[e],k=[];var l=0;for(d=h.length;l<d;l++)k.push(h[l].clone());this.faceVertexUvs[f].push(k)}}l=a.morphTargets;f=0;for(b=l.length;f<b;f++){d={};d.name=l[f].name;if(void 0!==l[f].vertices)for(d.vertices=[],e=0,c=l[f].vertices.length;e<c;e++)d.vertices.push(l[f].vertices[e].clone());
16900 if(void 0!==l[f].normals)for(d.normals=[],e=0,c=l[f].normals.length;e<c;e++)d.normals.push(l[f].normals[e].clone());this.morphTargets.push(d)}l=a.morphNormals;f=0;for(b=l.length;f<b;f++){d={};if(void 0!==l[f].vertexNormals)for(d.vertexNormals=[],e=0,c=l[f].vertexNormals.length;e<c;e++)g=l[f].vertexNormals[e],h={},h.a=g.a.clone(),h.b=g.b.clone(),h.c=g.c.clone(),d.vertexNormals.push(h);if(void 0!==l[f].faceNormals)for(d.faceNormals=[],e=0,c=l[f].faceNormals.length;e<c;e++)d.faceNormals.push(l[f].faceNormals[e].clone());
16901 this.morphNormals.push(d)}e=a.skinWeights;f=0;for(b=e.length;f<b;f++)this.skinWeights.push(e[f].clone());e=a.skinIndices;f=0;for(b=e.length;f<b;f++)this.skinIndices.push(e[f].clone());e=a.lineDistances;f=0;for(b=e.length;f<b;f++)this.lineDistances.push(e[f]);f=a.boundingBox;null!==f&&(this.boundingBox=f.clone());f=a.boundingSphere;null!==f&&(this.boundingSphere=f.clone());this.elementsNeedUpdate=a.elementsNeedUpdate;this.verticesNeedUpdate=a.verticesNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.normalsNeedUpdate=
16902 a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.lineDistancesNeedUpdate=a.lineDistancesNeedUpdate;this.groupsNeedUpdate=a.groupsNeedUpdate;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Object.defineProperty(P.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(P.prototype,{isBufferAttribute:!0,setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==
16903 a?a.length/this.itemSize:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=new a.array.constructor(a.array);this.itemSize=a.itemSize;this.count=a.count;this.normalized=a.normalized;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.itemSize;c*=b.itemSize;for(var d=0,e=this.itemSize;d<e;d++)this.array[a+d]=b.array[c+d];return this},copyArray:function(a){this.array.set(a);return this},copyColorsArray:function(a){for(var b=this.array,c=0,d=
16904 0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",d),f=new H);b[c++]=f.r;b[c++]=f.g;b[c++]=f.b}return this},copyIndicesArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];b[c++]=f.a;b[c++]=f.b;b[c++]=f.c}return this},copyVector2sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector2sArray(): vector is undefined",d),f=new C);
16905 b[c++]=f.x;b[c++]=f.y}return this},copyVector3sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector3sArray(): vector is undefined",d),f=new p);b[c++]=f.x;b[c++]=f.y;b[c++]=f.z}return this},copyVector4sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector4sArray(): vector is undefined",d),f=new da);b[c++]=f.x;b[c++]=f.y;b[c++]=f.z;
16906 b[c++]=f.w}return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},getX:function(a){return this.array[a*this.itemSize]},setX:function(a,b){this.array[a*this.itemSize]=b;return this},getY:function(a){return this.array[a*this.itemSize+1]},setY:function(a,b){this.array[a*this.itemSize+1]=b;return this},getZ:function(a){return this.array[a*this.itemSize+2]},setZ:function(a,b){this.array[a*this.itemSize+2]=b;return this},getW:function(a){return this.array[a*this.itemSize+3]},
16907 setW:function(a,b){this.array[a*this.itemSize+3]=b;return this},setXY:function(a,b,c){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;return this},setXYZ:function(a,b,c,d){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;this.array[a+2]=d;return this},setXYZW:function(a,b,c,d,e){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;this.array[a+2]=d;this.array[a+3]=e;return this},onUpload:function(a){this.onUploadCallback=a;return this},clone:function(){return(new this.constructor(this.array,
16908 this.itemSize)).copy(this)}});uc.prototype=Object.create(P.prototype);uc.prototype.constructor=uc;vc.prototype=Object.create(P.prototype);vc.prototype.constructor=vc;wc.prototype=Object.create(P.prototype);wc.prototype.constructor=wc;xc.prototype=Object.create(P.prototype);xc.prototype.constructor=xc;hb.prototype=Object.create(P.prototype);hb.prototype.constructor=hb;yc.prototype=Object.create(P.prototype);yc.prototype.constructor=yc;ib.prototype=Object.create(P.prototype);ib.prototype.constructor=
16909 ib;y.prototype=Object.create(P.prototype);y.prototype.constructor=y;zc.prototype=Object.create(P.prototype);zc.prototype.constructor=zc;Object.assign(Je.prototype,{computeGroups:function(a){var b=[],c=void 0;a=a.faces;for(var d=0;d<a.length;d++){var e=a[d];if(e.materialIndex!==c){c=e.materialIndex;void 0!==f&&(f.count=3*d-f.start,b.push(f));var f={start:3*d,materialIndex:c}}}void 0!==f&&(f.count=3*d-f.start,b.push(f));this.groups=b},fromGeometry:function(a){var b=a.faces,c=a.vertices,d=a.faceVertexUvs,
16910 e=d[0]&&0<d[0].length,f=d[1]&&0<d[1].length,g=a.morphTargets,h=g.length;if(0<h){var k=[];for(var l=0;l<h;l++)k[l]=[];this.morphTargets.position=k}var q=a.morphNormals,n=q.length;if(0<n){var m=[];for(l=0;l<n;l++)m[l]=[];this.morphTargets.normal=m}for(var p=a.skinIndices,u=a.skinWeights,v=p.length===c.length,w=u.length===c.length,l=0;l<b.length;l++){var x=b[l];this.vertices.push(c[x.a],c[x.b],c[x.c]);var z=x.vertexNormals;3===z.length?this.normals.push(z[0],z[1],z[2]):(z=x.normal,this.normals.push(z,
16911 z,z));z=x.vertexColors;3===z.length?this.colors.push(z[0],z[1],z[2]):(z=x.color,this.colors.push(z,z,z));!0===e&&(z=d[0][l],void 0!==z?this.uvs.push(z[0],z[1],z[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ",l),this.uvs.push(new C,new C,new C)));!0===f&&(z=d[1][l],void 0!==z?this.uvs2.push(z[0],z[1],z[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ",l),this.uvs2.push(new C,new C,new C)));for(z=0;z<h;z++){var I=g[z].vertices;k[z].push(I[x.a],
16912 I[x.b],I[x.c])}for(z=0;z<n;z++)I=q[z].vertexNormals[l],m[z].push(I.a,I.b,I.c);v&&this.skinIndices.push(p[x.a],p[x.b],p[x.c]);w&&this.skinWeights.push(u[x.a],u[x.b],u[x.c])}this.computeGroups(a);this.verticesNeedUpdate=a.verticesNeedUpdate;this.normalsNeedUpdate=a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.groupsNeedUpdate=a.groupsNeedUpdate;return this}});var Pf=1;Object.assign(D.prototype,ja.prototype,{isBufferGeometry:!0,getIndex:function(){return this.index},
16913 setIndex:function(a){Array.isArray(a)?this.index=new (65535<Qd(a)?ib:hb)(a,1):this.index=a},addAttribute:function(a,b,c){if(b&&b.isBufferAttribute||b&&b.isInterleavedBufferAttribute)if("index"===a)console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),this.setIndex(b);else return this.attributes[a]=b,this;else console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),this.addAttribute(a,new P(b,c))},getAttribute:function(a){return this.attributes[a]},
16914 removeAttribute:function(a){delete this.attributes[a];return this},addGroup:function(a,b,c){this.groups.push({start:a,count:b,materialIndex:void 0!==c?c:0})},clearGroups:function(){this.groups=[]},setDrawRange:function(a,b){this.drawRange.start=a;this.drawRange.count=b},applyMatrix:function(a){var b=this.attributes.position;void 0!==b&&(a.applyToBufferAttribute(b),b.needsUpdate=!0);b=this.attributes.normal;void 0!==b&&((new ra).getNormalMatrix(a).applyToBufferAttribute(b),b.needsUpdate=!0);null!==
16915 this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();return this},rotateX:function(){var a=new K;return function(b){a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a=new K;return function(b){a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new K;return function(b){a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a=new K;return function(b,c,d){a.makeTranslation(b,
16916 c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=new K;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new A;return function(b){a.lookAt(b);a.updateMatrix();this.applyMatrix(a.matrix)}}(),center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();this.translate(a.x,a.y,a.z);return a},setFromObject:function(a){var b=a.geometry;if(a.isPoints||a.isLine){a=new y(3*b.vertices.length,3);var c=new y(3*b.colors.length,
16917 3);this.addAttribute("position",a.copyVector3sArray(b.vertices));this.addAttribute("color",c.copyColorsArray(b.colors));b.lineDistances&&b.lineDistances.length===b.vertices.length&&(a=new y(b.lineDistances.length,1),this.addAttribute("lineDistance",a.copyArray(b.lineDistances)));null!==b.boundingSphere&&(this.boundingSphere=b.boundingSphere.clone());null!==b.boundingBox&&(this.boundingBox=b.boundingBox.clone())}else a.isMesh&&b&&b.isGeometry&&this.fromGeometry(b);return this},setFromPoints:function(a){for(var b=
16918 [],c=0,d=a.length;c<d;c++){var e=a[c];b.push(e.x,e.y,e.z||0)}this.addAttribute("position",new y(b,3));return this},updateFromObject:function(a){var b=a.geometry;if(a.isMesh){var c=b.__directGeometry;!0===b.elementsNeedUpdate&&(c=void 0,b.elementsNeedUpdate=!1);if(void 0===c)return this.fromGeometry(b);c.verticesNeedUpdate=b.verticesNeedUpdate;c.normalsNeedUpdate=b.normalsNeedUpdate;c.colorsNeedUpdate=b.colorsNeedUpdate;c.uvsNeedUpdate=b.uvsNeedUpdate;c.groupsNeedUpdate=b.groupsNeedUpdate;b.verticesNeedUpdate=
16919 !1;b.normalsNeedUpdate=!1;b.colorsNeedUpdate=!1;b.uvsNeedUpdate=!1;b.groupsNeedUpdate=!1;b=c}!0===b.verticesNeedUpdate&&(c=this.attributes.position,void 0!==c&&(c.copyVector3sArray(b.vertices),c.needsUpdate=!0),b.verticesNeedUpdate=!1);!0===b.normalsNeedUpdate&&(c=this.attributes.normal,void 0!==c&&(c.copyVector3sArray(b.normals),c.needsUpdate=!0),b.normalsNeedUpdate=!1);!0===b.colorsNeedUpdate&&(c=this.attributes.color,void 0!==c&&(c.copyColorsArray(b.colors),c.needsUpdate=!0),b.colorsNeedUpdate=
16920 !1);b.uvsNeedUpdate&&(c=this.attributes.uv,void 0!==c&&(c.copyVector2sArray(b.uvs),c.needsUpdate=!0),b.uvsNeedUpdate=!1);b.lineDistancesNeedUpdate&&(c=this.attributes.lineDistance,void 0!==c&&(c.copyArray(b.lineDistances),c.needsUpdate=!0),b.lineDistancesNeedUpdate=!1);b.groupsNeedUpdate&&(b.computeGroups(a.geometry),this.groups=b.groups,b.groupsNeedUpdate=!1);return this},fromGeometry:function(a){a.__directGeometry=(new Je).fromGeometry(a);return this.fromDirectGeometry(a.__directGeometry)},fromDirectGeometry:function(a){var b=
16921 new Float32Array(3*a.vertices.length);this.addAttribute("position",(new P(b,3)).copyVector3sArray(a.vertices));0<a.normals.length&&(b=new Float32Array(3*a.normals.length),this.addAttribute("normal",(new P(b,3)).copyVector3sArray(a.normals)));0<a.colors.length&&(b=new Float32Array(3*a.colors.length),this.addAttribute("color",(new P(b,3)).copyColorsArray(a.colors)));0<a.uvs.length&&(b=new Float32Array(2*a.uvs.length),this.addAttribute("uv",(new P(b,2)).copyVector2sArray(a.uvs)));0<a.uvs2.length&&(b=
16922 new Float32Array(2*a.uvs2.length),this.addAttribute("uv2",(new P(b,2)).copyVector2sArray(a.uvs2)));0<a.indices.length&&(b=new (65535<Qd(a.indices)?Uint32Array:Uint16Array)(3*a.indices.length),this.setIndex((new P(b,1)).copyIndicesArray(a.indices)));this.groups=a.groups;for(var c in a.morphTargets){for(var b=[],d=a.morphTargets[c],e=0,f=d.length;e<f;e++){var g=d[e],h=new y(3*g.length,3);b.push(h.copyVector3sArray(g))}this.morphAttributes[c]=b}0<a.skinIndices.length&&(c=new y(4*a.skinIndices.length,
16923 4),this.addAttribute("skinIndex",c.copyVector4sArray(a.skinIndices)));0<a.skinWeights.length&&(c=new y(4*a.skinWeights.length,4),this.addAttribute("skinWeight",c.copyVector4sArray(a.skinWeights)));null!==a.boundingSphere&&(this.boundingSphere=a.boundingSphere.clone());null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone());return this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new Oa);var a=this.attributes.position;void 0!==a?this.boundingBox.setFromBufferAttribute(a):
16924 this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)},computeBoundingSphere:function(){var a=new Oa,b=new p;return function(){null===this.boundingSphere&&(this.boundingSphere=new Da);var c=this.attributes.position;if(c){var d=this.boundingSphere.center;a.setFromBufferAttribute(c);
16925 a.getCenter(d);for(var e=0,f=0,g=c.count;f<g;f++)b.x=c.getX(f),b.y=c.getY(f),b.z=c.getZ(f),e=Math.max(e,d.distanceToSquared(b));this.boundingSphere.radius=Math.sqrt(e);isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}}(),computeFaceNormals:function(){},computeVertexNormals:function(){var a=this.index,b=this.attributes,c=this.groups;if(b.position){var d=b.position.array;
16926 if(void 0===b.normal)this.addAttribute("normal",new P(new Float32Array(d.length),3));else for(var e=b.normal.array,f=0,g=e.length;f<g;f++)e[f]=0;var e=b.normal.array,h=new p,k=new p,l=new p,q=new p,n=new p;if(a){a=a.array;0===c.length&&this.addGroup(0,a.length);for(var m=0,r=c.length;m<r;++m){f=c[m];g=f.start;var u=f.count;f=g;for(g+=u;f<g;f+=3){u=3*a[f+0];var v=3*a[f+1];var w=3*a[f+2];h.fromArray(d,u);k.fromArray(d,v);l.fromArray(d,w);q.subVectors(l,k);n.subVectors(h,k);q.cross(n);e[u]+=q.x;e[u+
16927 1]+=q.y;e[u+2]+=q.z;e[v]+=q.x;e[v+1]+=q.y;e[v+2]+=q.z;e[w]+=q.x;e[w+1]+=q.y;e[w+2]+=q.z}}}else for(f=0,g=d.length;f<g;f+=9)h.fromArray(d,f),k.fromArray(d,f+3),l.fromArray(d,f+6),q.subVectors(l,k),n.subVectors(h,k),q.cross(n),e[f]=q.x,e[f+1]=q.y,e[f+2]=q.z,e[f+3]=q.x,e[f+4]=q.y,e[f+5]=q.z,e[f+6]=q.x,e[f+7]=q.y,e[f+8]=q.z;this.normalizeNormals();b.normal.needsUpdate=!0}},merge:function(a,b){if(a&&a.isBufferGeometry){void 0===b&&(b=0);var c=this.attributes,d;for(d in c)if(void 0!==a.attributes[d])for(var e=
16928 c[d].array,f=a.attributes[d],g=f.array,h=0,f=f.itemSize*b;h<g.length;h++,f++)e[f]=g[h];return this}console.error("THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.",a)},normalizeNormals:function(){var a=new p;return function(){for(var b=this.attributes.normal,c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.normalize(),b.setXYZ(c,a.x,a.y,a.z)}}(),toNonIndexed:function(){if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed."),
16929 this;var a=new D,b=this.index.array,c=this.attributes,d;for(d in c){for(var e=c[d],f=e.array,e=e.itemSize,g=new f.constructor(b.length*e),h,k=0,l=0,q=b.length;l<q;l++){h=b[l]*e;for(var n=0;n<e;n++)g[k++]=f[h++]}a.addAttribute(d,new P(g,e))}return a},toJSON:function(){var a={metadata:{version:4.5,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};a.uuid=this.uuid;a.type=this.type;""!==this.name&&(a.name=this.name);if(void 0!==this.parameters){var b=this.parameters;for(var c in b)void 0!==b[c]&&
16930 (a[c]=b[c]);return a}a.data={attributes:{}};var d=this.index;null!==d&&(b=Array.prototype.slice.call(d.array),a.data.index={type:d.array.constructor.name,array:b});d=this.attributes;for(c in d){var e=d[c];b=Array.prototype.slice.call(e.array);a.data.attributes[c]={itemSize:e.itemSize,type:e.array.constructor.name,array:b,normalized:e.normalized}}c=this.groups;0<c.length&&(a.data.groups=JSON.parse(JSON.stringify(c)));c=this.boundingSphere;null!==c&&(a.data.boundingSphere={center:c.center.toArray(),
16931 radius:c.radius});return a},clone:function(){return(new D).copy(this)},copy:function(a){var b;this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.name=a.name;var c=a.index;null!==c&&this.setIndex(c.clone());c=a.attributes;for(g in c)this.addAttribute(g,c[g].clone());var d=a.morphAttributes;for(g in d){var e=[],f=d[g];c=0;for(b=f.length;c<b;c++)e.push(f[c].clone());this.morphAttributes[g]=e}var g=a.groups;c=0;for(b=g.length;c<b;c++)d=
16932 g[c],this.addGroup(d.start,d.count,d.materialIndex);g=a.boundingBox;null!==g&&(this.boundingBox=g.clone());g=a.boundingSphere;null!==g&&(this.boundingSphere=g.clone());this.drawRange.start=a.drawRange.start;this.drawRange.count=a.drawRange.count;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Lb.prototype=Object.create(N.prototype);Lb.prototype.constructor=Lb;jb.prototype=Object.create(D.prototype);jb.prototype.constructor=jb;Ac.prototype=Object.create(N.prototype);Ac.prototype.constructor=
16933 Ac;kb.prototype=Object.create(D.prototype);kb.prototype.constructor=kb;va.prototype=Object.create(Q.prototype);va.prototype.constructor=va;va.prototype.isMeshBasicMaterial=!0;va.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=
16934 a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;return this};oa.prototype=Object.create(Q.prototype);oa.prototype.constructor=oa;oa.prototype.isShaderMaterial=!0;oa.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.fragmentShader=a.fragmentShader;this.vertexShader=a.vertexShader;
16935 this.uniforms=Ea.clone(a.uniforms);this.defines=a.defines;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.lights=a.lights;this.clipping=a.clipping;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;this.extensions=a.extensions;return this};oa.prototype.toJSON=function(a){a=Q.prototype.toJSON.call(this,a);a.uniforms=this.uniforms;a.vertexShader=this.vertexShader;a.fragmentShader=this.fragmentShader;return a};Object.assign(lb.prototype,
16936 {set:function(a,b){this.origin.copy(a);this.direction.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.origin.copy(a.origin);this.direction.copy(a.direction);return this},at:function(a,b){return(b||new p).copy(this.direction).multiplyScalar(a).add(this.origin)},lookAt:function(a){this.direction.copy(a).sub(this.origin).normalize();return this},recast:function(){var a=new p;return function(b){this.origin.copy(this.at(b,a));return this}}(),closestPointToPoint:function(a,
16937 b){b=b||new p;b.subVectors(a,this.origin);a=b.dot(this.direction);return 0>a?b.copy(this.origin):b.copy(this.direction).multiplyScalar(a).add(this.origin)},distanceToPoint:function(a){return Math.sqrt(this.distanceSqToPoint(a))},distanceSqToPoint:function(){var a=new p;return function(b){var c=a.subVectors(b,this.origin).dot(this.direction);if(0>c)return this.origin.distanceToSquared(b);a.copy(this.direction).multiplyScalar(c).add(this.origin);return a.distanceToSquared(b)}}(),distanceSqToSegment:function(){var a=
16938 new p,b=new p,c=new p;return function(d,e,f,g){a.copy(d).add(e).multiplyScalar(.5);b.copy(e).sub(d).normalize();c.copy(this.origin).sub(a);var h=.5*d.distanceTo(e),k=-this.direction.dot(b),l=c.dot(this.direction),q=-c.dot(b),n=c.lengthSq(),m=Math.abs(1-k*k);if(0<m){d=k*q-l;e=k*l-q;var p=h*m;0<=d?e>=-p?e<=p?(h=1/m,d*=h,e*=h,k=d*(d+k*e+2*l)+e*(k*d+e+2*q)+n):(e=h,d=Math.max(0,-(k*e+l)),k=-d*d+e*(e+2*q)+n):(e=-h,d=Math.max(0,-(k*e+l)),k=-d*d+e*(e+2*q)+n):e<=-p?(d=Math.max(0,-(-k*h+l)),e=0<d?-h:Math.min(Math.max(-h,
16939 -q),h),k=-d*d+e*(e+2*q)+n):e<=p?(d=0,e=Math.min(Math.max(-h,-q),h),k=e*(e+2*q)+n):(d=Math.max(0,-(k*h+l)),e=0<d?h:Math.min(Math.max(-h,-q),h),k=-d*d+e*(e+2*q)+n)}else e=0<k?-h:h,d=Math.max(0,-(k*e+l)),k=-d*d+e*(e+2*q)+n;f&&f.copy(this.direction).multiplyScalar(d).add(this.origin);g&&g.copy(b).multiplyScalar(e).add(a);return k}}(),intersectSphere:function(){var a=new p;return function(b,c){a.subVectors(b.center,this.origin);var d=a.dot(this.direction),e=a.dot(a)-d*d;b=b.radius*b.radius;if(e>b)return null;
16940 b=Math.sqrt(b-e);e=d-b;d+=b;return 0>e&&0>d?null:0>e?this.at(d,c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<=a.radius},distanceToPlane:function(a){var b=a.normal.dot(this.direction);if(0===b)return 0===a.distanceToPoint(this.origin)?0:null;a=-(this.origin.dot(a.normal)+a.constant)/b;return 0<=a?a:null},intersectPlane:function(a,b){a=this.distanceToPlane(a);return null===a?null:this.at(a,b)},intersectsPlane:function(a){var b=a.distanceToPoint(this.origin);
16941 return 0===b||0>a.normal.dot(this.direction)*b?!0:!1},intersectBox:function(a,b){var c=1/this.direction.x;var d=1/this.direction.y;var e=1/this.direction.z,f=this.origin;if(0<=c){var g=(a.min.x-f.x)*c;c*=a.max.x-f.x}else g=(a.max.x-f.x)*c,c*=a.min.x-f.x;if(0<=d){var h=(a.min.y-f.y)*d;d*=a.max.y-f.y}else h=(a.max.y-f.y)*d,d*=a.min.y-f.y;if(g>d||h>c)return null;if(h>g||g!==g)g=h;if(d<c||c!==c)c=d;0<=e?(h=(a.min.z-f.z)*e,a=(a.max.z-f.z)*e):(h=(a.max.z-f.z)*e,a=(a.min.z-f.z)*e);if(g>a||h>c)return null;
16942 if(h>g||g!==g)g=h;if(a<c||c!==c)c=a;return 0>c?null:this.at(0<=g?g:c,b)},intersectsBox:function(){var a=new p;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a=new p,b=new p,c=new p,d=new p;return function(e,f,g,h,k){b.subVectors(f,e);c.subVectors(g,e);d.crossVectors(b,c);f=this.direction.dot(d);if(0<f){if(h)return null;h=1}else if(0>f)h=-1,f=-f;else return null;a.subVectors(this.origin,e);e=h*this.direction.dot(c.crossVectors(a,c));if(0>e)return null;
16943 g=h*this.direction.dot(b.cross(a));if(0>g||e+g>f)return null;e=-h*a.dot(d);return 0>e?null:this.at(e/f,k)}}(),applyMatrix4:function(a){this.origin.applyMatrix4(a);this.direction.transformDirection(a);return this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}});Object.assign(Mb.prototype,{set:function(a,b){this.start.copy(a);this.end.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.start.copy(a.start);
16944 this.end.copy(a.end);return this},getCenter:function(a){return(a||new p).addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){return(a||new p).subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(a,b){b=b||new p;return this.delta(b).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new p,b=new p;return function(c,d){a.subVectors(c,
16945 this.start);b.subVectors(this.end,this.start);c=b.dot(b);c=b.dot(a)/c;d&&(c=R.clamp(c,0,1));return c}}(),closestPointToPoint:function(a,b,c){a=this.closestPointToPointParameter(a,b);c=c||new p;return this.delta(c).multiplyScalar(a).add(this.start)},applyMatrix4:function(a){this.start.applyMatrix4(a);this.end.applyMatrix4(a);return this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)}});Object.assign(Qa,{normal:function(){var a=new p;return function(b,c,d,e){e=e||new p;
16946 e.subVectors(d,c);a.subVectors(b,c);e.cross(a);b=e.lengthSq();return 0<b?e.multiplyScalar(1/Math.sqrt(b)):e.set(0,0,0)}}(),barycoordFromPoint:function(){var a=new p,b=new p,c=new p;return function(d,e,f,g,h){a.subVectors(g,e);b.subVectors(f,e);c.subVectors(d,e);d=a.dot(a);e=a.dot(b);f=a.dot(c);var k=b.dot(b);g=b.dot(c);var l=d*k-e*e;h=h||new p;if(0===l)return h.set(-2,-1,-1);l=1/l;k=(k*f-e*g)*l;d=(d*g-e*f)*l;return h.set(1-k-d,d,k)}}(),containsPoint:function(){var a=new p;return function(b,c,d,e){b=
16947 Qa.barycoordFromPoint(b,c,d,e,a);return 0<=b.x&&0<=b.y&&1>=b.x+b.y}}()});Object.assign(Qa.prototype,{set:function(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this},setFromPointsAndIndices:function(a,b,c,d){this.a.copy(a[b]);this.b.copy(a[c]);this.c.copy(a[d]);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a.copy(a.a);this.b.copy(a.b);this.c.copy(a.c);return this},area:function(){var a=new p,b=new p;return function(){a.subVectors(this.c,
16948 this.b);b.subVectors(this.a,this.b);return.5*a.cross(b).length()}}(),midpoint:function(a){return(a||new p).addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(a){return Qa.normal(this.a,this.b,this.c,a)},plane:function(a){return(a||new Aa).setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return Qa.barycoordFromPoint(a,this.a,this.b,this.c,b)},containsPoint:function(a){return Qa.containsPoint(a,this.a,this.b,this.c)},closestPointToPoint:function(){var a=
16949 new Aa,b=[new Mb,new Mb,new Mb],c=new p,d=new p;return function(e,f){f=f||new p;var g=Infinity;a.setFromCoplanarPoints(this.a,this.b,this.c);a.projectPoint(e,c);if(!0===this.containsPoint(c))f.copy(c);else for(b[0].set(this.a,this.b),b[1].set(this.b,this.c),b[2].set(this.c,this.a),e=0;e<b.length;e++){b[e].closestPointToPoint(c,!0,d);var h=c.distanceToSquared(d);h<g&&(g=h,f.copy(d))}return f}}(),equals:function(a){return a.a.equals(this.a)&&a.b.equals(this.b)&&a.c.equals(this.c)}});pa.prototype=Object.assign(Object.create(A.prototype),
16950 {constructor:pa,isMesh:!0,setDrawMode:function(a){this.drawMode=a},copy:function(a){A.prototype.copy.call(this,a);this.drawMode=a.drawMode;void 0!==a.morphTargetInfluences&&(this.morphTargetInfluences=a.morphTargetInfluences.slice());void 0!==a.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},a.morphTargetDictionary));return this},updateMorphTargets:function(){var a=this.geometry;if(a.isBufferGeometry){a=a.morphAttributes;var b=Object.keys(a);if(0<b.length){var c=a[b[0]];if(void 0!==
16951 c)for(this.morphTargetInfluences=[],this.morphTargetDictionary={},a=0,b=c.length;a<b;a++){var d=c[a].name||String(a);this.morphTargetInfluences.push(0);this.morphTargetDictionary[d]=a}}}else if(c=a.morphTargets,void 0!==c&&0<c.length)for(this.morphTargetInfluences=[],this.morphTargetDictionary={},a=0,b=c.length;a<b;a++)d=c[a].name||String(a),this.morphTargetInfluences.push(0),this.morphTargetDictionary[d]=a},raycast:function(){function a(a,b,c,d,e,f,g){Qa.barycoordFromPoint(a,b,c,d,v);e.multiplyScalar(v.x);
16952 f.multiplyScalar(v.y);g.multiplyScalar(v.z);e.add(f).add(g);return e.clone()}function b(a,b,c,d,e,f,g,h){if(null===(1===b.side?d.intersectTriangle(g,f,e,!0,h):d.intersectTriangle(e,f,g,2!==b.side,h)))return null;x.copy(h);x.applyMatrix4(a.matrixWorld);b=c.ray.origin.distanceTo(x);return b<c.near||b>c.far?null:{distance:b,point:x.clone(),object:a}}function c(c,d,e,f,l,n,q,t){g.fromBufferAttribute(f,n);h.fromBufferAttribute(f,q);k.fromBufferAttribute(f,t);if(c=b(c,c.material,d,e,g,h,k,w))l&&(m.fromBufferAttribute(l,
16953 n),r.fromBufferAttribute(l,q),u.fromBufferAttribute(l,t),c.uv=a(w,g,h,k,m,r,u)),c.face=new Pa(n,q,t,Qa.normal(g,h,k)),c.faceIndex=n;return c}var d=new K,e=new lb,f=new Da,g=new p,h=new p,k=new p,l=new p,q=new p,n=new p,m=new C,r=new C,u=new C,v=new p,w=new p,x=new p;return function(t,p){var v=this.geometry,x=this.material,z=this.matrixWorld;if(void 0!==x&&(null===v.boundingSphere&&v.computeBoundingSphere(),f.copy(v.boundingSphere),f.applyMatrix4(z),!1!==t.ray.intersectsSphere(f)&&(d.getInverse(z),
16954 e.copy(t.ray).applyMatrix4(d),null===v.boundingBox||!1!==e.intersectsBox(v.boundingBox)))){var y;if(v.isBufferGeometry){var x=v.index,I=v.attributes.position,z=v.attributes.uv,C;if(null!==x){var A=0;for(C=x.count;A<C;A+=3){v=x.getX(A);var D=x.getX(A+1);var E=x.getX(A+2);if(y=c(this,t,e,I,z,v,D,E))y.faceIndex=Math.floor(A/3),p.push(y)}}else if(void 0!==I)for(A=0,C=I.count;A<C;A+=3)if(v=A,D=A+1,E=A+2,y=c(this,t,e,I,z,v,D,E))y.index=v,p.push(y)}else if(v.isGeometry){var z=Array.isArray(x);A=v.vertices;
16955 C=v.faces;D=v.faceVertexUvs[0];0<D.length&&(I=D);for(var H=0,N=C.length;H<N;H++){var M=C[H];y=z?x[M.materialIndex]:x;if(void 0!==y){D=A[M.a];E=A[M.b];var V=A[M.c];if(!0===y.morphTargets){var K=v.morphTargets,P=this.morphTargetInfluences;g.set(0,0,0);h.set(0,0,0);k.set(0,0,0);for(var Q=0,R=K.length;Q<R;Q++){var O=P[Q];if(0!==O){var S=K[Q].vertices;g.addScaledVector(l.subVectors(S[M.a],D),O);h.addScaledVector(q.subVectors(S[M.b],E),O);k.addScaledVector(n.subVectors(S[M.c],V),O)}}g.add(D);h.add(E);k.add(V);
16956 D=g;E=h;V=k}if(y=b(this,y,t,e,D,E,V,w))I&&I[H]&&(K=I[H],m.copy(K[0]),r.copy(K[1]),u.copy(K[2]),y.uv=a(w,D,E,V,m,r,u)),y.face=M,y.faceIndex=H,p.push(y)}}}}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});var ig=0;U.prototype=Object.assign(Object.create(La.prototype),{constructor:U,isPerspectiveCamera:!0,copy:function(a,b){La.prototype.copy.call(this,a,b);this.fov=a.fov;this.zoom=a.zoom;this.near=a.near;this.far=a.far;this.focus=a.focus;this.aspect=a.aspect;
16957 this.view=null===a.view?null:Object.assign({},a.view);this.filmGauge=a.filmGauge;this.filmOffset=a.filmOffset;return this},setFocalLength:function(a){a=.5*this.getFilmHeight()/a;this.fov=2*R.RAD2DEG*Math.atan(a);this.updateProjectionMatrix()},getFocalLength:function(){var a=Math.tan(.5*R.DEG2RAD*this.fov);return.5*this.getFilmHeight()/a},getEffectiveFOV:function(){return 2*R.RAD2DEG*Math.atan(Math.tan(.5*R.DEG2RAD*this.fov)/this.zoom)},getFilmWidth:function(){return this.filmGauge*Math.min(this.aspect,
16958 1)},getFilmHeight:function(){return this.filmGauge/Math.max(this.aspect,1)},setViewOffset:function(a,b,c,d,e,f){this.aspect=a/b;null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1});this.view.enabled=!0;this.view.fullWidth=a;this.view.fullHeight=b;this.view.offsetX=c;this.view.offsetY=d;this.view.width=e;this.view.height=f;this.updateProjectionMatrix()},clearViewOffset:function(){null!==this.view&&(this.view.enabled=!1);this.updateProjectionMatrix()},
16959 updateProjectionMatrix:function(){var a=this.near,b=a*Math.tan(.5*R.DEG2RAD*this.fov)/this.zoom,c=2*b,d=this.aspect*c,e=-.5*d,f=this.view;if(null!==this.view&&this.view.enabled)var g=f.fullWidth,h=f.fullHeight,e=e+f.offsetX*d/g,b=b-f.offsetY*c/h,d=f.width/g*d,c=f.height/h*c;f=this.filmOffset;0!==f&&(e+=a*f/this.getFilmWidth());this.projectionMatrix.makePerspective(e,e+d,b,b-c,a,this.far)},toJSON:function(a){a=A.prototype.toJSON.call(this,a);a.object.fov=this.fov;a.object.zoom=this.zoom;a.object.near=
16960 this.near;a.object.far=this.far;a.object.focus=this.focus;a.object.aspect=this.aspect;null!==this.view&&(a.object.view=Object.assign({},this.view));a.object.filmGauge=this.filmGauge;a.object.filmOffset=this.filmOffset;return a}});nd.prototype=Object.assign(Object.create(U.prototype),{constructor:nd,isArrayCamera:!0});Ob.prototype.isFogExp2=!0;Ob.prototype.clone=function(){return new Ob(this.color.getHex(),this.density)};Ob.prototype.toJSON=function(){return{type:"FogExp2",color:this.color.getHex(),
16961 density:this.density}};Pb.prototype.isFog=!0;Pb.prototype.clone=function(){return new Pb(this.color.getHex(),this.near,this.far)};Pb.prototype.toJSON=function(){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}};od.prototype=Object.assign(Object.create(A.prototype),{constructor:od,copy:function(a,b){A.prototype.copy.call(this,a,b);null!==a.background&&(this.background=a.background.clone());null!==a.fog&&(this.fog=a.fog.clone());null!==a.overrideMaterial&&(this.overrideMaterial=
16962 a.overrideMaterial.clone());this.autoUpdate=a.autoUpdate;this.matrixAutoUpdate=a.matrixAutoUpdate;return this},toJSON:function(a){var b=A.prototype.toJSON.call(this,a);null!==this.background&&(b.object.background=this.background.toJSON(a));null!==this.fog&&(b.object.fog=this.fog.toJSON());return b}});Xd.prototype=Object.assign(Object.create(A.prototype),{constructor:Xd,isLensFlare:!0,copy:function(a){A.prototype.copy.call(this,a);this.positionScreen.copy(a.positionScreen);this.customUpdateCallback=
16963 a.customUpdateCallback;for(var b=0,c=a.lensFlares.length;b<c;b++)this.lensFlares.push(a.lensFlares[b]);return this},add:function(a,b,c,d,e,f){void 0===b&&(b=-1);void 0===c&&(c=0);void 0===f&&(f=1);void 0===e&&(e=new H(16777215));void 0===d&&(d=1);c=Math.min(c,Math.max(0,c));this.lensFlares.push({texture:a,size:b,distance:c,x:0,y:0,z:0,scale:1,rotation:0,opacity:f,color:e,blending:d})},updateLensFlares:function(){var a,b=this.lensFlares.length,c=2*-this.positionScreen.x,d=2*-this.positionScreen.y;
16964 for(a=0;a<b;a++){var e=this.lensFlares[a];e.x=this.positionScreen.x+c*e.distance;e.y=this.positionScreen.y+d*e.distance;e.wantedRotation=e.x*Math.PI*.25;e.rotation+=.25*(e.wantedRotation-e.rotation)}}});Za.prototype=Object.create(Q.prototype);Za.prototype.constructor=Za;Za.prototype.isSpriteMaterial=!0;Za.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.rotation=a.rotation;return this};Cc.prototype=Object.assign(Object.create(A.prototype),{constructor:Cc,
16965 isSprite:!0,raycast:function(){var a=new p,b=new p,c=new p;return function(d,e){b.setFromMatrixPosition(this.matrixWorld);d.ray.closestPointToPoint(b,a);c.setFromMatrixScale(this.matrixWorld);var f=c.x*c.y/4;b.distanceToSquared(a)>f||(f=d.ray.origin.distanceTo(a),f<d.near||f>d.far||e.push({distance:f,point:a.clone(),face:null,object:this}))}}(),clone:function(){return(new this.constructor(this.material)).copy(this)}});Dc.prototype=Object.assign(Object.create(A.prototype),{constructor:Dc,copy:function(a){A.prototype.copy.call(this,
16966 a,!1);a=a.levels;for(var b=0,c=a.length;b<c;b++){var d=a[b];this.addLevel(d.object.clone(),d.distance)}return this},addLevel:function(a,b){void 0===b&&(b=0);b=Math.abs(b);for(var c=this.levels,d=0;d<c.length&&!(b<c[d].distance);d++);c.splice(d,0,{distance:b,object:a});this.add(a)},getObjectForDistance:function(a){for(var b=this.levels,c=1,d=b.length;c<d&&!(a<b[c].distance);c++);return b[c-1].object},raycast:function(){var a=new p;return function(b,c){a.setFromMatrixPosition(this.matrixWorld);var d=
16967 b.ray.origin.distanceTo(a);this.getObjectForDistance(d).raycast(b,c)}}(),update:function(){var a=new p,b=new p;return function(c){var d=this.levels;if(1<d.length){a.setFromMatrixPosition(c.matrixWorld);b.setFromMatrixPosition(this.matrixWorld);c=a.distanceTo(b);d[0].object.visible=!0;for(var e=1,f=d.length;e<f;e++)if(c>=d[e].distance)d[e-1].object.visible=!1,d[e].object.visible=!0;else break;for(;e<f;e++)d[e].object.visible=!1}}}(),toJSON:function(a){a=A.prototype.toJSON.call(this,a);a.object.levels=
16968 [];for(var b=this.levels,c=0,d=b.length;c<d;c++){var e=b[c];a.object.levels.push({object:e.object.uuid,distance:e.distance})}return a}});Object.assign(Ec.prototype,{calculateInverses:function(){this.boneInverses=[];for(var a=0,b=this.bones.length;a<b;a++){var c=new K;this.bones[a]&&c.getInverse(this.bones[a].matrixWorld);this.boneInverses.push(c)}},pose:function(){var a,b;var c=0;for(b=this.bones.length;c<b;c++)(a=this.bones[c])&&a.matrixWorld.getInverse(this.boneInverses[c]);c=0;for(b=this.bones.length;c<
16969 b;c++)if(a=this.bones[c])a.parent&&a.parent.isBone?(a.matrix.getInverse(a.parent.matrixWorld),a.matrix.multiply(a.matrixWorld)):a.matrix.copy(a.matrixWorld),a.matrix.decompose(a.position,a.quaternion,a.scale)},update:function(){var a=new K,b=new K;return function(){for(var c=this.bones,d=this.boneInverses,e=this.boneMatrices,f=this.boneTexture,g=0,h=c.length;g<h;g++)a.multiplyMatrices(c[g]?c[g].matrixWorld:b,d[g]),a.toArray(e,16*g);void 0!==f&&(f.needsUpdate=!0)}}(),clone:function(){return new Ec(this.bones,
16970 this.boneInverses)}});pd.prototype=Object.assign(Object.create(A.prototype),{constructor:pd,isBone:!0});qd.prototype=Object.assign(Object.create(pa.prototype),{constructor:qd,isSkinnedMesh:!0,initBones:function(){var a=[],b;if(this.geometry&&void 0!==this.geometry.bones){var c=0;for(b=this.geometry.bones.length;c<b;c++){var d=this.geometry.bones[c];var e=new pd;a.push(e);e.name=d.name;e.position.fromArray(d.pos);e.quaternion.fromArray(d.rotq);void 0!==d.scl&&e.scale.fromArray(d.scl)}c=0;for(b=this.geometry.bones.length;c<
16971 b;c++)d=this.geometry.bones[c],-1!==d.parent&&null!==d.parent&&void 0!==a[d.parent]?a[d.parent].add(a[c]):this.add(a[c])}this.updateMatrixWorld(!0);return a},bind:function(a,b){this.skeleton=a;void 0===b&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),b=this.matrixWorld);this.bindMatrix.copy(b);this.bindMatrixInverse.getInverse(b)},pose:function(){this.skeleton.pose()},normalizeSkinWeights:function(){var a;if(this.geometry&&this.geometry.isGeometry)for(a=0;a<this.geometry.skinWeights.length;a++){var b=
16972 this.geometry.skinWeights[a];var c=1/b.manhattanLength();Infinity!==c?b.multiplyScalar(c):b.set(1,0,0,0)}else if(this.geometry&&this.geometry.isBufferGeometry){var b=new da,d=this.geometry.attributes.skinWeight;for(a=0;a<d.count;a++)b.x=d.getX(a),b.y=d.getY(a),b.z=d.getZ(a),b.w=d.getW(a),c=1/b.manhattanLength(),Infinity!==c?b.multiplyScalar(c):b.set(1,0,0,0),d.setXYZW(a,b.x,b.y,b.z,b.w)}},updateMatrixWorld:function(a){pa.prototype.updateMatrixWorld.call(this,a);"attached"===this.bindMode?this.bindMatrixInverse.getInverse(this.matrixWorld):
16973 "detached"===this.bindMode?this.bindMatrixInverse.getInverse(this.bindMatrix):console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)},clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});O.prototype=Object.create(Q.prototype);O.prototype.constructor=O;O.prototype.isLineBasicMaterial=!0;O.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.linewidth=a.linewidth;this.linecap=a.linecap;this.linejoin=a.linejoin;return this};
16974 ma.prototype=Object.assign(Object.create(A.prototype),{constructor:ma,isLine:!0,raycast:function(){var a=new K,b=new lb,c=new Da;return function(d,e){var f=d.linePrecision,f=f*f,g=this.geometry,h=this.matrixWorld;null===g.boundingSphere&&g.computeBoundingSphere();c.copy(g.boundingSphere);c.applyMatrix4(h);if(!1!==d.ray.intersectsSphere(c)){a.getInverse(h);b.copy(d.ray).applyMatrix4(a);var k=new p,l=new p,h=new p,q=new p,n=this&&this.isLineSegments?2:1;if(g.isBufferGeometry){var m=g.index;var r=g.attributes.position.array;
16975 if(null!==m)for(var u=m.array,g=0,v=u.length-1;g<v;g+=n)m=u[g+1],k.fromArray(r,3*u[g]),l.fromArray(r,3*m),m=b.distanceSqToSegment(k,l,q,h),m>f||(q.applyMatrix4(this.matrixWorld),m=d.ray.origin.distanceTo(q),m<d.near||m>d.far||e.push({distance:m,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}));else for(g=0,v=r.length/3-1;g<v;g+=n)k.fromArray(r,3*g),l.fromArray(r,3*g+3),m=b.distanceSqToSegment(k,l,q,h),m>f||(q.applyMatrix4(this.matrixWorld),m=d.ray.origin.distanceTo(q),
16976 m<d.near||m>d.far||e.push({distance:m,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else if(g.isGeometry)for(k=g.vertices,l=k.length,g=0;g<l-1;g+=n)m=b.distanceSqToSegment(k[g],k[g+1],q,h),m>f||(q.applyMatrix4(this.matrixWorld),m=d.ray.origin.distanceTo(q),m<d.near||m>d.far||e.push({distance:m,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry,
16977 this.material)).copy(this)}});ca.prototype=Object.assign(Object.create(ma.prototype),{constructor:ca,isLineSegments:!0});rd.prototype=Object.assign(Object.create(ma.prototype),{constructor:rd,isLineLoop:!0});Ba.prototype=Object.create(Q.prototype);Ba.prototype.constructor=Ba;Ba.prototype.isPointsMaterial=!0;Ba.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.size=a.size;this.sizeAttenuation=a.sizeAttenuation;return this};Qb.prototype=Object.assign(Object.create(A.prototype),
16978 {constructor:Qb,isPoints:!0,raycast:function(){var a=new K,b=new lb,c=new Da;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a);if(f<m){a=b.closestPointToPoint(a);a.applyMatrix4(k);var h=d.ray.origin.distanceTo(a);h<d.near||h>d.far||e.push({distance:h,distanceToRay:Math.sqrt(f),point:a.clone(),index:c,face:null,object:g})}}var g=this,h=this.geometry,k=this.matrixWorld,l=d.params.Points.threshold;null===h.boundingSphere&&h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k);
16979 c.radius+=l;if(!1!==d.ray.intersectsSphere(c)){a.getInverse(k);b.copy(d.ray).applyMatrix4(a);var l=l/((this.scale.x+this.scale.y+this.scale.z)/3),m=l*l,l=new p;if(h.isBufferGeometry){var n=h.index,h=h.attributes.position.array;if(null!==n)for(var t=n.array,n=0,r=t.length;n<r;n++){var u=t[n];l.fromArray(h,3*u);f(l,u)}else for(n=0,t=h.length/3;n<t;n++)l.fromArray(h,3*n),f(l,n)}else for(l=h.vertices,n=0,t=l.length;n<t;n++)f(l[n],n)}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});
16980 Fc.prototype=Object.assign(Object.create(A.prototype),{constructor:Fc});sd.prototype=Object.create(ea.prototype);sd.prototype.constructor=sd;Rb.prototype=Object.create(ea.prototype);Rb.prototype.constructor=Rb;Rb.prototype.isCompressedTexture=!0;Gc.prototype=Object.create(ea.prototype);Gc.prototype.constructor=Gc;Gc.prototype.isDepthTexture=!0;Sb.prototype=Object.create(D.prototype);Sb.prototype.constructor=Sb;Hc.prototype=Object.create(N.prototype);Hc.prototype.constructor=Hc;Tb.prototype=Object.create(D.prototype);
16981 Tb.prototype.constructor=Tb;Ic.prototype=Object.create(N.prototype);Ic.prototype.constructor=Ic;qa.prototype=Object.create(D.prototype);qa.prototype.constructor=qa;Jc.prototype=Object.create(N.prototype);Jc.prototype.constructor=Jc;Ub.prototype=Object.create(qa.prototype);Ub.prototype.constructor=Ub;Kc.prototype=Object.create(N.prototype);Kc.prototype.constructor=Kc;nb.prototype=Object.create(qa.prototype);nb.prototype.constructor=nb;Lc.prototype=Object.create(N.prototype);Lc.prototype.constructor=
16982 Lc;Vb.prototype=Object.create(qa.prototype);Vb.prototype.constructor=Vb;Mc.prototype=Object.create(N.prototype);Mc.prototype.constructor=Mc;Wb.prototype=Object.create(qa.prototype);Wb.prototype.constructor=Wb;Nc.prototype=Object.create(N.prototype);Nc.prototype.constructor=Nc;Xb.prototype=Object.create(D.prototype);Xb.prototype.constructor=Xb;Oc.prototype=Object.create(N.prototype);Oc.prototype.constructor=Oc;Yb.prototype=Object.create(D.prototype);Yb.prototype.constructor=Yb;Pc.prototype=Object.create(N.prototype);
16983 Pc.prototype.constructor=Pc;Zb.prototype=Object.create(D.prototype);Zb.prototype.constructor=Zb;var Ha={area:function(a){for(var b=a.length,c=0,d=b-1,e=0;e<b;d=e++)c+=a[d].x*a[e].y-a[e].x*a[d].y;return.5*c},triangulate:function(){return function(a,b){var c=a.length;if(3>c)return null;var d=[],e=[],f=[],g;if(0<Ha.area(a))for(g=0;g<c;g++)e[g]=g;else for(g=0;g<c;g++)e[g]=c-1-g;var h=2*c;for(g=c-1;2<c;){if(0>=h--){console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()");break}var k=
16984 g;c<=k&&(k=0);g=k+1;c<=g&&(g=0);var l=g+1;c<=l&&(l=0);a:{var m;var n=a[e[k]].x;var p=a[e[k]].y;var r=a[e[g]].x;var u=a[e[g]].y;var v=a[e[l]].x;var w=a[e[l]].y;if(0>=(r-n)*(w-p)-(u-p)*(v-n))var x=!1;else{var z=v-r;var y=w-u;var B=n-v;var C=p-w;var A=r-n;x=u-p;for(m=0;m<c;m++){var D=a[e[m]].x;var E=a[e[m]].y;if(!(D===n&&E===p||D===r&&E===u||D===v&&E===w)){var H=D-n;var N=E-p;var K=D-r;var L=E-u;D-=v;E-=w;L=z*L-y*K;N=A*N-x*H;D=B*E-C*D;if(L>=-Number.EPSILON&&D>=-Number.EPSILON&&N>=-Number.EPSILON){x=
16985 !1;break a}}}x=!0}}if(x){d.push([a[e[k]],a[e[g]],a[e[l]]]);f.push([e[k],e[g],e[l]]);k=g;for(l=g+1;l<c;k++,l++)e[k]=e[l];c--;h=2*c}}return b?f:d}}(),triangulateShape:function(a,b){function c(a){var b=a.length;2<b&&a[b-1].equals(a[0])&&a.pop()}function d(a,b,c){return a.x!==b.x?a.x<b.x?a.x<=c.x&&c.x<=b.x:b.x<=c.x&&c.x<=a.x:a.y<b.y?a.y<=c.y&&c.y<=b.y:b.y<=c.y&&c.y<=a.y}function e(a,b,c,e,f){var g=b.x-a.x,h=b.y-a.y,k=e.x-c.x,l=e.y-c.y,m=a.x-c.x,n=a.y-c.y,q=h*k-g*l,p=h*m-g*n;if(Math.abs(q)>Number.EPSILON){if(0<
16986 q){if(0>p||p>q)return[];k=l*m-k*n;if(0>k||k>q)return[]}else{if(0<p||p<q)return[];k=l*m-k*n;if(0<k||k<q)return[]}if(0===k)return!f||0!==p&&p!==q?[a]:[];if(k===q)return!f||0!==p&&p!==q?[b]:[];if(0===p)return[c];if(p===q)return[e];f=k/q;return[{x:a.x+f*g,y:a.y+f*h}]}if(0!==p||l*m!==k*n)return[];h=0===g&&0===h;k=0===k&&0===l;if(h&&k)return a.x!==c.x||a.y!==c.y?[]:[a];if(h)return d(c,e,a)?[a]:[];if(k)return d(a,b,c)?[c]:[];0!==g?(a.x<b.x?(g=a,k=a.x,h=b,a=b.x):(g=b,k=b.x,h=a,a=a.x),c.x<e.x?(b=c,q=c.x,l=
16987 e,c=e.x):(b=e,q=e.x,l=c,c=c.x)):(a.y<b.y?(g=a,k=a.y,h=b,a=b.y):(g=b,k=b.y,h=a,a=a.y),c.y<e.y?(b=c,q=c.y,l=e,c=e.y):(b=e,q=e.y,l=c,c=c.y));return k<=q?a<q?[]:a===q?f?[]:[b]:a<=c?[b,h]:[b,l]:k>c?[]:k===c?f?[]:[g]:a<=c?[g,h]:[g,l]}function f(a,b,c,d){var e=b.x-a.x,f=b.y-a.y;b=c.x-a.x;c=c.y-a.y;var g=d.x-a.x;d=d.y-a.y;a=e*c-f*b;e=e*d-f*g;return Math.abs(a)>Number.EPSILON?(b=g*c-d*b,0<a?0<=e&&0<=b:0<=e||0<=b):0<e}c(a);b.forEach(c);var g,h={},k=a.concat();var l=0;for(g=b.length;l<g;l++)Array.prototype.push.apply(k,
16988 b[l]);l=0;for(g=k.length;l<g;l++){var m=k[l].x+":"+k[l].y;void 0!==h[m]&&console.warn("THREE.ShapeUtils: Duplicate point",m,l);h[m]=l}l=function(a,b){function c(a,b){var c=h.length-1,d=a-1;0>d&&(d=c);var e=a+1;e>c&&(e=0);c=f(h[a],h[d],h[e],D[b]);if(!c)return!1;c=D.length-1;d=b-1;0>d&&(d=c);e=b+1;e>c&&(e=0);return(c=f(D[b],D[d],D[e],h[a]))?!0:!1}function d(a,b){var c;for(c=0;c<h.length;c++){var d=c+1;d%=h.length;d=e(a,b,h[c],h[d],!0);if(0<d.length)return!0}return!1}function g(a,c){var d,f;for(d=0;d<
16989 k.length;d++){var g=b[k[d]];for(f=0;f<g.length;f++){var h=f+1;h%=g.length;h=e(a,c,g[f],g[h],!0);if(0<h.length)return!0}}return!1}var h=a.concat(),k=[],l,m;a=[];var q,n=0;for(l=b.length;n<l;n++)k.push(n);var p=0;for(var t=2*k.length;0<k.length;){t--;if(0>t){console.log('THREE.ShapeUtils: Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!');break}for(m=p;m<h.length;m++){var y=h[m];l=-1;for(n=0;n<k.length;n++){var C=k[n];var A=y.x+":"+y.y+":"+C;if(void 0===a[A]){var D=
16990 b[C];for(q=0;q<D.length;q++)if(C=D[q],c(m,q)&&!d(y,C)&&!g(y,C)){l=q;k.splice(n,1);p=h.slice(0,m+1);C=h.slice(m);q=D.slice(l);var E=D.slice(0,l+1);h=p.concat(q).concat(E).concat(C);p=m;break}if(0<=l)break;a[A]=!0}}if(0<=l)break}}return h}(a,b);k=Ha.triangulate(l,!1);l=0;for(g=k.length;l<g;l++)for(b=k[l],a=0;3>a;a++)m=b[a].x+":"+b[a].y,m=h[m],void 0!==m&&(b[a]=m);return k.concat()},isClockWise:function(a){return 0>Ha.area(a)}};$a.prototype=Object.create(N.prototype);$a.prototype.constructor=$a;Ga.prototype=
16991 Object.create(D.prototype);Ga.prototype.constructor=Ga;Ga.prototype.getArrays=function(){var a=this.getAttribute("position"),a=a?Array.prototype.slice.call(a.array):[],b=this.getAttribute("uv"),b=b?Array.prototype.slice.call(b.array):[],c=this.index,c=c?Array.prototype.slice.call(c.array):[];return{position:a,uv:b,index:c}};Ga.prototype.addShapeList=function(a,b){var c=a.length;b.arrays=this.getArrays();for(var d=0;d<c;d++)this.addShape(a[d],b);this.setIndex(b.arrays.index);this.addAttribute("position",
16992 new y(b.arrays.position,3));this.addAttribute("uv",new y(b.arrays.uv,2))};Ga.prototype.addShape=function(a,b){function c(a,b,c){b||console.error("THREE.ExtrudeGeometry: vec does not exist");return b.clone().multiplyScalar(c).add(a)}function d(a,b,c){var d=a.x-b.x;var e=a.y-b.y;var f=c.x-a.x;var g=c.y-a.y,h=d*d+e*e;if(Math.abs(d*g-e*f)>Number.EPSILON){var k=Math.sqrt(h),l=Math.sqrt(f*f+g*g),h=b.x-e/k;b=b.y+d/k;g=((c.x-g/l-h)*g-(c.y+f/l-b)*f)/(d*g-e*f);f=h+d*g-a.x;d=b+e*g-a.y;e=f*f+d*d;if(2>=e)return new C(f,
16993 d);e=Math.sqrt(e/2)}else a=!1,d>Number.EPSILON?f>Number.EPSILON&&(a=!0):d<-Number.EPSILON?f<-Number.EPSILON&&(a=!0):Math.sign(e)===Math.sign(g)&&(a=!0),a?(f=-e,e=Math.sqrt(h)):(f=d,d=e,e=Math.sqrt(h/2));return new C(f/e,d/e)}function e(a,b){for(G=a.length;0<=--G;){var c=G;var d=G-1;0>d&&(d=a.length-1);var e,f=A+2*w;for(e=0;e<f;e++){var g=Z*e,l=Z*(e+1),q=b+d+g,n=b+d+l,l=b+c+l;h(b+c+g);h(q);h(l);h(q);h(n);h(l);g=m.length/3;g=E.generateSideWallUV(R,m,g-6,g-3,g-2,g-1);k(g[0]);k(g[1]);k(g[3]);k(g[1]);
16994 k(g[2]);k(g[3])}}}function f(a,b,c){r.push(a);r.push(b);r.push(c)}function g(a,b,c){h(a);h(b);h(c);a=m.length/3;a=E.generateTopUV(R,m,a-3,a-2,a-1);k(a[0]);k(a[1]);k(a[2])}function h(a){n.push(m.length/3);m.push(r[3*a+0]);m.push(r[3*a+1]);m.push(r[3*a+2])}function k(a){t.push(a.x);t.push(a.y)}var l=b.arrays?b.arrays:this.getArrays(),m=l.position,n=l.index,t=l.uv,r=[],l=void 0!==b.amount?b.amount:100,u=void 0!==b.bevelThickness?b.bevelThickness:6,v=void 0!==b.bevelSize?b.bevelSize:u-2,w=void 0!==b.bevelSegments?
16995 b.bevelSegments:3,x=void 0!==b.bevelEnabled?b.bevelEnabled:!0,z=void 0!==b.curveSegments?b.curveSegments:12,A=void 0!==b.steps?b.steps:1,B=b.extrudePath,D=!1,E=void 0!==b.UVGenerator?b.UVGenerator:$a.WorldUVGenerator;if(B){var H=B.getSpacedPoints(A);D=!0;x=!1;var N=void 0!==b.frames?b.frames:B.computeFrenetFrames(A,!1);var K=new p;var Q=new p;var P=new p}x||(v=u=w=0);var L,R=this,z=a.extractPoints(z);a=z.shape;var O=z.holes;if(!Ha.isClockWise(a)){a=a.reverse();var M=0;for(L=O.length;M<L;M++){var V=
16996 O[M];Ha.isClockWise(V)&&(O[M]=V.reverse())}}var S=Ha.triangulateShape(a,O),W=a;M=0;for(L=O.length;M<L;M++)V=O[M],a=a.concat(V);var aa,Z=a.length,U,ca=S.length,z=[],G=0;var X=W.length;var fa=X-1;for(aa=G+1;G<X;G++,fa++,aa++)fa===X&&(fa=0),aa===X&&(aa=0),z[G]=d(W[G],W[fa],W[aa]);var B=[],ea=z.concat();M=0;for(L=O.length;M<L;M++){V=O[M];var da=[];G=0;X=V.length;fa=X-1;for(aa=G+1;G<X;G++,fa++,aa++)fa===X&&(fa=0),aa===X&&(aa=0),da[G]=d(V[G],V[fa],V[aa]);B.push(da);ea=ea.concat(da)}for(fa=0;fa<w;fa++){X=
16997 fa/w;var ga=u*Math.cos(X*Math.PI/2);aa=v*Math.sin(X*Math.PI/2);G=0;for(X=W.length;G<X;G++){var T=c(W[G],z[G],aa);f(T.x,T.y,-ga)}M=0;for(L=O.length;M<L;M++)for(V=O[M],da=B[M],G=0,X=V.length;G<X;G++)T=c(V[G],da[G],aa),f(T.x,T.y,-ga)}aa=v;for(G=0;G<Z;G++)T=x?c(a[G],ea[G],aa):a[G],D?(Q.copy(N.normals[0]).multiplyScalar(T.x),K.copy(N.binormals[0]).multiplyScalar(T.y),P.copy(H[0]).add(Q).add(K),f(P.x,P.y,P.z)):f(T.x,T.y,0);for(X=1;X<=A;X++)for(G=0;G<Z;G++)T=x?c(a[G],ea[G],aa):a[G],D?(Q.copy(N.normals[X]).multiplyScalar(T.x),
16998 K.copy(N.binormals[X]).multiplyScalar(T.y),P.copy(H[X]).add(Q).add(K),f(P.x,P.y,P.z)):f(T.x,T.y,l/A*X);for(fa=w-1;0<=fa;fa--){X=fa/w;ga=u*Math.cos(X*Math.PI/2);aa=v*Math.sin(X*Math.PI/2);G=0;for(X=W.length;G<X;G++)T=c(W[G],z[G],aa),f(T.x,T.y,l+ga);M=0;for(L=O.length;M<L;M++)for(V=O[M],da=B[M],G=0,X=V.length;G<X;G++)T=c(V[G],da[G],aa),D?f(T.x,T.y+H[A-1].y,H[A-1].x+ga):f(T.x,T.y,l+ga)}(function(){var a=m.length/3;if(x){var c=0*Z;for(G=0;G<ca;G++)U=S[G],g(U[2]+c,U[1]+c,U[0]+c);c=Z*(A+2*w);for(G=0;G<
16999 ca;G++)U=S[G],g(U[0]+c,U[1]+c,U[2]+c)}else{for(G=0;G<ca;G++)U=S[G],g(U[2],U[1],U[0]);for(G=0;G<ca;G++)U=S[G],g(U[0]+Z*A,U[1]+Z*A,U[2]+Z*A)}R.addGroup(a,m.length/3-a,void 0!==b.material?b.material:0)})();(function(){var a=m.length/3,c=0;e(W,c);c+=W.length;M=0;for(L=O.length;M<L;M++)V=O[M],e(V,c),c+=V.length;R.addGroup(a,m.length/3-a,void 0!==b.extrudeMaterial?b.extrudeMaterial:1)})();b.arrays||(this.setIndex(n),this.addAttribute("position",new y(m,3)),this.addAttribute("uv",new y(b.arrays.uv,2)))};
17000 $a.WorldUVGenerator={generateTopUV:function(a,b,c,d,e){a=b[3*d];d=b[3*d+1];var f=b[3*e];e=b[3*e+1];return[new C(b[3*c],b[3*c+1]),new C(a,d),new C(f,e)]},generateSideWallUV:function(a,b,c,d,e,f){a=b[3*c];var g=b[3*c+1];c=b[3*c+2];var h=b[3*d],k=b[3*d+1];d=b[3*d+2];var l=b[3*e],m=b[3*e+1];e=b[3*e+2];var n=b[3*f],p=b[3*f+1];b=b[3*f+2];return.01>Math.abs(g-k)?[new C(a,1-c),new C(h,1-d),new C(l,1-e),new C(n,1-b)]:[new C(g,1-c),new C(k,1-d),new C(m,1-e),new C(p,1-b)]}};Qc.prototype=Object.create(N.prototype);
17001 Qc.prototype.constructor=Qc;$b.prototype=Object.create(Ga.prototype);$b.prototype.constructor=$b;Rc.prototype=Object.create(N.prototype);Rc.prototype.constructor=Rc;ob.prototype=Object.create(D.prototype);ob.prototype.constructor=ob;Sc.prototype=Object.create(N.prototype);Sc.prototype.constructor=Sc;ac.prototype=Object.create(D.prototype);ac.prototype.constructor=ac;Tc.prototype=Object.create(N.prototype);Tc.prototype.constructor=Tc;bc.prototype=Object.create(D.prototype);bc.prototype.constructor=
17002 bc;cc.prototype=Object.create(N.prototype);cc.prototype.constructor=cc;dc.prototype=Object.create(D.prototype);dc.prototype.constructor=dc;ec.prototype=Object.create(D.prototype);ec.prototype.constructor=ec;pb.prototype=Object.create(N.prototype);pb.prototype.constructor=pb;Sa.prototype=Object.create(D.prototype);Sa.prototype.constructor=Sa;Uc.prototype=Object.create(pb.prototype);Uc.prototype.constructor=Uc;Vc.prototype=Object.create(Sa.prototype);Vc.prototype.constructor=Vc;Wc.prototype=Object.create(N.prototype);
17003 Wc.prototype.constructor=Wc;fc.prototype=Object.create(D.prototype);fc.prototype.constructor=fc;var Ca=Object.freeze({WireframeGeometry:Sb,ParametricGeometry:Hc,ParametricBufferGeometry:Tb,TetrahedronGeometry:Jc,TetrahedronBufferGeometry:Ub,OctahedronGeometry:Kc,OctahedronBufferGeometry:nb,IcosahedronGeometry:Lc,IcosahedronBufferGeometry:Vb,DodecahedronGeometry:Mc,DodecahedronBufferGeometry:Wb,PolyhedronGeometry:Ic,PolyhedronBufferGeometry:qa,TubeGeometry:Nc,TubeBufferGeometry:Xb,TorusKnotGeometry:Oc,
17004 TorusKnotBufferGeometry:Yb,TorusGeometry:Pc,TorusBufferGeometry:Zb,TextGeometry:Qc,TextBufferGeometry:$b,SphereGeometry:Rc,SphereBufferGeometry:ob,RingGeometry:Sc,RingBufferGeometry:ac,PlaneGeometry:Ac,PlaneBufferGeometry:kb,LatheGeometry:Tc,LatheBufferGeometry:bc,ShapeGeometry:cc,ShapeBufferGeometry:dc,ExtrudeGeometry:$a,ExtrudeBufferGeometry:Ga,EdgesGeometry:ec,ConeGeometry:Uc,ConeBufferGeometry:Vc,CylinderGeometry:pb,CylinderBufferGeometry:Sa,CircleGeometry:Wc,CircleBufferGeometry:fc,BoxGeometry:Lb,
17005 BoxBufferGeometry:jb});gc.prototype=Object.create(Q.prototype);gc.prototype.constructor=gc;gc.prototype.isShadowMaterial=!0;hc.prototype=Object.create(oa.prototype);hc.prototype.constructor=hc;hc.prototype.isRawShaderMaterial=!0;Ma.prototype=Object.create(Q.prototype);Ma.prototype.constructor=Ma;Ma.prototype.isMeshStandardMaterial=!0;Ma.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.defines={STANDARD:""};this.color.copy(a.color);this.roughness=a.roughness;this.metalness=a.metalness;
17006 this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.roughnessMap=a.roughnessMap;
17007 this.metalnessMap=a.metalnessMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.envMapIntensity=a.envMapIntensity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};qb.prototype=Object.create(Ma.prototype);qb.prototype.constructor=qb;qb.prototype.isMeshPhysicalMaterial=
17008 !0;qb.prototype.copy=function(a){Ma.prototype.copy.call(this,a);this.defines={PHYSICAL:""};this.reflectivity=a.reflectivity;this.clearCoat=a.clearCoat;this.clearCoatRoughness=a.clearCoatRoughness;return this};Ia.prototype=Object.create(Q.prototype);Ia.prototype.constructor=Ia;Ia.prototype.isMeshPhongMaterial=!0;Ia.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.specular.copy(a.specular);this.shininess=a.shininess;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=
17009 a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=
17010 a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};rb.prototype=Object.create(Ia.prototype);rb.prototype.constructor=rb;rb.prototype.isMeshToonMaterial=!0;rb.prototype.copy=function(a){Ia.prototype.copy.call(this,
17011 a);this.gradientMap=a.gradientMap;return this};sb.prototype=Object.create(Q.prototype);sb.prototype.constructor=sb;sb.prototype.isMeshNormalMaterial=!0;sb.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;
17012 this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};tb.prototype=Object.create(Q.prototype);tb.prototype.constructor=tb;tb.prototype.isMeshLambertMaterial=!0;tb.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=
17013 a.emissiveIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};ub.prototype=Object.create(O.prototype);ub.prototype.constructor=
17014 ub;ub.prototype.isLineDashedMaterial=!0;ub.prototype.copy=function(a){O.prototype.copy.call(this,a);this.scale=a.scale;this.dashSize=a.dashSize;this.gapSize=a.gapSize;return this};var tg=Object.freeze({ShadowMaterial:gc,SpriteMaterial:Za,RawShaderMaterial:hc,ShaderMaterial:oa,PointsMaterial:Ba,MeshPhysicalMaterial:qb,MeshStandardMaterial:Ma,MeshPhongMaterial:Ia,MeshToonMaterial:rb,MeshNormalMaterial:sb,MeshLambertMaterial:tb,MeshDepthMaterial:Wa,MeshDistanceMaterial:Xa,MeshBasicMaterial:va,LineDashedMaterial:ub,
17015 LineBasicMaterial:O,Material:Q}),jd={enabled:!1,files:{},add:function(a,b){!1!==this.enabled&&(this.files[a]=b)},get:function(a){if(!1!==this.enabled)return this.files[a]},remove:function(a){delete this.files[a]},clear:function(){this.files={}}},wa=new Yd,Ta={};Object.assign(Ja.prototype,{load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);a=this.manager.resolveURL(a);var e=this,f=jd.get(a);if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},
17016 0),f;if(void 0!==Ta[a])Ta[a].push({onLoad:b,onProgress:c,onError:d});else{var g=a.match(/^data:(.*?)(;base64)?,(.*)$/);if(g){c=g[1];var h=!!g[2],g=g[3],g=window.decodeURIComponent(g);h&&(g=window.atob(g));try{var k=(this.responseType||"").toLowerCase();switch(k){case "arraybuffer":case "blob":for(var l=new Uint8Array(g.length),h=0;h<g.length;h++)l[h]=g.charCodeAt(h);var m="blob"===k?new Blob([l.buffer],{type:c}):l.buffer;break;case "document":m=(new DOMParser).parseFromString(g,c);break;case "json":m=
17017 JSON.parse(g);break;default:m=g}window.setTimeout(function(){b&&b(m);e.manager.itemEnd(a)},0)}catch(t){window.setTimeout(function(){d&&d(t);e.manager.itemEnd(a);e.manager.itemError(a)},0)}}else{Ta[a]=[];Ta[a].push({onLoad:b,onProgress:c,onError:d});var n=new XMLHttpRequest;n.open("GET",a,!0);n.addEventListener("load",function(b){var c=b.target.response;jd.add(a,c);var d=Ta[a];delete Ta[a];if(200===this.status){for(var f=0,g=d.length;f<g;f++){var h=d[f];if(h.onLoad)h.onLoad(c)}e.manager.itemEnd(a)}else if(0===
17018 this.status){console.warn("THREE.FileLoader: HTTP Status 0 received.");f=0;for(g=d.length;f<g;f++)if(h=d[f],h.onLoad)h.onLoad(c);e.manager.itemEnd(a)}else{f=0;for(g=d.length;f<g;f++)if(h=d[f],h.onError)h.onError(b);e.manager.itemEnd(a);e.manager.itemError(a)}},!1);n.addEventListener("progress",function(b){for(var c=Ta[a],d=0,e=c.length;d<e;d++){var f=c[d];if(f.onProgress)f.onProgress(b)}},!1);n.addEventListener("error",function(b){var c=Ta[a];delete Ta[a];for(var d=0,f=c.length;d<f;d++){var g=c[d];
17019 if(g.onError)g.onError(b)}e.manager.itemEnd(a);e.manager.itemError(a)},!1);void 0!==this.responseType&&(n.responseType=this.responseType);void 0!==this.withCredentials&&(n.withCredentials=this.withCredentials);n.overrideMimeType&&n.overrideMimeType(void 0!==this.mimeType?this.mimeType:"text/plain");for(h in this.requestHeader)n.setRequestHeader(h,this.requestHeader[h]);n.send(null)}e.manager.itemStart(a);return n}},setPath:function(a){this.path=a;return this},setResponseType:function(a){this.responseType=
17020 a;return this},setWithCredentials:function(a){this.withCredentials=a;return this},setMimeType:function(a){this.mimeType=a;return this},setRequestHeader:function(a){this.requestHeader=a;return this}});Object.assign(Qe.prototype,{load:function(a,b,c,d){function e(e){l.load(a[e],function(a){a=g._parser(a,!0);h[e]={width:a.width,height:a.height,format:a.format,mipmaps:a.mipmaps};f+=1;6===f&&(1===a.mipmapCount&&(k.minFilter=1006),k.format=a.format,k.needsUpdate=!0,b&&b(k))},c,d)}var f,g=this,h=[],k=new Rb;
17021 k.image=h;var l=new Ja(this.manager);l.setPath(this.path);l.setResponseType("arraybuffer");if(Array.isArray(a))for(var m=f=0,n=a.length;m<n;++m)e(m);else l.load(a,function(a){a=g._parser(a,!0);if(a.isCubemap)for(var c=a.mipmaps.length/a.mipmapCount,d=0;d<c;d++){h[d]={mipmaps:[]};for(var e=0;e<a.mipmapCount;e++)h[d].mipmaps.push(a.mipmaps[d*a.mipmapCount+e]),h[d].format=a.format,h[d].width=a.width,h[d].height=a.height}else k.image.width=a.width,k.image.height=a.height,k.mipmaps=a.mipmaps;1===a.mipmapCount&&
17022 (k.minFilter=1006);k.format=a.format;k.needsUpdate=!0;b&&b(k)},c,d);return k},setPath:function(a){this.path=a;return this}});Object.assign(Zd.prototype,{load:function(a,b,c,d){var e=this,f=new fb,g=new Ja(this.manager);g.setResponseType("arraybuffer");g.load(a,function(a){if(a=e._parser(a))void 0!==a.image?f.image=a.image:void 0!==a.data&&(f.image.width=a.width,f.image.height=a.height,f.image.data=a.data),f.wrapS=void 0!==a.wrapS?a.wrapS:1001,f.wrapT=void 0!==a.wrapT?a.wrapT:1001,f.magFilter=void 0!==
17023 a.magFilter?a.magFilter:1006,f.minFilter=void 0!==a.minFilter?a.minFilter:1008,f.anisotropy=void 0!==a.anisotropy?a.anisotropy:1,void 0!==a.format&&(f.format=a.format),void 0!==a.type&&(f.type=a.type),void 0!==a.mipmaps&&(f.mipmaps=a.mipmaps),1===a.mipmapCount&&(f.minFilter=1006),f.needsUpdate=!0,b&&b(f,a)},c,d);return f}});Object.assign(Xc.prototype,{crossOrigin:"Anonymous",load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);a=this.manager.resolveURL(a);var e=this,f=jd.get(a);
17024 if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;c=document.createElementNS("http://www.w3.org/1999/xhtml","img");c.addEventListener("load",function(){jd.add(a,this);b&&b(this);e.manager.itemEnd(a)},!1);c.addEventListener("error",function(b){d&&d(b);e.manager.itemEnd(a);e.manager.itemError(a)},!1);"data:"!==a.substr(0,5)&&void 0!==this.crossOrigin&&(c.crossOrigin=this.crossOrigin);e.manager.itemStart(a);c.src=a;return c},setCrossOrigin:function(a){this.crossOrigin=
17025 a;return this},setPath:function(a){this.path=a;return this}});Object.assign($d.prototype,{crossOrigin:"Anonymous",load:function(a,b,c,d){function e(c){g.load(a[c],function(a){f.images[c]=a;h++;6===h&&(f.needsUpdate=!0,b&&b(f))},void 0,d)}var f=new Ua,g=new Xc(this.manager);g.setCrossOrigin(this.crossOrigin);g.setPath(this.path);var h=0;for(c=0;c<a.length;++c)e(c);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(td.prototype,
17026 {crossOrigin:"Anonymous",load:function(a,b,c,d){var e=new Xc(this.manager);e.setCrossOrigin(this.crossOrigin);e.setPath(this.path);var f=new ea;f.image=e.load(a,function(){var c=0<a.search(/\.(jpg|jpeg)$/)||0===a.search(/^data\:image\/jpeg/);f.format=c?1022:1023;f.needsUpdate=!0;void 0!==b&&b(f)},c,d);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});ga.prototype=Object.assign(Object.create(A.prototype),{constructor:ga,isLight:!0,copy:function(a){A.prototype.copy.call(this,
17027 a);this.color.copy(a.color);this.intensity=a.intensity;return this},toJSON:function(a){a=A.prototype.toJSON.call(this,a);a.object.color=this.color.getHex();a.object.intensity=this.intensity;void 0!==this.groundColor&&(a.object.groundColor=this.groundColor.getHex());void 0!==this.distance&&(a.object.distance=this.distance);void 0!==this.angle&&(a.object.angle=this.angle);void 0!==this.decay&&(a.object.decay=this.decay);void 0!==this.penumbra&&(a.object.penumbra=this.penumbra);void 0!==this.shadow&&
17028 (a.object.shadow=this.shadow.toJSON());return a}});ud.prototype=Object.assign(Object.create(ga.prototype),{constructor:ud,isHemisphereLight:!0,copy:function(a){ga.prototype.copy.call(this,a);this.groundColor.copy(a.groundColor);return this}});Object.assign(vb.prototype,{copy:function(a){this.camera=a.camera.clone();this.bias=a.bias;this.radius=a.radius;this.mapSize.copy(a.mapSize);return this},clone:function(){return(new this.constructor).copy(this)},toJSON:function(){var a={};0!==this.bias&&(a.bias=
17029 this.bias);1!==this.radius&&(a.radius=this.radius);if(512!==this.mapSize.x||512!==this.mapSize.y)a.mapSize=this.mapSize.toArray();a.camera=this.camera.toJSON(!1).object;delete a.camera.matrix;return a}});vd.prototype=Object.assign(Object.create(vb.prototype),{constructor:vd,isSpotLightShadow:!0,update:function(a){var b=this.camera,c=2*R.RAD2DEG*a.angle,d=this.mapSize.width/this.mapSize.height;a=a.distance||b.far;if(c!==b.fov||d!==b.aspect||a!==b.far)b.fov=c,b.aspect=d,b.far=a,b.updateProjectionMatrix()}});
17030 wd.prototype=Object.assign(Object.create(ga.prototype),{constructor:wd,isSpotLight:!0,copy:function(a){ga.prototype.copy.call(this,a);this.distance=a.distance;this.angle=a.angle;this.penumbra=a.penumbra;this.decay=a.decay;this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});xd.prototype=Object.assign(Object.create(ga.prototype),{constructor:xd,isPointLight:!0,copy:function(a){ga.prototype.copy.call(this,a);this.distance=a.distance;this.decay=a.decay;this.shadow=a.shadow.clone();
17031 return this}});yd.prototype=Object.assign(Object.create(vb.prototype),{constructor:yd});zd.prototype=Object.assign(Object.create(ga.prototype),{constructor:zd,isDirectionalLight:!0,copy:function(a){ga.prototype.copy.call(this,a);this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});Ad.prototype=Object.assign(Object.create(ga.prototype),{constructor:Ad,isAmbientLight:!0});Bd.prototype=Object.assign(Object.create(ga.prototype),{constructor:Bd,isRectAreaLight:!0,copy:function(a){ga.prototype.copy.call(this,
17032 a);this.width=a.width;this.height=a.height;return this},toJSON:function(a){a=ga.prototype.toJSON.call(this,a);a.object.width=this.width;a.object.height=this.height;return a}});var T={arraySlice:function(a,b,c){return T.isTypedArray(a)?new a.constructor(a.subarray(b,void 0!==c?c:a.length)):a.slice(b,c)},convertArray:function(a,b,c){return!a||!c&&a.constructor===b?a:"number"===typeof b.BYTES_PER_ELEMENT?new b(a):Array.prototype.slice.call(a)},isTypedArray:function(a){return ArrayBuffer.isView(a)&&!(a instanceof
17033 DataView)},getKeyframeOrder:function(a){for(var b=a.length,c=Array(b),d=0;d!==b;++d)c[d]=d;c.sort(function(b,c){return a[b]-a[c]});return c},sortedArray:function(a,b,c){for(var d=a.length,e=new a.constructor(d),f=0,g=0;g!==d;++f)for(var h=c[f]*b,k=0;k!==b;++k)e[g++]=a[h+k];return e},flattenJSON:function(a,b,c,d){for(var e=1,f=a[0];void 0!==f&&void 0===f[d];)f=a[e++];if(void 0!==f){var g=f[d];if(void 0!==g)if(Array.isArray(g)){do g=f[d],void 0!==g&&(b.push(f.time),c.push.apply(c,g)),f=a[e++];while(void 0!==
17034 f)}else if(void 0!==g.toArray){do g=f[d],void 0!==g&&(b.push(f.time),g.toArray(c,c.length)),f=a[e++];while(void 0!==f)}else{do g=f[d],void 0!==g&&(b.push(f.time),c.push(g)),f=a[e++];while(void 0!==f)}}}};Object.assign(xa.prototype,{evaluate:function(a){var b=this.parameterPositions,c=this._cachedIndex,d=b[c],e=b[c-1];a:{b:{c:{d:if(!(a<d)){for(var f=c+2;;){if(void 0===d){if(a<e)break d;this._cachedIndex=c=b.length;return this.afterEnd_(c-1,a,e)}if(c===f)break;e=d;d=b[++c];if(a<d)break b}d=b.length;
17035 break c}if(a>=e)break a;else{f=b[1];a<f&&(c=2,e=f);for(f=c-2;;){if(void 0===e)return this._cachedIndex=0,this.beforeStart_(0,a,d);if(c===f)break;d=e;e=b[--c-1];if(a>=e)break b}d=c;c=0}}for(;c<d;)e=c+d>>>1,a<b[e]?d=e:c=e+1;d=b[c];e=b[c-1];if(void 0===e)return this._cachedIndex=0,this.beforeStart_(0,a,d);if(void 0===d)return this._cachedIndex=c=b.length,this.afterEnd_(c-1,e,a)}this._cachedIndex=c;this.intervalChanged_(c,e,d)}return this.interpolate_(c,e,a,d)},settings:null,DefaultSettings_:{},getSettings_:function(){return this.settings||
17036 this.DefaultSettings_},copySampleValue_:function(a){var b=this.resultBuffer,c=this.sampleValues,d=this.valueSize;a*=d;for(var e=0;e!==d;++e)b[e]=c[a+e];return b},interpolate_:function(){throw Error("call to abstract method");},intervalChanged_:function(){}});Object.assign(xa.prototype,{beforeStart_:xa.prototype.copySampleValue_,afterEnd_:xa.prototype.copySampleValue_});Cd.prototype=Object.assign(Object.create(xa.prototype),{constructor:Cd,DefaultSettings_:{endingStart:2400,endingEnd:2400},intervalChanged_:function(a,
17037 b,c){var d=this.parameterPositions,e=a-2,f=a+1,g=d[e],h=d[f];if(void 0===g)switch(this.getSettings_().endingStart){case 2401:e=a;g=2*b-c;break;case 2402:e=d.length-2;g=b+d[e]-d[e+1];break;default:e=a,g=c}if(void 0===h)switch(this.getSettings_().endingEnd){case 2401:f=a;h=2*c-b;break;case 2402:f=1;h=c+d[1]-d[0];break;default:f=a-1,h=b}a=.5*(c-b);d=this.valueSize;this._weightPrev=a/(b-g);this._weightNext=a/(h-c);this._offsetPrev=e*d;this._offsetNext=f*d},interpolate_:function(a,b,c,d){var e=this.resultBuffer,
17038 f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g,k=this._offsetPrev,l=this._offsetNext,m=this._weightPrev,n=this._weightNext,p=(c-b)/(d-b);c=p*p;d=c*p;b=-m*d+2*m*c-m*p;m=(1+m)*d+(-1.5-2*m)*c+(-.5+m)*p+1;p=(-1-n)*d+(1.5+n)*c+.5*p;n=n*d-n*c;for(c=0;c!==g;++c)e[c]=b*f[k+c]+m*f[h+c]+p*f[a+c]+n*f[l+c];return e}});Yc.prototype=Object.assign(Object.create(xa.prototype),{constructor:Yc,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g;b=(c-b)/(d-
17039 b);c=1-b;for(d=0;d!==g;++d)e[d]=f[h+d]*c+f[a+d]*b;return e}});Dd.prototype=Object.assign(Object.create(xa.prototype),{constructor:Dd,interpolate_:function(a){return this.copySampleValue_(a-1)}});var eb={TimeBufferType:Float32Array,ValueBufferType:Float32Array,DefaultInterpolation:2301,InterpolantFactoryMethodDiscrete:function(a){return new Dd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodLinear:function(a){return new Yc(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:function(a){return new Cd(this.times,
17040 this.values,this.getValueSize(),a)},setInterpolation:function(a){switch(a){case 2300:var b=this.InterpolantFactoryMethodDiscrete;break;case 2301:b=this.InterpolantFactoryMethodLinear;break;case 2302:b=this.InterpolantFactoryMethodSmooth}if(void 0===b){b="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(void 0===this.createInterpolant)if(a!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(b);console.warn("THREE.KeyframeTrackPrototype:",
17041 b)}else this.createInterpolant=b},getInterpolation:function(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return 2300;case this.InterpolantFactoryMethodLinear:return 2301;case this.InterpolantFactoryMethodSmooth:return 2302}},getValueSize:function(){return this.values.length/this.times.length},shift:function(a){if(0!==a)for(var b=this.times,c=0,d=b.length;c!==d;++c)b[c]+=a;return this},scale:function(a){if(1!==a)for(var b=this.times,c=0,d=b.length;c!==d;++c)b[c]*=a;return this},
17042 trim:function(a,b){for(var c=this.times,d=c.length,e=0,f=d-1;e!==d&&c[e]<a;)++e;for(;-1!==f&&c[f]>b;)--f;++f;if(0!==e||f!==d)e>=f&&(f=Math.max(f,1),e=f-1),a=this.getValueSize(),this.times=T.arraySlice(c,e,f),this.values=T.arraySlice(this.values,e*a,f*a);return this},validate:function(){var a=!0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("THREE.KeyframeTrackPrototype: Invalid value size in track.",this),a=!1);var c=this.times,b=this.values,d=c.length;0===d&&(console.error("THREE.KeyframeTrackPrototype: Track is empty.",
17043 this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("THREE.KeyframeTrackPrototype: Time is not a valid number.",this,f,g);a=!1;break}if(null!==e&&e>g){console.error("THREE.KeyframeTrackPrototype: Out of order keys.",this,f,g,e);a=!1;break}e=g}if(void 0!==b&&T.isTypedArray(b))for(f=0,c=b.length;f!==c;++f)if(d=b[f],isNaN(d)){console.error("THREE.KeyframeTrackPrototype: Value is not a valid number.",this,f,d);a=!1;break}return a},optimize:function(){for(var a,
17044 b,c=this.times,d=this.values,e=this.getValueSize(),f=2302===this.getInterpolation(),g=1,h=c.length-1,k=1;k<h;++k){a=!1;var l=c[k];if(l!==c[k+1]&&(1!==k||l!==l[0]))if(f)a=!0;else{b=k*e;for(var m=b-e,n=b+e,l=0;l!==e;++l){var p=d[b+l];if(p!==d[m+l]||p!==d[n+l]){a=!0;break}}}if(a){if(k!==g)for(c[g]=c[k],b=k*e,a=g*e,l=0;l!==e;++l)d[a+l]=d[b+l];++g}}if(0<h){c[g]=c[h];b=h*e;a=g*e;for(l=0;l!==e;++l)d[a+l]=d[b+l];++g}g!==c.length&&(this.times=T.arraySlice(c,0,g),this.values=T.arraySlice(d,0,g*e));return this}};
17045 ic.prototype=Object.assign(Object.create(eb),{constructor:ic,ValueTypeName:"vector"});Ed.prototype=Object.assign(Object.create(xa.prototype),{constructor:Ed,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;b=(c-b)/(d-b);for(c=a+g;a!==c;a+=4)Z.slerpFlat(e,0,f,a-g,f,a,b);return e}});Zc.prototype=Object.assign(Object.create(eb),{constructor:Zc,ValueTypeName:"quaternion",DefaultInterpolation:2301,InterpolantFactoryMethodLinear:function(a){return new Ed(this.times,
17046 this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:void 0});jc.prototype=Object.assign(Object.create(eb),{constructor:jc,ValueTypeName:"number"});Fd.prototype=Object.assign(Object.create(eb),{constructor:Fd,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Gd.prototype=Object.assign(Object.create(eb),{constructor:Gd,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:2300,
17047 InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Hd.prototype=Object.assign(Object.create(eb),{constructor:Hd,ValueTypeName:"color"});xb.prototype=eb;eb.constructor=xb;Object.assign(xb,{parse:function(a){if(void 0===a.type)throw Error("track type undefined, can not parse");var b=xb._getTrackTypeForValueTypeName(a.type);if(void 0===a.times){var c=[],d=[];T.flattenJSON(a.keys,c,d,"value");a.times=c;a.values=d}return void 0!==b.parse?b.parse(a):new b(a.name,a.times,a.values,
17048 a.interpolation)},toJSON:function(a){var b=a.constructor;if(void 0!==b.toJSON)b=b.toJSON(a);else{var b={name:a.name,times:T.convertArray(a.times,Array),values:T.convertArray(a.values,Array)},c=a.getInterpolation();c!==a.DefaultInterpolation&&(b.interpolation=c)}b.type=a.ValueTypeName;return b},_getTrackTypeForValueTypeName:function(a){switch(a.toLowerCase()){case "scalar":case "double":case "float":case "number":case "integer":return jc;case "vector":case "vector2":case "vector3":case "vector4":return ic;
17049 case "color":return Hd;case "quaternion":return Zc;case "bool":case "boolean":return Gd;case "string":return Fd}throw Error("Unsupported typeName: "+a);}});Object.assign(ka,{parse:function(a){for(var b=[],c=a.tracks,d=1/(a.fps||1),e=0,f=c.length;e!==f;++e)b.push(xb.parse(c[e]).scale(d));return new ka(a.name,a.duration,b)},toJSON:function(a){var b=[],c=a.tracks;a={name:a.name,duration:a.duration,tracks:b};for(var d=0,e=c.length;d!==e;++d)b.push(xb.toJSON(c[d]));return a},CreateFromMorphTargetSequence:function(a,
17050 b,c,d){for(var e=b.length,f=[],g=0;g<e;g++){var h=[],k=[];h.push((g+e-1)%e,g,(g+1)%e);k.push(0,1,0);var l=T.getKeyframeOrder(h),h=T.sortedArray(h,1,l),k=T.sortedArray(k,1,l);d||0!==h[0]||(h.push(e),k.push(k[0]));f.push((new jc(".morphTargetInfluences["+b[g].name+"]",h,k)).scale(1/c))}return new ka(a,-1,f)},findByName:function(a,b){var c=a;Array.isArray(a)||(c=a.geometry&&a.geometry.animations||a.animations);for(a=0;a<c.length;a++)if(c[a].name===b)return c[a];return null},CreateClipsFromMorphTargetSequences:function(a,
17051 b,c){for(var d,e={},f=/^([\w-]*?)([\d]+)$/,g=0,h=a.length;g<h;g++){var k=a[g],l=k.name.match(f);l&&1<l.length&&(d=l[1],(l=e[d])||(e[d]=l=[]),l.push(k))}a=[];for(d in e)a.push(ka.CreateFromMorphTargetSequence(d,e[d],b,c));return a},parseAnimation:function(a,b){if(!a)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;var c=function(a,b,c,d,e){if(0!==c.length){var f=[],g=[];T.flattenJSON(c,f,g,d);0!==f.length&&e.push(new a(b,f,g))}},d=[],e=a.name||"default",f=a.length||
17052 -1,g=a.fps||30;a=a.hierarchy||[];for(var h=0;h<a.length;h++){var k=a[h].keys;if(k&&0!==k.length)if(k[0].morphTargets){for(var f={},l=0;l<k.length;l++)if(k[l].morphTargets)for(var m=0;m<k[l].morphTargets.length;m++)f[k[l].morphTargets[m]]=-1;for(var n in f){for(var p=[],r=[],m=0;m!==k[l].morphTargets.length;++m){var u=k[l];p.push(u.time);r.push(u.morphTarget===n?1:0)}d.push(new jc(".morphTargetInfluence["+n+"]",p,r))}f=f.length*(g||1)}else l=".bones["+b[h].name+"]",c(ic,l+".position",k,"pos",d),c(Zc,
17053 l+".quaternion",k,"rot",d),c(ic,l+".scale",k,"scl",d)}return 0===d.length?null:new ka(e,f,d)}});Object.assign(ka.prototype,{resetDuration:function(){for(var a=0,b=0,c=this.tracks.length;b!==c;++b)var d=this.tracks[b],a=Math.max(a,d.times[d.times.length-1]);this.duration=a},trim:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].trim(0,this.duration);return this},optimize:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].optimize();return this}});Object.assign(Id.prototype,
17054 {load:function(a,b,c,d){var e=this;(new Ja(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},setTextures:function(a){this.textures=a},parse:function(a){function b(a){void 0===c[a]&&console.warn("THREE.MaterialLoader: Undefined texture",a);return c[a]}var c=this.textures,d=new tg[a.type];void 0!==a.uuid&&(d.uuid=a.uuid);void 0!==a.name&&(d.name=a.name);void 0!==a.color&&d.color.setHex(a.color);void 0!==a.roughness&&(d.roughness=a.roughness);void 0!==a.metalness&&(d.metalness=a.metalness);
17055 void 0!==a.emissive&&d.emissive.setHex(a.emissive);void 0!==a.specular&&d.specular.setHex(a.specular);void 0!==a.shininess&&(d.shininess=a.shininess);void 0!==a.clearCoat&&(d.clearCoat=a.clearCoat);void 0!==a.clearCoatRoughness&&(d.clearCoatRoughness=a.clearCoatRoughness);void 0!==a.uniforms&&(d.uniforms=a.uniforms);void 0!==a.vertexShader&&(d.vertexShader=a.vertexShader);void 0!==a.fragmentShader&&(d.fragmentShader=a.fragmentShader);void 0!==a.vertexColors&&(d.vertexColors=a.vertexColors);void 0!==
17056 a.fog&&(d.fog=a.fog);void 0!==a.flatShading&&(d.flatShading=a.flatShading);void 0!==a.blending&&(d.blending=a.blending);void 0!==a.side&&(d.side=a.side);void 0!==a.opacity&&(d.opacity=a.opacity);void 0!==a.transparent&&(d.transparent=a.transparent);void 0!==a.alphaTest&&(d.alphaTest=a.alphaTest);void 0!==a.depthTest&&(d.depthTest=a.depthTest);void 0!==a.depthWrite&&(d.depthWrite=a.depthWrite);void 0!==a.colorWrite&&(d.colorWrite=a.colorWrite);void 0!==a.wireframe&&(d.wireframe=a.wireframe);void 0!==
17057 a.wireframeLinewidth&&(d.wireframeLinewidth=a.wireframeLinewidth);void 0!==a.wireframeLinecap&&(d.wireframeLinecap=a.wireframeLinecap);void 0!==a.wireframeLinejoin&&(d.wireframeLinejoin=a.wireframeLinejoin);void 0!==a.rotation&&(d.rotation=a.rotation);1!==a.linewidth&&(d.linewidth=a.linewidth);void 0!==a.dashSize&&(d.dashSize=a.dashSize);void 0!==a.gapSize&&(d.gapSize=a.gapSize);void 0!==a.scale&&(d.scale=a.scale);void 0!==a.skinning&&(d.skinning=a.skinning);void 0!==a.morphTargets&&(d.morphTargets=
17058 a.morphTargets);void 0!==a.dithering&&(d.dithering=a.dithering);void 0!==a.visible&&(d.visible=a.visible);void 0!==a.userData&&(d.userData=a.userData);void 0!==a.shading&&(d.flatShading=1===a.shading);void 0!==a.size&&(d.size=a.size);void 0!==a.sizeAttenuation&&(d.sizeAttenuation=a.sizeAttenuation);void 0!==a.map&&(d.map=b(a.map));void 0!==a.alphaMap&&(d.alphaMap=b(a.alphaMap),d.transparent=!0);void 0!==a.bumpMap&&(d.bumpMap=b(a.bumpMap));void 0!==a.bumpScale&&(d.bumpScale=a.bumpScale);void 0!==a.normalMap&&
17059 (d.normalMap=b(a.normalMap));if(void 0!==a.normalScale){var e=a.normalScale;!1===Array.isArray(e)&&(e=[e,e]);d.normalScale=(new C).fromArray(e)}void 0!==a.displacementMap&&(d.displacementMap=b(a.displacementMap));void 0!==a.displacementScale&&(d.displacementScale=a.displacementScale);void 0!==a.displacementBias&&(d.displacementBias=a.displacementBias);void 0!==a.roughnessMap&&(d.roughnessMap=b(a.roughnessMap));void 0!==a.metalnessMap&&(d.metalnessMap=b(a.metalnessMap));void 0!==a.emissiveMap&&(d.emissiveMap=
17060 b(a.emissiveMap));void 0!==a.emissiveIntensity&&(d.emissiveIntensity=a.emissiveIntensity);void 0!==a.specularMap&&(d.specularMap=b(a.specularMap));void 0!==a.envMap&&(d.envMap=b(a.envMap));void 0!==a.reflectivity&&(d.reflectivity=a.reflectivity);void 0!==a.lightMap&&(d.lightMap=b(a.lightMap));void 0!==a.lightMapIntensity&&(d.lightMapIntensity=a.lightMapIntensity);void 0!==a.aoMap&&(d.aoMap=b(a.aoMap));void 0!==a.aoMapIntensity&&(d.aoMapIntensity=a.aoMapIntensity);void 0!==a.gradientMap&&(d.gradientMap=
17061 b(a.gradientMap));return d}});Object.assign(ae.prototype,{load:function(a,b,c,d){var e=this;(new Ja(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},parse:function(a){var b=new D;var c=a.data.index;void 0!==c&&(c=new gf[c.type](c.array),b.setIndex(new P(c,1)));var d=a.data.attributes;for(f in d){var e=d[f];c=new gf[e.type](e.array);b.addAttribute(f,new P(c,e.itemSize,e.normalized))}var f=a.data.groups||a.data.drawcalls||a.data.offsets;if(void 0!==f)for(c=0,d=f.length;c!==d;++c)e=f[c],
17062 b.addGroup(e.start,e.count,e.materialIndex);a=a.data.boundingSphere;void 0!==a&&(f=new p,void 0!==a.center&&f.fromArray(a.center),b.boundingSphere=new Da(f,a.radius));return b}});var gf={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:"undefined"!==typeof Uint8ClampedArray?Uint8ClampedArray:Uint8Array,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};kc.Handlers={handlers:[],add:function(a,b){this.handlers.push(a,
17063 b)},get:function(a){for(var b=this.handlers,c=0,d=b.length;c<d;c+=2){var e=b[c+1];if(b[c].test(a))return e}return null}};Object.assign(kc.prototype,{crossOrigin:void 0,extractUrlBase:function(a){a=a.split("/");if(1===a.length)return"./";a.pop();return a.join("/")+"/"},initMaterials:function(a,b,c){for(var d=[],e=0;e<a.length;++e)d[e]=this.createMaterial(a[e],b,c);return d},createMaterial:function(){var a={NoBlending:0,NormalBlending:1,AdditiveBlending:2,SubtractiveBlending:3,MultiplyBlending:4,CustomBlending:5},
17064 b=new H,c=new td,d=new Id;return function(e,f,g){function h(a,b,d,e,h){a=f+a;var l=kc.Handlers.get(a);null!==l?a=l.load(a):(c.setCrossOrigin(g),a=c.load(a));void 0!==b&&(a.repeat.fromArray(b),1!==b[0]&&(a.wrapS=1E3),1!==b[1]&&(a.wrapT=1E3));void 0!==d&&a.offset.fromArray(d);void 0!==e&&("repeat"===e[0]&&(a.wrapS=1E3),"mirror"===e[0]&&(a.wrapS=1002),"repeat"===e[1]&&(a.wrapT=1E3),"mirror"===e[1]&&(a.wrapT=1002));void 0!==h&&(a.anisotropy=h);b=R.generateUUID();k[b]=a;return b}var k={},l={uuid:R.generateUUID(),
17065 type:"MeshLambertMaterial"},m;for(m in e){var n=e[m];switch(m){case "DbgColor":case "DbgIndex":case "opticalDensity":case "illumination":break;case "DbgName":l.name=n;break;case "blending":l.blending=a[n];break;case "colorAmbient":case "mapAmbient":console.warn("THREE.Loader.createMaterial:",m,"is no longer supported.");break;case "colorDiffuse":l.color=b.fromArray(n).getHex();break;case "colorSpecular":l.specular=b.fromArray(n).getHex();break;case "colorEmissive":l.emissive=b.fromArray(n).getHex();
17066 break;case "specularCoef":l.shininess=n;break;case "shading":"basic"===n.toLowerCase()&&(l.type="MeshBasicMaterial");"phong"===n.toLowerCase()&&(l.type="MeshPhongMaterial");"standard"===n.toLowerCase()&&(l.type="MeshStandardMaterial");break;case "mapDiffuse":l.map=h(n,e.mapDiffuseRepeat,e.mapDiffuseOffset,e.mapDiffuseWrap,e.mapDiffuseAnisotropy);break;case "mapDiffuseRepeat":case "mapDiffuseOffset":case "mapDiffuseWrap":case "mapDiffuseAnisotropy":break;case "mapEmissive":l.emissiveMap=h(n,e.mapEmissiveRepeat,
17067 e.mapEmissiveOffset,e.mapEmissiveWrap,e.mapEmissiveAnisotropy);break;case "mapEmissiveRepeat":case "mapEmissiveOffset":case "mapEmissiveWrap":case "mapEmissiveAnisotropy":break;case "mapLight":l.lightMap=h(n,e.mapLightRepeat,e.mapLightOffset,e.mapLightWrap,e.mapLightAnisotropy);break;case "mapLightRepeat":case "mapLightOffset":case "mapLightWrap":case "mapLightAnisotropy":break;case "mapAO":l.aoMap=h(n,e.mapAORepeat,e.mapAOOffset,e.mapAOWrap,e.mapAOAnisotropy);break;case "mapAORepeat":case "mapAOOffset":case "mapAOWrap":case "mapAOAnisotropy":break;
17068 case "mapBump":l.bumpMap=h(n,e.mapBumpRepeat,e.mapBumpOffset,e.mapBumpWrap,e.mapBumpAnisotropy);break;case "mapBumpScale":l.bumpScale=n;break;case "mapBumpRepeat":case "mapBumpOffset":case "mapBumpWrap":case "mapBumpAnisotropy":break;case "mapNormal":l.normalMap=h(n,e.mapNormalRepeat,e.mapNormalOffset,e.mapNormalWrap,e.mapNormalAnisotropy);break;case "mapNormalFactor":l.normalScale=[n,n];break;case "mapNormalRepeat":case "mapNormalOffset":case "mapNormalWrap":case "mapNormalAnisotropy":break;case "mapSpecular":l.specularMap=
17069 h(n,e.mapSpecularRepeat,e.mapSpecularOffset,e.mapSpecularWrap,e.mapSpecularAnisotropy);break;case "mapSpecularRepeat":case "mapSpecularOffset":case "mapSpecularWrap":case "mapSpecularAnisotropy":break;case "mapMetalness":l.metalnessMap=h(n,e.mapMetalnessRepeat,e.mapMetalnessOffset,e.mapMetalnessWrap,e.mapMetalnessAnisotropy);break;case "mapMetalnessRepeat":case "mapMetalnessOffset":case "mapMetalnessWrap":case "mapMetalnessAnisotropy":break;case "mapRoughness":l.roughnessMap=h(n,e.mapRoughnessRepeat,
17070 e.mapRoughnessOffset,e.mapRoughnessWrap,e.mapRoughnessAnisotropy);break;case "mapRoughnessRepeat":case "mapRoughnessOffset":case "mapRoughnessWrap":case "mapRoughnessAnisotropy":break;case "mapAlpha":l.alphaMap=h(n,e.mapAlphaRepeat,e.mapAlphaOffset,e.mapAlphaWrap,e.mapAlphaAnisotropy);break;case "mapAlphaRepeat":case "mapAlphaOffset":case "mapAlphaWrap":case "mapAlphaAnisotropy":break;case "flipSided":l.side=1;break;case "doubleSided":l.side=2;break;case "transparency":console.warn("THREE.Loader.createMaterial: transparency has been renamed to opacity");
17071 l.opacity=n;break;case "depthTest":case "depthWrite":case "colorWrite":case "opacity":case "reflectivity":case "transparent":case "visible":case "wireframe":l[m]=n;break;case "vertexColors":!0===n&&(l.vertexColors=2);"face"===n&&(l.vertexColors=1);break;default:console.error("THREE.Loader.createMaterial: Unsupported",m,n)}}"MeshBasicMaterial"===l.type&&delete l.emissive;"MeshPhongMaterial"!==l.type&&delete l.specular;1>l.opacity&&(l.transparent=!0);d.setTextures(k);return d.parse(l)}}()});Object.assign(be.prototype,
17072 {load:function(a,b,c,d){var e=this,f=this.texturePath&&"string"===typeof this.texturePath?this.texturePath:kc.prototype.extractUrlBase(a),g=new Ja(this.manager);g.setWithCredentials(this.withCredentials);g.load(a,function(c){c=JSON.parse(c);var d=c.metadata;if(void 0!==d&&(d=d.type,void 0!==d)){if("object"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.ObjectLoader instead.");return}if("scene"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.SceneLoader instead.");
17073 return}}c=e.parse(c,f);b(c.geometry,c.materials)},c,d)},setTexturePath:function(a){this.texturePath=a},parse:function(){return function(a,b){void 0!==a.data&&(a=a.data);a.scale=void 0!==a.scale?1/a.scale:1;var c=new N,d=a,e,f,g,h=d.faces;var k=d.vertices;var l=d.normals,m=d.colors;var n=d.scale;var t=0;if(void 0!==d.uvs){for(e=0;e<d.uvs.length;e++)d.uvs[e].length&&t++;for(e=0;e<t;e++)c.faceVertexUvs[e]=[]}var r=0;for(g=k.length;r<g;)e=new p,e.x=k[r++]*n,e.y=k[r++]*n,e.z=k[r++]*n,c.vertices.push(e);
17074 r=0;for(g=h.length;r<g;){k=h[r++];var u=k&1;var v=k&2;e=k&8;var w=k&16;var x=k&32;n=k&64;k&=128;if(u){u=new Pa;u.a=h[r];u.b=h[r+1];u.c=h[r+3];var z=new Pa;z.a=h[r+1];z.b=h[r+2];z.c=h[r+3];r+=4;v&&(v=h[r++],u.materialIndex=v,z.materialIndex=v);v=c.faces.length;if(e)for(e=0;e<t;e++){var y=d.uvs[e];c.faceVertexUvs[e][v]=[];c.faceVertexUvs[e][v+1]=[];for(f=0;4>f;f++){var B=h[r++];var A=y[2*B];B=y[2*B+1];A=new C(A,B);2!==f&&c.faceVertexUvs[e][v].push(A);0!==f&&c.faceVertexUvs[e][v+1].push(A)}}w&&(w=3*
17075 h[r++],u.normal.set(l[w++],l[w++],l[w]),z.normal.copy(u.normal));if(x)for(e=0;4>e;e++)w=3*h[r++],x=new p(l[w++],l[w++],l[w]),2!==e&&u.vertexNormals.push(x),0!==e&&z.vertexNormals.push(x);n&&(n=h[r++],n=m[n],u.color.setHex(n),z.color.setHex(n));if(k)for(e=0;4>e;e++)n=h[r++],n=m[n],2!==e&&u.vertexColors.push(new H(n)),0!==e&&z.vertexColors.push(new H(n));c.faces.push(u);c.faces.push(z)}else{u=new Pa;u.a=h[r++];u.b=h[r++];u.c=h[r++];v&&(v=h[r++],u.materialIndex=v);v=c.faces.length;if(e)for(e=0;e<t;e++)for(y=
17076 d.uvs[e],c.faceVertexUvs[e][v]=[],f=0;3>f;f++)B=h[r++],A=y[2*B],B=y[2*B+1],A=new C(A,B),c.faceVertexUvs[e][v].push(A);w&&(w=3*h[r++],u.normal.set(l[w++],l[w++],l[w]));if(x)for(e=0;3>e;e++)w=3*h[r++],x=new p(l[w++],l[w++],l[w]),u.vertexNormals.push(x);n&&(n=h[r++],u.color.setHex(m[n]));if(k)for(e=0;3>e;e++)n=h[r++],u.vertexColors.push(new H(m[n]));c.faces.push(u)}}d=a;r=void 0!==d.influencesPerVertex?d.influencesPerVertex:2;if(d.skinWeights)for(g=0,h=d.skinWeights.length;g<h;g+=r)c.skinWeights.push(new da(d.skinWeights[g],
17077 1<r?d.skinWeights[g+1]:0,2<r?d.skinWeights[g+2]:0,3<r?d.skinWeights[g+3]:0));if(d.skinIndices)for(g=0,h=d.skinIndices.length;g<h;g+=r)c.skinIndices.push(new da(d.skinIndices[g],1<r?d.skinIndices[g+1]:0,2<r?d.skinIndices[g+2]:0,3<r?d.skinIndices[g+3]:0));c.bones=d.bones;c.bones&&0<c.bones.length&&(c.skinWeights.length!==c.skinIndices.length||c.skinIndices.length!==c.vertices.length)&&console.warn("When skinning, number of vertices ("+c.vertices.length+"), skinIndices ("+c.skinIndices.length+"), and skinWeights ("+
17078 c.skinWeights.length+") should match.");g=a;h=g.scale;if(void 0!==g.morphTargets)for(d=0,r=g.morphTargets.length;d<r;d++)for(c.morphTargets[d]={},c.morphTargets[d].name=g.morphTargets[d].name,c.morphTargets[d].vertices=[],l=c.morphTargets[d].vertices,m=g.morphTargets[d].vertices,t=0,k=m.length;t<k;t+=3)n=new p,n.x=m[t]*h,n.y=m[t+1]*h,n.z=m[t+2]*h,l.push(n);if(void 0!==g.morphColors&&0<g.morphColors.length)for(console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.'),
17079 h=c.faces,g=g.morphColors[0].colors,d=0,r=h.length;d<r;d++)h[d].color.fromArray(g,3*d);g=a;d=[];r=[];void 0!==g.animation&&r.push(g.animation);void 0!==g.animations&&(g.animations.length?r=r.concat(g.animations):r.push(g.animations));for(g=0;g<r.length;g++)(h=ka.parseAnimation(r[g],c.bones))&&d.push(h);c.morphTargets&&(r=ka.CreateClipsFromMorphTargetSequences(c.morphTargets,10),d=d.concat(r));0<d.length&&(c.animations=d);c.computeFaceNormals();c.computeBoundingSphere();if(void 0===a.materials||0===
17080 a.materials.length)return{geometry:c};a=kc.prototype.initMaterials(a.materials,b,this.crossOrigin);return{geometry:c,materials:a}}}()});Object.assign(Re.prototype,{load:function(a,b,c,d){""===this.texturePath&&(this.texturePath=a.substring(0,a.lastIndexOf("/")+1));var e=this;(new Ja(e.manager)).load(a,function(c){var f=null;try{f=JSON.parse(c)}catch(h){void 0!==d&&d(h);console.error("THREE:ObjectLoader: Can't parse "+a+".",h.message);return}c=f.metadata;void 0===c||void 0===c.type||"geometry"===c.type.toLowerCase()?
17081 console.error("THREE.ObjectLoader: Can't load "+a+". Use THREE.JSONLoader instead."):e.parse(f,b)},c,d)},setTexturePath:function(a){this.texturePath=a},setCrossOrigin:function(a){this.crossOrigin=a},parse:function(a,b){var c=this.parseGeometries(a.geometries),d=this.parseImages(a.images,function(){void 0!==b&&b(e)}),d=this.parseTextures(a.textures,d),d=this.parseMaterials(a.materials,d),e=this.parseObject(a.object,c,d);a.animations&&(e.animations=this.parseAnimations(a.animations));void 0!==a.images&&
17082 0!==a.images.length||void 0===b||b(e);return e},parseGeometries:function(a){var b={};if(void 0!==a)for(var c=new be,d=new ae,e=0,f=a.length;e<f;e++){var g=a[e];switch(g.type){case "PlaneGeometry":case "PlaneBufferGeometry":var h=new Ca[g.type](g.width,g.height,g.widthSegments,g.heightSegments);break;case "BoxGeometry":case "BoxBufferGeometry":case "CubeGeometry":h=new Ca[g.type](g.width,g.height,g.depth,g.widthSegments,g.heightSegments,g.depthSegments);break;case "CircleGeometry":case "CircleBufferGeometry":h=
17083 new Ca[g.type](g.radius,g.segments,g.thetaStart,g.thetaLength);break;case "CylinderGeometry":case "CylinderBufferGeometry":h=new Ca[g.type](g.radiusTop,g.radiusBottom,g.height,g.radialSegments,g.heightSegments,g.openEnded,g.thetaStart,g.thetaLength);break;case "ConeGeometry":case "ConeBufferGeometry":h=new Ca[g.type](g.radius,g.height,g.radialSegments,g.heightSegments,g.openEnded,g.thetaStart,g.thetaLength);break;case "SphereGeometry":case "SphereBufferGeometry":h=new Ca[g.type](g.radius,g.widthSegments,
17084 g.heightSegments,g.phiStart,g.phiLength,g.thetaStart,g.thetaLength);break;case "DodecahedronGeometry":case "DodecahedronBufferGeometry":case "IcosahedronGeometry":case "IcosahedronBufferGeometry":case "OctahedronGeometry":case "OctahedronBufferGeometry":case "TetrahedronGeometry":case "TetrahedronBufferGeometry":h=new Ca[g.type](g.radius,g.detail);break;case "RingGeometry":case "RingBufferGeometry":h=new Ca[g.type](g.innerRadius,g.outerRadius,g.thetaSegments,g.phiSegments,g.thetaStart,g.thetaLength);
17085 break;case "TorusGeometry":case "TorusBufferGeometry":h=new Ca[g.type](g.radius,g.tube,g.radialSegments,g.tubularSegments,g.arc);break;case "TorusKnotGeometry":case "TorusKnotBufferGeometry":h=new Ca[g.type](g.radius,g.tube,g.tubularSegments,g.radialSegments,g.p,g.q);break;case "LatheGeometry":case "LatheBufferGeometry":h=new Ca[g.type](g.points,g.segments,g.phiStart,g.phiLength);break;case "PolyhedronGeometry":case "PolyhedronBufferGeometry":h=new Ca[g.type](g.vertices,g.indices,g.radius,g.details);
17086 break;case "BufferGeometry":h=d.parse(g);break;case "Geometry":h=c.parse(g,this.texturePath).geometry;break;default:console.warn('THREE.ObjectLoader: Unsupported geometry type "'+g.type+'"');continue}h.uuid=g.uuid;void 0!==g.name&&(h.name=g.name);b[g.uuid]=h}return b},parseMaterials:function(a,b){var c={};if(void 0!==a){var d=new Id;d.setTextures(b);b=0;for(var e=a.length;b<e;b++){var f=a[b];if("MultiMaterial"===f.type){for(var g=[],h=0;h<f.materials.length;h++)g.push(d.parse(f.materials[h]));c[f.uuid]=
17087 g}else c[f.uuid]=d.parse(f)}}return c},parseAnimations:function(a){for(var b=[],c=0;c<a.length;c++){var d=ka.parse(a[c]);b.push(d)}return b},parseImages:function(a,b){function c(a){d.manager.itemStart(a);return f.load(a,function(){d.manager.itemEnd(a)},void 0,function(){d.manager.itemEnd(a);d.manager.itemError(a)})}var d=this,e={};if(void 0!==a&&0<a.length){b=new Yd(b);var f=new Xc(b);f.setCrossOrigin(this.crossOrigin);b=0;for(var g=a.length;b<g;b++){var h=a[b],k=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(h.url)?
17088 h.url:d.texturePath+h.url;e[h.uuid]=c(k)}}return e},parseTextures:function(a,b){function c(a,b){if("number"===typeof a)return a;console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",a);return b[a]}var d={};if(void 0!==a)for(var e=0,f=a.length;e<f;e++){var g=a[e];void 0===g.image&&console.warn('THREE.ObjectLoader: No "image" specified for',g.uuid);void 0===b[g.image]&&console.warn("THREE.ObjectLoader: Undefined image",g.image);var h=new ea(b[g.image]);h.needsUpdate=!0;
17089 h.uuid=g.uuid;void 0!==g.name&&(h.name=g.name);void 0!==g.mapping&&(h.mapping=c(g.mapping,ug));void 0!==g.offset&&h.offset.fromArray(g.offset);void 0!==g.repeat&&h.repeat.fromArray(g.repeat);void 0!==g.center&&h.center.fromArray(g.center);void 0!==g.rotation&&(h.rotation=g.rotation);void 0!==g.wrap&&(h.wrapS=c(g.wrap[0],hf),h.wrapT=c(g.wrap[1],hf));void 0!==g.minFilter&&(h.minFilter=c(g.minFilter,jf));void 0!==g.magFilter&&(h.magFilter=c(g.magFilter,jf));void 0!==g.anisotropy&&(h.anisotropy=g.anisotropy);
17090 void 0!==g.flipY&&(h.flipY=g.flipY);d[g.uuid]=h}return d},parseObject:function(){var a=new K;return function(b,c,d){function e(a){void 0===c[a]&&console.warn("THREE.ObjectLoader: Undefined geometry",a);return c[a]}function f(a){if(void 0!==a){if(Array.isArray(a)){for(var b=[],c=0,e=a.length;c<e;c++){var f=a[c];void 0===d[f]&&console.warn("THREE.ObjectLoader: Undefined material",f);b.push(d[f])}return b}void 0===d[a]&&console.warn("THREE.ObjectLoader: Undefined material",a);return d[a]}}switch(b.type){case "Scene":var g=
17091 new od;void 0!==b.background&&Number.isInteger(b.background)&&(g.background=new H(b.background));void 0!==b.fog&&("Fog"===b.fog.type?g.fog=new Pb(b.fog.color,b.fog.near,b.fog.far):"FogExp2"===b.fog.type&&(g.fog=new Ob(b.fog.color,b.fog.density)));break;case "PerspectiveCamera":g=new U(b.fov,b.aspect,b.near,b.far);void 0!==b.focus&&(g.focus=b.focus);void 0!==b.zoom&&(g.zoom=b.zoom);void 0!==b.filmGauge&&(g.filmGauge=b.filmGauge);void 0!==b.filmOffset&&(g.filmOffset=b.filmOffset);void 0!==b.view&&(g.view=
17092 Object.assign({},b.view));break;case "OrthographicCamera":g=new Kb(b.left,b.right,b.top,b.bottom,b.near,b.far);break;case "AmbientLight":g=new Ad(b.color,b.intensity);break;case "DirectionalLight":g=new zd(b.color,b.intensity);break;case "PointLight":g=new xd(b.color,b.intensity,b.distance,b.decay);break;case "RectAreaLight":g=new Bd(b.color,b.intensity,b.width,b.height);break;case "SpotLight":g=new wd(b.color,b.intensity,b.distance,b.angle,b.penumbra,b.decay);break;case "HemisphereLight":g=new ud(b.color,
17093 b.groundColor,b.intensity);break;case "SkinnedMesh":console.warn("THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.");case "Mesh":g=e(b.geometry);var h=f(b.material);g=g.bones&&0<g.bones.length?new qd(g,h):new pa(g,h);break;case "LOD":g=new Dc;break;case "Line":g=new ma(e(b.geometry),f(b.material),b.mode);break;case "LineLoop":g=new rd(e(b.geometry),f(b.material));break;case "LineSegments":g=new ca(e(b.geometry),f(b.material));break;case "PointCloud":case "Points":g=new Qb(e(b.geometry),
17094 f(b.material));break;case "Sprite":g=new Cc(f(b.material));break;case "Group":g=new Fc;break;default:g=new A}g.uuid=b.uuid;void 0!==b.name&&(g.name=b.name);void 0!==b.matrix?(a.fromArray(b.matrix),a.decompose(g.position,g.quaternion,g.scale)):(void 0!==b.position&&g.position.fromArray(b.position),void 0!==b.rotation&&g.rotation.fromArray(b.rotation),void 0!==b.quaternion&&g.quaternion.fromArray(b.quaternion),void 0!==b.scale&&g.scale.fromArray(b.scale));void 0!==b.castShadow&&(g.castShadow=b.castShadow);
17095 void 0!==b.receiveShadow&&(g.receiveShadow=b.receiveShadow);b.shadow&&(void 0!==b.shadow.bias&&(g.shadow.bias=b.shadow.bias),void 0!==b.shadow.radius&&(g.shadow.radius=b.shadow.radius),void 0!==b.shadow.mapSize&&g.shadow.mapSize.fromArray(b.shadow.mapSize),void 0!==b.shadow.camera&&(g.shadow.camera=this.parseObject(b.shadow.camera)));void 0!==b.visible&&(g.visible=b.visible);void 0!==b.userData&&(g.userData=b.userData);if(void 0!==b.children)for(var h=b.children,k=0;k<h.length;k++)g.add(this.parseObject(h[k],
17096 c,d));if("LOD"===b.type)for(b=b.levels,h=0;h<b.length;h++){var k=b[h],l=g.getObjectByProperty("uuid",k.object);void 0!==l&&g.addLevel(l,k.distance)}return g}}()});var ug={UVMapping:300,CubeReflectionMapping:301,CubeRefractionMapping:302,EquirectangularReflectionMapping:303,EquirectangularRefractionMapping:304,SphericalReflectionMapping:305,CubeUVReflectionMapping:306,CubeUVRefractionMapping:307},hf={RepeatWrapping:1E3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002},jf={NearestFilter:1003,NearestMipMapNearestFilter:1004,
17097 NearestMipMapLinearFilter:1005,LinearFilter:1006,LinearMipMapNearestFilter:1007,LinearMipMapLinearFilter:1008};Object.assign(S.prototype,{getPoint:function(){console.warn("THREE.Curve: .getPoint() not implemented.");return null},getPointAt:function(a,b){a=this.getUtoTmapping(a);return this.getPoint(a,b)},getPoints:function(a){void 0===a&&(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/a));return b},getSpacedPoints:function(a){void 0===a&&(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPointAt(c/
17098 a));return b},getLength:function(){var a=this.getLengths();return a[a.length-1]},getLengths:function(a){void 0===a&&(a=this.arcLengthDivisions);if(this.cacheArcLengths&&this.cacheArcLengths.length===a+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var b=[],c=this.getPoint(0),d,e=0;b.push(0);for(d=1;d<=a;d++){var f=this.getPoint(d/a);e+=f.distanceTo(c);b.push(e);c=f}return this.cacheArcLengths=b},updateArcLengths:function(){this.needsUpdate=!0;this.getLengths()},getUtoTmapping:function(a,
17099 b){var c=this.getLengths(),d=c.length;b=b?b:a*c[d-1];for(var e=0,f=d-1,g;e<=f;)if(a=Math.floor(e+(f-e)/2),g=c[a]-b,0>g)e=a+1;else if(0<g)f=a-1;else{f=a;break}a=f;if(c[a]===b)return a/(d-1);e=c[a];return(a+(b-e)/(c[a+1]-e))/(d-1)},getTangent:function(a){var b=a-1E-4;a+=1E-4;0>b&&(b=0);1<a&&(a=1);b=this.getPoint(b);return this.getPoint(a).clone().sub(b).normalize()},getTangentAt:function(a){a=this.getUtoTmapping(a);return this.getTangent(a)},computeFrenetFrames:function(a,b){var c=new p,d=[],e=[],f=
17100 [],g=new p,h=new K,k;for(k=0;k<=a;k++){var l=k/a;d[k]=this.getTangentAt(l);d[k].normalize()}e[0]=new p;f[0]=new p;k=Number.MAX_VALUE;l=Math.abs(d[0].x);var m=Math.abs(d[0].y),n=Math.abs(d[0].z);l<=k&&(k=l,c.set(1,0,0));m<=k&&(k=m,c.set(0,1,0));n<=k&&c.set(0,0,1);g.crossVectors(d[0],c).normalize();e[0].crossVectors(d[0],g);f[0].crossVectors(d[0],e[0]);for(k=1;k<=a;k++)e[k]=e[k-1].clone(),f[k]=f[k-1].clone(),g.crossVectors(d[k-1],d[k]),g.length()>Number.EPSILON&&(g.normalize(),c=Math.acos(R.clamp(d[k-
17101 1].dot(d[k]),-1,1)),e[k].applyMatrix4(h.makeRotationAxis(g,c))),f[k].crossVectors(d[k],e[k]);if(!0===b)for(c=Math.acos(R.clamp(e[0].dot(e[a]),-1,1)),c/=a,0<d[0].dot(g.crossVectors(e[0],e[a]))&&(c=-c),k=1;k<=a;k++)e[k].applyMatrix4(h.makeRotationAxis(d[k],c*k)),f[k].crossVectors(d[k],e[k]);return{tangents:d,normals:e,binormals:f}},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.arcLengthDivisions=a.arcLengthDivisions;return this}});Ka.prototype=Object.create(S.prototype);
17102 Ka.prototype.constructor=Ka;Ka.prototype.isLineCurve=!0;Ka.prototype.getPoint=function(a,b){b=b||new C;1===a?b.copy(this.v2):(b.copy(this.v2).sub(this.v1),b.multiplyScalar(a).add(this.v1));return b};Ka.prototype.getPointAt=function(a,b){return this.getPoint(a,b)};Ka.prototype.getTangent=function(){return this.v2.clone().sub(this.v1).normalize()};Ka.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};Ab.prototype=Object.assign(Object.create(S.prototype),
17103 {constructor:Ab,add:function(a){this.curves.push(a)},closePath:function(){var a=this.curves[0].getPoint(0),b=this.curves[this.curves.length-1].getPoint(1);a.equals(b)||this.curves.push(new Ka(b,a))},getPoint:function(a){var b=a*this.getLength(),c=this.getCurveLengths();for(a=0;a<c.length;){if(c[a]>=b)return b=c[a]-b,a=this.curves[a],c=a.getLength(),a.getPointAt(0===c?0:1-b/c);a++}return null},getLength:function(){var a=this.getCurveLengths();return a[a.length-1]},updateArcLengths:function(){this.needsUpdate=
17104 !0;this.cacheLengths=null;this.getCurveLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var a=[],b=0,c=0,d=this.curves.length;c<d;c++)b+=this.curves[c].getLength(),a.push(b);return this.cacheLengths=a},getSpacedPoints:function(a){void 0===a&&(a=40);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/a));this.autoClose&&b.push(b[0]);return b},getPoints:function(a){a=a||12;for(var b=[],c,d=0,e=this.curves;d<e.length;d++)for(var f=
17105 e[d],f=f.getPoints(f&&f.isEllipseCurve?2*a:f&&f.isLineCurve?1:f&&f.isSplineCurve?a*f.points.length:a),g=0;g<f.length;g++){var h=f[g];c&&c.equals(h)||(b.push(h),c=h)}this.autoClose&&1<b.length&&!b[b.length-1].equals(b[0])&&b.push(b[0]);return b},copy:function(a){S.prototype.copy.call(this,a);this.curves=[];for(var b=0,c=a.curves.length;b<c;b++)this.curves.push(a.curves[b].clone());this.autoClose=a.autoClose;return this}});Na.prototype=Object.create(S.prototype);Na.prototype.constructor=Na;Na.prototype.isEllipseCurve=
17106 !0;Na.prototype.getPoint=function(a,b){b=b||new C;for(var c=2*Math.PI,d=this.aEndAngle-this.aStartAngle,e=Math.abs(d)<Number.EPSILON;0>d;)d+=c;for(;d>c;)d-=c;d<Number.EPSILON&&(d=e?0:c);!0!==this.aClockwise||e||(d=d===c?-c:d-c);c=this.aStartAngle+a*d;a=this.aX+this.xRadius*Math.cos(c);var f=this.aY+this.yRadius*Math.sin(c);0!==this.aRotation&&(c=Math.cos(this.aRotation),d=Math.sin(this.aRotation),e=a-this.aX,f-=this.aY,a=e*c-f*d+this.aX,f=e*d+f*c+this.aY);return b.set(a,f)};Na.prototype.copy=function(a){S.prototype.copy.call(this,
17107 a);this.aX=a.aX;this.aY=a.aY;this.xRadius=a.xRadius;this.yRadius=a.yRadius;this.aStartAngle=a.aStartAngle;this.aEndAngle=a.aEndAngle;this.aClockwise=a.aClockwise;this.aRotation=a.aRotation;return this};ab.prototype=Object.create(S.prototype);ab.prototype.constructor=ab;ab.prototype.isSplineCurve=!0;ab.prototype.getPoint=function(a,b){b=b||new C;var c=this.points,d=(c.length-1)*a;a=Math.floor(d);var d=d-a,e=c[0===a?a:a-1],f=c[a],g=c[a>c.length-2?c.length-1:a+1],c=c[a>c.length-3?c.length-1:a+2];b.set(Se(d,
17108 e.x,f.x,g.x,c.x),Se(d,e.y,f.y,g.y,c.y));return b};ab.prototype.copy=function(a){S.prototype.copy.call(this,a);this.points=[];for(var b=0,c=a.points.length;b<c;b++)this.points.push(a.points[b].clone());return this};bb.prototype=Object.create(S.prototype);bb.prototype.constructor=bb;bb.prototype.isCubicBezierCurve=!0;bb.prototype.getPoint=function(a,b){b=b||new C;var c=this.v0,d=this.v1,e=this.v2,f=this.v3;b.set(zb(a,c.x,d.x,e.x,f.x),zb(a,c.y,d.y,e.y,f.y));return b};bb.prototype.copy=function(a){S.prototype.copy.call(this,
17109 a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);this.v3.copy(a.v3);return this};cb.prototype=Object.create(S.prototype);cb.prototype.constructor=cb;cb.prototype.isQuadraticBezierCurve=!0;cb.prototype.getPoint=function(a,b){b=b||new C;var c=this.v0,d=this.v1,e=this.v2;b.set(yb(a,c.x,d.x,e.x),yb(a,c.y,d.y,e.y));return b};cb.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};var se=Object.assign(Object.create(Ab.prototype),
17110 {setFromPoints:function(a){this.moveTo(a[0].x,a[0].y);for(var b=1,c=a.length;b<c;b++)this.lineTo(a[b].x,a[b].y)},moveTo:function(a,b){this.currentPoint.set(a,b)},lineTo:function(a,b){var c=new Ka(this.currentPoint.clone(),new C(a,b));this.curves.push(c);this.currentPoint.set(a,b)},quadraticCurveTo:function(a,b,c,d){a=new cb(this.currentPoint.clone(),new C(a,b),new C(c,d));this.curves.push(a);this.currentPoint.set(c,d)},bezierCurveTo:function(a,b,c,d,e,f){a=new bb(this.currentPoint.clone(),new C(a,
17111 b),new C(c,d),new C(e,f));this.curves.push(a);this.currentPoint.set(e,f)},splineThru:function(a){var b=[this.currentPoint.clone()].concat(a),b=new ab(b);this.curves.push(b);this.currentPoint.copy(a[a.length-1])},arc:function(a,b,c,d,e,f){this.absarc(a+this.currentPoint.x,b+this.currentPoint.y,c,d,e,f)},absarc:function(a,b,c,d,e,f){this.absellipse(a,b,c,c,d,e,f)},ellipse:function(a,b,c,d,e,f,g,h){this.absellipse(a+this.currentPoint.x,b+this.currentPoint.y,c,d,e,f,g,h)},absellipse:function(a,b,c,d,
17112 e,f,g,h){a=new Na(a,b,c,d,e,f,g,h);0<this.curves.length&&(b=a.getPoint(0),b.equals(this.currentPoint)||this.lineTo(b.x,b.y));this.curves.push(a);a=a.getPoint(1);this.currentPoint.copy(a)},copy:function(a){Ab.prototype.copy.call(this,a);this.currentPoint.copy(a.currentPoint);return this}});Bb.prototype=se;se.constructor=Bb;Cb.prototype=Object.assign(Object.create(se),{constructor:Cb,getPointsHoles:function(a){for(var b=[],c=0,d=this.holes.length;c<d;c++)b[c]=this.holes[c].getPoints(a);return b},extractPoints:function(a){return{shape:this.getPoints(a),
17113 holes:this.getPointsHoles(a)}},copy:function(a){Bb.prototype.copy.call(this,a);this.holes=[];for(var b=0,c=a.holes.length;b<c;b++)this.holes.push(a.holes[b].clone());return this}});Object.assign(ce.prototype,{moveTo:function(a,b){this.currentPath=new Bb;this.subPaths.push(this.currentPath);this.currentPath.moveTo(a,b)},lineTo:function(a,b){this.currentPath.lineTo(a,b)},quadraticCurveTo:function(a,b,c,d){this.currentPath.quadraticCurveTo(a,b,c,d)},bezierCurveTo:function(a,b,c,d,e,f){this.currentPath.bezierCurveTo(a,
17114 b,c,d,e,f)},splineThru:function(a){this.currentPath.splineThru(a)},toShapes:function(a,b){function c(a){for(var b=[],c=0,d=a.length;c<d;c++){var e=a[c],f=new Cb;f.curves=e.curves;b.push(f)}return b}function d(a,b){for(var c=b.length,d=!1,e=c-1,f=0;f<c;e=f++){var g=b[e],h=b[f],k=h.x-g.x,l=h.y-g.y;if(Math.abs(l)>Number.EPSILON){if(0>l&&(g=b[f],k=-k,h=b[e],l=-l),!(a.y<g.y||a.y>h.y))if(a.y===g.y){if(a.x===g.x)return!0}else{e=l*(a.x-g.x)-k*(a.y-g.y);if(0===e)return!0;0>e||(d=!d)}}else if(a.y===g.y&&(h.x<=
17115 a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=Ha.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);b=[];if(1===f.length){var g=f[0];var h=new Cb;h.curves=g.curves;b.push(h);return b}var k=!e(f[0].getPoints()),k=a?!k:k;h=[];var l=[],m=[],n=0;l[n]=void 0;m[n]=[];for(var p=0,r=f.length;p<r;p++){g=f[p];var u=g.getPoints();var v=e(u);(v=a?!v:v)?(!k&&l[n]&&n++,l[n]={s:new Cb,p:u},l[n].s.curves=g.curves,k&&n++,m[n]=[]):m[n].push({h:g,p:u[0]})}if(!l[0])return c(f);if(1<
17116 l.length){p=!1;a=[];e=0;for(f=l.length;e<f;e++)h[e]=[];e=0;for(f=l.length;e<f;e++)for(g=m[e],v=0;v<g.length;v++){k=g[v];n=!0;for(u=0;u<l.length;u++)d(k.p,l[u].p)&&(e!==u&&a.push({froms:e,tos:u,hole:v}),n?(n=!1,h[u].push(k)):p=!0);n&&h[e].push(k)}0<a.length&&(p||(m=h))}p=0;for(e=l.length;p<e;p++)for(h=l[p].s,b.push(h),a=m[p],f=0,g=a.length;f<g;f++)h.holes.push(a[f].h);return b}});Object.assign(de.prototype,{isFont:!0,generateShapes:function(a,b,c){void 0===b&&(b=100);void 0===c&&(c=4);var d=this.data;
17117 a=String(a).split("");var e=b/d.resolution,f=(d.boundingBox.yMax-d.boundingBox.yMin+d.underlineThickness)*e,g=0,h=0;b=[];for(var k=0;k<a.length;k++){var l=a[k];if("\n"===l)g=0,h-=f;else{var m;var n=e;var p=g,r=h;if(l=d.glyphs[l]||d.glyphs["?"]){var u=new ce,v=[];if(l.o)for(var w=l._cachedOutline||(l._cachedOutline=l.o.split(" ")),x=0,y=w.length;x<y;)switch(w[x++]){case "m":var A=w[x++]*n+p;var B=w[x++]*n+r;u.moveTo(A,B);break;case "l":A=w[x++]*n+p;B=w[x++]*n+r;u.lineTo(A,B);break;case "q":var C=w[x++]*
17118 n+p;var D=w[x++]*n+r;var E=w[x++]*n+p;var H=w[x++]*n+r;u.quadraticCurveTo(E,H,C,D);if(m=v[v.length-1]){var N=m.x;m=m.y;for(var K=1;K<=c;K++){var O=K/c;yb(O,N,E,C);yb(O,m,H,D)}}break;case "b":if(C=w[x++]*n+p,D=w[x++]*n+r,E=w[x++]*n+p,H=w[x++]*n+r,A=w[x++]*n+p,B=w[x++]*n+r,u.bezierCurveTo(E,H,A,B,C,D),m=v[v.length-1])for(N=m.x,m=m.y,K=1;K<=c;K++)O=K/c,zb(O,N,E,A,C),zb(O,m,H,B,D)}n={offsetX:l.ha*n,path:u}}else n=void 0;g+=n.offsetX;b.push(n.path)}}c=[];d=0;for(a=b.length;d<a;d++)Array.prototype.push.apply(c,
17119 b[d].toShapes());return c}});Object.assign(Te.prototype,{load:function(a,b,c,d){var e=this,f=new Ja(this.manager);f.setPath(this.path);f.load(a,function(a){try{var c=JSON.parse(a)}catch(k){console.warn("THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead."),c=JSON.parse(a.substring(65,a.length-2))}a=e.parse(c);b&&b(a)},c,d)},parse:function(a){return new de(a)},setPath:function(a){this.path=a;return this}});var Md,ge={getContext:function(){void 0===Md&&(Md=new (window.AudioContext||
17120 window.webkitAudioContext));return Md},setContext:function(a){Md=a}};Object.assign(ee.prototype,{load:function(a,b,c,d){var e=new Ja(this.manager);e.setResponseType("arraybuffer");e.load(a,function(a){ge.getContext().decodeAudioData(a,function(a){b(a)})},c,d)}});Object.assign(Ue.prototype,{update:function(){var a,b,c,d,e,f,g,h,k=new K,l=new K;return function(m){if(a!==this||b!==m.focus||c!==m.fov||d!==m.aspect*this.aspect||e!==m.near||f!==m.far||g!==m.zoom||h!==this.eyeSep){a=this;b=m.focus;c=m.fov;
17121 d=m.aspect*this.aspect;e=m.near;f=m.far;g=m.zoom;var n=m.projectionMatrix.clone();h=this.eyeSep/2;var q=h*e/b,p=e*Math.tan(R.DEG2RAD*c*.5)/g;l.elements[12]=-h;k.elements[12]=h;var u=-p*d+q;var v=p*d+q;n.elements[0]=2*e/(v-u);n.elements[8]=(v+u)/(v-u);this.cameraL.projectionMatrix.copy(n);u=-p*d-q;v=p*d-q;n.elements[0]=2*e/(v-u);n.elements[8]=(v+u)/(v-u);this.cameraR.projectionMatrix.copy(n)}this.cameraL.matrixWorld.copy(m.matrixWorld).multiply(l);this.cameraR.matrixWorld.copy(m.matrixWorld).multiply(k)}}()});
17122 $c.prototype=Object.create(A.prototype);$c.prototype.constructor=$c;fe.prototype=Object.assign(Object.create(A.prototype),{constructor:fe,getInput:function(){return this.gain},removeFilter:function(){null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null)},getFilter:function(){return this.filter},setFilter:function(a){null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):
17123 this.gain.disconnect(this.context.destination);this.filter=a;this.gain.connect(this.filter);this.filter.connect(this.context.destination)},getMasterVolume:function(){return this.gain.gain.value},setMasterVolume:function(a){this.gain.gain.value=a},updateMatrixWorld:function(){var a=new p,b=new Z,c=new p,d=new p;return function(e){A.prototype.updateMatrixWorld.call(this,e);e=this.context.listener;var f=this.up;this.matrixWorld.decompose(a,b,c);d.set(0,0,-1).applyQuaternion(b);e.positionX?(e.positionX.setValueAtTime(a.x,
17124 this.context.currentTime),e.positionY.setValueAtTime(a.y,this.context.currentTime),e.positionZ.setValueAtTime(a.z,this.context.currentTime),e.forwardX.setValueAtTime(d.x,this.context.currentTime),e.forwardY.setValueAtTime(d.y,this.context.currentTime),e.forwardZ.setValueAtTime(d.z,this.context.currentTime),e.upX.setValueAtTime(f.x,this.context.currentTime),e.upY.setValueAtTime(f.y,this.context.currentTime),e.upZ.setValueAtTime(f.z,this.context.currentTime)):(e.setPosition(a.x,a.y,a.z),e.setOrientation(d.x,
17125 d.y,d.z,f.x,f.y,f.z))}}()});lc.prototype=Object.assign(Object.create(A.prototype),{constructor:lc,getOutput:function(){return this.gain},setNodeSource:function(a){this.hasPlaybackControl=!1;this.sourceType="audioNode";this.source=a;this.connect();return this},setBuffer:function(a){this.buffer=a;this.sourceType="buffer";this.autoplay&&this.play();return this},play:function(){if(!0===this.isPlaying)console.warn("THREE.Audio: Audio is already playing.");else if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");
17126 else{var a=this.context.createBufferSource();a.buffer=this.buffer;a.loop=this.loop;a.onended=this.onEnded.bind(this);a.playbackRate.setValueAtTime(this.playbackRate,this.startTime);this.startTime=this.context.currentTime;a.start(this.startTime,this.offset);this.isPlaying=!0;this.source=a;return this.connect()}},pause:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return!0===this.isPlaying&&(this.source.stop(),this.offset+=(this.context.currentTime-
17127 this.startTime)*this.playbackRate,this.isPlaying=!1),this},stop:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.source.stop(),this.offset=0,this.isPlaying=!1,this},connect:function(){if(0<this.filters.length){this.source.connect(this.filters[0]);for(var a=1,b=this.filters.length;a<b;a++)this.filters[a-1].connect(this.filters[a]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());
17128 return this},disconnect:function(){if(0<this.filters.length){this.source.disconnect(this.filters[0]);for(var a=1,b=this.filters.length;a<b;a++)this.filters[a-1].disconnect(this.filters[a]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this},getFilters:function(){return this.filters},setFilters:function(a){a||(a=[]);!0===this.isPlaying?(this.disconnect(),this.filters=a,this.connect()):this.filters=a;return this},getFilter:function(){return this.getFilters()[0]},
17129 setFilter:function(a){return this.setFilters(a?[a]:[])},setPlaybackRate:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.playbackRate=a,!0===this.isPlaying&&this.source.playbackRate.setValueAtTime(this.playbackRate,this.context.currentTime),this},getPlaybackRate:function(){return this.playbackRate},onEnded:function(){this.isPlaying=!1},getLoop:function(){return!1===this.hasPlaybackControl?(console.warn("THREE.Audio: this Audio has no playback control."),
17130 !1):this.loop},setLoop:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.loop=a,!0===this.isPlaying&&(this.source.loop=this.loop),this},getVolume:function(){return this.gain.gain.value},setVolume:function(a){this.gain.gain.value=a;return this}});he.prototype=Object.assign(Object.create(lc.prototype),{constructor:he,getOutput:function(){return this.panner},getRefDistance:function(){return this.panner.refDistance},setRefDistance:function(a){this.panner.refDistance=
17131 a},getRolloffFactor:function(){return this.panner.rolloffFactor},setRolloffFactor:function(a){this.panner.rolloffFactor=a},getDistanceModel:function(){return this.panner.distanceModel},setDistanceModel:function(a){this.panner.distanceModel=a},getMaxDistance:function(){return this.panner.maxDistance},setMaxDistance:function(a){this.panner.maxDistance=a},updateMatrixWorld:function(){var a=new p;return function(b){A.prototype.updateMatrixWorld.call(this,b);a.setFromMatrixPosition(this.matrixWorld);this.panner.setPosition(a.x,
17132 a.y,a.z)}}()});Object.assign(ie.prototype,{getFrequencyData:function(){this.analyser.getByteFrequencyData(this.data);return this.data},getAverageFrequency:function(){for(var a=0,b=this.getFrequencyData(),c=0;c<b.length;c++)a+=b[c];return a/b.length}});Object.assign(je.prototype,{accumulate:function(a,b){var c=this.buffer,d=this.valueSize;a=a*d+d;var e=this.cumulativeWeight;if(0===e){for(e=0;e!==d;++e)c[a+e]=c[e];e=b}else e+=b,this._mixBufferRegion(c,a,0,b/e,d);this.cumulativeWeight=e},apply:function(a){var b=
17133 this.valueSize,c=this.buffer;a=a*b+b;var d=this.cumulativeWeight,e=this.binding;this.cumulativeWeight=0;1>d&&this._mixBufferRegion(c,a,3*b,1-d,b);for(var d=b,f=b+b;d!==f;++d)if(c[d]!==c[d+b]){e.setValue(c,a);break}},saveOriginalState:function(){var a=this.buffer,b=this.valueSize,c=3*b;this.binding.getValue(a,c);for(var d=b;d!==c;++d)a[d]=a[c+d%b];this.cumulativeWeight=0},restoreOriginalState:function(){this.binding.setValue(this.buffer,3*this.valueSize)},_select:function(a,b,c,d,e){if(.5<=d)for(d=
17134 0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d){Z.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f=1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}});Object.assign(Ve.prototype,{getValue:function(a,b){this.bind();var c=this._bindings[this._targetGroup.nCachedObjects_];void 0!==c&&c.getValue(a,b)},setValue:function(a,b){for(var c=this._bindings,d=this._targetGroup.nCachedObjects_,e=c.length;d!==e;++d)c[d].setValue(a,b)},bind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,
17135 c=a.length;b!==c;++b)a[b].bind()},unbind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].unbind()}});Object.assign(na,{Composite:Ve,create:function(a,b,c){return a&&a.isAnimationObjectGroup?new na.Composite(a,b,c):new na(a,b,c)},sanitizeNodeName:function(a){return a.replace(/\s/g,"_").replace(/[^\w-]/g,"")},parseTrackName:function(){var a=new RegExp("^"+/((?:[\w-]+[\/:])*)/.source+/([\w-\.]+)?/.source+/(?:\.([\w-]+)(?:\[(.+)\])?)?/.source+/\.([\w-]+)(?:\[(.+)\])?/.source+
17136 "$"),b=["material","materials","bones"];return function(c){var d=a.exec(c);if(!d)throw Error("PropertyBinding: Cannot parse trackName: "+c);var d={nodeName:d[2],objectName:d[3],objectIndex:d[4],propertyName:d[5],propertyIndex:d[6]},e=d.nodeName&&d.nodeName.lastIndexOf(".");if(void 0!==e&&-1!==e){var f=d.nodeName.substring(e+1);-1!==b.indexOf(f)&&(d.nodeName=d.nodeName.substring(0,e),d.objectName=f)}if(null===d.propertyName||0===d.propertyName.length)throw Error("PropertyBinding: can not parse propertyName from trackName: "+
17137 c);return d}}(),findNode:function(a,b){if(!b||""===b||"root"===b||"."===b||-1===b||b===a.name||b===a.uuid)return a;if(a.skeleton){var c=function(a){for(var c=0;c<a.bones.length;c++){var d=a.bones[c];if(d.name===b)return d}return null}(a.skeleton);if(c)return c}if(a.children){var d=function(a){for(var c=0;c<a.length;c++){var e=a[c];if(e.name===b||e.uuid===b||(e=d(e.children)))return e}return null};if(a=d(a.children))return a}return null}});Object.assign(na.prototype,{_getValue_unavailable:function(){},
17138 _setValue_unavailable:function(){},BindingType:{Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Versioning:{None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},GetterByBindingType:[function(a,b){a[b]=this.node[this.propertyName]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)a[b++]=c[d]},function(a,b){a[b]=this.resolvedProperty[this.propertyIndex]},function(a,b){this.resolvedProperty.toArray(a,b)}],SetterByBindingTypeAndVersioning:[[function(a,b){this.targetObject[this.propertyName]=
17139 a[b]},function(a,b){this.targetObject[this.propertyName]=a[b];this.targetObject.needsUpdate=!0},function(a,b){this.targetObject[this.propertyName]=a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.needsUpdate=!0},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.matrixWorldNeedsUpdate=
17140 !0}],[function(a,b){this.resolvedProperty[this.propertyIndex]=a[b]},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty.fromArray(a,b)},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.matrixWorldNeedsUpdate=!0}]],
17141 getValue:function(a,b){this.bind();this.getValue(a,b)},setValue:function(a,b){this.bind();this.setValue(a,b)},bind:function(){var a=this.node,b=this.parsedPath,c=b.objectName,d=b.propertyName,e=b.propertyIndex;a||(this.node=a=na.findNode(this.rootNode,b.nodeName)||this.rootNode);this.getValue=this._getValue_unavailable;this.setValue=this._setValue_unavailable;if(a){if(c){var f=b.objectIndex;switch(c){case "materials":if(!a.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",
17142 this);return}if(!a.material.materials){console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}a=a.material.materials;break;case "bones":if(!a.skeleton){console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}a=a.skeleton.bones;for(c=0;c<a.length;c++)if(a[c].name===f){f=c;break}break;default:if(void 0===a[c]){console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",
17143 this);return}a=a[c]}if(void 0!==f){if(void 0===a[f]){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,a);return}a=a[f]}}f=a[d];if(void 0===f)console.error("THREE.PropertyBinding: Trying to update property for track: "+b.nodeName+"."+d+" but it wasn't found.",a);else{b=this.Versioning.None;void 0!==a.needsUpdate?(b=this.Versioning.NeedsUpdate,this.targetObject=a):void 0!==a.matrixWorldNeedsUpdate&&(b=this.Versioning.MatrixWorldNeedsUpdate,this.targetObject=
17144 a);c=this.BindingType.Direct;if(void 0!==e){if("morphTargetInfluences"===d){if(!a.geometry){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(a.geometry.isBufferGeometry){if(!a.geometry.morphAttributes){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}for(c=0;c<this.node.geometry.morphAttributes.position.length;c++)if(a.geometry.morphAttributes.position[c].name===
17145 e){e=c;break}}else{if(!a.geometry.morphTargets){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.",this);return}for(c=0;c<this.node.geometry.morphTargets.length;c++)if(a.geometry.morphTargets[c].name===e){e=c;break}}}c=this.BindingType.ArrayElement;this.resolvedProperty=f;this.propertyIndex=e}else void 0!==f.fromArray&&void 0!==f.toArray?(c=this.BindingType.HasFromToArray,this.resolvedProperty=f):Array.isArray(f)?(c=this.BindingType.EntireArray,
17146 this.resolvedProperty=f):this.propertyName=d;this.getValue=this.GetterByBindingType[c];this.setValue=this.SetterByBindingTypeAndVersioning[c][b]}}else console.error("THREE.PropertyBinding: Trying to update node for track: "+this.path+" but it wasn't found.")},unbind:function(){this.node=null;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}});Object.assign(na.prototype,{_getValue_unbound:na.prototype.getValue,_setValue_unbound:na.prototype.setValue});Object.assign(We.prototype,
17147 {isAnimationObjectGroup:!0,add:function(){for(var a=this._objects,b=a.length,c=this.nCachedObjects_,d=this._indicesByUUID,e=this._paths,f=this._parsedPaths,g=this._bindings,h=g.length,k=0,l=arguments.length;k!==l;++k){var m=arguments[k],n=m.uuid,p=d[n];if(void 0===p){p=b++;d[n]=p;a.push(m);for(var n=0,r=h;n!==r;++n)g[n].push(new na(m,e[n],f[n]))}else if(p<c){var u=--c,r=a[u];d[r.uuid]=p;a[p]=r;d[n]=u;a[u]=m;n=0;for(r=h;n!==r;++n){var v=g[n],w=v[p];v[p]=v[u];void 0===w&&(w=new na(m,e[n],f[n]));v[u]=
17148 w}}else void 0!==a[p]&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=c},remove:function(){for(var a=this._objects,b=this.nCachedObjects_,c=this._indicesByUUID,d=this._bindings,e=d.length,f=0,g=arguments.length;f!==g;++f){var h=arguments[f],k=h.uuid,l=c[k];if(void 0!==l&&l>=b){var m=b++,n=a[m];c[n.uuid]=l;a[l]=n;c[k]=m;a[m]=h;h=0;for(k=e;h!==k;++h){var n=d[h],p=
17149 n[l];n[l]=n[m];n[m]=p}}}this.nCachedObjects_=b},uncache:function(){for(var a,b,c=this._objects,d=c.length,e=this.nCachedObjects_,f=this._indicesByUUID,g=this._bindings,h=g.length,k=0,l=arguments.length;k!==l;++k){b=arguments[k].uuid;var m=f[b];if(void 0!==m)if(delete f[b],m<e){var n=--e,p=c[n];b=--d;a=c[b];f[p.uuid]=m;c[m]=p;f[a.uuid]=n;c[n]=a;c.pop();for(var p=0,r=h;p!==r;++p){a=g[p];var u=a[b];a[m]=a[n];a[n]=u;a.pop()}}else for(b=--d,a=c[b],f[a.uuid]=m,c[m]=a,c.pop(),p=0,r=h;p!==r;++p)a=g[p],a[m]=
17150 a[b],a.pop()}this.nCachedObjects_=e},subscribe_:function(a,b){var c=this._bindingsIndicesByPath,d=c[a],e=this._bindings;if(void 0!==d)return e[d];var f=this._paths,g=this._parsedPaths,h=this._objects,k=this.nCachedObjects_,l=Array(h.length),d=e.length;c[a]=d;f.push(a);g.push(b);e.push(l);c=k;for(d=h.length;c!==d;++c)l[c]=new na(h[c],a,b);return l},unsubscribe_:function(a){var b=this._bindingsIndicesByPath,c=b[a];if(void 0!==c){var d=this._paths,e=this._parsedPaths,f=this._bindings,g=f.length-1,h=
17151 f[g];b[a[g]]=c;f[c]=h;f.pop();e[c]=e[g];e.pop();d[c]=d[g];d.pop()}}});Object.assign(Xe.prototype,{play:function(){this._mixer._activateAction(this);return this},stop:function(){this._mixer._deactivateAction(this);return this.reset()},reset:function(){this.paused=!1;this.enabled=!0;this.time=0;this._loopCount=-1;this._startTime=null;return this.stopFading().stopWarping()},isRunning:function(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)},
17152 isScheduled:function(){return this._mixer._isActiveAction(this)},startAt:function(a){this._startTime=a;return this},setLoop:function(a,b){this.loop=a;this.repetitions=b;return this},setEffectiveWeight:function(a){this.weight=a;this._effectiveWeight=this.enabled?a:0;return this.stopFading()},getEffectiveWeight:function(){return this._effectiveWeight},fadeIn:function(a){return this._scheduleFading(a,0,1)},fadeOut:function(a){return this._scheduleFading(a,1,0)},crossFadeFrom:function(a,b,c){a.fadeOut(b);
17153 this.fadeIn(b);if(c){c=this._clip.duration;var d=a._clip.duration,e=c/d;a.warp(1,d/c,b);this.warp(e,1,b)}return this},crossFadeTo:function(a,b,c){return a.crossFadeFrom(this,b,c)},stopFading:function(){var a=this._weightInterpolant;null!==a&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(a));return this},setEffectiveTimeScale:function(a){this.timeScale=a;this._effectiveTimeScale=this.paused?0:a;return this.stopWarping()},getEffectiveTimeScale:function(){return this._effectiveTimeScale},
17154 setDuration:function(a){this.timeScale=this._clip.duration/a;return this.stopWarping()},syncWith:function(a){this.time=a.time;this.timeScale=a.timeScale;return this.stopWarping()},halt:function(a){return this.warp(this._effectiveTimeScale,0,a)},warp:function(a,b,c){var d=this._mixer,e=d.time,f=this._timeScaleInterpolant,g=this.timeScale;null===f&&(this._timeScaleInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;d[1]=e+c;f[0]=a/g;f[1]=b/g;return this},stopWarping:function(){var a=
17155 this._timeScaleInterpolant;null!==a&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(a));return this},getMixer:function(){return this._mixer},getClip:function(){return this._clip},getRoot:function(){return this._localRoot||this._mixer._root},_update:function(a,b,c,d){if(this.enabled){var e=this._startTime;if(null!==e){b=(a-e)*c;if(0>b||0===c)return;this._startTime=null;b*=c}b*=this._updateTimeScale(a);c=this._updateTime(b);a=this._updateWeight(a);if(0<a){b=this._interpolants;
17156 for(var e=this._propertyBindings,f=0,g=b.length;f!==g;++f)b[f].evaluate(c),e[f].accumulate(d,a)}}else this._updateWeight(a)},_updateWeight:function(a){var b=0;if(this.enabled){var b=this.weight,c=this._weightInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.parameterPositions[1]&&(this.stopFading(),0===d&&(this.enabled=!1))}}return this._effectiveWeight=b},_updateTimeScale:function(a){var b=0;if(!this.paused){var b=this.timeScale,c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0],
17157 b=b*d;a>c.parameterPositions[1]&&(this.stopWarping(),0===b?this.paused=!0:this.timeScale=b)}}return this._effectiveTimeScale=b},_updateTime:function(a){var b=this.time+a;if(0===a)return b;var c=this._clip.duration,d=this.loop,e=this._loopCount;if(2200===d)a:{if(-1===e&&(this._loopCount=0,this._setEndings(!0,!0,!1)),b>=c)b=c;else if(0>b)b=0;else break a;this.clampWhenFinished?this.paused=!0:this.enabled=!1;this._mixer.dispatchEvent({type:"finished",action:this,direction:0>a?-1:1})}else{d=2202===d;
17158 -1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions,d)):this._setEndings(0===this.repetitions,!0,d));if(b>=c||0>b){var f=Math.floor(b/c),b=b-c*f,e=e+Math.abs(f),g=this.repetitions-e;0>g?(this.clampWhenFinished?this.paused=!0:this.enabled=!1,b=0<a?c:0,this._mixer.dispatchEvent({type:"finished",action:this,direction:0<a?1:-1})):(0===g?(a=0>a,this._setEndings(a,!a,d)):this._setEndings(!1,!1,d),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:f}))}if(d&&1===(e&1))return this.time=
17159 b,c-b}return this.time=b},_setEndings:function(a,b,c){var d=this._interpolantSettings;c?(d.endingStart=2401,d.endingEnd=2401):(d.endingStart=a?this.zeroSlopeAtStart?2401:2400:2402,d.endingEnd=b?this.zeroSlopeAtEnd?2401:2400:2402)},_scheduleFading:function(a,b,c){var d=this._mixer,e=d.time,f=this._weightInterpolant;null===f&&(this._weightInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;f[0]=b;d[1]=e+a;f[1]=c;return this}});Object.assign(Ye.prototype,ja.prototype,
17160 {_bindAction:function(a,b){var c=a._localRoot||this._root,d=a._clip.tracks,e=d.length,f=a._propertyBindings;a=a._interpolants;var g=c.uuid,h=this._bindingsByRootAndName,k=h[g];void 0===k&&(k={},h[g]=k);for(h=0;h!==e;++h){var l=d[h],m=l.name,n=k[m];if(void 0===n){n=f[h];if(void 0!==n){null===n._cacheIndex&&(++n.referenceCount,this._addInactiveBinding(n,g,m));continue}n=new je(na.create(c,m,b&&b._propertyBindings[h].binding.parsedPath),l.ValueTypeName,l.getValueSize());++n.referenceCount;this._addInactiveBinding(n,
17161 g,m)}f[h]=n;a[h].resultBuffer=n.buffer}},_activateAction:function(a){if(!this._isActiveAction(a)){if(null===a._cacheIndex){var b=(a._localRoot||this._root).uuid,c=a._clip.uuid,d=this._actionsByClip[c];this._bindAction(a,d&&d.knownActions[0]);this._addInactiveAction(a,c,b)}b=a._propertyBindings;c=0;for(d=b.length;c!==d;++c){var e=b[c];0===e.useCount++&&(this._lendBinding(e),e.saveOriginalState())}this._lendAction(a)}},_deactivateAction:function(a){if(this._isActiveAction(a)){for(var b=a._propertyBindings,
17162 c=0,d=b.length;c!==d;++c){var e=b[c];0===--e.useCount&&(e.restoreOriginalState(),this._takeBackBinding(e))}this._takeBackAction(a)}},_initMemoryManager:function(){this._actions=[];this._nActiveActions=0;this._actionsByClip={};this._bindings=[];this._nActiveBindings=0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var a=this;this.stats={actions:{get total(){return a._actions.length},get inUse(){return a._nActiveActions}},bindings:{get total(){return a._bindings.length},
17163 get inUse(){return a._nActiveBindings}},controlInterpolants:{get total(){return a._controlInterpolants.length},get inUse(){return a._nActiveControlInterpolants}}}},_isActiveAction:function(a){a=a._cacheIndex;return null!==a&&a<this._nActiveActions},_addInactiveAction:function(a,b,c){var d=this._actions,e=this._actionsByClip,f=e[b];void 0===f?(f={knownActions:[a],actionByRoot:{}},a._byClipCacheIndex=0,e[b]=f):(b=f.knownActions,a._byClipCacheIndex=b.length,b.push(a));a._cacheIndex=d.length;d.push(a);
17164 f.actionByRoot[c]=a},_removeInactiveAction:function(a){var b=this._actions,c=b[b.length-1],d=a._cacheIndex;c._cacheIndex=d;b[d]=c;b.pop();a._cacheIndex=null;var b=a._clip.uuid,c=this._actionsByClip,d=c[b],e=d.knownActions,f=e[e.length-1],g=a._byClipCacheIndex;f._byClipCacheIndex=g;e[g]=f;e.pop();a._byClipCacheIndex=null;delete d.actionByRoot[(a._localRoot||this._root).uuid];0===e.length&&delete c[b];this._removeInactiveBindingsForAction(a)},_removeInactiveBindingsForAction:function(a){a=a._propertyBindings;
17165 for(var b=0,c=a.length;b!==c;++b){var d=a[b];0===--d.referenceCount&&this._removeInactiveBinding(d)}},_lendAction:function(a){var b=this._actions,c=a._cacheIndex,d=this._nActiveActions++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackAction:function(a){var b=this._actions,c=a._cacheIndex,d=--this._nActiveActions,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_addInactiveBinding:function(a,b,c){var d=this._bindingsByRootAndName,e=d[b],f=this._bindings;void 0===e&&(e={},d[b]=
17166 e);e[c]=a;a._cacheIndex=f.length;f.push(a)},_removeInactiveBinding:function(a){var b=this._bindings,c=a.binding,d=c.rootNode.uuid,c=c.path,e=this._bindingsByRootAndName,f=e[d],g=b[b.length-1];a=a._cacheIndex;g._cacheIndex=a;b[a]=g;b.pop();delete f[c];a:{for(var h in f)break a;delete e[d]}},_lendBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=this._nActiveBindings++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=
17167 --this._nActiveBindings,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_lendControlInterpolant:function(){var a=this._controlInterpolants,b=this._nActiveControlInterpolants++,c=a[b];void 0===c&&(c=new Yc(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer),c.__cacheIndex=b,a[b]=c);return c},_takeBackControlInterpolant:function(a){var b=this._controlInterpolants,c=a.__cacheIndex,d=--this._nActiveControlInterpolants,e=b[d];a.__cacheIndex=d;b[d]=a;e.__cacheIndex=c;
17168 b[c]=e},_controlInterpolantsResultBuffer:new Float32Array(1),clipAction:function(a,b){var c=b||this._root,d=c.uuid,c="string"===typeof a?ka.findByName(c,a):a;a=null!==c?c.uuid:a;var e=this._actionsByClip[a],f=null;if(void 0!==e){f=e.actionByRoot[d];if(void 0!==f)return f;f=e.knownActions[0];null===c&&(c=f._clip)}if(null===c)return null;b=new Xe(this,c,b);this._bindAction(b,f);this._addInactiveAction(b,a,d);return b},existingAction:function(a,b){var c=b||this._root;b=c.uuid;c="string"===typeof a?ka.findByName(c,
17169 a):a;a=this._actionsByClip[c?c.uuid:a];return void 0!==a?a.actionByRoot[b]||null:null},stopAllAction:function(){for(var a=this._actions,b=this._nActiveActions,c=this._bindings,d=this._nActiveBindings,e=this._nActiveBindings=this._nActiveActions=0;e!==b;++e)a[e].reset();for(e=0;e!==d;++e)c[e].useCount=0;return this},update:function(a){a*=this.timeScale;for(var b=this._actions,c=this._nActiveActions,d=this.time+=a,e=Math.sign(a),f=this._accuIndex^=1,g=0;g!==c;++g)b[g]._update(d,a,e,f);a=this._bindings;
17170 b=this._nActiveBindings;for(g=0;g!==b;++g)a[g].apply(f);return this},getRoot:function(){return this._root},uncacheClip:function(a){var b=this._actions;a=a.uuid;var c=this._actionsByClip,d=c[a];if(void 0!==d){for(var d=d.knownActions,e=0,f=d.length;e!==f;++e){var g=d[e];this._deactivateAction(g);var h=g._cacheIndex,k=b[b.length-1];g._cacheIndex=null;g._byClipCacheIndex=null;k._cacheIndex=h;b[h]=k;b.pop();this._removeInactiveBindingsForAction(g)}delete c[a]}},uncacheRoot:function(a){a=a.uuid;var b=
17171 this._actionsByClip;for(d in b){var c=b[d].actionByRoot[a];void 0!==c&&(this._deactivateAction(c),this._removeInactiveAction(c))}var d=this._bindingsByRootAndName[a];if(void 0!==d)for(var e in d)a=d[e],a.restoreOriginalState(),this._removeInactiveBinding(a)},uncacheAction:function(a,b){a=this.existingAction(a,b);null!==a&&(this._deactivateAction(a),this._removeInactiveAction(a))}});Jd.prototype.clone=function(){return new Jd(void 0===this.value.clone?this.value:this.value.clone())};ke.prototype=Object.assign(Object.create(D.prototype),
17172 {constructor:ke,isInstancedBufferGeometry:!0,copy:function(a){D.prototype.copy.call(this,a);this.maxInstancedCount=a.maxInstancedCount;return this},clone:function(){return(new this.constructor).copy(this)}});Object.defineProperties(le.prototype,{count:{get:function(){return this.data.count}},array:{get:function(){return this.data.array}}});Object.assign(le.prototype,{isInterleavedBufferAttribute:!0,setX:function(a,b){this.data.array[a*this.data.stride+this.offset]=b;return this},setY:function(a,b){this.data.array[a*
17173 this.data.stride+this.offset+1]=b;return this},setZ:function(a,b){this.data.array[a*this.data.stride+this.offset+2]=b;return this},setW:function(a,b){this.data.array[a*this.data.stride+this.offset+3]=b;return this},getX:function(a){return this.data.array[a*this.data.stride+this.offset]},getY:function(a){return this.data.array[a*this.data.stride+this.offset+1]},getZ:function(a){return this.data.array[a*this.data.stride+this.offset+2]},getW:function(a){return this.data.array[a*this.data.stride+this.offset+
17174 3]},setXY:function(a,b,c){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;return this},setXYZ:function(a,b,c,d){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;return this},setXYZW:function(a,b,c,d,e){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;this.data.array[a+3]=e;return this}});Object.defineProperty(mc.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});
17175 Object.assign(mc.prototype,{isInterleavedBuffer:!0,setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==a?a.length/this.stride:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=new a.array.constructor(a.array);this.count=a.count;this.stride=a.stride;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.stride;c*=b.stride;for(var d=0,e=this.stride;d<e;d++)this.array[a+
17176 d]=b.array[c+d];return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},clone:function(){return(new this.constructor).copy(this)},onUpload:function(a){this.onUploadCallback=a;return this}});me.prototype=Object.assign(Object.create(mc.prototype),{constructor:me,isInstancedInterleavedBuffer:!0,copy:function(a){mc.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});ne.prototype=Object.assign(Object.create(P.prototype),{constructor:ne,isInstancedBufferAttribute:!0,
17177 copy:function(a){P.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});Object.assign(Ze.prototype,{linePrecision:1,set:function(a,b){this.ray.set(a,b)},setFromCamera:function(a,b){b&&b.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(b.matrixWorld),this.ray.direction.set(a.x,a.y,.5).unproject(b).sub(this.ray.origin).normalize()):b&&b.isOrthographicCamera?(this.ray.origin.set(a.x,a.y,(b.near+b.far)/(b.near-b.far)).unproject(b),this.ray.direction.set(0,0,-1).transformDirection(b.matrixWorld)):
17178 console.error("THREE.Raycaster: Unsupported camera type.")},intersectObject:function(a,b){var c=[];oe(a,this,c,b);c.sort($e);return c},intersectObjects:function(a,b){var c=[];if(!1===Array.isArray(a))return console.warn("THREE.Raycaster.intersectObjects: objects is not an Array."),c;for(var d=0,e=a.length;d<e;d++)oe(a[d],this,c,b);c.sort($e);return c}});Object.assign(af.prototype,{start:function(){this.oldTime=this.startTime=("undefined"===typeof performance?Date:performance).now();this.elapsedTime=
17179 0;this.running=!0},stop:function(){this.getElapsedTime();this.autoStart=this.running=!1},getElapsedTime:function(){this.getDelta();return this.elapsedTime},getDelta:function(){var a=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){var b=("undefined"===typeof performance?Date:performance).now(),a=(b-this.oldTime)/1E3;this.oldTime=b;this.elapsedTime+=a}return a}});Object.assign(bf.prototype,{set:function(a,b,c){this.radius=a;this.phi=b;this.theta=c;return this},clone:function(){return(new this.constructor).copy(this)},
17180 copy:function(a){this.radius=a.radius;this.phi=a.phi;this.theta=a.theta;return this},makeSafe:function(){this.phi=Math.max(1E-6,Math.min(Math.PI-1E-6,this.phi));return this},setFromVector3:function(a){this.radius=a.length();0===this.radius?this.phi=this.theta=0:(this.theta=Math.atan2(a.x,a.z),this.phi=Math.acos(R.clamp(a.y/this.radius,-1,1)));return this}});Object.assign(cf.prototype,{set:function(a,b,c){this.radius=a;this.theta=b;this.y=c;return this},clone:function(){return(new this.constructor).copy(this)},
17181 copy:function(a){this.radius=a.radius;this.theta=a.theta;this.y=a.y;return this},setFromVector3:function(a){this.radius=Math.sqrt(a.x*a.x+a.z*a.z);this.theta=Math.atan2(a.x,a.z);this.y=a.y;return this}});ad.prototype=Object.create(A.prototype);ad.prototype.constructor=ad;ad.prototype.isImmediateRenderObject=!0;bd.prototype=Object.create(ca.prototype);bd.prototype.constructor=bd;bd.prototype.update=function(){var a=new p,b=new p,c=new ra;return function(){var d,e=["a","b","c"];this.object.updateMatrixWorld(!0);
17182 c.getNormalMatrix(this.object.matrixWorld);var f=this.object.matrixWorld,g=this.geometry.attributes.position;if((d=this.object.geometry)&&d.isGeometry)for(var h=d.vertices,k=d.faces,l=d=0,m=k.length;l<m;l++)for(var n=k[l],p=0,r=n.vertexNormals.length;p<r;p++){var u=n.vertexNormals[p];a.copy(h[n[e[p]]]).applyMatrix4(f);b.copy(u).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);g.setXYZ(d,a.x,a.y,a.z);d+=1;g.setXYZ(d,b.x,b.y,b.z);d+=1}else if(d&&d.isBufferGeometry)for(e=d.attributes.position,
17183 h=d.attributes.normal,p=d=0,r=e.count;p<r;p++)a.set(e.getX(p),e.getY(p),e.getZ(p)).applyMatrix4(f),b.set(h.getX(p),h.getY(p),h.getZ(p)),b.applyMatrix3(c).normalize().multiplyScalar(this.size).add(a),g.setXYZ(d,a.x,a.y,a.z),d+=1,g.setXYZ(d,b.x,b.y,b.z),d+=1;g.needsUpdate=!0}}();nc.prototype=Object.create(A.prototype);nc.prototype.constructor=nc;nc.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()};nc.prototype.update=function(){var a=new p,b=new p;return function(){this.light.updateMatrixWorld();
17184 var c=this.light.distance?this.light.distance:1E3,d=c*Math.tan(this.light.angle);this.cone.scale.set(d,d,c);a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);this.cone.lookAt(b.sub(a));void 0!==this.color?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}}();oc.prototype=Object.create(ca.prototype);oc.prototype.constructor=oc;oc.prototype.updateMatrixWorld=function(){var a=new p,b=new K,c=new K;return function(d){var e=
17185 this.bones,f=this.geometry,g=f.getAttribute("position");c.getInverse(this.root.matrixWorld);for(var h=0,k=0;h<e.length;h++){var l=e[h];l.parent&&l.parent.isBone&&(b.multiplyMatrices(c,l.matrixWorld),a.setFromMatrixPosition(b),g.setXYZ(k,a.x,a.y,a.z),b.multiplyMatrices(c,l.parent.matrixWorld),a.setFromMatrixPosition(b),g.setXYZ(k+1,a.x,a.y,a.z),k+=2)}f.getAttribute("position").needsUpdate=!0;A.prototype.updateMatrixWorld.call(this,d)}}();pc.prototype=Object.create(pa.prototype);pc.prototype.constructor=
17186 pc;pc.prototype.dispose=function(){this.geometry.dispose();this.material.dispose()};pc.prototype.update=function(){void 0!==this.color?this.material.color.set(this.color):this.material.color.copy(this.light.color)};qc.prototype=Object.create(A.prototype);qc.prototype.constructor=qc;qc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};qc.prototype.update=function(){var a=.5*this.light.width,b=.5*this.light.height,c=this.line.geometry.attributes.position,
17187 d=c.array;d[0]=a;d[1]=-b;d[2]=0;d[3]=a;d[4]=b;d[5]=0;d[6]=-a;d[7]=b;d[8]=0;d[9]=-a;d[10]=-b;d[11]=0;d[12]=a;d[13]=-b;d[14]=0;c.needsUpdate=!0;void 0!==this.color?this.line.material.color.set(this.color):this.line.material.color.copy(this.light.color)};rc.prototype=Object.create(A.prototype);rc.prototype.constructor=rc;rc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};rc.prototype.update=function(){var a=new p,b=new H,c=new H;return function(){var d=
17188 this.children[0];if(void 0!==this.color)this.material.color.set(this.color);else{var e=d.geometry.getAttribute("color");b.copy(this.light.color);c.copy(this.light.groundColor);for(var f=0,g=e.count;f<g;f++){var h=f<g/2?b:c;e.setXYZ(f,h.r,h.g,h.b)}e.needsUpdate=!0}d.lookAt(a.setFromMatrixPosition(this.light.matrixWorld).negate())}}();cd.prototype=Object.create(ca.prototype);cd.prototype.constructor=cd;Kd.prototype=Object.create(ca.prototype);Kd.prototype.constructor=Kd;dd.prototype=Object.create(ca.prototype);
17189 dd.prototype.constructor=dd;dd.prototype.update=function(){var a=new p,b=new p,c=new ra;return function(){this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);for(var d=this.object.matrixWorld,e=this.geometry.attributes.position,f=this.object.geometry,g=f.vertices,f=f.faces,h=0,k=0,l=f.length;k<l;k++){var m=f[k],n=m.normal;a.copy(g[m.a]).add(g[m.b]).add(g[m.c]).divideScalar(3).applyMatrix4(d);b.copy(n).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);e.setXYZ(h,
17190 a.x,a.y,a.z);h+=1;e.setXYZ(h,b.x,b.y,b.z);h+=1}e.needsUpdate=!0}}();sc.prototype=Object.create(A.prototype);sc.prototype.constructor=sc;sc.prototype.dispose=function(){this.lightPlane.geometry.dispose();this.lightPlane.material.dispose();this.targetLine.geometry.dispose();this.targetLine.material.dispose()};sc.prototype.update=function(){var a=new p,b=new p,c=new p;return function(){a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);c.subVectors(b,
17191 a);this.lightPlane.lookAt(c);void 0!==this.color?(this.lightPlane.material.color.set(this.color),this.targetLine.material.color.set(this.color)):(this.lightPlane.material.color.copy(this.light.color),this.targetLine.material.color.copy(this.light.color));this.targetLine.lookAt(c);this.targetLine.scale.z=c.length()}}();ed.prototype=Object.create(ca.prototype);ed.prototype.constructor=ed;ed.prototype.update=function(){function a(a,g,h,k){d.set(g,h,k).unproject(e);a=c[a];if(void 0!==a)for(g=b.getAttribute("position"),
17192 h=0,k=a.length;h<k;h++)g.setXYZ(a[h],d.x,d.y,d.z)}var b,c,d=new p,e=new La;return function(){b=this.geometry;c=this.pointMap;e.projectionMatrix.copy(this.camera.projectionMatrix);a("c",0,0,-1);a("t",0,0,1);a("n1",-1,-1,-1);a("n2",1,-1,-1);a("n3",-1,1,-1);a("n4",1,1,-1);a("f1",-1,-1,1);a("f2",1,-1,1);a("f3",-1,1,1);a("f4",1,1,1);a("u1",.7,1.1,-1);a("u2",-.7,1.1,-1);a("u3",0,2,-1);a("cf1",-1,0,1);a("cf2",1,0,1);a("cf3",0,-1,1);a("cf4",0,1,1);a("cn1",-1,0,-1);a("cn2",1,0,-1);a("cn3",0,-1,-1);a("cn4",
17193 0,1,-1);b.getAttribute("position").needsUpdate=!0}}();Db.prototype=Object.create(ca.prototype);Db.prototype.constructor=Db;Db.prototype.update=function(){var a=new Oa;return function(b){void 0!==b&&console.warn("THREE.BoxHelper: .update() has no longer arguments.");void 0!==this.object&&a.setFromObject(this.object);if(!a.isEmpty()){b=a.min;var c=a.max,d=this.geometry.attributes.position,e=d.array;e[0]=c.x;e[1]=c.y;e[2]=c.z;e[3]=b.x;e[4]=c.y;e[5]=c.z;e[6]=b.x;e[7]=b.y;e[8]=c.z;e[9]=c.x;e[10]=b.y;e[11]=
17194 c.z;e[12]=c.x;e[13]=c.y;e[14]=b.z;e[15]=b.x;e[16]=c.y;e[17]=b.z;e[18]=b.x;e[19]=b.y;e[20]=b.z;e[21]=c.x;e[22]=b.y;e[23]=b.z;d.needsUpdate=!0;this.geometry.computeBoundingSphere()}}}();Db.prototype.setFromObject=function(a){this.object=a;this.update();return this};fd.prototype=Object.create(ca.prototype);fd.prototype.constructor=fd;fd.prototype.updateMatrixWorld=function(a){var b=this.box;b.isEmpty()||(b.getCenter(this.position),b.getSize(this.scale),this.scale.multiplyScalar(.5),A.prototype.updateMatrixWorld.call(this,
17195 a))};gd.prototype=Object.create(ma.prototype);gd.prototype.constructor=gd;gd.prototype.updateMatrixWorld=function(a){var b=-this.plane.constant;1E-8>Math.abs(b)&&(b=1E-8);this.scale.set(.5*this.size,.5*this.size,b);this.lookAt(this.plane.normal);A.prototype.updateMatrixWorld.call(this,a)};var Ld,pe;Eb.prototype=Object.create(A.prototype);Eb.prototype.constructor=Eb;Eb.prototype.setDirection=function(){var a=new p,b;return function(c){.99999<c.y?this.quaternion.set(0,0,0,1):-.99999>c.y?this.quaternion.set(1,
17196 0,0,0):(a.set(c.z,0,-c.x).normalize(),b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a,b))}}();Eb.prototype.setLength=function(a,b,c){void 0===b&&(b=.2*a);void 0===c&&(c=.2*b);this.line.scale.set(1,Math.max(0,a-b),1);this.line.updateMatrix();this.cone.scale.set(c,b,c);this.cone.position.y=a;this.cone.updateMatrix()};Eb.prototype.setColor=function(a){this.line.material.color.copy(a);this.cone.material.color.copy(a)};hd.prototype=Object.create(ca.prototype);hd.prototype.constructor=hd;var Nd=new p,
17197 te=new qe,ue=new qe,ve=new qe;ya.prototype=Object.create(S.prototype);ya.prototype.constructor=ya;ya.prototype.isCatmullRomCurve3=!0;ya.prototype.getPoint=function(a,b){b=b||new p;var c=this.points,d=c.length;a*=d-(this.closed?0:1);var e=Math.floor(a);a-=e;this.closed?e+=0<e?0:(Math.floor(Math.abs(e)/c.length)+1)*c.length:0===a&&e===d-1&&(e=d-2,a=1);if(this.closed||0<e)var f=c[(e-1)%d];else Nd.subVectors(c[0],c[1]).add(c[0]),f=Nd;var g=c[e%d];var h=c[(e+1)%d];this.closed||e+2<d?c=c[(e+2)%d]:(Nd.subVectors(c[d-
17198 1],c[d-2]).add(c[d-1]),c=Nd);if("centripetal"===this.curveType||"chordal"===this.curveType){var k="chordal"===this.curveType?.5:.25,d=Math.pow(f.distanceToSquared(g),k),e=Math.pow(g.distanceToSquared(h),k),k=Math.pow(h.distanceToSquared(c),k);1E-4>e&&(e=1);1E-4>d&&(d=e);1E-4>k&&(k=e);te.initNonuniformCatmullRom(f.x,g.x,h.x,c.x,d,e,k);ue.initNonuniformCatmullRom(f.y,g.y,h.y,c.y,d,e,k);ve.initNonuniformCatmullRom(f.z,g.z,h.z,c.z,d,e,k)}else"catmullrom"===this.curveType&&(te.initCatmullRom(f.x,g.x,h.x,
17199 c.x,this.tension),ue.initCatmullRom(f.y,g.y,h.y,c.y,this.tension),ve.initCatmullRom(f.z,g.z,h.z,c.z,this.tension));b.set(te.calc(a),ue.calc(a),ve.calc(a));return b};ya.prototype.copy=function(a){S.prototype.copy.call(this,a);this.points=[];for(var b=0,c=a.points.length;b<c;b++)this.points.push(a.points[b].clone());this.closed=a.closed;this.curveType=a.curveType;this.tension=a.tension;return this};Fb.prototype=Object.create(S.prototype);Fb.prototype.constructor=Fb;Fb.prototype.isCubicBezierCurve3=
17200 !0;Fb.prototype.getPoint=function(a,b){b=b||new p;var c=this.v0,d=this.v1,e=this.v2,f=this.v3;b.set(zb(a,c.x,d.x,e.x,f.x),zb(a,c.y,d.y,e.y,f.y),zb(a,c.z,d.z,e.z,f.z));return b};Fb.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);this.v3.copy(a.v3);return this};Gb.prototype=Object.create(S.prototype);Gb.prototype.constructor=Gb;Gb.prototype.isQuadraticBezierCurve3=!0;Gb.prototype.getPoint=function(a,b){b=b||new p;var c=this.v0,d=this.v1,
17201 e=this.v2;b.set(yb(a,c.x,d.x,e.x),yb(a,c.y,d.y,e.y),yb(a,c.z,d.z,e.z));return b};Gb.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};db.prototype=Object.create(S.prototype);db.prototype.constructor=db;db.prototype.isLineCurve3=!0;db.prototype.getPoint=function(a,b){b=b||new p;1===a?b.copy(this.v2):(b.copy(this.v2).sub(this.v1),b.multiplyScalar(a).add(this.v1));return b};db.prototype.getPointAt=function(a,b){return this.getPoint(a,
17202 b)};db.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};id.prototype=Object.create(Na.prototype);id.prototype.constructor=id;id.prototype.isArcCurve=!0;S.create=function(a,b){console.log("THREE.Curve.create() has been deprecated");a.prototype=Object.create(S.prototype);a.prototype.constructor=a;a.prototype.getPoint=b;return a};Object.assign(Ab.prototype,{createPointsGeometry:function(a){console.warn("THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");
17203 a=this.getPoints(a);return this.createGeometry(a)},createSpacedPointsGeometry:function(a){console.warn("THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");a=this.getSpacedPoints(a);return this.createGeometry(a)},createGeometry:function(a){console.warn("THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");for(var b=new N,c=0,d=a.length;c<d;c++){var e=a[c];b.vertices.push(new p(e.x,
17204 e.y,e.z||0))}return b}});Object.assign(Bb.prototype,{fromPoints:function(a){console.warn("THREE.Path: .fromPoints() has been renamed to .setFromPoints().");this.setFromPoints(a)}});ef.prototype=Object.create(ya.prototype);ff.prototype=Object.create(ya.prototype);re.prototype=Object.create(ya.prototype);Object.assign(re.prototype,{initFromArray:function(){console.error("THREE.Spline: .initFromArray() has been removed.")},getControlPointsArray:function(){console.error("THREE.Spline: .getControlPointsArray() has been removed.")},
17205 reparametrizeByArcLength:function(){console.error("THREE.Spline: .reparametrizeByArcLength() has been removed.")}});cd.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")};oc.prototype.update=function(){console.error("THREE.SkeletonHelper: update() no longer needs to be called.")};Object.assign(kd.prototype,{center:function(a){console.warn("THREE.Box2: .center() has been renamed to .getCenter().");return this.getCenter(a)},
17206 empty:function(){console.warn("THREE.Box2: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},size:function(a){console.warn("THREE.Box2: .size() has been renamed to .getSize().");return this.getSize(a)}});Object.assign(Oa.prototype,{center:function(a){console.warn("THREE.Box3: .center() has been renamed to .getCenter().");return this.getCenter(a)},
17207 empty:function(){console.warn("THREE.Box3: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionSphere:function(a){console.warn("THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)},size:function(a){console.warn("THREE.Box3: .size() has been renamed to .getSize().");return this.getSize(a)}});
17208 Mb.prototype.center=function(a){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");return this.getCenter(a)};Object.assign(R,{random16:function(){console.warn("THREE.Math: .random16() has been deprecated. Use Math.random() instead.");return Math.random()},nearestPowerOfTwo:function(a){console.warn("THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().");return R.floorPowerOfTwo(a)},nextPowerOfTwo:function(a){console.warn("THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().");
17209 return R.ceilPowerOfTwo(a)}});Object.assign(ra.prototype,{flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},multiplyVector3:function(a){console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.");return a.applyMatrix3(this)},multiplyVector3Array:function(){console.error("THREE.Matrix3: .multiplyVector3Array() has been removed.")},applyToBuffer:function(a){console.warn("THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");
17210 return this.applyToBufferAttribute(a)},applyToVector3Array:function(){console.error("THREE.Matrix3: .applyToVector3Array() has been removed.")}});Object.assign(K.prototype,{extractPosition:function(a){console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().");return this.copyPosition(a)},flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},getPosition:function(){var a;
17211 return function(){void 0===a&&(a=new p);console.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.");return a.setFromMatrixColumn(this,3)}}(),setRotationFromQuaternion:function(a){console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().");return this.makeRotationFromQuaternion(a)},multiplyToArray:function(){console.warn("THREE.Matrix4: .multiplyToArray() has been removed.")},multiplyVector3:function(a){console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.");
17212 return a.applyMatrix4(this)},multiplyVector4:function(a){console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.");return a.applyMatrix4(this)},multiplyVector3Array:function(){console.error("THREE.Matrix4: .multiplyVector3Array() has been removed.")},rotateAxis:function(a){console.warn("THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.");a.transformDirection(this)},crossVector:function(a){console.warn("THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.");
17213 return a.applyMatrix4(this)},translate:function(){console.error("THREE.Matrix4: .translate() has been removed.")},rotateX:function(){console.error("THREE.Matrix4: .rotateX() has been removed.")},rotateY:function(){console.error("THREE.Matrix4: .rotateY() has been removed.")},rotateZ:function(){console.error("THREE.Matrix4: .rotateZ() has been removed.")},rotateByAxis:function(){console.error("THREE.Matrix4: .rotateByAxis() has been removed.")},applyToBuffer:function(a){console.warn("THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");
17214 return this.applyToBufferAttribute(a)},applyToVector3Array:function(){console.error("THREE.Matrix4: .applyToVector3Array() has been removed.")},makeFrustum:function(a,b,c,d,e,f){console.warn("THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.");return this.makePerspective(a,b,d,c,e,f)}});Aa.prototype.isIntersectionLine=function(a){console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().");return this.intersectsLine(a)};
17215 Z.prototype.multiplyVector3=function(a){console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.");return a.applyQuaternion(this)};Object.assign(lb.prototype,{isIntersectionBox:function(a){console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionPlane:function(a){console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().");return this.intersectsPlane(a)},
17216 isIntersectionSphere:function(a){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)}});Object.assign(Cb.prototype,{extractAllPoints:function(a){console.warn("THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.");return this.extractPoints(a)},extrude:function(a){console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.");return new $a(this,a)},makeGeometry:function(a){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");
17217 return new cc(this,a)}});Object.assign(C.prototype,{fromAttribute:function(a,b,c){console.warn("THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)},distanceToManhattan:function(a){console.warn("THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().");return this.manhattanDistanceTo(a)},lengthManhattan:function(){console.warn("THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().");return this.manhattanLength()}});
17218 Object.assign(p.prototype,{setEulerFromRotationMatrix:function(){console.error("THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.")},setEulerFromQuaternion:function(){console.error("THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.")},getPositionFromMatrix:function(a){console.warn("THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().");return this.setFromMatrixPosition(a)},
17219 getScaleFromMatrix:function(a){console.warn("THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().");return this.setFromMatrixScale(a)},getColumnFromMatrix:function(a,b){console.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().");return this.setFromMatrixColumn(b,a)},applyProjection:function(a){console.warn("THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.");return this.applyMatrix4(a)},fromAttribute:function(a,
17220 b,c){console.warn("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)},distanceToManhattan:function(a){console.warn("THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().");return this.manhattanDistanceTo(a)},lengthManhattan:function(){console.warn("THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().");return this.manhattanLength()}});Object.assign(da.prototype,{fromAttribute:function(a,
17221 b,c){console.warn("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)},lengthManhattan:function(){console.warn("THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().");return this.manhattanLength()}});N.prototype.computeTangents=function(){console.warn("THREE.Geometry: .computeTangents() has been removed.")};Object.assign(A.prototype,{getChildByName:function(a){console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().");
17222 return this.getObjectByName(a)},renderDepth:function(){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.")},translate:function(a,b){console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.");return this.translateOnAxis(b,a)}});Object.defineProperties(A.prototype,{eulerOrder:{get:function(){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");return this.rotation.order},set:function(a){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");
17223 this.rotation.order=a}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}});Object.defineProperties(Dc.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Object.defineProperty(Ec.prototype,"useVertexTexture",{get:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")},
17224 set:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")}});Object.defineProperty(S.prototype,"__arcLengthDivisions",{get:function(){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");return this.arcLengthDivisions},set:function(a){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");this.arcLengthDivisions=a}});U.prototype.setLens=function(a,b){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup.");
17225 void 0!==b&&(this.filmGauge=b);this.setFocalLength(a)};Object.defineProperties(ga.prototype,{onlyShadow:{set:function(){console.warn("THREE.Light: .onlyShadow has been removed.")}},shadowCameraFov:{set:function(a){console.warn("THREE.Light: .shadowCameraFov is now .shadow.camera.fov.");this.shadow.camera.fov=a}},shadowCameraLeft:{set:function(a){console.warn("THREE.Light: .shadowCameraLeft is now .shadow.camera.left.");this.shadow.camera.left=a}},shadowCameraRight:{set:function(a){console.warn("THREE.Light: .shadowCameraRight is now .shadow.camera.right.");
17226 this.shadow.camera.right=a}},shadowCameraTop:{set:function(a){console.warn("THREE.Light: .shadowCameraTop is now .shadow.camera.top.");this.shadow.camera.top=a}},shadowCameraBottom:{set:function(a){console.warn("THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.");this.shadow.camera.bottom=a}},shadowCameraNear:{set:function(a){console.warn("THREE.Light: .shadowCameraNear is now .shadow.camera.near.");this.shadow.camera.near=a}},shadowCameraFar:{set:function(a){console.warn("THREE.Light: .shadowCameraFar is now .shadow.camera.far.");
17227 this.shadow.camera.far=a}},shadowCameraVisible:{set:function(){console.warn("THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.")}},shadowBias:{set:function(a){console.warn("THREE.Light: .shadowBias is now .shadow.bias.");this.shadow.bias=a}},shadowDarkness:{set:function(){console.warn("THREE.Light: .shadowDarkness has been removed.")}},shadowMapWidth:{set:function(a){console.warn("THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.");
17228 this.shadow.mapSize.width=a}},shadowMapHeight:{set:function(a){console.warn("THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.");this.shadow.mapSize.height=a}}});Object.defineProperties(P.prototype,{length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead.");return this.array.length}}});Object.assign(D.prototype,{addIndex:function(a){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().");this.setIndex(a)},addDrawCall:function(a,
17229 b,c){void 0!==c&&console.warn("THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.");console.warn("THREE.BufferGeometry: .addDrawCall() is now .addGroup().");this.addGroup(a,b)},clearDrawCalls:function(){console.warn("THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().");this.clearGroups()},computeTangents:function(){console.warn("THREE.BufferGeometry: .computeTangents() has been removed.")},computeOffsets:function(){console.warn("THREE.BufferGeometry: .computeOffsets() has been removed.")}});
17230 Object.defineProperties(D.prototype,{drawcalls:{get:function(){console.error("THREE.BufferGeometry: .drawcalls has been renamed to .groups.");return this.groups}},offsets:{get:function(){console.warn("THREE.BufferGeometry: .offsets has been renamed to .groups.");return this.groups}}});Object.defineProperties(Jd.prototype,{dynamic:{set:function(){console.warn("THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.")}},onUpdate:{value:function(){console.warn("THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.");
17231 return this}}});Object.defineProperties(Q.prototype,{wrapAround:{get:function(){console.warn("THREE.Material: .wrapAround has been removed.")},set:function(){console.warn("THREE.Material: .wrapAround has been removed.")}},wrapRGB:{get:function(){console.warn("THREE.Material: .wrapRGB has been removed.");return new H}},shading:{get:function(){console.error("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.")},set:function(a){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.");
17232 this.flatShading=1===a}}});Object.defineProperties(Ia.prototype,{metal:{get:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.");return!1},set:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead")}}});Object.defineProperties(oa.prototype,{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");return this.extensions.derivatives},
17233 set:function(a){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=a}}});Object.assign(Wd.prototype,{getCurrentRenderTarget:function(){console.warn("THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().");return this.getRenderTarget()},getMaxAnisotropy:function(){console.warn("THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().");return this.capabilities.getMaxAnisotropy()},getPrecision:function(){console.warn("THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.");
17234 return this.capabilities.precision},resetGLState:function(){console.warn("THREE.WebGLRenderer: .resetGLState() is now .state.reset().");return this.state.reset()},supportsFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' ).");return this.extensions.get("OES_texture_float")},supportsHalfFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( 'OES_texture_half_float' ).");
17235 return this.extensions.get("OES_texture_half_float")},supportsStandardDerivatives:function(){console.warn("THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( 'OES_standard_derivatives' ).");return this.extensions.get("OES_standard_derivatives")},supportsCompressedTextureS3TC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( 'WEBGL_compressed_texture_s3tc' ).");return this.extensions.get("WEBGL_compressed_texture_s3tc")},
17236 supportsCompressedTexturePVRTC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( 'WEBGL_compressed_texture_pvrtc' ).");return this.extensions.get("WEBGL_compressed_texture_pvrtc")},supportsBlendMinMax:function(){console.warn("THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( 'EXT_blend_minmax' ).");return this.extensions.get("EXT_blend_minmax")},supportsVertexTextures:function(){console.warn("THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.");
17237 return this.capabilities.vertexTextures},supportsInstancedArrays:function(){console.warn("THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( 'ANGLE_instanced_arrays' ).");return this.extensions.get("ANGLE_instanced_arrays")},enableScissorTest:function(a){console.warn("THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().");this.setScissorTest(a)},initMaterial:function(){console.warn("THREE.WebGLRenderer: .initMaterial() has been removed.")},addPrePlugin:function(){console.warn("THREE.WebGLRenderer: .addPrePlugin() has been removed.")},
17238 addPostPlugin:function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},updateShadowMap:function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")}});Object.defineProperties(Wd.prototype,{shadowMapEnabled:{get:function(){return this.shadowMap.enabled},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.");this.shadowMap.enabled=a}},shadowMapType:{get:function(){return this.shadowMap.type},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.");
17239 this.shadowMap.type=a}},shadowMapCullFace:{get:function(){return this.shadowMap.cullFace},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.");this.shadowMap.cullFace=a}}});Object.defineProperties(Ie.prototype,{cullFace:{get:function(){return this.renderReverseSided?2:1},set:function(a){a=1!==a;console.warn("WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to "+a+".");this.renderReverseSided=a}}});Object.defineProperties(Hb.prototype,
17240 {wrapS:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");return this.texture.wrapS},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");this.texture.wrapS=a}},wrapT:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");return this.texture.wrapT},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");this.texture.wrapT=a}},magFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");
17241 return this.texture.magFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");this.texture.magFilter=a}},minFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");return this.texture.minFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");this.texture.minFilter=a}},anisotropy:{get:function(){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");
17242 return this.texture.anisotropy},set:function(a){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");this.texture.anisotropy=a}},offset:{get:function(){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");return this.texture.offset},set:function(a){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");this.texture.offset=a}},repeat:{get:function(){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");return this.texture.repeat},
17243 set:function(a){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");this.texture.repeat=a}},format:{get:function(){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");return this.texture.format},set:function(a){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");this.texture.format=a}},type:{get:function(){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");return this.texture.type},set:function(a){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");
17244 this.texture.type=a}},generateMipmaps:{get:function(){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");return this.texture.generateMipmaps},set:function(a){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");this.texture.generateMipmaps=a}}});lc.prototype.load=function(a){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");var b=this;(new ee).load(a,function(a){b.setBuffer(a)});return this};
17245 ie.prototype.getData=function(){console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData().");return this.getFrequencyData()};$c.prototype.updateCubeMap=function(a,b){console.warn("THREE.CubeCamera: .updateCubeMap() is now .update().");return this.update(a,b)};m.WebGLRenderTargetCube=Ib;m.WebGLRenderTarget=Hb;m.WebGLRenderer=Wd;m.ShaderLib=mb;m.UniformsLib=E;m.UniformsUtils=Ea;m.ShaderChunk=W;m.FogExp2=Ob;m.Fog=Pb;m.Scene=od;m.LensFlare=Xd;m.Sprite=Cc;m.LOD=Dc;m.SkinnedMesh=qd;m.Skeleton=
17246 Ec;m.Bone=pd;m.Mesh=pa;m.LineSegments=ca;m.LineLoop=rd;m.Line=ma;m.Points=Qb;m.Group=Fc;m.VideoTexture=sd;m.DataTexture=fb;m.CompressedTexture=Rb;m.CubeTexture=Ua;m.CanvasTexture=tc;m.DepthTexture=Gc;m.Texture=ea;m.CompressedTextureLoader=Qe;m.DataTextureLoader=Zd;m.CubeTextureLoader=$d;m.TextureLoader=td;m.ObjectLoader=Re;m.MaterialLoader=Id;m.BufferGeometryLoader=ae;m.DefaultLoadingManager=wa;m.LoadingManager=Yd;m.JSONLoader=be;m.ImageLoader=Xc;m.FontLoader=Te;m.FileLoader=Ja;m.Loader=kc;m.Cache=
17247 jd;m.AudioLoader=ee;m.SpotLightShadow=vd;m.SpotLight=wd;m.PointLight=xd;m.RectAreaLight=Bd;m.HemisphereLight=ud;m.DirectionalLightShadow=yd;m.DirectionalLight=zd;m.AmbientLight=Ad;m.LightShadow=vb;m.Light=ga;m.StereoCamera=Ue;m.PerspectiveCamera=U;m.OrthographicCamera=Kb;m.CubeCamera=$c;m.ArrayCamera=nd;m.Camera=La;m.AudioListener=fe;m.PositionalAudio=he;m.AudioContext=ge;m.AudioAnalyser=ie;m.Audio=lc;m.VectorKeyframeTrack=ic;m.StringKeyframeTrack=Fd;m.QuaternionKeyframeTrack=Zc;m.NumberKeyframeTrack=
17248 jc;m.ColorKeyframeTrack=Hd;m.BooleanKeyframeTrack=Gd;m.PropertyMixer=je;m.PropertyBinding=na;m.KeyframeTrack=xb;m.AnimationUtils=T;m.AnimationObjectGroup=We;m.AnimationMixer=Ye;m.AnimationClip=ka;m.Uniform=Jd;m.InstancedBufferGeometry=ke;m.BufferGeometry=D;m.Geometry=N;m.InterleavedBufferAttribute=le;m.InstancedInterleavedBuffer=me;m.InterleavedBuffer=mc;m.InstancedBufferAttribute=ne;m.Face3=Pa;m.Object3D=A;m.Raycaster=Ze;m.Layers=Pd;m.EventDispatcher=ja;m.Clock=af;m.QuaternionLinearInterpolant=Ed;
17249 m.LinearInterpolant=Yc;m.DiscreteInterpolant=Dd;m.CubicInterpolant=Cd;m.Interpolant=xa;m.Triangle=Qa;m.Math=R;m.Spherical=bf;m.Cylindrical=cf;m.Plane=Aa;m.Frustum=ld;m.Sphere=Da;m.Ray=lb;m.Matrix4=K;m.Matrix3=ra;m.Box3=Oa;m.Box2=kd;m.Line3=Mb;m.Euler=Ya;m.Vector4=da;m.Vector3=p;m.Vector2=C;m.Quaternion=Z;m.Color=H;m.ImmediateRenderObject=ad;m.VertexNormalsHelper=bd;m.SpotLightHelper=nc;m.SkeletonHelper=oc;m.PointLightHelper=pc;m.RectAreaLightHelper=qc;m.HemisphereLightHelper=rc;m.GridHelper=cd;m.PolarGridHelper=
17250 Kd;m.FaceNormalsHelper=dd;m.DirectionalLightHelper=sc;m.CameraHelper=ed;m.BoxHelper=Db;m.Box3Helper=fd;m.PlaneHelper=gd;m.ArrowHelper=Eb;m.AxesHelper=hd;m.CatmullRomCurve3=ya;m.CubicBezierCurve3=Fb;m.QuadraticBezierCurve3=Gb;m.LineCurve3=db;m.ArcCurve=id;m.EllipseCurve=Na;m.SplineCurve=ab;m.CubicBezierCurve=bb;m.QuadraticBezierCurve=cb;m.LineCurve=Ka;m.Shape=Cb;m.Path=Bb;m.ShapePath=ce;m.Font=de;m.CurvePath=Ab;m.Curve=S;m.ShapeUtils=Ha;m.SceneUtils={createMultiMaterialObject:function(a,b){for(var c=
17251 new Fc,d=0,e=b.length;d<e;d++)c.add(new pa(a,b[d]));return c},detach:function(a,b,c){a.applyMatrix(b.matrixWorld);b.remove(a);c.add(a)},attach:function(a,b,c){a.applyMatrix((new K).getInverse(c.matrixWorld));b.remove(a);c.add(a)}};m.WebGLUtils=Pe;m.WireframeGeometry=Sb;m.ParametricGeometry=Hc;m.ParametricBufferGeometry=Tb;m.TetrahedronGeometry=Jc;m.TetrahedronBufferGeometry=Ub;m.OctahedronGeometry=Kc;m.OctahedronBufferGeometry=nb;m.IcosahedronGeometry=Lc;m.IcosahedronBufferGeometry=Vb;m.DodecahedronGeometry=
17252 Mc;m.DodecahedronBufferGeometry=Wb;m.PolyhedronGeometry=Ic;m.PolyhedronBufferGeometry=qa;m.TubeGeometry=Nc;m.TubeBufferGeometry=Xb;m.TorusKnotGeometry=Oc;m.TorusKnotBufferGeometry=Yb;m.TorusGeometry=Pc;m.TorusBufferGeometry=Zb;m.TextGeometry=Qc;m.TextBufferGeometry=$b;m.SphereGeometry=Rc;m.SphereBufferGeometry=ob;m.RingGeometry=Sc;m.RingBufferGeometry=ac;m.PlaneGeometry=Ac;m.PlaneBufferGeometry=kb;m.LatheGeometry=Tc;m.LatheBufferGeometry=bc;m.ShapeGeometry=cc;m.ShapeBufferGeometry=dc;m.ExtrudeGeometry=
17253 $a;m.ExtrudeBufferGeometry=Ga;m.EdgesGeometry=ec;m.ConeGeometry=Uc;m.ConeBufferGeometry=Vc;m.CylinderGeometry=pb;m.CylinderBufferGeometry=Sa;m.CircleGeometry=Wc;m.CircleBufferGeometry=fc;m.BoxGeometry=Lb;m.BoxBufferGeometry=jb;m.ShadowMaterial=gc;m.SpriteMaterial=Za;m.RawShaderMaterial=hc;m.ShaderMaterial=oa;m.PointsMaterial=Ba;m.MeshPhysicalMaterial=qb;m.MeshStandardMaterial=Ma;m.MeshPhongMaterial=Ia;m.MeshToonMaterial=rb;m.MeshNormalMaterial=sb;m.MeshLambertMaterial=tb;m.MeshDepthMaterial=Wa;m.MeshDistanceMaterial=
17254 Xa;m.MeshBasicMaterial=va;m.LineDashedMaterial=ub;m.LineBasicMaterial=O;m.Material=Q;m.Float64BufferAttribute=zc;m.Float32BufferAttribute=y;m.Uint32BufferAttribute=ib;m.Int32BufferAttribute=yc;m.Uint16BufferAttribute=hb;m.Int16BufferAttribute=xc;m.Uint8ClampedBufferAttribute=wc;m.Uint8BufferAttribute=vc;m.Int8BufferAttribute=uc;m.BufferAttribute=P;m.REVISION="88";m.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2};m.CullFaceNone=0;m.CullFaceBack=1;m.CullFaceFront=2;m.CullFaceFrontBack=3;m.FrontFaceDirectionCW=0;m.FrontFaceDirectionCCW=
17255 1;m.BasicShadowMap=0;m.PCFShadowMap=1;m.PCFSoftShadowMap=2;m.FrontSide=0;m.BackSide=1;m.DoubleSide=2;m.FlatShading=1;m.SmoothShading=2;m.NoColors=0;m.FaceColors=1;m.VertexColors=2;m.NoBlending=0;m.NormalBlending=1;m.AdditiveBlending=2;m.SubtractiveBlending=3;m.MultiplyBlending=4;m.CustomBlending=5;m.AddEquation=100;m.SubtractEquation=101;m.ReverseSubtractEquation=102;m.MinEquation=103;m.MaxEquation=104;m.ZeroFactor=200;m.OneFactor=201;m.SrcColorFactor=202;m.OneMinusSrcColorFactor=203;m.SrcAlphaFactor=
17256 204;m.OneMinusSrcAlphaFactor=205;m.DstAlphaFactor=206;m.OneMinusDstAlphaFactor=207;m.DstColorFactor=208;m.OneMinusDstColorFactor=209;m.SrcAlphaSaturateFactor=210;m.NeverDepth=0;m.AlwaysDepth=1;m.LessDepth=2;m.LessEqualDepth=3;m.EqualDepth=4;m.GreaterEqualDepth=5;m.GreaterDepth=6;m.NotEqualDepth=7;m.MultiplyOperation=0;m.MixOperation=1;m.AddOperation=2;m.NoToneMapping=0;m.LinearToneMapping=1;m.ReinhardToneMapping=2;m.Uncharted2ToneMapping=3;m.CineonToneMapping=4;m.UVMapping=300;m.CubeReflectionMapping=
17257 301;m.CubeRefractionMapping=302;m.EquirectangularReflectionMapping=303;m.EquirectangularRefractionMapping=304;m.SphericalReflectionMapping=305;m.CubeUVReflectionMapping=306;m.CubeUVRefractionMapping=307;m.RepeatWrapping=1E3;m.ClampToEdgeWrapping=1001;m.MirroredRepeatWrapping=1002;m.NearestFilter=1003;m.NearestMipMapNearestFilter=1004;m.NearestMipMapLinearFilter=1005;m.LinearFilter=1006;m.LinearMipMapNearestFilter=1007;m.LinearMipMapLinearFilter=1008;m.UnsignedByteType=1009;m.ByteType=1010;m.ShortType=
17258 1011;m.UnsignedShortType=1012;m.IntType=1013;m.UnsignedIntType=1014;m.FloatType=1015;m.HalfFloatType=1016;m.UnsignedShort4444Type=1017;m.UnsignedShort5551Type=1018;m.UnsignedShort565Type=1019;m.UnsignedInt248Type=1020;m.AlphaFormat=1021;m.RGBFormat=1022;m.RGBAFormat=1023;m.LuminanceFormat=1024;m.LuminanceAlphaFormat=1025;m.RGBEFormat=1023;m.DepthFormat=1026;m.DepthStencilFormat=1027;m.RGB_S3TC_DXT1_Format=2001;m.RGBA_S3TC_DXT1_Format=2002;m.RGBA_S3TC_DXT3_Format=2003;m.RGBA_S3TC_DXT5_Format=2004;
17259 m.RGB_PVRTC_4BPPV1_Format=2100;m.RGB_PVRTC_2BPPV1_Format=2101;m.RGBA_PVRTC_4BPPV1_Format=2102;m.RGBA_PVRTC_2BPPV1_Format=2103;m.RGB_ETC1_Format=2151;m.LoopOnce=2200;m.LoopRepeat=2201;m.LoopPingPong=2202;m.InterpolateDiscrete=2300;m.InterpolateLinear=2301;m.InterpolateSmooth=2302;m.ZeroCurvatureEnding=2400;m.ZeroSlopeEnding=2401;m.WrapAroundEnding=2402;m.TrianglesDrawMode=0;m.TriangleStripDrawMode=1;m.TriangleFanDrawMode=2;m.LinearEncoding=3E3;m.sRGBEncoding=3001;m.GammaEncoding=3007;m.RGBEEncoding=
17260 3002;m.LogLuvEncoding=3003;m.RGBM7Encoding=3004;m.RGBM16Encoding=3005;m.RGBDEncoding=3006;m.BasicDepthPacking=3200;m.RGBADepthPacking=3201;m.CubeGeometry=Lb;m.Face4=function(a,b,c,d,e,f,g){console.warn("THREE.Face4 has been removed. A THREE.Face3 will be created instead.");return new Pa(a,b,c,e,f,g)};m.LineStrip=0;m.LinePieces=1;m.MeshFaceMaterial=function(a){console.warn("THREE.MeshFaceMaterial has been removed. Use an Array instead.");return a};m.MultiMaterial=function(a){void 0===a&&(a=[]);console.warn("THREE.MultiMaterial has been removed. Use an Array instead.");
17261 a.isMultiMaterial=!0;a.materials=a;a.clone=function(){return a.slice()};return a};m.PointCloud=function(a,b){console.warn("THREE.PointCloud has been renamed to THREE.Points.");return new Qb(a,b)};m.Particle=function(a){console.warn("THREE.Particle has been renamed to THREE.Sprite.");return new Cc(a)};m.ParticleSystem=function(a,b){console.warn("THREE.ParticleSystem has been renamed to THREE.Points.");return new Qb(a,b)};m.PointCloudMaterial=function(a){console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.");
17262 return new Ba(a)};m.ParticleBasicMaterial=function(a){console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.");return new Ba(a)};m.ParticleSystemMaterial=function(a){console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.");return new Ba(a)};m.Vertex=function(a,b,c){console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead.");return new p(a,b,c)};m.DynamicBufferAttribute=function(a,b){console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.");
17263 return(new P(a,b)).setDynamic(!0)};m.Int8Attribute=function(a,b){console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.");return new uc(a,b)};m.Uint8Attribute=function(a,b){console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.");return new vc(a,b)};m.Uint8ClampedAttribute=function(a,b){console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.");return new wc(a,
17264 b)};m.Int16Attribute=function(a,b){console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.");return new xc(a,b)};m.Uint16Attribute=function(a,b){console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.");return new hb(a,b)};m.Int32Attribute=function(a,b){console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.");return new yc(a,b)};m.Uint32Attribute=function(a,b){console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.");
17265 return new ib(a,b)};m.Float32Attribute=function(a,b){console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.");return new y(a,b)};m.Float64Attribute=function(a,b){console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.");return new zc(a,b)};m.ClosedSplineCurve3=ef;m.SplineCurve3=ff;m.Spline=re;m.AxisHelper=function(a){console.warn("THREE.AxisHelper has been renamed to THREE.AxesHelper.");return new hd(a)};
17266 m.BoundingBoxHelper=function(a,b){console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.");return new Db(a,b)};m.EdgesHelper=function(a,b){console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.");return new ca(new ec(a.geometry),new O({color:void 0!==b?b:16777215}))};m.WireframeHelper=function(a,b){console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.");return new ca(new Sb(a.geometry),new O({color:void 0!==
17267 b?b:16777215}))};m.XHRLoader=function(a){console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader.");return new Ja(a)};m.BinaryTextureLoader=function(a){console.warn("THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.");return new Zd(a)};m.GeometryUtils={merge:function(a,b,c){console.warn("THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.");if(b.isMesh){b.matrixAutoUpdate&&b.updateMatrix();
17268 var d=b.matrix;b=b.geometry}a.merge(b,d,c)},center:function(a){console.warn("THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.");return a.center()}};m.ImageUtils={crossOrigin:void 0,loadTexture:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");var e=new td;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a},loadTextureCube:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");
17269 var e=new $d;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a},loadCompressedTexture:function(){console.error("THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.")},loadCompressedTextureCube:function(){console.error("THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.")}};m.Projector=function(){console.error("THREE.Projector has been moved to /examples/js/renderers/Projector.js.");this.projectVector=
17270 function(a,b){console.warn("THREE.Projector: .projectVector() is now vector.project().");a.project(b)};this.unprojectVector=function(a,b){console.warn("THREE.Projector: .unprojectVector() is now vector.unproject().");a.unproject(b)};this.pickingRay=function(){console.error("THREE.Projector: .pickingRay() is now raycaster.setFromCamera().")}};m.CanvasRenderer=function(){console.error("THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js");this.domElement=document.createElementNS("http://www.w3.org/1999/xhtml",
17271 "canvas");this.clear=function(){};this.render=function(){};this.setClearColor=function(){};this.setSize=function(){}};Object.defineProperty(m,"__esModule",{value:!0})});
17273 },{}],241:[function(require,module,exports){
17276 module.exports = TinyQueue;
17278 function TinyQueue(data, compare) {
17279 if (!(this instanceof TinyQueue)) return new TinyQueue(data, compare);
17281 this.data = data || [];
17282 this.length = this.data.length;
17283 this.compare = compare || defaultCompare;
17285 if (this.length > 0) {
17286 for (var i = (this.length >> 1); i >= 0; i--) this._down(i);
17290 function defaultCompare(a, b) {
17291 return a < b ? -1 : a > b ? 1 : 0;
17294 TinyQueue.prototype = {
17296 push: function (item) {
17297 this.data.push(item);
17299 this._up(this.length - 1);
17303 if (this.length === 0) return undefined;
17304 var top = this.data[0];
17306 if (this.length > 0) {
17307 this.data[0] = this.data[this.length];
17314 peek: function () {
17315 return this.data[0];
17318 _up: function (pos) {
17319 var data = this.data;
17320 var compare = this.compare;
17321 var item = data[pos];
17324 var parent = (pos - 1) >> 1;
17325 var current = data[parent];
17326 if (compare(item, current) >= 0) break;
17327 data[pos] = current;
17334 _down: function (pos) {
17335 var data = this.data;
17336 var compare = this.compare;
17337 var len = this.length;
17338 var halfLen = len >> 1;
17339 var item = data[pos];
17341 while (pos < halfLen) {
17342 var left = (pos << 1) + 1;
17343 var right = left + 1;
17344 var best = data[left];
17346 if (right < len && compare(data[right], best) < 0) {
17348 best = data[right];
17350 if (compare(best, item) >= 0) break;
17360 },{}],242:[function(require,module,exports){
17361 // Underscore.js 1.8.3
17362 // http://underscorejs.org
17363 // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
17364 // Underscore may be freely distributed under the MIT license.
17371 // Establish the root object, `window` in the browser, or `exports` on the server.
17374 // Save the previous value of the `_` variable.
17375 var previousUnderscore = root._;
17377 // Save bytes in the minified (but not gzipped) version:
17378 var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
17380 // Create quick reference variables for speed access to core prototypes.
17382 push = ArrayProto.push,
17383 slice = ArrayProto.slice,
17384 toString = ObjProto.toString,
17385 hasOwnProperty = ObjProto.hasOwnProperty;
17387 // All **ECMAScript 5** native function implementations that we hope to use
17388 // are declared here.
17390 nativeIsArray = Array.isArray,
17391 nativeKeys = Object.keys,
17392 nativeBind = FuncProto.bind,
17393 nativeCreate = Object.create;
17395 // Naked function reference for surrogate-prototype-swapping.
17396 var Ctor = function(){};
17398 // Create a safe reference to the Underscore object for use below.
17399 var _ = function(obj) {
17400 if (obj instanceof _) return obj;
17401 if (!(this instanceof _)) return new _(obj);
17402 this._wrapped = obj;
17405 // Export the Underscore object for **Node.js**, with
17406 // backwards-compatibility for the old `require()` API. If we're in
17407 // the browser, add `_` as a global object.
17408 if (typeof exports !== 'undefined') {
17409 if (typeof module !== 'undefined' && module.exports) {
17410 exports = module.exports = _;
17417 // Current version.
17418 _.VERSION = '1.8.3';
17420 // Internal function that returns an efficient (for current engines) version
17421 // of the passed-in callback, to be repeatedly applied in other Underscore
17423 var optimizeCb = function(func, context, argCount) {
17424 if (context === void 0) return func;
17425 switch (argCount == null ? 3 : argCount) {
17426 case 1: return function(value) {
17427 return func.call(context, value);
17429 case 2: return function(value, other) {
17430 return func.call(context, value, other);
17432 case 3: return function(value, index, collection) {
17433 return func.call(context, value, index, collection);
17435 case 4: return function(accumulator, value, index, collection) {
17436 return func.call(context, accumulator, value, index, collection);
17439 return function() {
17440 return func.apply(context, arguments);
17444 // A mostly-internal function to generate callbacks that can be applied
17445 // to each element in a collection, returning the desired result — either
17446 // identity, an arbitrary callback, a property matcher, or a property accessor.
17447 var cb = function(value, context, argCount) {
17448 if (value == null) return _.identity;
17449 if (_.isFunction(value)) return optimizeCb(value, context, argCount);
17450 if (_.isObject(value)) return _.matcher(value);
17451 return _.property(value);
17453 _.iteratee = function(value, context) {
17454 return cb(value, context, Infinity);
17457 // An internal function for creating assigner functions.
17458 var createAssigner = function(keysFunc, undefinedOnly) {
17459 return function(obj) {
17460 var length = arguments.length;
17461 if (length < 2 || obj == null) return obj;
17462 for (var index = 1; index < length; index++) {
17463 var source = arguments[index],
17464 keys = keysFunc(source),
17466 for (var i = 0; i < l; i++) {
17468 if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
17475 // An internal function for creating a new object that inherits from another.
17476 var baseCreate = function(prototype) {
17477 if (!_.isObject(prototype)) return {};
17478 if (nativeCreate) return nativeCreate(prototype);
17479 Ctor.prototype = prototype;
17480 var result = new Ctor;
17481 Ctor.prototype = null;
17485 var property = function(key) {
17486 return function(obj) {
17487 return obj == null ? void 0 : obj[key];
17491 // Helper for collection methods to determine whether a collection
17492 // should be iterated as an array or as an object
17493 // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
17494 // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
17495 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
17496 var getLength = property('length');
17497 var isArrayLike = function(collection) {
17498 var length = getLength(collection);
17499 return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
17502 // Collection Functions
17503 // --------------------
17505 // The cornerstone, an `each` implementation, aka `forEach`.
17506 // Handles raw objects in addition to array-likes. Treats all
17507 // sparse array-likes as if they were dense.
17508 _.each = _.forEach = function(obj, iteratee, context) {
17509 iteratee = optimizeCb(iteratee, context);
17511 if (isArrayLike(obj)) {
17512 for (i = 0, length = obj.length; i < length; i++) {
17513 iteratee(obj[i], i, obj);
17516 var keys = _.keys(obj);
17517 for (i = 0, length = keys.length; i < length; i++) {
17518 iteratee(obj[keys[i]], keys[i], obj);
17524 // Return the results of applying the iteratee to each element.
17525 _.map = _.collect = function(obj, iteratee, context) {
17526 iteratee = cb(iteratee, context);
17527 var keys = !isArrayLike(obj) && _.keys(obj),
17528 length = (keys || obj).length,
17529 results = Array(length);
17530 for (var index = 0; index < length; index++) {
17531 var currentKey = keys ? keys[index] : index;
17532 results[index] = iteratee(obj[currentKey], currentKey, obj);
17537 // Create a reducing function iterating left or right.
17538 function createReduce(dir) {
17539 // Optimized iterator function as using arguments.length
17540 // in the main function will deoptimize the, see #1991.
17541 function iterator(obj, iteratee, memo, keys, index, length) {
17542 for (; index >= 0 && index < length; index += dir) {
17543 var currentKey = keys ? keys[index] : index;
17544 memo = iteratee(memo, obj[currentKey], currentKey, obj);
17549 return function(obj, iteratee, memo, context) {
17550 iteratee = optimizeCb(iteratee, context, 4);
17551 var keys = !isArrayLike(obj) && _.keys(obj),
17552 length = (keys || obj).length,
17553 index = dir > 0 ? 0 : length - 1;
17554 // Determine the initial value if none is provided.
17555 if (arguments.length < 3) {
17556 memo = obj[keys ? keys[index] : index];
17559 return iterator(obj, iteratee, memo, keys, index, length);
17563 // **Reduce** builds up a single result from a list of values, aka `inject`,
17565 _.reduce = _.foldl = _.inject = createReduce(1);
17567 // The right-associative version of reduce, also known as `foldr`.
17568 _.reduceRight = _.foldr = createReduce(-1);
17570 // Return the first value which passes a truth test. Aliased as `detect`.
17571 _.find = _.detect = function(obj, predicate, context) {
17573 if (isArrayLike(obj)) {
17574 key = _.findIndex(obj, predicate, context);
17576 key = _.findKey(obj, predicate, context);
17578 if (key !== void 0 && key !== -1) return obj[key];
17581 // Return all the elements that pass a truth test.
17582 // Aliased as `select`.
17583 _.filter = _.select = function(obj, predicate, context) {
17585 predicate = cb(predicate, context);
17586 _.each(obj, function(value, index, list) {
17587 if (predicate(value, index, list)) results.push(value);
17592 // Return all the elements for which a truth test fails.
17593 _.reject = function(obj, predicate, context) {
17594 return _.filter(obj, _.negate(cb(predicate)), context);
17597 // Determine whether all of the elements match a truth test.
17598 // Aliased as `all`.
17599 _.every = _.all = function(obj, predicate, context) {
17600 predicate = cb(predicate, context);
17601 var keys = !isArrayLike(obj) && _.keys(obj),
17602 length = (keys || obj).length;
17603 for (var index = 0; index < length; index++) {
17604 var currentKey = keys ? keys[index] : index;
17605 if (!predicate(obj[currentKey], currentKey, obj)) return false;
17610 // Determine if at least one element in the object matches a truth test.
17611 // Aliased as `any`.
17612 _.some = _.any = function(obj, predicate, context) {
17613 predicate = cb(predicate, context);
17614 var keys = !isArrayLike(obj) && _.keys(obj),
17615 length = (keys || obj).length;
17616 for (var index = 0; index < length; index++) {
17617 var currentKey = keys ? keys[index] : index;
17618 if (predicate(obj[currentKey], currentKey, obj)) return true;
17623 // Determine if the array or object contains a given item (using `===`).
17624 // Aliased as `includes` and `include`.
17625 _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
17626 if (!isArrayLike(obj)) obj = _.values(obj);
17627 if (typeof fromIndex != 'number' || guard) fromIndex = 0;
17628 return _.indexOf(obj, item, fromIndex) >= 0;
17631 // Invoke a method (with arguments) on every item in a collection.
17632 _.invoke = function(obj, method) {
17633 var args = slice.call(arguments, 2);
17634 var isFunc = _.isFunction(method);
17635 return _.map(obj, function(value) {
17636 var func = isFunc ? method : value[method];
17637 return func == null ? func : func.apply(value, args);
17641 // Convenience version of a common use case of `map`: fetching a property.
17642 _.pluck = function(obj, key) {
17643 return _.map(obj, _.property(key));
17646 // Convenience version of a common use case of `filter`: selecting only objects
17647 // containing specific `key:value` pairs.
17648 _.where = function(obj, attrs) {
17649 return _.filter(obj, _.matcher(attrs));
17652 // Convenience version of a common use case of `find`: getting the first object
17653 // containing specific `key:value` pairs.
17654 _.findWhere = function(obj, attrs) {
17655 return _.find(obj, _.matcher(attrs));
17658 // Return the maximum element (or element-based computation).
17659 _.max = function(obj, iteratee, context) {
17660 var result = -Infinity, lastComputed = -Infinity,
17662 if (iteratee == null && obj != null) {
17663 obj = isArrayLike(obj) ? obj : _.values(obj);
17664 for (var i = 0, length = obj.length; i < length; i++) {
17666 if (value > result) {
17671 iteratee = cb(iteratee, context);
17672 _.each(obj, function(value, index, list) {
17673 computed = iteratee(value, index, list);
17674 if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
17676 lastComputed = computed;
17683 // Return the minimum element (or element-based computation).
17684 _.min = function(obj, iteratee, context) {
17685 var result = Infinity, lastComputed = Infinity,
17687 if (iteratee == null && obj != null) {
17688 obj = isArrayLike(obj) ? obj : _.values(obj);
17689 for (var i = 0, length = obj.length; i < length; i++) {
17691 if (value < result) {
17696 iteratee = cb(iteratee, context);
17697 _.each(obj, function(value, index, list) {
17698 computed = iteratee(value, index, list);
17699 if (computed < lastComputed || computed === Infinity && result === Infinity) {
17701 lastComputed = computed;
17708 // Shuffle a collection, using the modern version of the
17709 // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
17710 _.shuffle = function(obj) {
17711 var set = isArrayLike(obj) ? obj : _.values(obj);
17712 var length = set.length;
17713 var shuffled = Array(length);
17714 for (var index = 0, rand; index < length; index++) {
17715 rand = _.random(0, index);
17716 if (rand !== index) shuffled[index] = shuffled[rand];
17717 shuffled[rand] = set[index];
17722 // Sample **n** random values from a collection.
17723 // If **n** is not specified, returns a single random element.
17724 // The internal `guard` argument allows it to work with `map`.
17725 _.sample = function(obj, n, guard) {
17726 if (n == null || guard) {
17727 if (!isArrayLike(obj)) obj = _.values(obj);
17728 return obj[_.random(obj.length - 1)];
17730 return _.shuffle(obj).slice(0, Math.max(0, n));
17733 // Sort the object's values by a criterion produced by an iteratee.
17734 _.sortBy = function(obj, iteratee, context) {
17735 iteratee = cb(iteratee, context);
17736 return _.pluck(_.map(obj, function(value, index, list) {
17740 criteria: iteratee(value, index, list)
17742 }).sort(function(left, right) {
17743 var a = left.criteria;
17744 var b = right.criteria;
17746 if (a > b || a === void 0) return 1;
17747 if (a < b || b === void 0) return -1;
17749 return left.index - right.index;
17753 // An internal function used for aggregate "group by" operations.
17754 var group = function(behavior) {
17755 return function(obj, iteratee, context) {
17757 iteratee = cb(iteratee, context);
17758 _.each(obj, function(value, index) {
17759 var key = iteratee(value, index, obj);
17760 behavior(result, value, key);
17766 // Groups the object's values by a criterion. Pass either a string attribute
17767 // to group by, or a function that returns the criterion.
17768 _.groupBy = group(function(result, value, key) {
17769 if (_.has(result, key)) result[key].push(value); else result[key] = [value];
17772 // Indexes the object's values by a criterion, similar to `groupBy`, but for
17773 // when you know that your index values will be unique.
17774 _.indexBy = group(function(result, value, key) {
17775 result[key] = value;
17778 // Counts instances of an object that group by a certain criterion. Pass
17779 // either a string attribute to count by, or a function that returns the
17781 _.countBy = group(function(result, value, key) {
17782 if (_.has(result, key)) result[key]++; else result[key] = 1;
17785 // Safely create a real, live array from anything iterable.
17786 _.toArray = function(obj) {
17787 if (!obj) return [];
17788 if (_.isArray(obj)) return slice.call(obj);
17789 if (isArrayLike(obj)) return _.map(obj, _.identity);
17790 return _.values(obj);
17793 // Return the number of elements in an object.
17794 _.size = function(obj) {
17795 if (obj == null) return 0;
17796 return isArrayLike(obj) ? obj.length : _.keys(obj).length;
17799 // Split a collection into two arrays: one whose elements all satisfy the given
17800 // predicate, and one whose elements all do not satisfy the predicate.
17801 _.partition = function(obj, predicate, context) {
17802 predicate = cb(predicate, context);
17803 var pass = [], fail = [];
17804 _.each(obj, function(value, key, obj) {
17805 (predicate(value, key, obj) ? pass : fail).push(value);
17807 return [pass, fail];
17813 // Get the first element of an array. Passing **n** will return the first N
17814 // values in the array. Aliased as `head` and `take`. The **guard** check
17815 // allows it to work with `_.map`.
17816 _.first = _.head = _.take = function(array, n, guard) {
17817 if (array == null) return void 0;
17818 if (n == null || guard) return array[0];
17819 return _.initial(array, array.length - n);
17822 // Returns everything but the last entry of the array. Especially useful on
17823 // the arguments object. Passing **n** will return all the values in
17824 // the array, excluding the last N.
17825 _.initial = function(array, n, guard) {
17826 return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
17829 // Get the last element of an array. Passing **n** will return the last N
17830 // values in the array.
17831 _.last = function(array, n, guard) {
17832 if (array == null) return void 0;
17833 if (n == null || guard) return array[array.length - 1];
17834 return _.rest(array, Math.max(0, array.length - n));
17837 // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
17838 // Especially useful on the arguments object. Passing an **n** will return
17839 // the rest N values in the array.
17840 _.rest = _.tail = _.drop = function(array, n, guard) {
17841 return slice.call(array, n == null || guard ? 1 : n);
17844 // Trim out all falsy values from an array.
17845 _.compact = function(array) {
17846 return _.filter(array, _.identity);
17849 // Internal implementation of a recursive `flatten` function.
17850 var flatten = function(input, shallow, strict, startIndex) {
17851 var output = [], idx = 0;
17852 for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
17853 var value = input[i];
17854 if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
17855 //flatten current level of array or arguments object
17856 if (!shallow) value = flatten(value, shallow, strict);
17857 var j = 0, len = value.length;
17858 output.length += len;
17860 output[idx++] = value[j++];
17862 } else if (!strict) {
17863 output[idx++] = value;
17869 // Flatten out an array, either recursively (by default), or just one level.
17870 _.flatten = function(array, shallow) {
17871 return flatten(array, shallow, false);
17874 // Return a version of the array that does not contain the specified value(s).
17875 _.without = function(array) {
17876 return _.difference(array, slice.call(arguments, 1));
17879 // Produce a duplicate-free version of the array. If the array has already
17880 // been sorted, you have the option of using a faster algorithm.
17881 // Aliased as `unique`.
17882 _.uniq = _.unique = function(array, isSorted, iteratee, context) {
17883 if (!_.isBoolean(isSorted)) {
17884 context = iteratee;
17885 iteratee = isSorted;
17888 if (iteratee != null) iteratee = cb(iteratee, context);
17891 for (var i = 0, length = getLength(array); i < length; i++) {
17892 var value = array[i],
17893 computed = iteratee ? iteratee(value, i, array) : value;
17895 if (!i || seen !== computed) result.push(value);
17897 } else if (iteratee) {
17898 if (!_.contains(seen, computed)) {
17899 seen.push(computed);
17900 result.push(value);
17902 } else if (!_.contains(result, value)) {
17903 result.push(value);
17909 // Produce an array that contains the union: each distinct element from all of
17910 // the passed-in arrays.
17911 _.union = function() {
17912 return _.uniq(flatten(arguments, true, true));
17915 // Produce an array that contains every item shared between all the
17916 // passed-in arrays.
17917 _.intersection = function(array) {
17919 var argsLength = arguments.length;
17920 for (var i = 0, length = getLength(array); i < length; i++) {
17921 var item = array[i];
17922 if (_.contains(result, item)) continue;
17923 for (var j = 1; j < argsLength; j++) {
17924 if (!_.contains(arguments[j], item)) break;
17926 if (j === argsLength) result.push(item);
17931 // Take the difference between one array and a number of other arrays.
17932 // Only the elements present in just the first array will remain.
17933 _.difference = function(array) {
17934 var rest = flatten(arguments, true, true, 1);
17935 return _.filter(array, function(value){
17936 return !_.contains(rest, value);
17940 // Zip together multiple lists into a single array -- elements that share
17941 // an index go together.
17942 _.zip = function() {
17943 return _.unzip(arguments);
17946 // Complement of _.zip. Unzip accepts an array of arrays and groups
17947 // each array's elements on shared indices
17948 _.unzip = function(array) {
17949 var length = array && _.max(array, getLength).length || 0;
17950 var result = Array(length);
17952 for (var index = 0; index < length; index++) {
17953 result[index] = _.pluck(array, index);
17958 // Converts lists into objects. Pass either a single array of `[key, value]`
17959 // pairs, or two parallel arrays of the same length -- one of keys, and one of
17960 // the corresponding values.
17961 _.object = function(list, values) {
17963 for (var i = 0, length = getLength(list); i < length; i++) {
17965 result[list[i]] = values[i];
17967 result[list[i][0]] = list[i][1];
17973 // Generator function to create the findIndex and findLastIndex functions
17974 function createPredicateIndexFinder(dir) {
17975 return function(array, predicate, context) {
17976 predicate = cb(predicate, context);
17977 var length = getLength(array);
17978 var index = dir > 0 ? 0 : length - 1;
17979 for (; index >= 0 && index < length; index += dir) {
17980 if (predicate(array[index], index, array)) return index;
17986 // Returns the first index on an array-like that passes a predicate test
17987 _.findIndex = createPredicateIndexFinder(1);
17988 _.findLastIndex = createPredicateIndexFinder(-1);
17990 // Use a comparator function to figure out the smallest index at which
17991 // an object should be inserted so as to maintain order. Uses binary search.
17992 _.sortedIndex = function(array, obj, iteratee, context) {
17993 iteratee = cb(iteratee, context, 1);
17994 var value = iteratee(obj);
17995 var low = 0, high = getLength(array);
17996 while (low < high) {
17997 var mid = Math.floor((low + high) / 2);
17998 if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
18003 // Generator function to create the indexOf and lastIndexOf functions
18004 function createIndexFinder(dir, predicateFind, sortedIndex) {
18005 return function(array, item, idx) {
18006 var i = 0, length = getLength(array);
18007 if (typeof idx == 'number') {
18009 i = idx >= 0 ? idx : Math.max(idx + length, i);
18011 length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
18013 } else if (sortedIndex && idx && length) {
18014 idx = sortedIndex(array, item);
18015 return array[idx] === item ? idx : -1;
18017 if (item !== item) {
18018 idx = predicateFind(slice.call(array, i, length), _.isNaN);
18019 return idx >= 0 ? idx + i : -1;
18021 for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
18022 if (array[idx] === item) return idx;
18028 // Return the position of the first occurrence of an item in an array,
18029 // or -1 if the item is not included in the array.
18030 // If the array is large and already in sort order, pass `true`
18031 // for **isSorted** to use binary search.
18032 _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
18033 _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
18035 // Generate an integer Array containing an arithmetic progression. A port of
18036 // the native Python `range()` function. See
18037 // [the Python documentation](http://docs.python.org/library/functions.html#range).
18038 _.range = function(start, stop, step) {
18039 if (stop == null) {
18045 var length = Math.max(Math.ceil((stop - start) / step), 0);
18046 var range = Array(length);
18048 for (var idx = 0; idx < length; idx++, start += step) {
18049 range[idx] = start;
18055 // Function (ahem) Functions
18056 // ------------------
18058 // Determines whether to execute a function as a constructor
18059 // or a normal function with the provided arguments
18060 var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
18061 if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
18062 var self = baseCreate(sourceFunc.prototype);
18063 var result = sourceFunc.apply(self, args);
18064 if (_.isObject(result)) return result;
18068 // Create a function bound to a given object (assigning `this`, and arguments,
18069 // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
18071 _.bind = function(func, context) {
18072 if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
18073 if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
18074 var args = slice.call(arguments, 2);
18075 var bound = function() {
18076 return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
18081 // Partially apply a function by creating a version that has had some of its
18082 // arguments pre-filled, without changing its dynamic `this` context. _ acts
18083 // as a placeholder, allowing any combination of arguments to be pre-filled.
18084 _.partial = function(func) {
18085 var boundArgs = slice.call(arguments, 1);
18086 var bound = function() {
18087 var position = 0, length = boundArgs.length;
18088 var args = Array(length);
18089 for (var i = 0; i < length; i++) {
18090 args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
18092 while (position < arguments.length) args.push(arguments[position++]);
18093 return executeBound(func, bound, this, this, args);
18098 // Bind a number of an object's methods to that object. Remaining arguments
18099 // are the method names to be bound. Useful for ensuring that all callbacks
18100 // defined on an object belong to it.
18101 _.bindAll = function(obj) {
18102 var i, length = arguments.length, key;
18103 if (length <= 1) throw new Error('bindAll must be passed function names');
18104 for (i = 1; i < length; i++) {
18105 key = arguments[i];
18106 obj[key] = _.bind(obj[key], obj);
18111 // Memoize an expensive function by storing its results.
18112 _.memoize = function(func, hasher) {
18113 var memoize = function(key) {
18114 var cache = memoize.cache;
18115 var address = '' + (hasher ? hasher.apply(this, arguments) : key);
18116 if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
18117 return cache[address];
18119 memoize.cache = {};
18123 // Delays a function for the given number of milliseconds, and then calls
18124 // it with the arguments supplied.
18125 _.delay = function(func, wait) {
18126 var args = slice.call(arguments, 2);
18127 return setTimeout(function(){
18128 return func.apply(null, args);
18132 // Defers a function, scheduling it to run after the current call stack has
18134 _.defer = _.partial(_.delay, _, 1);
18136 // Returns a function, that, when invoked, will only be triggered at most once
18137 // during a given window of time. Normally, the throttled function will run
18138 // as much as it can, without ever going more than once per `wait` duration;
18139 // but if you'd like to disable the execution on the leading edge, pass
18140 // `{leading: false}`. To disable execution on the trailing edge, ditto.
18141 _.throttle = function(func, wait, options) {
18142 var context, args, result;
18143 var timeout = null;
18145 if (!options) options = {};
18146 var later = function() {
18147 previous = options.leading === false ? 0 : _.now();
18149 result = func.apply(context, args);
18150 if (!timeout) context = args = null;
18152 return function() {
18154 if (!previous && options.leading === false) previous = now;
18155 var remaining = wait - (now - previous);
18158 if (remaining <= 0 || remaining > wait) {
18160 clearTimeout(timeout);
18164 result = func.apply(context, args);
18165 if (!timeout) context = args = null;
18166 } else if (!timeout && options.trailing !== false) {
18167 timeout = setTimeout(later, remaining);
18173 // Returns a function, that, as long as it continues to be invoked, will not
18174 // be triggered. The function will be called after it stops being called for
18175 // N milliseconds. If `immediate` is passed, trigger the function on the
18176 // leading edge, instead of the trailing.
18177 _.debounce = function(func, wait, immediate) {
18178 var timeout, args, context, timestamp, result;
18180 var later = function() {
18181 var last = _.now() - timestamp;
18183 if (last < wait && last >= 0) {
18184 timeout = setTimeout(later, wait - last);
18188 result = func.apply(context, args);
18189 if (!timeout) context = args = null;
18194 return function() {
18197 timestamp = _.now();
18198 var callNow = immediate && !timeout;
18199 if (!timeout) timeout = setTimeout(later, wait);
18201 result = func.apply(context, args);
18202 context = args = null;
18209 // Returns the first function passed as an argument to the second,
18210 // allowing you to adjust arguments, run code before and after, and
18211 // conditionally execute the original function.
18212 _.wrap = function(func, wrapper) {
18213 return _.partial(wrapper, func);
18216 // Returns a negated version of the passed-in predicate.
18217 _.negate = function(predicate) {
18218 return function() {
18219 return !predicate.apply(this, arguments);
18223 // Returns a function that is the composition of a list of functions, each
18224 // consuming the return value of the function that follows.
18225 _.compose = function() {
18226 var args = arguments;
18227 var start = args.length - 1;
18228 return function() {
18230 var result = args[start].apply(this, arguments);
18231 while (i--) result = args[i].call(this, result);
18236 // Returns a function that will only be executed on and after the Nth call.
18237 _.after = function(times, func) {
18238 return function() {
18240 return func.apply(this, arguments);
18245 // Returns a function that will only be executed up to (but not including) the Nth call.
18246 _.before = function(times, func) {
18248 return function() {
18250 memo = func.apply(this, arguments);
18252 if (times <= 1) func = null;
18257 // Returns a function that will be executed at most one time, no matter how
18258 // often you call it. Useful for lazy initialization.
18259 _.once = _.partial(_.before, 2);
18261 // Object Functions
18262 // ----------------
18264 // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
18265 var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
18266 var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
18267 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
18269 function collectNonEnumProps(obj, keys) {
18270 var nonEnumIdx = nonEnumerableProps.length;
18271 var constructor = obj.constructor;
18272 var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
18274 // Constructor is a special case.
18275 var prop = 'constructor';
18276 if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
18278 while (nonEnumIdx--) {
18279 prop = nonEnumerableProps[nonEnumIdx];
18280 if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
18286 // Retrieve the names of an object's own properties.
18287 // Delegates to **ECMAScript 5**'s native `Object.keys`
18288 _.keys = function(obj) {
18289 if (!_.isObject(obj)) return [];
18290 if (nativeKeys) return nativeKeys(obj);
18292 for (var key in obj) if (_.has(obj, key)) keys.push(key);
18294 if (hasEnumBug) collectNonEnumProps(obj, keys);
18298 // Retrieve all the property names of an object.
18299 _.allKeys = function(obj) {
18300 if (!_.isObject(obj)) return [];
18302 for (var key in obj) keys.push(key);
18304 if (hasEnumBug) collectNonEnumProps(obj, keys);
18308 // Retrieve the values of an object's properties.
18309 _.values = function(obj) {
18310 var keys = _.keys(obj);
18311 var length = keys.length;
18312 var values = Array(length);
18313 for (var i = 0; i < length; i++) {
18314 values[i] = obj[keys[i]];
18319 // Returns the results of applying the iteratee to each element of the object
18320 // In contrast to _.map it returns an object
18321 _.mapObject = function(obj, iteratee, context) {
18322 iteratee = cb(iteratee, context);
18323 var keys = _.keys(obj),
18324 length = keys.length,
18327 for (var index = 0; index < length; index++) {
18328 currentKey = keys[index];
18329 results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
18334 // Convert an object into a list of `[key, value]` pairs.
18335 _.pairs = function(obj) {
18336 var keys = _.keys(obj);
18337 var length = keys.length;
18338 var pairs = Array(length);
18339 for (var i = 0; i < length; i++) {
18340 pairs[i] = [keys[i], obj[keys[i]]];
18345 // Invert the keys and values of an object. The values must be serializable.
18346 _.invert = function(obj) {
18348 var keys = _.keys(obj);
18349 for (var i = 0, length = keys.length; i < length; i++) {
18350 result[obj[keys[i]]] = keys[i];
18355 // Return a sorted list of the function names available on the object.
18356 // Aliased as `methods`
18357 _.functions = _.methods = function(obj) {
18359 for (var key in obj) {
18360 if (_.isFunction(obj[key])) names.push(key);
18362 return names.sort();
18365 // Extend a given object with all the properties in passed-in object(s).
18366 _.extend = createAssigner(_.allKeys);
18368 // Assigns a given object with all the own properties in the passed-in object(s)
18369 // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
18370 _.extendOwn = _.assign = createAssigner(_.keys);
18372 // Returns the first key on an object that passes a predicate test
18373 _.findKey = function(obj, predicate, context) {
18374 predicate = cb(predicate, context);
18375 var keys = _.keys(obj), key;
18376 for (var i = 0, length = keys.length; i < length; i++) {
18378 if (predicate(obj[key], key, obj)) return key;
18382 // Return a copy of the object only containing the whitelisted properties.
18383 _.pick = function(object, oiteratee, context) {
18384 var result = {}, obj = object, iteratee, keys;
18385 if (obj == null) return result;
18386 if (_.isFunction(oiteratee)) {
18387 keys = _.allKeys(obj);
18388 iteratee = optimizeCb(oiteratee, context);
18390 keys = flatten(arguments, false, false, 1);
18391 iteratee = function(value, key, obj) { return key in obj; };
18394 for (var i = 0, length = keys.length; i < length; i++) {
18396 var value = obj[key];
18397 if (iteratee(value, key, obj)) result[key] = value;
18402 // Return a copy of the object without the blacklisted properties.
18403 _.omit = function(obj, iteratee, context) {
18404 if (_.isFunction(iteratee)) {
18405 iteratee = _.negate(iteratee);
18407 var keys = _.map(flatten(arguments, false, false, 1), String);
18408 iteratee = function(value, key) {
18409 return !_.contains(keys, key);
18412 return _.pick(obj, iteratee, context);
18415 // Fill in a given object with default properties.
18416 _.defaults = createAssigner(_.allKeys, true);
18418 // Creates an object that inherits from the given prototype object.
18419 // If additional properties are provided then they will be added to the
18421 _.create = function(prototype, props) {
18422 var result = baseCreate(prototype);
18423 if (props) _.extendOwn(result, props);
18427 // Create a (shallow-cloned) duplicate of an object.
18428 _.clone = function(obj) {
18429 if (!_.isObject(obj)) return obj;
18430 return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
18433 // Invokes interceptor with the obj, and then returns obj.
18434 // The primary purpose of this method is to "tap into" a method chain, in
18435 // order to perform operations on intermediate results within the chain.
18436 _.tap = function(obj, interceptor) {
18441 // Returns whether an object has a given set of `key:value` pairs.
18442 _.isMatch = function(object, attrs) {
18443 var keys = _.keys(attrs), length = keys.length;
18444 if (object == null) return !length;
18445 var obj = Object(object);
18446 for (var i = 0; i < length; i++) {
18448 if (attrs[key] !== obj[key] || !(key in obj)) return false;
18454 // Internal recursive comparison function for `isEqual`.
18455 var eq = function(a, b, aStack, bStack) {
18456 // Identical objects are equal. `0 === -0`, but they aren't identical.
18457 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
18458 if (a === b) return a !== 0 || 1 / a === 1 / b;
18459 // A strict comparison is necessary because `null == undefined`.
18460 if (a == null || b == null) return a === b;
18461 // Unwrap any wrapped objects.
18462 if (a instanceof _) a = a._wrapped;
18463 if (b instanceof _) b = b._wrapped;
18464 // Compare `[[Class]]` names.
18465 var className = toString.call(a);
18466 if (className !== toString.call(b)) return false;
18467 switch (className) {
18468 // Strings, numbers, regular expressions, dates, and booleans are compared by value.
18469 case '[object RegExp]':
18470 // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
18471 case '[object String]':
18472 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
18473 // equivalent to `new String("5")`.
18474 return '' + a === '' + b;
18475 case '[object Number]':
18476 // `NaN`s are equivalent, but non-reflexive.
18477 // Object(NaN) is equivalent to NaN
18478 if (+a !== +a) return +b !== +b;
18479 // An `egal` comparison is performed for other numeric values.
18480 return +a === 0 ? 1 / +a === 1 / b : +a === +b;
18481 case '[object Date]':
18482 case '[object Boolean]':
18483 // Coerce dates and booleans to numeric primitive values. Dates are compared by their
18484 // millisecond representations. Note that invalid dates with millisecond representations
18485 // of `NaN` are not equivalent.
18489 var areArrays = className === '[object Array]';
18491 if (typeof a != 'object' || typeof b != 'object') return false;
18493 // Objects with different constructors are not equivalent, but `Object`s or `Array`s
18494 // from different frames are.
18495 var aCtor = a.constructor, bCtor = b.constructor;
18496 if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
18497 _.isFunction(bCtor) && bCtor instanceof bCtor)
18498 && ('constructor' in a && 'constructor' in b)) {
18502 // Assume equality for cyclic structures. The algorithm for detecting cyclic
18503 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
18505 // Initializing stack of traversed objects.
18506 // It's done here since we only need them for objects and arrays comparison.
18507 aStack = aStack || [];
18508 bStack = bStack || [];
18509 var length = aStack.length;
18511 // Linear search. Performance is inversely proportional to the number of
18512 // unique nested structures.
18513 if (aStack[length] === a) return bStack[length] === b;
18516 // Add the first object to the stack of traversed objects.
18520 // Recursively compare objects and arrays.
18522 // Compare array lengths to determine if a deep comparison is necessary.
18524 if (length !== b.length) return false;
18525 // Deep compare the contents, ignoring non-numeric properties.
18527 if (!eq(a[length], b[length], aStack, bStack)) return false;
18530 // Deep compare objects.
18531 var keys = _.keys(a), key;
18532 length = keys.length;
18533 // Ensure that both objects contain the same number of properties before comparing deep equality.
18534 if (_.keys(b).length !== length) return false;
18536 // Deep compare each member
18537 key = keys[length];
18538 if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
18541 // Remove the first object from the stack of traversed objects.
18547 // Perform a deep comparison to check if two objects are equal.
18548 _.isEqual = function(a, b) {
18552 // Is a given array, string, or object empty?
18553 // An "empty" object has no enumerable own-properties.
18554 _.isEmpty = function(obj) {
18555 if (obj == null) return true;
18556 if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
18557 return _.keys(obj).length === 0;
18560 // Is a given value a DOM element?
18561 _.isElement = function(obj) {
18562 return !!(obj && obj.nodeType === 1);
18565 // Is a given value an array?
18566 // Delegates to ECMA5's native Array.isArray
18567 _.isArray = nativeIsArray || function(obj) {
18568 return toString.call(obj) === '[object Array]';
18571 // Is a given variable an object?
18572 _.isObject = function(obj) {
18573 var type = typeof obj;
18574 return type === 'function' || type === 'object' && !!obj;
18577 // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
18578 _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
18579 _['is' + name] = function(obj) {
18580 return toString.call(obj) === '[object ' + name + ']';
18584 // Define a fallback version of the method in browsers (ahem, IE < 9), where
18585 // there isn't any inspectable "Arguments" type.
18586 if (!_.isArguments(arguments)) {
18587 _.isArguments = function(obj) {
18588 return _.has(obj, 'callee');
18592 // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
18593 // IE 11 (#1621), and in Safari 8 (#1929).
18594 if (typeof /./ != 'function' && typeof Int8Array != 'object') {
18595 _.isFunction = function(obj) {
18596 return typeof obj == 'function' || false;
18600 // Is a given object a finite number?
18601 _.isFinite = function(obj) {
18602 return isFinite(obj) && !isNaN(parseFloat(obj));
18605 // Is the given value `NaN`? (NaN is the only number which does not equal itself).
18606 _.isNaN = function(obj) {
18607 return _.isNumber(obj) && obj !== +obj;
18610 // Is a given value a boolean?
18611 _.isBoolean = function(obj) {
18612 return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
18615 // Is a given value equal to null?
18616 _.isNull = function(obj) {
18617 return obj === null;
18620 // Is a given variable undefined?
18621 _.isUndefined = function(obj) {
18622 return obj === void 0;
18625 // Shortcut function for checking if an object has a given property directly
18626 // on itself (in other words, not on a prototype).
18627 _.has = function(obj, key) {
18628 return obj != null && hasOwnProperty.call(obj, key);
18631 // Utility Functions
18632 // -----------------
18634 // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
18635 // previous owner. Returns a reference to the Underscore object.
18636 _.noConflict = function() {
18637 root._ = previousUnderscore;
18641 // Keep the identity function around for default iteratees.
18642 _.identity = function(value) {
18646 // Predicate-generating functions. Often useful outside of Underscore.
18647 _.constant = function(value) {
18648 return function() {
18653 _.noop = function(){};
18655 _.property = property;
18657 // Generates a function for a given object that returns a given property.
18658 _.propertyOf = function(obj) {
18659 return obj == null ? function(){} : function(key) {
18664 // Returns a predicate for checking whether an object has a given set of
18665 // `key:value` pairs.
18666 _.matcher = _.matches = function(attrs) {
18667 attrs = _.extendOwn({}, attrs);
18668 return function(obj) {
18669 return _.isMatch(obj, attrs);
18673 // Run a function **n** times.
18674 _.times = function(n, iteratee, context) {
18675 var accum = Array(Math.max(0, n));
18676 iteratee = optimizeCb(iteratee, context, 1);
18677 for (var i = 0; i < n; i++) accum[i] = iteratee(i);
18681 // Return a random integer between min and max (inclusive).
18682 _.random = function(min, max) {
18687 return min + Math.floor(Math.random() * (max - min + 1));
18690 // A (possibly faster) way to get the current timestamp as an integer.
18691 _.now = Date.now || function() {
18692 return new Date().getTime();
18695 // List of HTML entities for escaping.
18704 var unescapeMap = _.invert(escapeMap);
18706 // Functions for escaping and unescaping strings to/from HTML interpolation.
18707 var createEscaper = function(map) {
18708 var escaper = function(match) {
18711 // Regexes for identifying a key that needs to be escaped
18712 var source = '(?:' + _.keys(map).join('|') + ')';
18713 var testRegexp = RegExp(source);
18714 var replaceRegexp = RegExp(source, 'g');
18715 return function(string) {
18716 string = string == null ? '' : '' + string;
18717 return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
18720 _.escape = createEscaper(escapeMap);
18721 _.unescape = createEscaper(unescapeMap);
18723 // If the value of the named `property` is a function then invoke it with the
18724 // `object` as context; otherwise, return it.
18725 _.result = function(object, property, fallback) {
18726 var value = object == null ? void 0 : object[property];
18727 if (value === void 0) {
18730 return _.isFunction(value) ? value.call(object) : value;
18733 // Generate a unique integer id (unique within the entire client session).
18734 // Useful for temporary DOM ids.
18736 _.uniqueId = function(prefix) {
18737 var id = ++idCounter + '';
18738 return prefix ? prefix + id : id;
18741 // By default, Underscore uses ERB-style template delimiters, change the
18742 // following template settings to use alternative delimiters.
18743 _.templateSettings = {
18744 evaluate : /<%([\s\S]+?)%>/g,
18745 interpolate : /<%=([\s\S]+?)%>/g,
18746 escape : /<%-([\s\S]+?)%>/g
18749 // When customizing `templateSettings`, if you don't want to define an
18750 // interpolation, evaluation or escaping regex, we need one that is
18751 // guaranteed not to match.
18752 var noMatch = /(.)^/;
18754 // Certain characters need to be escaped so that they can be put into a
18765 var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
18767 var escapeChar = function(match) {
18768 return '\\' + escapes[match];
18771 // JavaScript micro-templating, similar to John Resig's implementation.
18772 // Underscore templating handles arbitrary delimiters, preserves whitespace,
18773 // and correctly escapes quotes within interpolated code.
18774 // NB: `oldSettings` only exists for backwards compatibility.
18775 _.template = function(text, settings, oldSettings) {
18776 if (!settings && oldSettings) settings = oldSettings;
18777 settings = _.defaults({}, settings, _.templateSettings);
18779 // Combine delimiters into one regular expression via alternation.
18780 var matcher = RegExp([
18781 (settings.escape || noMatch).source,
18782 (settings.interpolate || noMatch).source,
18783 (settings.evaluate || noMatch).source
18784 ].join('|') + '|$', 'g');
18786 // Compile the template source, escaping string literals appropriately.
18788 var source = "__p+='";
18789 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
18790 source += text.slice(index, offset).replace(escaper, escapeChar);
18791 index = offset + match.length;
18794 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
18795 } else if (interpolate) {
18796 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
18797 } else if (evaluate) {
18798 source += "';\n" + evaluate + "\n__p+='";
18801 // Adobe VMs need the match returned to produce the correct offest.
18806 // If a variable is not specified, place data values in local scope.
18807 if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
18809 source = "var __t,__p='',__j=Array.prototype.join," +
18810 "print=function(){__p+=__j.call(arguments,'');};\n" +
18811 source + 'return __p;\n';
18814 var render = new Function(settings.variable || 'obj', '_', source);
18820 var template = function(data) {
18821 return render.call(this, data, _);
18824 // Provide the compiled source as a convenience for precompilation.
18825 var argument = settings.variable || 'obj';
18826 template.source = 'function(' + argument + '){\n' + source + '}';
18831 // Add a "chain" function. Start chaining a wrapped Underscore object.
18832 _.chain = function(obj) {
18833 var instance = _(obj);
18834 instance._chain = true;
18840 // If Underscore is called as a function, it returns a wrapped object that
18841 // can be used OO-style. This wrapper holds altered versions of all the
18842 // underscore functions. Wrapped objects may be chained.
18844 // Helper function to continue chaining intermediate results.
18845 var result = function(instance, obj) {
18846 return instance._chain ? _(obj).chain() : obj;
18849 // Add your own custom functions to the Underscore object.
18850 _.mixin = function(obj) {
18851 _.each(_.functions(obj), function(name) {
18852 var func = _[name] = obj[name];
18853 _.prototype[name] = function() {
18854 var args = [this._wrapped];
18855 push.apply(args, arguments);
18856 return result(this, func.apply(_, args));
18861 // Add all of the Underscore functions to the wrapper object.
18864 // Add all mutator Array functions to the wrapper.
18865 _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
18866 var method = ArrayProto[name];
18867 _.prototype[name] = function() {
18868 var obj = this._wrapped;
18869 method.apply(obj, arguments);
18870 if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
18871 return result(this, obj);
18875 // Add all accessor Array functions to the wrapper.
18876 _.each(['concat', 'join', 'slice'], function(name) {
18877 var method = ArrayProto[name];
18878 _.prototype[name] = function() {
18879 return result(this, method.apply(this._wrapped, arguments));
18883 // Extracts the result from a wrapped and chained object.
18884 _.prototype.value = function() {
18885 return this._wrapped;
18888 // Provide unwrapping proxy for some methods used in engine operations
18889 // such as arithmetic and JSON stringification.
18890 _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
18892 _.prototype.toString = function() {
18893 return '' + this._wrapped;
18896 // AMD registration happens at the end for compatibility with AMD loaders
18897 // that may not enforce next-turn semantics on modules. Even though general
18898 // practice for AMD registration is to be anonymous, underscore registers
18899 // as a named module because, like jQuery, it is a base library that is
18900 // popular enough to be bundled in a third party lib, but not be part of
18901 // an AMD load request. Those cases could generate an error when an
18902 // anonymous define() is called outside of a loader request.
18903 if (typeof define === 'function' && define.amd) {
18904 define('underscore', [], function() {
18910 },{}],243:[function(require,module,exports){
18911 var createElement = require("./vdom/create-element.js")
18913 module.exports = createElement
18915 },{"./vdom/create-element.js":249}],244:[function(require,module,exports){
18916 var diff = require("./vtree/diff.js")
18918 module.exports = diff
18920 },{"./vtree/diff.js":269}],245:[function(require,module,exports){
18921 var h = require("./virtual-hyperscript/index.js")
18925 },{"./virtual-hyperscript/index.js":256}],246:[function(require,module,exports){
18926 var diff = require("./diff.js")
18927 var patch = require("./patch.js")
18928 var h = require("./h.js")
18929 var create = require("./create-element.js")
18930 var VNode = require('./vnode/vnode.js')
18931 var VText = require('./vnode/vtext.js')
18942 },{"./create-element.js":243,"./diff.js":244,"./h.js":245,"./patch.js":247,"./vnode/vnode.js":265,"./vnode/vtext.js":267}],247:[function(require,module,exports){
18943 var patch = require("./vdom/patch.js")
18945 module.exports = patch
18947 },{"./vdom/patch.js":252}],248:[function(require,module,exports){
18948 var isObject = require("is-object")
18949 var isHook = require("../vnode/is-vhook.js")
18951 module.exports = applyProperties
18953 function applyProperties(node, props, previous) {
18954 for (var propName in props) {
18955 var propValue = props[propName]
18957 if (propValue === undefined) {
18958 removeProperty(node, propName, propValue, previous);
18959 } else if (isHook(propValue)) {
18960 removeProperty(node, propName, propValue, previous)
18961 if (propValue.hook) {
18962 propValue.hook(node,
18964 previous ? previous[propName] : undefined)
18967 if (isObject(propValue)) {
18968 patchObject(node, props, previous, propName, propValue);
18970 node[propName] = propValue
18976 function removeProperty(node, propName, propValue, previous) {
18978 var previousValue = previous[propName]
18980 if (!isHook(previousValue)) {
18981 if (propName === "attributes") {
18982 for (var attrName in previousValue) {
18983 node.removeAttribute(attrName)
18985 } else if (propName === "style") {
18986 for (var i in previousValue) {
18989 } else if (typeof previousValue === "string") {
18990 node[propName] = ""
18992 node[propName] = null
18994 } else if (previousValue.unhook) {
18995 previousValue.unhook(node, propName, propValue)
19000 function patchObject(node, props, previous, propName, propValue) {
19001 var previousValue = previous ? previous[propName] : undefined
19004 if (propName === "attributes") {
19005 for (var attrName in propValue) {
19006 var attrValue = propValue[attrName]
19008 if (attrValue === undefined) {
19009 node.removeAttribute(attrName)
19011 node.setAttribute(attrName, attrValue)
19018 if(previousValue && isObject(previousValue) &&
19019 getPrototype(previousValue) !== getPrototype(propValue)) {
19020 node[propName] = propValue
19024 if (!isObject(node[propName])) {
19025 node[propName] = {}
19028 var replacer = propName === "style" ? "" : undefined
19030 for (var k in propValue) {
19031 var value = propValue[k]
19032 node[propName][k] = (value === undefined) ? replacer : value
19036 function getPrototype(value) {
19037 if (Object.getPrototypeOf) {
19038 return Object.getPrototypeOf(value)
19039 } else if (value.__proto__) {
19040 return value.__proto__
19041 } else if (value.constructor) {
19042 return value.constructor.prototype
19046 },{"../vnode/is-vhook.js":260,"is-object":20}],249:[function(require,module,exports){
19047 var document = require("global/document")
19049 var applyProperties = require("./apply-properties")
19051 var isVNode = require("../vnode/is-vnode.js")
19052 var isVText = require("../vnode/is-vtext.js")
19053 var isWidget = require("../vnode/is-widget.js")
19054 var handleThunk = require("../vnode/handle-thunk.js")
19056 module.exports = createElement
19058 function createElement(vnode, opts) {
19059 var doc = opts ? opts.document || document : document
19060 var warn = opts ? opts.warn : null
19062 vnode = handleThunk(vnode).a
19064 if (isWidget(vnode)) {
19065 return vnode.init()
19066 } else if (isVText(vnode)) {
19067 return doc.createTextNode(vnode.text)
19068 } else if (!isVNode(vnode)) {
19070 warn("Item is not a valid virtual dom node", vnode)
19075 var node = (vnode.namespace === null) ?
19076 doc.createElement(vnode.tagName) :
19077 doc.createElementNS(vnode.namespace, vnode.tagName)
19079 var props = vnode.properties
19080 applyProperties(node, props)
19082 var children = vnode.children
19084 for (var i = 0; i < children.length; i++) {
19085 var childNode = createElement(children[i], opts)
19087 node.appendChild(childNode)
19094 },{"../vnode/handle-thunk.js":258,"../vnode/is-vnode.js":261,"../vnode/is-vtext.js":262,"../vnode/is-widget.js":263,"./apply-properties":248,"global/document":16}],250:[function(require,module,exports){
19095 // Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
19096 // We don't want to read all of the DOM nodes in the tree so we use
19097 // the in-order tree indexing to eliminate recursion down certain branches.
19098 // We only recurse into a DOM node if we know that it contains a child of
19103 module.exports = domIndex
19105 function domIndex(rootNode, tree, indices, nodes) {
19106 if (!indices || indices.length === 0) {
19109 indices.sort(ascending)
19110 return recurse(rootNode, tree, indices, nodes, 0)
19114 function recurse(rootNode, tree, indices, nodes, rootIndex) {
19115 nodes = nodes || {}
19119 if (indexInRange(indices, rootIndex, rootIndex)) {
19120 nodes[rootIndex] = rootNode
19123 var vChildren = tree.children
19127 var childNodes = rootNode.childNodes
19129 for (var i = 0; i < tree.children.length; i++) {
19132 var vChild = vChildren[i] || noChild
19133 var nextIndex = rootIndex + (vChild.count || 0)
19135 // skip recursion down the tree if there are no nodes down here
19136 if (indexInRange(indices, rootIndex, nextIndex)) {
19137 recurse(childNodes[i], vChild, indices, nodes, rootIndex)
19140 rootIndex = nextIndex
19148 // Binary search for an index in the interval [left, right]
19149 function indexInRange(indices, left, right) {
19150 if (indices.length === 0) {
19155 var maxIndex = indices.length - 1
19159 while (minIndex <= maxIndex) {
19160 currentIndex = ((maxIndex + minIndex) / 2) >> 0
19161 currentItem = indices[currentIndex]
19163 if (minIndex === maxIndex) {
19164 return currentItem >= left && currentItem <= right
19165 } else if (currentItem < left) {
19166 minIndex = currentIndex + 1
19167 } else if (currentItem > right) {
19168 maxIndex = currentIndex - 1
19177 function ascending(a, b) {
19178 return a > b ? 1 : -1
19181 },{}],251:[function(require,module,exports){
19182 var applyProperties = require("./apply-properties")
19184 var isWidget = require("../vnode/is-widget.js")
19185 var VPatch = require("../vnode/vpatch.js")
19187 var updateWidget = require("./update-widget")
19189 module.exports = applyPatch
19191 function applyPatch(vpatch, domNode, renderOptions) {
19192 var type = vpatch.type
19193 var vNode = vpatch.vNode
19194 var patch = vpatch.patch
19197 case VPatch.REMOVE:
19198 return removeNode(domNode, vNode)
19199 case VPatch.INSERT:
19200 return insertNode(domNode, patch, renderOptions)
19202 return stringPatch(domNode, vNode, patch, renderOptions)
19203 case VPatch.WIDGET:
19204 return widgetPatch(domNode, vNode, patch, renderOptions)
19206 return vNodePatch(domNode, vNode, patch, renderOptions)
19208 reorderChildren(domNode, patch)
19211 applyProperties(domNode, patch, vNode.properties)
19214 return replaceRoot(domNode,
19215 renderOptions.patch(domNode, patch, renderOptions))
19221 function removeNode(domNode, vNode) {
19222 var parentNode = domNode.parentNode
19225 parentNode.removeChild(domNode)
19228 destroyWidget(domNode, vNode);
19233 function insertNode(parentNode, vNode, renderOptions) {
19234 var newNode = renderOptions.render(vNode, renderOptions)
19237 parentNode.appendChild(newNode)
19243 function stringPatch(domNode, leftVNode, vText, renderOptions) {
19246 if (domNode.nodeType === 3) {
19247 domNode.replaceData(0, domNode.length, vText.text)
19250 var parentNode = domNode.parentNode
19251 newNode = renderOptions.render(vText, renderOptions)
19253 if (parentNode && newNode !== domNode) {
19254 parentNode.replaceChild(newNode, domNode)
19261 function widgetPatch(domNode, leftVNode, widget, renderOptions) {
19262 var updating = updateWidget(leftVNode, widget)
19266 newNode = widget.update(leftVNode, domNode) || domNode
19268 newNode = renderOptions.render(widget, renderOptions)
19271 var parentNode = domNode.parentNode
19273 if (parentNode && newNode !== domNode) {
19274 parentNode.replaceChild(newNode, domNode)
19278 destroyWidget(domNode, leftVNode)
19284 function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
19285 var parentNode = domNode.parentNode
19286 var newNode = renderOptions.render(vNode, renderOptions)
19288 if (parentNode && newNode !== domNode) {
19289 parentNode.replaceChild(newNode, domNode)
19295 function destroyWidget(domNode, w) {
19296 if (typeof w.destroy === "function" && isWidget(w)) {
19301 function reorderChildren(domNode, moves) {
19302 var childNodes = domNode.childNodes
19308 for (var i = 0; i < moves.removes.length; i++) {
19309 remove = moves.removes[i]
19310 node = childNodes[remove.from]
19312 keyMap[remove.key] = node
19314 domNode.removeChild(node)
19317 var length = childNodes.length
19318 for (var j = 0; j < moves.inserts.length; j++) {
19319 insert = moves.inserts[j]
19320 node = keyMap[insert.key]
19321 // this is the weirdest bug i've ever seen in webkit
19322 domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to])
19326 function replaceRoot(oldRoot, newRoot) {
19327 if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
19328 oldRoot.parentNode.replaceChild(newRoot, oldRoot)
19334 },{"../vnode/is-widget.js":263,"../vnode/vpatch.js":266,"./apply-properties":248,"./update-widget":253}],252:[function(require,module,exports){
19335 var document = require("global/document")
19336 var isArray = require("x-is-array")
19338 var render = require("./create-element")
19339 var domIndex = require("./dom-index")
19340 var patchOp = require("./patch-op")
19341 module.exports = patch
19343 function patch(rootNode, patches, renderOptions) {
19344 renderOptions = renderOptions || {}
19345 renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch
19346 ? renderOptions.patch
19348 renderOptions.render = renderOptions.render || render
19350 return renderOptions.patch(rootNode, patches, renderOptions)
19353 function patchRecursive(rootNode, patches, renderOptions) {
19354 var indices = patchIndices(patches)
19356 if (indices.length === 0) {
19360 var index = domIndex(rootNode, patches.a, indices)
19361 var ownerDocument = rootNode.ownerDocument
19363 if (!renderOptions.document && ownerDocument !== document) {
19364 renderOptions.document = ownerDocument
19367 for (var i = 0; i < indices.length; i++) {
19368 var nodeIndex = indices[i]
19369 rootNode = applyPatch(rootNode,
19371 patches[nodeIndex],
19378 function applyPatch(rootNode, domNode, patchList, renderOptions) {
19385 if (isArray(patchList)) {
19386 for (var i = 0; i < patchList.length; i++) {
19387 newNode = patchOp(patchList[i], domNode, renderOptions)
19389 if (domNode === rootNode) {
19394 newNode = patchOp(patchList, domNode, renderOptions)
19396 if (domNode === rootNode) {
19404 function patchIndices(patches) {
19407 for (var key in patches) {
19409 indices.push(Number(key))
19416 },{"./create-element":249,"./dom-index":250,"./patch-op":251,"global/document":16,"x-is-array":288}],253:[function(require,module,exports){
19417 var isWidget = require("../vnode/is-widget.js")
19419 module.exports = updateWidget
19421 function updateWidget(a, b) {
19422 if (isWidget(a) && isWidget(b)) {
19423 if ("name" in a && "name" in b) {
19424 return a.id === b.id
19426 return a.init === b.init
19433 },{"../vnode/is-widget.js":263}],254:[function(require,module,exports){
19436 var EvStore = require('ev-store');
19438 module.exports = EvHook;
19440 function EvHook(value) {
19441 if (!(this instanceof EvHook)) {
19442 return new EvHook(value);
19445 this.value = value;
19448 EvHook.prototype.hook = function (node, propertyName) {
19449 var es = EvStore(node);
19450 var propName = propertyName.substr(3);
19452 es[propName] = this.value;
19455 EvHook.prototype.unhook = function(node, propertyName) {
19456 var es = EvStore(node);
19457 var propName = propertyName.substr(3);
19459 es[propName] = undefined;
19462 },{"ev-store":9}],255:[function(require,module,exports){
19465 module.exports = SoftSetHook;
19467 function SoftSetHook(value) {
19468 if (!(this instanceof SoftSetHook)) {
19469 return new SoftSetHook(value);
19472 this.value = value;
19475 SoftSetHook.prototype.hook = function (node, propertyName) {
19476 if (node[propertyName] !== this.value) {
19477 node[propertyName] = this.value;
19481 },{}],256:[function(require,module,exports){
19484 var isArray = require('x-is-array');
19486 var VNode = require('../vnode/vnode.js');
19487 var VText = require('../vnode/vtext.js');
19488 var isVNode = require('../vnode/is-vnode');
19489 var isVText = require('../vnode/is-vtext');
19490 var isWidget = require('../vnode/is-widget');
19491 var isHook = require('../vnode/is-vhook');
19492 var isVThunk = require('../vnode/is-thunk');
19494 var parseTag = require('./parse-tag.js');
19495 var softSetHook = require('./hooks/soft-set-hook.js');
19496 var evHook = require('./hooks/ev-hook.js');
19498 module.exports = h;
19500 function h(tagName, properties, children) {
19501 var childNodes = [];
19502 var tag, props, key, namespace;
19504 if (!children && isChildren(properties)) {
19505 children = properties;
19509 props = props || properties || {};
19510 tag = parseTag(tagName, props);
19513 if (props.hasOwnProperty('key')) {
19515 props.key = undefined;
19518 // support namespace
19519 if (props.hasOwnProperty('namespace')) {
19520 namespace = props.namespace;
19521 props.namespace = undefined;
19525 if (tag === 'INPUT' &&
19527 props.hasOwnProperty('value') &&
19528 props.value !== undefined &&
19529 !isHook(props.value)
19531 props.value = softSetHook(props.value);
19534 transformProperties(props);
19536 if (children !== undefined && children !== null) {
19537 addChild(children, childNodes, tag, props);
19541 return new VNode(tag, props, childNodes, key, namespace);
19544 function addChild(c, childNodes, tag, props) {
19545 if (typeof c === 'string') {
19546 childNodes.push(new VText(c));
19547 } else if (typeof c === 'number') {
19548 childNodes.push(new VText(String(c)));
19549 } else if (isChild(c)) {
19550 childNodes.push(c);
19551 } else if (isArray(c)) {
19552 for (var i = 0; i < c.length; i++) {
19553 addChild(c[i], childNodes, tag, props);
19555 } else if (c === null || c === undefined) {
19558 throw UnexpectedVirtualElement({
19568 function transformProperties(props) {
19569 for (var propName in props) {
19570 if (props.hasOwnProperty(propName)) {
19571 var value = props[propName];
19573 if (isHook(value)) {
19577 if (propName.substr(0, 3) === 'ev-') {
19578 // add ev-foo support
19579 props[propName] = evHook(value);
19585 function isChild(x) {
19586 return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x);
19589 function isChildren(x) {
19590 return typeof x === 'string' || isArray(x) || isChild(x);
19593 function UnexpectedVirtualElement(data) {
19594 var err = new Error();
19596 err.type = 'virtual-hyperscript.unexpected.virtual-element';
19597 err.message = 'Unexpected virtual child passed to h().\n' +
19598 'Expected a VNode / Vthunk / VWidget / string but:\n' +
19600 errorString(data.foreignObject) +
19602 'The parent vnode is:\n' +
19603 errorString(data.parentVnode)
19605 'Suggested fix: change your `h(..., [ ... ])` callsite.';
19606 err.foreignObject = data.foreignObject;
19607 err.parentVnode = data.parentVnode;
19612 function errorString(obj) {
19614 return JSON.stringify(obj, null, ' ');
19616 return String(obj);
19620 },{"../vnode/is-thunk":259,"../vnode/is-vhook":260,"../vnode/is-vnode":261,"../vnode/is-vtext":262,"../vnode/is-widget":263,"../vnode/vnode.js":265,"../vnode/vtext.js":267,"./hooks/ev-hook.js":254,"./hooks/soft-set-hook.js":255,"./parse-tag.js":257,"x-is-array":288}],257:[function(require,module,exports){
19623 var split = require('browser-split');
19625 var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
19626 var notClassId = /^\.|#/;
19628 module.exports = parseTag;
19630 function parseTag(tag, props) {
19635 var noId = !(props.hasOwnProperty('id'));
19637 var tagParts = split(tag, classIdSplit);
19638 var tagName = null;
19640 if (notClassId.test(tagParts[1])) {
19644 var classes, part, type, i;
19646 for (i = 0; i < tagParts.length; i++) {
19647 part = tagParts[i];
19653 type = part.charAt(0);
19657 } else if (type === '.') {
19658 classes = classes || [];
19659 classes.push(part.substring(1, part.length));
19660 } else if (type === '#' && noId) {
19661 props.id = part.substring(1, part.length);
19666 if (props.className) {
19667 classes.push(props.className);
19670 props.className = classes.join(' ');
19673 return props.namespace ? tagName : tagName.toUpperCase();
19676 },{"browser-split":5}],258:[function(require,module,exports){
19677 var isVNode = require("./is-vnode")
19678 var isVText = require("./is-vtext")
19679 var isWidget = require("./is-widget")
19680 var isThunk = require("./is-thunk")
19682 module.exports = handleThunk
19684 function handleThunk(a, b) {
19689 renderedB = renderThunk(b, a)
19693 renderedA = renderThunk(a, null)
19702 function renderThunk(thunk, previous) {
19703 var renderedThunk = thunk.vnode
19705 if (!renderedThunk) {
19706 renderedThunk = thunk.vnode = thunk.render(previous)
19709 if (!(isVNode(renderedThunk) ||
19710 isVText(renderedThunk) ||
19711 isWidget(renderedThunk))) {
19712 throw new Error("thunk did not return a valid node");
19715 return renderedThunk
19718 },{"./is-thunk":259,"./is-vnode":261,"./is-vtext":262,"./is-widget":263}],259:[function(require,module,exports){
19719 module.exports = isThunk
19721 function isThunk(t) {
19722 return t && t.type === "Thunk"
19725 },{}],260:[function(require,module,exports){
19726 module.exports = isHook
19728 function isHook(hook) {
19730 (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") ||
19731 typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook"))
19734 },{}],261:[function(require,module,exports){
19735 var version = require("./version")
19737 module.exports = isVirtualNode
19739 function isVirtualNode(x) {
19740 return x && x.type === "VirtualNode" && x.version === version
19743 },{"./version":264}],262:[function(require,module,exports){
19744 var version = require("./version")
19746 module.exports = isVirtualText
19748 function isVirtualText(x) {
19749 return x && x.type === "VirtualText" && x.version === version
19752 },{"./version":264}],263:[function(require,module,exports){
19753 module.exports = isWidget
19755 function isWidget(w) {
19756 return w && w.type === "Widget"
19759 },{}],264:[function(require,module,exports){
19760 module.exports = "2"
19762 },{}],265:[function(require,module,exports){
19763 var version = require("./version")
19764 var isVNode = require("./is-vnode")
19765 var isWidget = require("./is-widget")
19766 var isThunk = require("./is-thunk")
19767 var isVHook = require("./is-vhook")
19769 module.exports = VirtualNode
19771 var noProperties = {}
19772 var noChildren = []
19774 function VirtualNode(tagName, properties, children, key, namespace) {
19775 this.tagName = tagName
19776 this.properties = properties || noProperties
19777 this.children = children || noChildren
19778 this.key = key != null ? String(key) : undefined
19779 this.namespace = (typeof namespace === "string") ? namespace : null
19781 var count = (children && children.length) || 0
19782 var descendants = 0
19783 var hasWidgets = false
19784 var hasThunks = false
19785 var descendantHooks = false
19788 for (var propName in properties) {
19789 if (properties.hasOwnProperty(propName)) {
19790 var property = properties[propName]
19791 if (isVHook(property) && property.unhook) {
19796 hooks[propName] = property
19801 for (var i = 0; i < count; i++) {
19802 var child = children[i]
19803 if (isVNode(child)) {
19804 descendants += child.count || 0
19806 if (!hasWidgets && child.hasWidgets) {
19810 if (!hasThunks && child.hasThunks) {
19814 if (!descendantHooks && (child.hooks || child.descendantHooks)) {
19815 descendantHooks = true
19817 } else if (!hasWidgets && isWidget(child)) {
19818 if (typeof child.destroy === "function") {
19821 } else if (!hasThunks && isThunk(child)) {
19826 this.count = count + descendants
19827 this.hasWidgets = hasWidgets
19828 this.hasThunks = hasThunks
19830 this.descendantHooks = descendantHooks
19833 VirtualNode.prototype.version = version
19834 VirtualNode.prototype.type = "VirtualNode"
19836 },{"./is-thunk":259,"./is-vhook":260,"./is-vnode":261,"./is-widget":263,"./version":264}],266:[function(require,module,exports){
19837 var version = require("./version")
19839 VirtualPatch.NONE = 0
19840 VirtualPatch.VTEXT = 1
19841 VirtualPatch.VNODE = 2
19842 VirtualPatch.WIDGET = 3
19843 VirtualPatch.PROPS = 4
19844 VirtualPatch.ORDER = 5
19845 VirtualPatch.INSERT = 6
19846 VirtualPatch.REMOVE = 7
19847 VirtualPatch.THUNK = 8
19849 module.exports = VirtualPatch
19851 function VirtualPatch(type, vNode, patch) {
19852 this.type = Number(type)
19857 VirtualPatch.prototype.version = version
19858 VirtualPatch.prototype.type = "VirtualPatch"
19860 },{"./version":264}],267:[function(require,module,exports){
19861 var version = require("./version")
19863 module.exports = VirtualText
19865 function VirtualText(text) {
19866 this.text = String(text)
19869 VirtualText.prototype.version = version
19870 VirtualText.prototype.type = "VirtualText"
19872 },{"./version":264}],268:[function(require,module,exports){
19873 var isObject = require("is-object")
19874 var isHook = require("../vnode/is-vhook")
19876 module.exports = diffProps
19878 function diffProps(a, b) {
19881 for (var aKey in a) {
19882 if (!(aKey in b)) {
19884 diff[aKey] = undefined
19887 var aValue = a[aKey]
19888 var bValue = b[aKey]
19890 if (aValue === bValue) {
19892 } else if (isObject(aValue) && isObject(bValue)) {
19893 if (getPrototype(bValue) !== getPrototype(aValue)) {
19895 diff[aKey] = bValue
19896 } else if (isHook(bValue)) {
19898 diff[aKey] = bValue
19900 var objectDiff = diffProps(aValue, bValue)
19903 diff[aKey] = objectDiff
19908 diff[aKey] = bValue
19912 for (var bKey in b) {
19913 if (!(bKey in a)) {
19915 diff[bKey] = b[bKey]
19922 function getPrototype(value) {
19923 if (Object.getPrototypeOf) {
19924 return Object.getPrototypeOf(value)
19925 } else if (value.__proto__) {
19926 return value.__proto__
19927 } else if (value.constructor) {
19928 return value.constructor.prototype
19932 },{"../vnode/is-vhook":260,"is-object":20}],269:[function(require,module,exports){
19933 var isArray = require("x-is-array")
19935 var VPatch = require("../vnode/vpatch")
19936 var isVNode = require("../vnode/is-vnode")
19937 var isVText = require("../vnode/is-vtext")
19938 var isWidget = require("../vnode/is-widget")
19939 var isThunk = require("../vnode/is-thunk")
19940 var handleThunk = require("../vnode/handle-thunk")
19942 var diffProps = require("./diff-props")
19944 module.exports = diff
19946 function diff(a, b) {
19947 var patch = { a: a }
19948 walk(a, b, patch, 0)
19952 function walk(a, b, patch, index) {
19957 var apply = patch[index]
19958 var applyClear = false
19960 if (isThunk(a) || isThunk(b)) {
19961 thunks(a, b, patch, index)
19962 } else if (b == null) {
19964 // If a is a widget we will add a remove patch for it
19965 // Otherwise any child widgets/hooks must be destroyed.
19966 // This prevents adding two remove patches for a widget.
19967 if (!isWidget(a)) {
19968 clearState(a, patch, index)
19969 apply = patch[index]
19972 apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
19973 } else if (isVNode(b)) {
19975 if (a.tagName === b.tagName &&
19976 a.namespace === b.namespace &&
19978 var propsPatch = diffProps(a.properties, b.properties)
19980 apply = appendPatch(apply,
19981 new VPatch(VPatch.PROPS, a, propsPatch))
19983 apply = diffChildren(a, b, patch, apply, index)
19985 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
19989 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
19992 } else if (isVText(b)) {
19994 apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
19996 } else if (a.text !== b.text) {
19997 apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
19999 } else if (isWidget(b)) {
20000 if (!isWidget(a)) {
20004 apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
20008 patch[index] = apply
20012 clearState(a, patch, index)
20016 function diffChildren(a, b, patch, apply, index) {
20017 var aChildren = a.children
20018 var orderedSet = reorder(aChildren, b.children)
20019 var bChildren = orderedSet.children
20021 var aLen = aChildren.length
20022 var bLen = bChildren.length
20023 var len = aLen > bLen ? aLen : bLen
20025 for (var i = 0; i < len; i++) {
20026 var leftNode = aChildren[i]
20027 var rightNode = bChildren[i]
20032 // Excess nodes in b need to be added
20033 apply = appendPatch(apply,
20034 new VPatch(VPatch.INSERT, null, rightNode))
20037 walk(leftNode, rightNode, patch, index)
20040 if (isVNode(leftNode) && leftNode.count) {
20041 index += leftNode.count
20045 if (orderedSet.moves) {
20046 // Reorder nodes last
20047 apply = appendPatch(apply, new VPatch(
20057 function clearState(vNode, patch, index) {
20058 // TODO: Make this a single walk, not two
20059 unhook(vNode, patch, index)
20060 destroyWidgets(vNode, patch, index)
20063 // Patch records for all destroyed widgets must be added because we need
20064 // a DOM node reference for the destroy function
20065 function destroyWidgets(vNode, patch, index) {
20066 if (isWidget(vNode)) {
20067 if (typeof vNode.destroy === "function") {
20068 patch[index] = appendPatch(
20070 new VPatch(VPatch.REMOVE, vNode, null)
20073 } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
20074 var children = vNode.children
20075 var len = children.length
20076 for (var i = 0; i < len; i++) {
20077 var child = children[i]
20080 destroyWidgets(child, patch, index)
20082 if (isVNode(child) && child.count) {
20083 index += child.count
20086 } else if (isThunk(vNode)) {
20087 thunks(vNode, null, patch, index)
20091 // Create a sub-patch for thunks
20092 function thunks(a, b, patch, index) {
20093 var nodes = handleThunk(a, b)
20094 var thunkPatch = diff(nodes.a, nodes.b)
20095 if (hasPatches(thunkPatch)) {
20096 patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
20100 function hasPatches(patch) {
20101 for (var index in patch) {
20102 if (index !== "a") {
20110 // Execute hooks when two nodes are identical
20111 function unhook(vNode, patch, index) {
20112 if (isVNode(vNode)) {
20114 patch[index] = appendPatch(
20119 undefinedKeys(vNode.hooks)
20124 if (vNode.descendantHooks || vNode.hasThunks) {
20125 var children = vNode.children
20126 var len = children.length
20127 for (var i = 0; i < len; i++) {
20128 var child = children[i]
20131 unhook(child, patch, index)
20133 if (isVNode(child) && child.count) {
20134 index += child.count
20138 } else if (isThunk(vNode)) {
20139 thunks(vNode, null, patch, index)
20143 function undefinedKeys(obj) {
20146 for (var key in obj) {
20147 result[key] = undefined
20153 // List diff, naive left to right reordering
20154 function reorder(aChildren, bChildren) {
20155 // O(M) time, O(M) memory
20156 var bChildIndex = keyIndex(bChildren)
20157 var bKeys = bChildIndex.keys
20158 var bFree = bChildIndex.free
20160 if (bFree.length === bChildren.length) {
20162 children: bChildren,
20167 // O(N) time, O(N) memory
20168 var aChildIndex = keyIndex(aChildren)
20169 var aKeys = aChildIndex.keys
20170 var aFree = aChildIndex.free
20172 if (aFree.length === aChildren.length) {
20174 children: bChildren,
20179 // O(MAX(N, M)) memory
20180 var newChildren = []
20183 var freeCount = bFree.length
20184 var deletedItems = 0
20186 // Iterate through a and match a node in b
20188 for (var i = 0 ; i < aChildren.length; i++) {
20189 var aItem = aChildren[i]
20193 if (bKeys.hasOwnProperty(aItem.key)) {
20194 // Match up the old keys
20195 itemIndex = bKeys[aItem.key]
20196 newChildren.push(bChildren[itemIndex])
20199 // Remove old keyed items
20200 itemIndex = i - deletedItems++
20201 newChildren.push(null)
20204 // Match the item in a with the next free item in b
20205 if (freeIndex < freeCount) {
20206 itemIndex = bFree[freeIndex++]
20207 newChildren.push(bChildren[itemIndex])
20209 // There are no free items in b to match with
20210 // the free items in a, so the extra free nodes
20212 itemIndex = i - deletedItems++
20213 newChildren.push(null)
20218 var lastFreeIndex = freeIndex >= bFree.length ?
20222 // Iterate through b and append any new keys
20224 for (var j = 0; j < bChildren.length; j++) {
20225 var newItem = bChildren[j]
20228 if (!aKeys.hasOwnProperty(newItem.key)) {
20229 // Add any new keyed items
20230 // We are adding new items to the end and then sorting them
20231 // in place. In future we should insert new items in place.
20232 newChildren.push(newItem)
20234 } else if (j >= lastFreeIndex) {
20235 // Add any leftover non-keyed items
20236 newChildren.push(newItem)
20240 var simulate = newChildren.slice()
20241 var simulateIndex = 0
20246 for (var k = 0; k < bChildren.length;) {
20247 var wantedItem = bChildren[k]
20248 simulateItem = simulate[simulateIndex]
20251 while (simulateItem === null && simulate.length) {
20252 removes.push(remove(simulate, simulateIndex, null))
20253 simulateItem = simulate[simulateIndex]
20256 if (!simulateItem || simulateItem.key !== wantedItem.key) {
20257 // if we need a key in this position...
20258 if (wantedItem.key) {
20259 if (simulateItem && simulateItem.key) {
20260 // if an insert doesn't put this key in place, it needs to move
20261 if (bKeys[simulateItem.key] !== k + 1) {
20262 removes.push(remove(simulate, simulateIndex, simulateItem.key))
20263 simulateItem = simulate[simulateIndex]
20264 // if the remove didn't put the wanted item in place, we need to insert it
20265 if (!simulateItem || simulateItem.key !== wantedItem.key) {
20266 inserts.push({key: wantedItem.key, to: k})
20268 // items are matching, so skip ahead
20274 inserts.push({key: wantedItem.key, to: k})
20278 inserts.push({key: wantedItem.key, to: k})
20282 // a key in simulate has no matching wanted key, remove it
20283 else if (simulateItem && simulateItem.key) {
20284 removes.push(remove(simulate, simulateIndex, simulateItem.key))
20293 // remove all the remaining nodes from simulate
20294 while(simulateIndex < simulate.length) {
20295 simulateItem = simulate[simulateIndex]
20296 removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key))
20299 // If the only moves we have are deletes then we can just
20300 // let the delete patch remove these items.
20301 if (removes.length === deletedItems && !inserts.length) {
20303 children: newChildren,
20309 children: newChildren,
20317 function remove(arr, index, key) {
20318 arr.splice(index, 1)
20326 function keyIndex(children) {
20329 var length = children.length
20331 for (var i = 0; i < length; i++) {
20332 var child = children[i]
20335 keys[child.key] = i
20342 keys: keys, // A hash of key name to index
20343 free: free // An array of unkeyed item indices
20347 function appendPatch(apply, patch) {
20349 if (isArray(apply)) {
20352 apply = [apply, patch]
20361 },{"../vnode/handle-thunk":258,"../vnode/is-thunk":259,"../vnode/is-vnode":261,"../vnode/is-vtext":262,"../vnode/is-widget":263,"../vnode/vpatch":266,"./diff-props":268,"x-is-array":288}],270:[function(require,module,exports){
20362 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20363 /** @author Brian Cavalier */
20364 /** @author John Hann */
20366 (function(define) { 'use strict';
20367 define(function (require) {
20369 var makePromise = require('./makePromise');
20370 var Scheduler = require('./Scheduler');
20371 var async = require('./env').asap;
20373 return makePromise({
20374 scheduler: new Scheduler(async)
20378 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
20380 },{"./Scheduler":271,"./env":283,"./makePromise":285}],271:[function(require,module,exports){
20381 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20382 /** @author Brian Cavalier */
20383 /** @author John Hann */
20385 (function(define) { 'use strict';
20386 define(function() {
20388 // Credit to Twisol (https://github.com/Twisol) for suggesting
20389 // this type of extensible queue + trampoline approach for next-tick conflation.
20392 * Async task scheduler
20393 * @param {function} async function to schedule a single async function
20396 function Scheduler(async) {
20397 this._async = async;
20398 this._running = false;
20400 this._queue = this;
20401 this._queueLen = 0;
20402 this._afterQueue = {};
20403 this._afterQueueLen = 0;
20406 this.drain = function() {
20413 * @param {{ run:function }} task
20415 Scheduler.prototype.enqueue = function(task) {
20416 this._queue[this._queueLen++] = task;
20421 * Enqueue a task to run after the main task queue
20422 * @param {{ run:function }} task
20424 Scheduler.prototype.afterQueue = function(task) {
20425 this._afterQueue[this._afterQueueLen++] = task;
20429 Scheduler.prototype.run = function() {
20430 if (!this._running) {
20431 this._running = true;
20432 this._async(this.drain);
20437 * Drain the handler queue entirely, and then the after queue
20439 Scheduler.prototype._drain = function() {
20441 for (; i < this._queueLen; ++i) {
20442 this._queue[i].run();
20443 this._queue[i] = void 0;
20446 this._queueLen = 0;
20447 this._running = false;
20449 for (i = 0; i < this._afterQueueLen; ++i) {
20450 this._afterQueue[i].run();
20451 this._afterQueue[i] = void 0;
20454 this._afterQueueLen = 0;
20460 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20462 },{}],272:[function(require,module,exports){
20463 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20464 /** @author Brian Cavalier */
20465 /** @author John Hann */
20467 (function(define) { 'use strict';
20468 define(function() {
20471 * Custom error type for promises rejected by promise.timeout
20472 * @param {string} message
20475 function TimeoutError (message) {
20477 this.message = message;
20478 this.name = TimeoutError.name;
20479 if (typeof Error.captureStackTrace === 'function') {
20480 Error.captureStackTrace(this, TimeoutError);
20484 TimeoutError.prototype = Object.create(Error.prototype);
20485 TimeoutError.prototype.constructor = TimeoutError;
20487 return TimeoutError;
20489 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20490 },{}],273:[function(require,module,exports){
20491 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20492 /** @author Brian Cavalier */
20493 /** @author John Hann */
20495 (function(define) { 'use strict';
20496 define(function() {
20498 makeApply.tryCatchResolve = tryCatchResolve;
20502 function makeApply(Promise, call) {
20503 if(arguments.length < 2) {
20504 call = tryCatchResolve;
20509 function apply(f, thisArg, args) {
20510 var p = Promise._defer();
20511 var l = args.length;
20512 var params = new Array(l);
20513 callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
20518 function callAndResolve(c, h) {
20520 return call(c.f, c.thisArg, c.params, h);
20523 var handler = Promise._handler(c.args[c.i]);
20524 handler.fold(callAndResolveNext, c, void 0, h);
20527 function callAndResolveNext(c, x, h) {
20530 callAndResolve(c, h);
20534 function tryCatchResolve(f, thisArg, args, resolver) {
20536 resolver.resolve(f.apply(thisArg, args));
20538 resolver.reject(e);
20543 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20547 },{}],274:[function(require,module,exports){
20548 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20549 /** @author Brian Cavalier */
20550 /** @author John Hann */
20552 (function(define) { 'use strict';
20553 define(function(require) {
20555 var state = require('../state');
20556 var applier = require('../apply');
20558 return function array(Promise) {
20560 var applyFold = applier(Promise);
20561 var toPromise = Promise.resolve;
20562 var all = Promise.all;
20564 var ar = Array.prototype.reduce;
20565 var arr = Array.prototype.reduceRight;
20566 var slice = Array.prototype.slice;
20568 // Additional array combinators
20571 Promise.some = some;
20572 Promise.settle = settle;
20575 Promise.filter = filter;
20576 Promise.reduce = reduce;
20577 Promise.reduceRight = reduceRight;
20580 * When this promise fulfills with an array, do
20581 * onFulfilled.apply(void 0, array)
20582 * @param {function} onFulfilled function to apply
20583 * @returns {Promise} promise for the result of applying onFulfilled
20585 Promise.prototype.spread = function(onFulfilled) {
20586 return this.then(all).then(function(array) {
20587 return onFulfilled.apply(this, array);
20594 * One-winner competitive race.
20595 * Return a promise that will fulfill when one of the promises
20596 * in the input array fulfills, or will reject when all promises
20598 * @param {array} promises
20599 * @returns {Promise} promise for the first fulfilled value
20601 function any(promises) {
20602 var p = Promise._defer();
20603 var resolver = p._handler;
20604 var l = promises.length>>>0;
20609 for (var h, x, i = 0; i < l; ++i) {
20611 if(x === void 0 && !(i in promises)) {
20616 h = Promise._handler(x);
20617 if(h.state() > 0) {
20618 resolver.become(h);
20619 Promise._visitRemaining(promises, i, h);
20622 h.visit(resolver, handleFulfill, handleReject);
20626 if(pending === 0) {
20627 resolver.reject(new RangeError('any(): array must not be empty'));
20632 function handleFulfill(x) {
20633 /*jshint validthis:true*/
20635 this.resolve(x); // this === resolver
20638 function handleReject(e) {
20639 /*jshint validthis:true*/
20640 if(this.resolved) { // this === resolver
20645 if(--pending === 0) {
20646 this.reject(errors);
20652 * N-winner competitive race
20653 * Return a promise that will fulfill when n input promises have
20654 * fulfilled, or will reject when it becomes impossible for n
20655 * input promises to fulfill (ie when promises.length - n + 1
20657 * @param {array} promises
20658 * @param {number} n
20659 * @returns {Promise} promise for the earliest n fulfillment values
20663 function some(promises, n) {
20664 /*jshint maxcomplexity:7*/
20665 var p = Promise._defer();
20666 var resolver = p._handler;
20671 var l = promises.length>>>0;
20674 var x, i; // reused in both for() loops
20676 // First pass: count actual array items
20677 for(i=0; i<l; ++i) {
20679 if(x === void 0 && !(i in promises)) {
20685 // Compute actual goals
20686 n = Math.max(n, 0);
20687 nReject = (nFulfill - n + 1);
20688 nFulfill = Math.min(n, nFulfill);
20691 resolver.reject(new RangeError('some(): array must contain at least '
20692 + n + ' item(s), but had ' + nFulfill));
20693 } else if(nFulfill === 0) {
20694 resolver.resolve(results);
20697 // Second pass: observe each array item, make progress toward goals
20698 for(i=0; i<l; ++i) {
20700 if(x === void 0 && !(i in promises)) {
20704 Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
20709 function fulfill(x) {
20710 /*jshint validthis:true*/
20711 if(this.resolved) { // this === resolver
20716 if(--nFulfill === 0) {
20718 this.resolve(results);
20722 function reject(e) {
20723 /*jshint validthis:true*/
20724 if(this.resolved) { // this === resolver
20729 if(--nReject === 0) {
20731 this.reject(errors);
20737 * Apply f to the value of each promise in a list of promises
20738 * and return a new list containing the results.
20739 * @param {array} promises
20740 * @param {function(x:*, index:Number):*} f mapping function
20741 * @returns {Promise}
20743 function map(promises, f) {
20744 return Promise._traverse(f, promises);
20748 * Filter the provided array of promises using the provided predicate. Input may
20749 * contain promises and values
20750 * @param {Array} promises array of promises and values
20751 * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
20752 * Must return truthy (or promise for truthy) for items to retain.
20753 * @returns {Promise} promise that will fulfill with an array containing all items
20754 * for which predicate returned truthy.
20756 function filter(promises, predicate) {
20757 var a = slice.call(promises);
20758 return Promise._traverse(predicate, a).then(function(keep) {
20759 return filterSync(a, keep);
20763 function filterSync(promises, keep) {
20764 // Safe because we know all promises have fulfilled if we've made it this far
20765 var l = keep.length;
20766 var filtered = new Array(l);
20767 for(var i=0, j=0; i<l; ++i) {
20769 filtered[j++] = Promise._handler(promises[i]).value;
20772 filtered.length = j;
20778 * Return a promise that will always fulfill with an array containing
20779 * the outcome states of all input promises. The returned promise
20780 * will never reject.
20781 * @param {Array} promises
20782 * @returns {Promise} promise for array of settled state descriptors
20784 function settle(promises) {
20785 return all(promises.map(settleOne));
20788 function settleOne(p) {
20789 // Optimize the case where we get an already-resolved when.js promise
20790 // by extracting its state:
20792 if (p instanceof Promise) {
20793 // This is our own Promise type and we can reach its handler internals:
20794 handler = p._handler.join();
20796 if((handler && handler.state() === 0) || !handler) {
20797 // Either still pending, or not a Promise at all:
20798 return toPromise(p).then(state.fulfilled, state.rejected);
20801 // The promise is our own, but it is already resolved. Take a shortcut.
20802 // Since we're not actually handling the resolution, we need to disable
20803 // rejection reporting.
20804 handler._unreport();
20805 return state.inspect(handler);
20809 * Traditional reduce function, similar to `Array.prototype.reduce()`, but
20810 * input may contain promises and/or values, and reduceFunc
20811 * may return either a value or a promise, *and* initialValue may
20812 * be a promise for the starting value.
20813 * @param {Array|Promise} promises array or promise for an array of anything,
20814 * may contain a mix of promises and values.
20815 * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
20816 * @returns {Promise} that will resolve to the final reduced value
20818 function reduce(promises, f /*, initialValue */) {
20819 return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
20820 : ar.call(promises, liftCombine(f));
20824 * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
20825 * input may contain promises and/or values, and reduceFunc
20826 * may return either a value or a promise, *and* initialValue may
20827 * be a promise for the starting value.
20828 * @param {Array|Promise} promises array or promise for an array of anything,
20829 * may contain a mix of promises and values.
20830 * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
20831 * @returns {Promise} that will resolve to the final reduced value
20833 function reduceRight(promises, f /*, initialValue */) {
20834 return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
20835 : arr.call(promises, liftCombine(f));
20838 function liftCombine(f) {
20839 return function(z, x, i) {
20840 return applyFold(f, void 0, [z,x,i]);
20846 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
20848 },{"../apply":273,"../state":286}],275:[function(require,module,exports){
20849 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20850 /** @author Brian Cavalier */
20851 /** @author John Hann */
20853 (function(define) { 'use strict';
20854 define(function() {
20856 return function flow(Promise) {
20858 var resolve = Promise.resolve;
20859 var reject = Promise.reject;
20860 var origCatch = Promise.prototype['catch'];
20863 * Handle the ultimate fulfillment value or rejection reason, and assume
20864 * responsibility for all errors. If an error propagates out of result
20865 * or handleFatalError, it will be rethrown to the host, resulting in a
20866 * loud stack track on most platforms and a crash on some.
20867 * @param {function?} onResult
20868 * @param {function?} onError
20869 * @returns {undefined}
20871 Promise.prototype.done = function(onResult, onError) {
20872 this._handler.visit(this._handler.receiver, onResult, onError);
20876 * Add Error-type and predicate matching to catch. Examples:
20877 * promise.catch(TypeError, handleTypeError)
20878 * .catch(predicate, handleMatchedErrors)
20879 * .catch(handleRemainingErrors)
20880 * @param onRejected
20883 Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
20884 if (arguments.length < 2) {
20885 return origCatch.call(this, onRejected);
20888 if(typeof onRejected !== 'function') {
20889 return this.ensure(rejectInvalidPredicate);
20892 return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
20896 * Wraps the provided catch handler, so that it will only be called
20897 * if the predicate evaluates truthy
20898 * @param {?function} handler
20899 * @param {function} predicate
20900 * @returns {function} conditional catch handler
20902 function createCatchFilter(handler, predicate) {
20903 return function(e) {
20904 return evaluatePredicate(e, predicate)
20905 ? handler.call(this, e)
20911 * Ensures that onFulfilledOrRejected will be called regardless of whether
20912 * this promise is fulfilled or rejected. onFulfilledOrRejected WILL NOT
20913 * receive the promises' value or reason. Any returned value will be disregarded.
20914 * onFulfilledOrRejected may throw or return a rejected promise to signal
20915 * an additional error.
20916 * @param {function} handler handler to be called regardless of
20917 * fulfillment or rejection
20918 * @returns {Promise}
20920 Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
20921 if(typeof handler !== 'function') {
20925 return this.then(function(x) {
20926 return runSideEffect(handler, this, identity, x);
20928 return runSideEffect(handler, this, reject, e);
20932 function runSideEffect (handler, thisArg, propagate, value) {
20933 var result = handler.call(thisArg);
20934 return maybeThenable(result)
20935 ? propagateValue(result, propagate, value)
20936 : propagate(value);
20939 function propagateValue (result, propagate, x) {
20940 return resolve(result).then(function () {
20941 return propagate(x);
20946 * Recover from a failure by returning a defaultValue. If defaultValue
20947 * is a promise, it's fulfillment value will be used. If defaultValue is
20948 * a promise that rejects, the returned promise will reject with the
20950 * @param {*} defaultValue
20951 * @returns {Promise} new promise
20953 Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
20954 return this.then(void 0, function() {
20955 return defaultValue;
20960 * Shortcut for .then(function() { return value; })
20962 * @return {Promise} a promise that:
20963 * - is fulfilled if value is not a promise, or
20964 * - if value is a promise, will fulfill with its value, or reject
20967 Promise.prototype['yield'] = function(value) {
20968 return this.then(function() {
20974 * Runs a side effect when this promise fulfills, without changing the
20975 * fulfillment value.
20976 * @param {function} onFulfilledSideEffect
20977 * @returns {Promise}
20979 Promise.prototype.tap = function(onFulfilledSideEffect) {
20980 return this.then(onFulfilledSideEffect)['yield'](this);
20986 function rejectInvalidPredicate() {
20987 throw new TypeError('catch predicate must be a function');
20990 function evaluatePredicate(e, predicate) {
20991 return isError(predicate) ? e instanceof predicate : predicate(e);
20994 function isError(predicate) {
20995 return predicate === Error
20996 || (predicate != null && predicate.prototype instanceof Error);
20999 function maybeThenable(x) {
21000 return (typeof x === 'object' || typeof x === 'function') && x !== null;
21003 function identity(x) {
21008 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21010 },{}],276:[function(require,module,exports){
21011 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21012 /** @author Brian Cavalier */
21013 /** @author John Hann */
21014 /** @author Jeff Escalante */
21016 (function(define) { 'use strict';
21017 define(function() {
21019 return function fold(Promise) {
21021 Promise.prototype.fold = function(f, z) {
21022 var promise = this._beget();
21024 this._handler.fold(function(z, x, to) {
21025 Promise._handler(z).fold(function(x, z, to) {
21026 to.resolve(f.call(this, z, x));
21028 }, z, promise._handler.receiver, promise._handler);
21037 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21039 },{}],277:[function(require,module,exports){
21040 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21041 /** @author Brian Cavalier */
21042 /** @author John Hann */
21044 (function(define) { 'use strict';
21045 define(function(require) {
21047 var inspect = require('../state').inspect;
21049 return function inspection(Promise) {
21051 Promise.prototype.inspect = function() {
21052 return inspect(Promise._handler(this));
21059 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
21061 },{"../state":286}],278:[function(require,module,exports){
21062 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21063 /** @author Brian Cavalier */
21064 /** @author John Hann */
21066 (function(define) { 'use strict';
21067 define(function() {
21069 return function generate(Promise) {
21071 var resolve = Promise.resolve;
21073 Promise.iterate = iterate;
21074 Promise.unfold = unfold;
21079 * @deprecated Use github.com/cujojs/most streams and most.iterate
21080 * Generate a (potentially infinite) stream of promised values:
21081 * x, f(x), f(f(x)), etc. until condition(x) returns true
21082 * @param {function} f function to generate a new x from the previous x
21083 * @param {function} condition function that, given the current x, returns
21084 * truthy when the iterate should stop
21085 * @param {function} handler function to handle the value produced by f
21086 * @param {*|Promise} x starting value, may be a promise
21087 * @return {Promise} the result of the last call to f before
21088 * condition returns true
21090 function iterate(f, condition, handler, x) {
21091 return unfold(function(x) {
21093 }, condition, handler, x);
21097 * @deprecated Use github.com/cujojs/most streams and most.unfold
21098 * Generate a (potentially infinite) stream of promised values
21099 * by applying handler(generator(seed)) iteratively until
21100 * condition(seed) returns true.
21101 * @param {function} unspool function that generates a [value, newSeed]
21103 * @param {function} condition function that, given the current seed, returns
21104 * truthy when the unfold should stop
21105 * @param {function} handler function to handle the value produced by unspool
21106 * @param x {*|Promise} starting value, may be a promise
21107 * @return {Promise} the result of the last value produced by unspool before
21108 * condition returns true
21110 function unfold(unspool, condition, handler, x) {
21111 return resolve(x).then(function(seed) {
21112 return resolve(condition(seed)).then(function(done) {
21113 return done ? seed : resolve(unspool(seed)).spread(next);
21117 function next(item, newSeed) {
21118 return resolve(handler(item)).then(function() {
21119 return unfold(unspool, condition, handler, newSeed);
21126 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21128 },{}],279:[function(require,module,exports){
21129 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21130 /** @author Brian Cavalier */
21131 /** @author John Hann */
21133 (function(define) { 'use strict';
21134 define(function() {
21136 return function progress(Promise) {
21140 * Register a progress handler for this promise
21141 * @param {function} onProgress
21142 * @returns {Promise}
21144 Promise.prototype.progress = function(onProgress) {
21145 return this.then(void 0, void 0, onProgress);
21152 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21154 },{}],280:[function(require,module,exports){
21155 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21156 /** @author Brian Cavalier */
21157 /** @author John Hann */
21159 (function(define) { 'use strict';
21160 define(function(require) {
21162 var env = require('../env');
21163 var TimeoutError = require('../TimeoutError');
21165 function setTimeout(f, ms, x, y) {
21166 return env.setTimer(function() {
21171 return function timed(Promise) {
21173 * Return a new promise whose fulfillment value is revealed only
21174 * after ms milliseconds
21175 * @param {number} ms milliseconds
21176 * @returns {Promise}
21178 Promise.prototype.delay = function(ms) {
21179 var p = this._beget();
21180 this._handler.fold(handleDelay, ms, void 0, p._handler);
21184 function handleDelay(ms, x, h) {
21185 setTimeout(resolveDelay, ms, x, h);
21188 function resolveDelay(x, h) {
21193 * Return a new promise that rejects after ms milliseconds unless
21194 * this promise fulfills earlier, in which case the returned promise
21195 * fulfills with the same value.
21196 * @param {number} ms milliseconds
21197 * @param {Error|*=} reason optional rejection reason to use, defaults
21198 * to a TimeoutError if not provided
21199 * @returns {Promise}
21201 Promise.prototype.timeout = function(ms, reason) {
21202 var p = this._beget();
21203 var h = p._handler;
21205 var t = setTimeout(onTimeout, ms, reason, p._handler);
21207 this._handler.visit(h,
21208 function onFulfill(x) {
21210 this.resolve(x); // this = h
21212 function onReject(x) {
21214 this.reject(x); // this = h
21221 function onTimeout(reason, h, ms) {
21222 var e = typeof reason === 'undefined'
21223 ? new TimeoutError('timed out after ' + ms + 'ms')
21232 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
21234 },{"../TimeoutError":272,"../env":283}],281:[function(require,module,exports){
21235 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21236 /** @author Brian Cavalier */
21237 /** @author John Hann */
21239 (function(define) { 'use strict';
21240 define(function(require) {
21242 var setTimer = require('../env').setTimer;
21243 var format = require('../format');
21245 return function unhandledRejection(Promise) {
21247 var logError = noop;
21248 var logInfo = noop;
21251 if(typeof console !== 'undefined') {
21252 // Alias console to prevent things like uglify's drop_console option from
21253 // removing console.log/error. Unhandled rejections fall into the same
21254 // category as uncaught exceptions, and build tools shouldn't silence them.
21255 localConsole = console;
21256 logError = typeof localConsole.error !== 'undefined'
21257 ? function (e) { localConsole.error(e); }
21258 : function (e) { localConsole.log(e); };
21260 logInfo = typeof localConsole.info !== 'undefined'
21261 ? function (e) { localConsole.info(e); }
21262 : function (e) { localConsole.log(e); };
21265 Promise.onPotentiallyUnhandledRejection = function(rejection) {
21266 enqueue(report, rejection);
21269 Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
21270 enqueue(unreport, rejection);
21273 Promise.onFatalRejection = function(rejection) {
21274 enqueue(throwit, rejection.value);
21279 var running = null;
21281 function report(r) {
21284 logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
21288 function unreport(r) {
21289 var i = reported.indexOf(r);
21291 reported.splice(i, 1);
21292 logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
21296 function enqueue(f, x) {
21298 if(running === null) {
21299 running = setTimer(flush, 0);
21305 while(tasks.length > 0) {
21306 tasks.shift()(tasks.shift());
21313 function throwit(e) {
21320 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
21322 },{"../env":283,"../format":284}],282:[function(require,module,exports){
21323 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21324 /** @author Brian Cavalier */
21325 /** @author John Hann */
21327 (function(define) { 'use strict';
21328 define(function() {
21330 return function addWith(Promise) {
21332 * Returns a promise whose handlers will be called with `this` set to
21333 * the supplied receiver. Subsequent promises derived from the
21334 * returned promise will also have their handlers called with receiver
21335 * as `this`. Calling `with` with undefined or no arguments will return
21336 * a promise whose handlers will again be called in the usual Promises/A+
21337 * way (no `this`) thus safely undoing any previous `with` in the
21340 * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
21341 * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
21343 * @param {object} receiver `this` value for all handlers attached to
21344 * the returned promise.
21345 * @returns {Promise}
21347 Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
21348 var p = this._beget();
21349 var child = p._handler;
21350 child.receiver = receiver;
21351 this._handler.chain(child, receiver);
21359 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21362 },{}],283:[function(require,module,exports){
21363 (function (process){
21364 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21365 /** @author Brian Cavalier */
21366 /** @author John Hann */
21368 /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
21369 (function(define) { 'use strict';
21370 define(function(require) {
21371 /*jshint maxcomplexity:6*/
21373 // Sniff "best" async scheduling option
21374 // Prefer process.nextTick or MutationObserver, then check for
21375 // setTimeout, and finally vertx, since its the only env that doesn't
21379 var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
21382 var setTimer = function(f, ms) { return setTimeout(f, ms); };
21383 var clearTimer = function(t) { return clearTimeout(t); };
21384 var asap = function (f) { return capturedSetTimeout(f, 0); };
21386 // Detect specific env
21387 if (isNode()) { // Node
21388 asap = function (f) { return process.nextTick(f); };
21390 } else if (MutationObs = hasMutationObserver()) { // Modern browser
21391 asap = initMutationObserver(MutationObs);
21393 } else if (!capturedSetTimeout) { // vert.x
21394 var vertxRequire = require;
21395 var vertx = vertxRequire('vertx');
21396 setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
21397 clearTimer = vertx.cancelTimer;
21398 asap = vertx.runOnLoop || vertx.runOnContext;
21402 setTimer: setTimer,
21403 clearTimer: clearTimer,
21407 function isNode () {
21408 return typeof process !== 'undefined' &&
21409 Object.prototype.toString.call(process) === '[object process]';
21412 function hasMutationObserver () {
21413 return (typeof MutationObserver !== 'undefined' && MutationObserver) ||
21414 (typeof WebKitMutationObserver !== 'undefined' && WebKitMutationObserver);
21417 function initMutationObserver(MutationObserver) {
21419 var node = document.createTextNode('');
21420 var o = new MutationObserver(run);
21421 o.observe(node, { characterData: true });
21425 scheduled = void 0;
21430 return function (f) {
21432 node.data = (i ^= 1);
21436 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
21438 }).call(this,require('_process'))
21440 },{"_process":6}],284:[function(require,module,exports){
21441 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21442 /** @author Brian Cavalier */
21443 /** @author John Hann */
21445 (function(define) { 'use strict';
21446 define(function() {
21449 formatError: formatError,
21450 formatObject: formatObject,
21451 tryStringify: tryStringify
21455 * Format an error into a string. If e is an Error and has a stack property,
21456 * it's returned. Otherwise, e is formatted using formatObject, with a
21457 * warning added about e not being a proper Error.
21459 * @returns {String} formatted string, suitable for output to developers
21461 function formatError(e) {
21462 var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
21463 return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
21467 * Format an object, detecting "plain" objects and running them through
21468 * JSON.stringify if possible.
21469 * @param {Object} o
21470 * @returns {string}
21472 function formatObject(o) {
21474 if(s === '[object Object]' && typeof JSON !== 'undefined') {
21475 s = tryStringify(o, s);
21481 * Try to return the result of JSON.stringify(x). If that fails, return
21484 * @param {*} defaultValue
21485 * @returns {String|*} JSON.stringify(x) or defaultValue
21487 function tryStringify(x, defaultValue) {
21489 return JSON.stringify(x);
21491 return defaultValue;
21496 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21498 },{}],285:[function(require,module,exports){
21499 (function (process){
21500 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21501 /** @author Brian Cavalier */
21502 /** @author John Hann */
21504 (function(define) { 'use strict';
21505 define(function() {
21507 return function makePromise(environment) {
21509 var tasks = environment.scheduler;
21510 var emitRejection = initEmitRejection();
21512 var objectCreate = Object.create ||
21514 function Child() {}
21515 Child.prototype = proto;
21516 return new Child();
21520 * Create a promise whose fate is determined by resolver
21522 * @returns {Promise} promise
21525 function Promise(resolver, handler) {
21526 this._handler = resolver === Handler ? handler : init(resolver);
21530 * Run the supplied resolver
21532 * @returns {Pending}
21534 function init(resolver) {
21535 var handler = new Pending();
21538 resolver(promiseResolve, promiseReject, promiseNotify);
21546 * Transition from pre-resolution state to post-resolution state, notifying
21547 * all listeners of the ultimate fulfillment or rejection
21548 * @param {*} x resolution value
21550 function promiseResolve (x) {
21551 handler.resolve(x);
21554 * Reject this promise with reason, which will be used verbatim
21555 * @param {Error|*} reason rejection reason, strongly suggested
21556 * to be an Error type
21558 function promiseReject (reason) {
21559 handler.reject(reason);
21564 * Issue a progress event, notifying all progress listeners
21565 * @param {*} x progress event payload to pass to all listeners
21567 function promiseNotify (x) {
21574 Promise.resolve = resolve;
21575 Promise.reject = reject;
21576 Promise.never = never;
21578 Promise._defer = defer;
21579 Promise._handler = getHandler;
21582 * Returns a trusted promise. If x is already a trusted promise, it is
21583 * returned, otherwise returns a new trusted Promise which follows x.
21585 * @return {Promise} promise
21587 function resolve(x) {
21588 return isPromise(x) ? x
21589 : new Promise(Handler, new Async(getHandler(x)));
21593 * Return a reject promise with x as its reason (x is used verbatim)
21595 * @returns {Promise} rejected promise
21597 function reject(x) {
21598 return new Promise(Handler, new Async(new Rejected(x)));
21602 * Return a promise that remains pending forever
21603 * @returns {Promise} forever-pending promise.
21606 return foreverPendingPromise; // Should be frozen
21610 * Creates an internal {promise, resolver} pair
21612 * @returns {Promise}
21615 return new Promise(Handler, new Pending());
21618 // Transformation and flow control
21621 * Transform this promise's fulfillment value, returning a new Promise
21622 * for the transformed result. If the promise cannot be fulfilled, onRejected
21623 * is called with the reason. onProgress *may* be called with updates toward
21624 * this promise's fulfillment.
21625 * @param {function=} onFulfilled fulfillment handler
21626 * @param {function=} onRejected rejection handler
21627 * @param {function=} onProgress @deprecated progress handler
21628 * @return {Promise} new promise
21630 Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
21631 var parent = this._handler;
21632 var state = parent.join().state();
21634 if ((typeof onFulfilled !== 'function' && state > 0) ||
21635 (typeof onRejected !== 'function' && state < 0)) {
21636 // Short circuit: value will not change, simply share handler
21637 return new this.constructor(Handler, parent);
21640 var p = this._beget();
21641 var child = p._handler;
21643 parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
21649 * If this promise cannot be fulfilled due to an error, call onRejected to
21650 * handle the error. Shortcut for .then(undefined, onRejected)
21651 * @param {function?} onRejected
21652 * @return {Promise}
21654 Promise.prototype['catch'] = function(onRejected) {
21655 return this.then(void 0, onRejected);
21659 * Creates a new, pending promise of the same type as this promise
21661 * @returns {Promise}
21663 Promise.prototype._beget = function() {
21664 return begetFrom(this._handler, this.constructor);
21667 function begetFrom(parent, Promise) {
21668 var child = new Pending(parent.receiver, parent.join().context);
21669 return new Promise(Handler, child);
21672 // Array combinators
21675 Promise.race = race;
21676 Promise._traverse = traverse;
21679 * Return a promise that will fulfill when all promises in the
21680 * input array have fulfilled, or will reject when one of the
21681 * promises rejects.
21682 * @param {array} promises array of promises
21683 * @returns {Promise} promise for array of fulfillment values
21685 function all(promises) {
21686 return traverseWith(snd, null, promises);
21690 * Array<Promise<X>> -> Promise<Array<f(X)>>
21692 * @param {function} f function to apply to each promise's value
21693 * @param {Array} promises array of promises
21694 * @returns {Promise} promise for transformed values
21696 function traverse(f, promises) {
21697 return traverseWith(tryCatch2, f, promises);
21700 function traverseWith(tryMap, f, promises) {
21701 var handler = typeof f === 'function' ? mapAt : settleAt;
21703 var resolver = new Pending();
21704 var pending = promises.length >>> 0;
21705 var results = new Array(pending);
21707 for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
21710 if (x === void 0 && !(i in promises)) {
21715 traverseAt(promises, handler, i, x, resolver);
21718 if(pending === 0) {
21719 resolver.become(new Fulfilled(results));
21722 return new Promise(Handler, resolver);
21724 function mapAt(i, x, resolver) {
21725 if(!resolver.resolved) {
21726 traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
21730 function settleAt(i, x, resolver) {
21732 if(--pending === 0) {
21733 resolver.become(new Fulfilled(results));
21738 function traverseAt(promises, handler, i, x, resolver) {
21739 if (maybeThenable(x)) {
21740 var h = getHandlerMaybeThenable(x);
21744 h.fold(handler, i, void 0, resolver);
21745 } else if (s > 0) {
21746 handler(i, h.value, resolver);
21748 resolver.become(h);
21749 visitRemaining(promises, i+1, h);
21752 handler(i, x, resolver);
21756 Promise._visitRemaining = visitRemaining;
21757 function visitRemaining(promises, start, handler) {
21758 for(var i=start; i<promises.length; ++i) {
21759 markAsHandled(getHandler(promises[i]), handler);
21763 function markAsHandled(h, handler) {
21764 if(h === handler) {
21770 h.visit(h, void 0, h._unreport);
21777 * Fulfill-reject competitive race. Return a promise that will settle
21778 * to the same state as the earliest input promise to settle.
21780 * WARNING: The ES6 Promise spec requires that race()ing an empty array
21781 * must return a promise that is pending forever. This implementation
21782 * returns a singleton forever-pending promise, the same singleton that is
21783 * returned by Promise.never(), thus can be checked with ===
21785 * @param {array} promises array of promises to race
21786 * @returns {Promise} if input is non-empty, a promise that will settle
21787 * to the same outcome as the earliest input promise to settle. if empty
21788 * is empty, returns a promise that will never settle.
21790 function race(promises) {
21791 if(typeof promises !== 'object' || promises === null) {
21792 return reject(new TypeError('non-iterable passed to race()'));
21795 // Sigh, race([]) is untestable unless we return *something*
21796 // that is recognizable without calling .then() on it.
21797 return promises.length === 0 ? never()
21798 : promises.length === 1 ? resolve(promises[0])
21799 : runRace(promises);
21802 function runRace(promises) {
21803 var resolver = new Pending();
21805 for(i=0; i<promises.length; ++i) {
21807 if (x === void 0 && !(i in promises)) {
21812 if(h.state() !== 0) {
21813 resolver.become(h);
21814 visitRemaining(promises, i+1, h);
21817 h.visit(resolver, resolver.resolve, resolver.reject);
21820 return new Promise(Handler, resolver);
21823 // Promise internals
21824 // Below this, everything is @private
21827 * Get an appropriate handler for x, without checking for cycles
21829 * @returns {object} handler
21831 function getHandler(x) {
21833 return x._handler.join();
21835 return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
21839 * Get a handler for thenable x.
21840 * NOTE: You must only call this if maybeThenable(x) == true
21841 * @param {object|function|Promise} x
21842 * @returns {object} handler
21844 function getHandlerMaybeThenable(x) {
21845 return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
21849 * Get a handler for potentially untrusted thenable x
21851 * @returns {object} handler
21853 function getHandlerUntrusted(x) {
21855 var untrustedThen = x.then;
21856 return typeof untrustedThen === 'function'
21857 ? new Thenable(untrustedThen, x)
21858 : new Fulfilled(x);
21860 return new Rejected(e);
21865 * Handler for a promise that is pending forever
21868 function Handler() {}
21870 Handler.prototype.when
21871 = Handler.prototype.become
21872 = Handler.prototype.notify // deprecated
21873 = Handler.prototype.fail
21874 = Handler.prototype._unreport
21875 = Handler.prototype._report
21878 Handler.prototype._state = 0;
21880 Handler.prototype.state = function() {
21881 return this._state;
21885 * Recursively collapse handler chain to find the handler
21886 * nearest to the fully resolved value.
21887 * @returns {object} handler nearest the fully resolved value
21889 Handler.prototype.join = function() {
21891 while(h.handler !== void 0) {
21897 Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
21900 receiver: receiver,
21901 fulfilled: fulfilled,
21902 rejected: rejected,
21907 Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
21908 this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
21911 Handler.prototype.fold = function(f, z, c, to) {
21912 this.when(new Fold(f, z, c, to));
21916 * Handler that invokes fail() on any handler it becomes
21919 function FailIfRejected() {}
21921 inherit(Handler, FailIfRejected);
21923 FailIfRejected.prototype.become = function(h) {
21927 var failIfRejected = new FailIfRejected();
21930 * Handler that manages a queue of consumers waiting on a pending promise
21933 function Pending(receiver, inheritedContext) {
21934 Promise.createContext(this, inheritedContext);
21936 this.consumers = void 0;
21937 this.receiver = receiver;
21938 this.handler = void 0;
21939 this.resolved = false;
21942 inherit(Handler, Pending);
21944 Pending.prototype._state = 0;
21946 Pending.prototype.resolve = function(x) {
21947 this.become(getHandler(x));
21950 Pending.prototype.reject = function(x) {
21951 if(this.resolved) {
21955 this.become(new Rejected(x));
21958 Pending.prototype.join = function() {
21959 if (!this.resolved) {
21965 while (h.handler !== void 0) {
21968 return this.handler = cycle();
21975 Pending.prototype.run = function() {
21976 var q = this.consumers;
21977 var handler = this.handler;
21978 this.handler = this.handler.join();
21979 this.consumers = void 0;
21981 for (var i = 0; i < q.length; ++i) {
21982 handler.when(q[i]);
21986 Pending.prototype.become = function(handler) {
21987 if(this.resolved) {
21991 this.resolved = true;
21992 this.handler = handler;
21993 if(this.consumers !== void 0) {
21994 tasks.enqueue(this);
21997 if(this.context !== void 0) {
21998 handler._report(this.context);
22002 Pending.prototype.when = function(continuation) {
22003 if(this.resolved) {
22004 tasks.enqueue(new ContinuationTask(continuation, this.handler));
22006 if(this.consumers === void 0) {
22007 this.consumers = [continuation];
22009 this.consumers.push(continuation);
22017 Pending.prototype.notify = function(x) {
22018 if(!this.resolved) {
22019 tasks.enqueue(new ProgressTask(x, this));
22023 Pending.prototype.fail = function(context) {
22024 var c = typeof context === 'undefined' ? this.context : context;
22025 this.resolved && this.handler.join().fail(c);
22028 Pending.prototype._report = function(context) {
22029 this.resolved && this.handler.join()._report(context);
22032 Pending.prototype._unreport = function() {
22033 this.resolved && this.handler.join()._unreport();
22037 * Wrap another handler and force it into a future stack
22038 * @param {object} handler
22041 function Async(handler) {
22042 this.handler = handler;
22045 inherit(Handler, Async);
22047 Async.prototype.when = function(continuation) {
22048 tasks.enqueue(new ContinuationTask(continuation, this));
22051 Async.prototype._report = function(context) {
22052 this.join()._report(context);
22055 Async.prototype._unreport = function() {
22056 this.join()._unreport();
22060 * Handler that wraps an untrusted thenable and assimilates it in a future stack
22061 * @param {function} then
22062 * @param {{then: function}} thenable
22065 function Thenable(then, thenable) {
22066 Pending.call(this);
22067 tasks.enqueue(new AssimilateTask(then, thenable, this));
22070 inherit(Pending, Thenable);
22073 * Handler for a fulfilled promise
22074 * @param {*} x fulfillment value
22077 function Fulfilled(x) {
22078 Promise.createContext(this);
22082 inherit(Handler, Fulfilled);
22084 Fulfilled.prototype._state = 1;
22086 Fulfilled.prototype.fold = function(f, z, c, to) {
22087 runContinuation3(f, z, this, c, to);
22090 Fulfilled.prototype.when = function(cont) {
22091 runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
22097 * Handler for a rejected promise
22098 * @param {*} x rejection reason
22101 function Rejected(x) {
22102 Promise.createContext(this);
22104 this.id = ++errorId;
22106 this.handled = false;
22107 this.reported = false;
22112 inherit(Handler, Rejected);
22114 Rejected.prototype._state = -1;
22116 Rejected.prototype.fold = function(f, z, c, to) {
22120 Rejected.prototype.when = function(cont) {
22121 if(typeof cont.rejected === 'function') {
22124 runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
22127 Rejected.prototype._report = function(context) {
22128 tasks.afterQueue(new ReportTask(this, context));
22131 Rejected.prototype._unreport = function() {
22135 this.handled = true;
22136 tasks.afterQueue(new UnreportTask(this));
22139 Rejected.prototype.fail = function(context) {
22140 this.reported = true;
22141 emitRejection('unhandledRejection', this);
22142 Promise.onFatalRejection(this, context === void 0 ? this.context : context);
22145 function ReportTask(rejection, context) {
22146 this.rejection = rejection;
22147 this.context = context;
22150 ReportTask.prototype.run = function() {
22151 if(!this.rejection.handled && !this.rejection.reported) {
22152 this.rejection.reported = true;
22153 emitRejection('unhandledRejection', this.rejection) ||
22154 Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
22158 function UnreportTask(rejection) {
22159 this.rejection = rejection;
22162 UnreportTask.prototype.run = function() {
22163 if(this.rejection.reported) {
22164 emitRejection('rejectionHandled', this.rejection) ||
22165 Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
22169 // Unhandled rejection hooks
22170 // By default, everything is a noop
22172 Promise.createContext
22173 = Promise.enterContext
22174 = Promise.exitContext
22175 = Promise.onPotentiallyUnhandledRejection
22176 = Promise.onPotentiallyUnhandledRejectionHandled
22177 = Promise.onFatalRejection
22180 // Errors and singletons
22182 var foreverPendingHandler = new Handler();
22183 var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
22186 return new Rejected(new TypeError('Promise cycle'));
22192 * Run a single consumer
22195 function ContinuationTask(continuation, handler) {
22196 this.continuation = continuation;
22197 this.handler = handler;
22200 ContinuationTask.prototype.run = function() {
22201 this.handler.join().when(this.continuation);
22205 * Run a queue of progress handlers
22208 function ProgressTask(value, handler) {
22209 this.handler = handler;
22210 this.value = value;
22213 ProgressTask.prototype.run = function() {
22214 var q = this.handler.consumers;
22219 for (var c, i = 0; i < q.length; ++i) {
22221 runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
22226 * Assimilate a thenable, sending it's value to resolver
22227 * @param {function} then
22228 * @param {object|function} thenable
22229 * @param {object} resolver
22232 function AssimilateTask(then, thenable, resolver) {
22234 this.thenable = thenable;
22235 this.resolver = resolver;
22238 AssimilateTask.prototype.run = function() {
22239 var h = this.resolver;
22240 tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
22242 function _resolve(x) { h.resolve(x); }
22243 function _reject(x) { h.reject(x); }
22244 function _notify(x) { h.notify(x); }
22247 function tryAssimilate(then, thenable, resolve, reject, notify) {
22249 then.call(thenable, resolve, reject, notify);
22256 * Fold a handler value with z
22259 function Fold(f, z, c, to) {
22260 this.f = f; this.z = z; this.c = c; this.to = to;
22261 this.resolver = failIfRejected;
22262 this.receiver = this;
22265 Fold.prototype.fulfilled = function(x) {
22266 this.f.call(this.c, this.z, x, this.to);
22269 Fold.prototype.rejected = function(x) {
22273 Fold.prototype.progress = function(x) {
22281 * @returns {boolean} true iff x is a trusted Promise
22283 function isPromise(x) {
22284 return x instanceof Promise;
22288 * Test just enough to rule out primitives, in order to take faster
22289 * paths in some code
22291 * @returns {boolean} false iff x is guaranteed *not* to be a thenable
22293 function maybeThenable(x) {
22294 return (typeof x === 'object' || typeof x === 'function') && x !== null;
22297 function runContinuation1(f, h, receiver, next) {
22298 if(typeof f !== 'function') {
22299 return next.become(h);
22302 Promise.enterContext(h);
22303 tryCatchReject(f, h.value, receiver, next);
22304 Promise.exitContext();
22307 function runContinuation3(f, x, h, receiver, next) {
22308 if(typeof f !== 'function') {
22309 return next.become(h);
22312 Promise.enterContext(h);
22313 tryCatchReject3(f, x, h.value, receiver, next);
22314 Promise.exitContext();
22320 function runNotify(f, x, h, receiver, next) {
22321 if(typeof f !== 'function') {
22322 return next.notify(x);
22325 Promise.enterContext(h);
22326 tryCatchReturn(f, x, receiver, next);
22327 Promise.exitContext();
22330 function tryCatch2(f, a, b) {
22339 * Return f.call(thisArg, x), or if it throws return a rejected promise for
22340 * the thrown exception
22342 function tryCatchReject(f, x, thisArg, next) {
22344 next.become(getHandler(f.call(thisArg, x)));
22346 next.become(new Rejected(e));
22351 * Same as above, but includes the extra argument parameter.
22353 function tryCatchReject3(f, x, y, thisArg, next) {
22355 f.call(thisArg, x, y, next);
22357 next.become(new Rejected(e));
22363 * Return f.call(thisArg, x), or if it throws, *return* the exception
22365 function tryCatchReturn(f, x, thisArg, next) {
22367 next.notify(f.call(thisArg, x));
22373 function inherit(Parent, Child) {
22374 Child.prototype = objectCreate(Parent.prototype);
22375 Child.prototype.constructor = Child;
22378 function snd(x, y) {
22384 function hasCustomEvent() {
22385 if(typeof CustomEvent === 'function') {
22387 var ev = new CustomEvent('unhandledRejection');
22388 return ev instanceof CustomEvent;
22389 } catch (ignoredException) {}
22394 function hasInternetExplorerCustomEvent() {
22395 if(typeof document !== 'undefined' && typeof document.createEvent === 'function') {
22397 // Try to create one event to make sure it's supported
22398 var ev = document.createEvent('CustomEvent');
22399 ev.initCustomEvent('eventType', false, true, {});
22401 } catch (ignoredException) {}
22406 function initEmitRejection() {
22407 /*global process, self, CustomEvent*/
22408 if(typeof process !== 'undefined' && process !== null
22409 && typeof process.emit === 'function') {
22410 // Returning falsy here means to call the default
22411 // onPotentiallyUnhandledRejection API. This is safe even in
22412 // browserify since process.emit always returns falsy in browserify:
22413 // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
22414 return function(type, rejection) {
22415 return type === 'unhandledRejection'
22416 ? process.emit(type, rejection.value, rejection)
22417 : process.emit(type, rejection);
22419 } else if(typeof self !== 'undefined' && hasCustomEvent()) {
22420 return (function (self, CustomEvent) {
22421 return function (type, rejection) {
22422 var ev = new CustomEvent(type, {
22424 reason: rejection.value,
22431 return !self.dispatchEvent(ev);
22433 }(self, CustomEvent));
22434 } else if(typeof self !== 'undefined' && hasInternetExplorerCustomEvent()) {
22435 return (function(self, document) {
22436 return function(type, rejection) {
22437 var ev = document.createEvent('CustomEvent');
22438 ev.initCustomEvent(type, false, true, {
22439 reason: rejection.value,
22443 return !self.dispatchEvent(ev);
22445 }(self, document));
22454 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
22456 }).call(this,require('_process'))
22458 },{"_process":6}],286:[function(require,module,exports){
22459 /** @license MIT License (c) copyright 2010-2014 original author or authors */
22460 /** @author Brian Cavalier */
22461 /** @author John Hann */
22463 (function(define) { 'use strict';
22464 define(function() {
22467 pending: toPendingState,
22468 fulfilled: toFulfilledState,
22469 rejected: toRejectedState,
22473 function toPendingState() {
22474 return { state: 'pending' };
22477 function toRejectedState(e) {
22478 return { state: 'rejected', reason: e };
22481 function toFulfilledState(x) {
22482 return { state: 'fulfilled', value: x };
22485 function inspect(handler) {
22486 var state = handler.state();
22487 return state === 0 ? toPendingState()
22488 : state > 0 ? toFulfilledState(handler.value)
22489 : toRejectedState(handler.value);
22493 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
22495 },{}],287:[function(require,module,exports){
22496 /** @license MIT License (c) copyright 2010-2014 original author or authors */
22499 * Promises/A+ and when() implementation
22500 * when is part of the cujoJS family of libraries (http://cujojs.com/)
22501 * @author Brian Cavalier
22502 * @author John Hann
22504 (function(define) { 'use strict';
22505 define(function (require) {
22507 var timed = require('./lib/decorators/timed');
22508 var array = require('./lib/decorators/array');
22509 var flow = require('./lib/decorators/flow');
22510 var fold = require('./lib/decorators/fold');
22511 var inspect = require('./lib/decorators/inspect');
22512 var generate = require('./lib/decorators/iterate');
22513 var progress = require('./lib/decorators/progress');
22514 var withThis = require('./lib/decorators/with');
22515 var unhandledRejection = require('./lib/decorators/unhandledRejection');
22516 var TimeoutError = require('./lib/TimeoutError');
22518 var Promise = [array, flow, fold, generate, progress,
22519 inspect, withThis, timed, unhandledRejection]
22520 .reduce(function(Promise, feature) {
22521 return feature(Promise);
22522 }, require('./lib/Promise'));
22524 var apply = require('./lib/apply')(Promise);
22528 when.promise = promise; // Create a pending promise
22529 when.resolve = Promise.resolve; // Create a resolved promise
22530 when.reject = Promise.reject; // Create a rejected promise
22532 when.lift = lift; // lift a function to return promises
22533 when['try'] = attempt; // call a function and return a promise
22534 when.attempt = attempt; // alias for when.try
22536 when.iterate = Promise.iterate; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
22537 when.unfold = Promise.unfold; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
22539 when.join = join; // Join 2 or more promises
22541 when.all = all; // Resolve a list of promises
22542 when.settle = settle; // Settle a list of promises
22544 when.any = lift(Promise.any); // One-winner race
22545 when.some = lift(Promise.some); // Multi-winner race
22546 when.race = lift(Promise.race); // First-to-settle race
22548 when.map = map; // Array.map() for promises
22549 when.filter = filter; // Array.filter() for promises
22550 when.reduce = lift(Promise.reduce); // Array.reduce() for promises
22551 when.reduceRight = lift(Promise.reduceRight); // Array.reduceRight() for promises
22553 when.isPromiseLike = isPromiseLike; // Is something promise-like, aka thenable
22555 when.Promise = Promise; // Promise constructor
22556 when.defer = defer; // Create a {promise, resolve, reject} tuple
22560 when.TimeoutError = TimeoutError;
22563 * Get a trusted promise for x, or by transforming x with onFulfilled
22566 * @param {function?} onFulfilled callback to be called when x is
22567 * successfully fulfilled. If promiseOrValue is an immediate value, callback
22568 * will be invoked immediately.
22569 * @param {function?} onRejected callback to be called when x is
22571 * @param {function?} onProgress callback to be called when progress updates
22572 * are issued for x. @deprecated
22573 * @returns {Promise} a new promise that will fulfill with the return
22574 * value of callback or errback or the completion value of promiseOrValue if
22575 * callback and/or errback is not supplied.
22577 function when(x, onFulfilled, onRejected, onProgress) {
22578 var p = Promise.resolve(x);
22579 if (arguments.length < 2) {
22583 return p.then(onFulfilled, onRejected, onProgress);
22587 * Creates a new promise whose fate is determined by resolver.
22588 * @param {function} resolver function(resolve, reject, notify)
22589 * @returns {Promise} promise whose fate is determine by resolver
22591 function promise(resolver) {
22592 return new Promise(resolver);
22596 * Lift the supplied function, creating a version of f that returns
22597 * promises, and accepts promises as arguments.
22598 * @param {function} f
22599 * @returns {Function} version of f that returns promises
22602 return function() {
22603 for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
22604 a[i] = arguments[i];
22606 return apply(f, this, a);
22611 * Call f in a future turn, with the supplied args, and return a promise
22613 * @param {function} f
22614 * @returns {Promise}
22616 function attempt(f /*, args... */) {
22617 /*jshint validthis:true */
22618 for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
22619 a[i] = arguments[i+1];
22621 return apply(f, this, a);
22625 * Creates a {promise, resolver} pair, either or both of which
22626 * may be given out safely to consumers.
22627 * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
22630 return new Deferred();
22633 function Deferred() {
22634 var p = Promise._defer();
22636 function resolve(x) { p._handler.resolve(x); }
22637 function reject(x) { p._handler.reject(x); }
22638 function notify(x) { p._handler.notify(x); }
22641 this.resolve = resolve;
22642 this.reject = reject;
22643 this.notify = notify;
22644 this.resolver = { resolve: resolve, reject: reject, notify: notify };
22648 * Determines if x is promise-like, i.e. a thenable object
22649 * NOTE: Will return true for *any thenable object*, and isn't truly
22650 * safe, since it may attempt to access the `then` property of x (i.e.
22651 * clever/malicious getters may do weird things)
22652 * @param {*} x anything
22653 * @returns {boolean} true if x is promise-like
22655 function isPromiseLike(x) {
22656 return x && typeof x.then === 'function';
22660 * Return a promise that will resolve only once all the supplied arguments
22661 * have resolved. The resolution value of the returned promise will be an array
22662 * containing the resolution values of each of the arguments.
22663 * @param {...*} arguments may be a mix of promises and values
22664 * @returns {Promise}
22666 function join(/* ...promises */) {
22667 return Promise.all(arguments);
22671 * Return a promise that will fulfill once all input promises have
22672 * fulfilled, or reject when any one input promise rejects.
22673 * @param {array|Promise} promises array (or promise for an array) of promises
22674 * @returns {Promise}
22676 function all(promises) {
22677 return when(promises, Promise.all);
22681 * Return a promise that will always fulfill with an array containing
22682 * the outcome states of all input promises. The returned promise
22683 * will only reject if `promises` itself is a rejected promise.
22684 * @param {array|Promise} promises array (or promise for an array) of promises
22685 * @returns {Promise} promise for array of settled state descriptors
22687 function settle(promises) {
22688 return when(promises, Promise.settle);
22692 * Promise-aware array map function, similar to `Array.prototype.map()`,
22693 * but input array may contain promises or values.
22694 * @param {Array|Promise} promises array of anything, may contain promises and values
22695 * @param {function(x:*, index:Number):*} mapFunc map function which may
22696 * return a promise or value
22697 * @returns {Promise} promise that will fulfill with an array of mapped values
22698 * or reject if any input promise rejects.
22700 function map(promises, mapFunc) {
22701 return when(promises, function(promises) {
22702 return Promise.map(promises, mapFunc);
22707 * Filter the provided array of promises using the provided predicate. Input may
22708 * contain promises and values
22709 * @param {Array|Promise} promises array of promises and values
22710 * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
22711 * Must return truthy (or promise for truthy) for items to retain.
22712 * @returns {Promise} promise that will fulfill with an array containing all items
22713 * for which predicate returned truthy.
22715 function filter(promises, predicate) {
22716 return when(promises, function(promises) {
22717 return Promise.filter(promises, predicate);
22723 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
22725 },{"./lib/Promise":270,"./lib/TimeoutError":272,"./lib/apply":273,"./lib/decorators/array":274,"./lib/decorators/flow":275,"./lib/decorators/fold":276,"./lib/decorators/inspect":277,"./lib/decorators/iterate":278,"./lib/decorators/progress":279,"./lib/decorators/timed":280,"./lib/decorators/unhandledRejection":281,"./lib/decorators/with":282}],288:[function(require,module,exports){
22726 var nativeIsArray = Array.isArray
22727 var toString = Object.prototype.toString
22729 module.exports = nativeIsArray || isArray
22731 function isArray(obj) {
22732 return toString.call(obj) === "[object Array]"
22735 },{}],289:[function(require,module,exports){
22737 Object.defineProperty(exports, "__esModule", { value: true });
22738 var APIv3_1 = require("./api/APIv3");
22739 exports.APIv3 = APIv3_1.APIv3;
22740 var ModelCreator_1 = require("./api/ModelCreator");
22741 exports.ModelCreator = ModelCreator_1.ModelCreator;
22743 },{"./api/APIv3":302,"./api/ModelCreator":303}],290:[function(require,module,exports){
22745 function __export(m) {
22746 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
22748 Object.defineProperty(exports, "__esModule", { value: true });
22749 var Component_1 = require("./component/Component");
22750 exports.Component = Component_1.Component;
22751 var ComponentService_1 = require("./component/ComponentService");
22752 exports.ComponentService = ComponentService_1.ComponentService;
22753 var HandlerBase_1 = require("./component/utils/HandlerBase");
22754 exports.HandlerBase = HandlerBase_1.HandlerBase;
22755 var MeshFactory_1 = require("./component/utils/MeshFactory");
22756 exports.MeshFactory = MeshFactory_1.MeshFactory;
22757 var MeshScene_1 = require("./component/utils/MeshScene");
22758 exports.MeshScene = MeshScene_1.MeshScene;
22759 var AttributionComponent_1 = require("./component/AttributionComponent");
22760 exports.AttributionComponent = AttributionComponent_1.AttributionComponent;
22761 var BackgroundComponent_1 = require("./component/BackgroundComponent");
22762 exports.BackgroundComponent = BackgroundComponent_1.BackgroundComponent;
22763 var BearingComponent_1 = require("./component/BearingComponent");
22764 exports.BearingComponent = BearingComponent_1.BearingComponent;
22765 var CacheComponent_1 = require("./component/CacheComponent");
22766 exports.CacheComponent = CacheComponent_1.CacheComponent;
22767 var CoverComponent_1 = require("./component/CoverComponent");
22768 exports.CoverComponent = CoverComponent_1.CoverComponent;
22769 var DebugComponent_1 = require("./component/DebugComponent");
22770 exports.DebugComponent = DebugComponent_1.DebugComponent;
22771 var DirectionComponent_1 = require("./component/direction/DirectionComponent");
22772 exports.DirectionComponent = DirectionComponent_1.DirectionComponent;
22773 var DirectionDOMCalculator_1 = require("./component/direction/DirectionDOMCalculator");
22774 exports.DirectionDOMCalculator = DirectionDOMCalculator_1.DirectionDOMCalculator;
22775 var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer");
22776 exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer;
22777 var ImageComponent_1 = require("./component/ImageComponent");
22778 exports.ImageComponent = ImageComponent_1.ImageComponent;
22779 var KeyboardComponent_1 = require("./component/keyboard/KeyboardComponent");
22780 exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent;
22781 var KeyPlayHandler_1 = require("./component/keyboard/KeyPlayHandler");
22782 exports.KeyPlayHandler = KeyPlayHandler_1.KeyPlayHandler;
22783 var KeyZoomHandler_1 = require("./component/keyboard/KeyZoomHandler");
22784 exports.KeyZoomHandler = KeyZoomHandler_1.KeyZoomHandler;
22785 var KeySequenceNavigationHandler_1 = require("./component/keyboard/KeySequenceNavigationHandler");
22786 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler_1.KeySequenceNavigationHandler;
22787 var KeySpatialNavigationHandler_1 = require("./component/keyboard/KeySpatialNavigationHandler");
22788 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler_1.KeySpatialNavigationHandler;
22789 var LoadingComponent_1 = require("./component/LoadingComponent");
22790 exports.LoadingComponent = LoadingComponent_1.LoadingComponent;
22791 var Marker_1 = require("./component/marker/marker/Marker");
22792 exports.Marker = Marker_1.Marker;
22793 var MarkerComponent_1 = require("./component/marker/MarkerComponent");
22794 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
22795 var MarkerScene_1 = require("./component/marker/MarkerScene");
22796 exports.MarkerScene = MarkerScene_1.MarkerScene;
22797 var MarkerSet_1 = require("./component/marker/MarkerSet");
22798 exports.MarkerSet = MarkerSet_1.MarkerSet;
22799 var MouseComponent_1 = require("./component/mouse/MouseComponent");
22800 exports.MouseComponent = MouseComponent_1.MouseComponent;
22801 var BounceHandler_1 = require("./component/mouse/BounceHandler");
22802 exports.BounceHandler = BounceHandler_1.BounceHandler;
22803 var DragPanHandler_1 = require("./component/mouse/DragPanHandler");
22804 exports.DragPanHandler = DragPanHandler_1.DragPanHandler;
22805 var DoubleClickZoomHandler_1 = require("./component/mouse/DoubleClickZoomHandler");
22806 exports.DoubleClickZoomHandler = DoubleClickZoomHandler_1.DoubleClickZoomHandler;
22807 var ScrollZoomHandler_1 = require("./component/mouse/ScrollZoomHandler");
22808 exports.ScrollZoomHandler = ScrollZoomHandler_1.ScrollZoomHandler;
22809 var TouchZoomHandler_1 = require("./component/mouse/TouchZoomHandler");
22810 exports.TouchZoomHandler = TouchZoomHandler_1.TouchZoomHandler;
22811 var Popup_1 = require("./component/popup/popup/Popup");
22812 exports.Popup = Popup_1.Popup;
22813 var PopupComponent_1 = require("./component/popup/PopupComponent");
22814 exports.PopupComponent = PopupComponent_1.PopupComponent;
22815 var NavigationComponent_1 = require("./component/NavigationComponent");
22816 exports.NavigationComponent = NavigationComponent_1.NavigationComponent;
22817 var RouteComponent_1 = require("./component/RouteComponent");
22818 exports.RouteComponent = RouteComponent_1.RouteComponent;
22819 var SequenceComponent_1 = require("./component/sequence/SequenceComponent");
22820 exports.SequenceComponent = SequenceComponent_1.SequenceComponent;
22821 var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer");
22822 exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer;
22823 var SequenceMode_1 = require("./component/sequence/SequenceMode");
22824 exports.SequenceMode = SequenceMode_1.SequenceMode;
22825 var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent");
22826 exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent;
22827 var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer");
22828 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer;
22829 var Shaders_1 = require("./component/shaders/Shaders");
22830 exports.Shaders = Shaders_1.Shaders;
22831 var SimpleMarker_1 = require("./component/marker/marker/SimpleMarker");
22832 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
22833 var CircleMarker_1 = require("./component/marker/marker/CircleMarker");
22834 exports.CircleMarker = CircleMarker_1.CircleMarker;
22835 var SliderComponent_1 = require("./component/slider/SliderComponent");
22836 exports.SliderComponent = SliderComponent_1.SliderComponent;
22837 var SliderDOMRenderer_1 = require("./component/slider/SliderDOMRenderer");
22838 exports.SliderDOMRenderer = SliderDOMRenderer_1.SliderDOMRenderer;
22839 var SliderGLRenderer_1 = require("./component/slider/SliderGLRenderer");
22840 exports.SliderGLRenderer = SliderGLRenderer_1.SliderGLRenderer;
22841 var StatsComponent_1 = require("./component/StatsComponent");
22842 exports.StatsComponent = StatsComponent_1.StatsComponent;
22843 var TagHandlerBase_1 = require("./component/tag/handlers/TagHandlerBase");
22844 exports.TagHandlerBase = TagHandlerBase_1.TagHandlerBase;
22845 var CreateHandlerBase_1 = require("./component/tag/handlers/CreateHandlerBase");
22846 exports.CreateHandlerBase = CreateHandlerBase_1.CreateHandlerBase;
22847 var CreatePointHandler_1 = require("./component/tag/handlers/CreatePointHandler");
22848 exports.CreatePointHandler = CreatePointHandler_1.CreatePointHandler;
22849 var CreateVertexHandler_1 = require("./component/tag/handlers/CreateVertexHandler");
22850 exports.CreateVertexHandler = CreateVertexHandler_1.CreateVertexHandler;
22851 var CreatePolygonHandler_1 = require("./component/tag/handlers/CreatePolygonHandler");
22852 exports.CreatePolygonHandler = CreatePolygonHandler_1.CreatePolygonHandler;
22853 var CreateRectHandler_1 = require("./component/tag/handlers/CreateRectHandler");
22854 exports.CreateRectHandler = CreateRectHandler_1.CreateRectHandler;
22855 var CreateRectDragHandler_1 = require("./component/tag/handlers/CreateRectDragHandler");
22856 exports.CreateRectDragHandler = CreateRectDragHandler_1.CreateRectDragHandler;
22857 var EditVertexHandler_1 = require("./component/tag/handlers/EditVertexHandler");
22858 exports.EditVertexHandler = EditVertexHandler_1.EditVertexHandler;
22859 var Tag_1 = require("./component/tag/tag/Tag");
22860 exports.Tag = Tag_1.Tag;
22861 var OutlineTag_1 = require("./component/tag/tag/OutlineTag");
22862 exports.OutlineTag = OutlineTag_1.OutlineTag;
22863 var RenderTag_1 = require("./component/tag/tag/RenderTag");
22864 exports.RenderTag = RenderTag_1.RenderTag;
22865 var OutlineRenderTag_1 = require("./component/tag/tag/OutlineRenderTag");
22866 exports.OutlineRenderTag = OutlineRenderTag_1.OutlineRenderTag;
22867 var OutlineCreateTag_1 = require("./component/tag/tag/OutlineCreateTag");
22868 exports.OutlineCreateTag = OutlineCreateTag_1.OutlineCreateTag;
22869 var SpotTag_1 = require("./component/tag/tag/SpotTag");
22870 exports.SpotTag = SpotTag_1.SpotTag;
22871 var SpotRenderTag_1 = require("./component/tag/tag/SpotRenderTag");
22872 exports.SpotRenderTag = SpotRenderTag_1.SpotRenderTag;
22873 var TagComponent_1 = require("./component/tag/TagComponent");
22874 exports.TagComponent = TagComponent_1.TagComponent;
22875 var TagCreator_1 = require("./component/tag/TagCreator");
22876 exports.TagCreator = TagCreator_1.TagCreator;
22877 var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer");
22878 exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer;
22879 var TagMode_1 = require("./component/tag/TagMode");
22880 exports.TagMode = TagMode_1.TagMode;
22881 var TagOperation_1 = require("./component/tag/TagOperation");
22882 exports.TagOperation = TagOperation_1.TagOperation;
22883 var TagScene_1 = require("./component/tag/TagScene");
22884 exports.TagScene = TagScene_1.TagScene;
22885 var TagSet_1 = require("./component/tag/TagSet");
22886 exports.TagSet = TagSet_1.TagSet;
22887 var Geometry_1 = require("./component/tag/geometry/Geometry");
22888 exports.Geometry = Geometry_1.Geometry;
22889 var VertexGeometry_1 = require("./component/tag/geometry/VertexGeometry");
22890 exports.VertexGeometry = VertexGeometry_1.VertexGeometry;
22891 var RectGeometry_1 = require("./component/tag/geometry/RectGeometry");
22892 exports.RectGeometry = RectGeometry_1.RectGeometry;
22893 var PointGeometry_1 = require("./component/tag/geometry/PointGeometry");
22894 exports.PointGeometry = PointGeometry_1.PointGeometry;
22895 var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry");
22896 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
22897 var GeometryTagError_1 = require("./component/tag/error/GeometryTagError");
22898 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
22899 var ZoomComponent_1 = require("./component/zoom/ZoomComponent");
22900 exports.ZoomComponent = ZoomComponent_1.ZoomComponent;
22901 __export(require("./component/interfaces/interfaces"));
22903 },{"./component/AttributionComponent":304,"./component/BackgroundComponent":305,"./component/BearingComponent":306,"./component/CacheComponent":307,"./component/Component":308,"./component/ComponentService":309,"./component/CoverComponent":310,"./component/DebugComponent":311,"./component/ImageComponent":312,"./component/LoadingComponent":313,"./component/NavigationComponent":314,"./component/RouteComponent":315,"./component/StatsComponent":316,"./component/direction/DirectionComponent":317,"./component/direction/DirectionDOMCalculator":318,"./component/direction/DirectionDOMRenderer":319,"./component/imageplane/ImagePlaneComponent":320,"./component/imageplane/ImagePlaneGLRenderer":321,"./component/interfaces/interfaces":324,"./component/keyboard/KeyPlayHandler":325,"./component/keyboard/KeySequenceNavigationHandler":326,"./component/keyboard/KeySpatialNavigationHandler":327,"./component/keyboard/KeyZoomHandler":328,"./component/keyboard/KeyboardComponent":329,"./component/marker/MarkerComponent":331,"./component/marker/MarkerScene":332,"./component/marker/MarkerSet":333,"./component/marker/marker/CircleMarker":334,"./component/marker/marker/Marker":335,"./component/marker/marker/SimpleMarker":336,"./component/mouse/BounceHandler":337,"./component/mouse/DoubleClickZoomHandler":338,"./component/mouse/DragPanHandler":339,"./component/mouse/MouseComponent":340,"./component/mouse/ScrollZoomHandler":341,"./component/mouse/TouchZoomHandler":342,"./component/popup/PopupComponent":344,"./component/popup/popup/Popup":345,"./component/sequence/SequenceComponent":346,"./component/sequence/SequenceDOMRenderer":347,"./component/sequence/SequenceMode":348,"./component/shaders/Shaders":349,"./component/slider/SliderComponent":350,"./component/slider/SliderDOMRenderer":351,"./component/slider/SliderGLRenderer":352,"./component/tag/TagComponent":354,"./component/tag/TagCreator":355,"./component/tag/TagDOMRenderer":356,"./component/tag/TagMode":357,"./component/tag/TagOperation":358,"./component/tag/TagScene":359,"./component/tag/TagSet":360,"./component/tag/error/GeometryTagError":361,"./component/tag/geometry/Geometry":362,"./component/tag/geometry/PointGeometry":363,"./component/tag/geometry/PolygonGeometry":364,"./component/tag/geometry/RectGeometry":365,"./component/tag/geometry/VertexGeometry":366,"./component/tag/handlers/CreateHandlerBase":367,"./component/tag/handlers/CreatePointHandler":368,"./component/tag/handlers/CreatePolygonHandler":369,"./component/tag/handlers/CreateRectDragHandler":370,"./component/tag/handlers/CreateRectHandler":371,"./component/tag/handlers/CreateVertexHandler":372,"./component/tag/handlers/EditVertexHandler":373,"./component/tag/handlers/TagHandlerBase":374,"./component/tag/tag/OutlineCreateTag":375,"./component/tag/tag/OutlineRenderTag":376,"./component/tag/tag/OutlineTag":377,"./component/tag/tag/RenderTag":378,"./component/tag/tag/SpotRenderTag":379,"./component/tag/tag/SpotTag":380,"./component/tag/tag/Tag":381,"./component/utils/HandlerBase":382,"./component/utils/MeshFactory":383,"./component/utils/MeshScene":384,"./component/zoom/ZoomComponent":385}],291:[function(require,module,exports){
22905 Object.defineProperty(exports, "__esModule", { value: true });
22906 var EdgeDirection_1 = require("./graph/edge/EdgeDirection");
22907 exports.EdgeDirection = EdgeDirection_1.EdgeDirection;
22908 var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings");
22909 exports.EdgeCalculatorSettings = EdgeCalculatorSettings_1.EdgeCalculatorSettings;
22910 var EdgeCalculatorDirections_1 = require("./graph/edge/EdgeCalculatorDirections");
22911 exports.EdgeCalculatorDirections = EdgeCalculatorDirections_1.EdgeCalculatorDirections;
22912 var EdgeCalculatorCoefficients_1 = require("./graph/edge/EdgeCalculatorCoefficients");
22913 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculatorCoefficients;
22914 var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator");
22915 exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator;
22917 },{"./graph/edge/EdgeCalculator":405,"./graph/edge/EdgeCalculatorCoefficients":406,"./graph/edge/EdgeCalculatorDirections":407,"./graph/edge/EdgeCalculatorSettings":408,"./graph/edge/EdgeDirection":409}],292:[function(require,module,exports){
22919 Object.defineProperty(exports, "__esModule", { value: true });
22920 var AbortMapillaryError_1 = require("./error/AbortMapillaryError");
22921 exports.AbortMapillaryError = AbortMapillaryError_1.AbortMapillaryError;
22922 var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError");
22923 exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError;
22924 var GraphMapillaryError_1 = require("./error/GraphMapillaryError");
22925 exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError;
22926 var MapillaryError_1 = require("./error/MapillaryError");
22927 exports.MapillaryError = MapillaryError_1.MapillaryError;
22929 },{"./error/AbortMapillaryError":386,"./error/ArgumentMapillaryError":387,"./error/GraphMapillaryError":388,"./error/MapillaryError":389}],293:[function(require,module,exports){
22931 Object.defineProperty(exports, "__esModule", { value: true });
22932 var Camera_1 = require("./geo/Camera");
22933 exports.Camera = Camera_1.Camera;
22934 var GeoCoords_1 = require("./geo/GeoCoords");
22935 exports.GeoCoords = GeoCoords_1.GeoCoords;
22936 var ViewportCoords_1 = require("./geo/ViewportCoords");
22937 exports.ViewportCoords = ViewportCoords_1.ViewportCoords;
22938 var Spatial_1 = require("./geo/Spatial");
22939 exports.Spatial = Spatial_1.Spatial;
22940 var Transform_1 = require("./geo/Transform");
22941 exports.Transform = Transform_1.Transform;
22943 },{"./geo/Camera":390,"./geo/GeoCoords":391,"./geo/Spatial":392,"./geo/Transform":393,"./geo/ViewportCoords":394}],294:[function(require,module,exports){
22945 Object.defineProperty(exports, "__esModule", { value: true });
22946 var FilterCreator_1 = require("./graph/FilterCreator");
22947 exports.FilterCreator = FilterCreator_1.FilterCreator;
22948 var Graph_1 = require("./graph/Graph");
22949 exports.Graph = Graph_1.Graph;
22950 var GraphCalculator_1 = require("./graph/GraphCalculator");
22951 exports.GraphCalculator = GraphCalculator_1.GraphCalculator;
22952 var GraphMode_1 = require("./graph/GraphMode");
22953 exports.GraphMode = GraphMode_1.GraphMode;
22954 var GraphService_1 = require("./graph/GraphService");
22955 exports.GraphService = GraphService_1.GraphService;
22956 var ImageLoadingService_1 = require("./graph/ImageLoadingService");
22957 exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService;
22958 var MeshReader_1 = require("./graph/MeshReader");
22959 exports.MeshReader = MeshReader_1.MeshReader;
22960 var Node_1 = require("./graph/Node");
22961 exports.Node = Node_1.Node;
22962 var NodeCache_1 = require("./graph/NodeCache");
22963 exports.NodeCache = NodeCache_1.NodeCache;
22964 var Sequence_1 = require("./graph/Sequence");
22965 exports.Sequence = Sequence_1.Sequence;
22967 },{"./graph/FilterCreator":395,"./graph/Graph":396,"./graph/GraphCalculator":397,"./graph/GraphMode":398,"./graph/GraphService":399,"./graph/ImageLoadingService":400,"./graph/MeshReader":401,"./graph/Node":402,"./graph/NodeCache":403,"./graph/Sequence":404}],295:[function(require,module,exports){
22970 * MapillaryJS is a WebGL JavaScript library for exploring street level imagery
22973 function __export(m) {
22974 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
22976 Object.defineProperty(exports, "__esModule", { value: true });
22977 __export(require("./Support"));
22978 var Edge_1 = require("./Edge");
22979 exports.EdgeDirection = Edge_1.EdgeDirection;
22980 var Error_1 = require("./Error");
22981 exports.AbortMapillaryError = Error_1.AbortMapillaryError;
22982 var Render_1 = require("./Render");
22983 exports.RenderMode = Render_1.RenderMode;
22984 var State_1 = require("./State");
22985 exports.TransitionMode = State_1.TransitionMode;
22986 var Viewer_1 = require("./Viewer");
22987 exports.Alignment = Viewer_1.Alignment;
22988 exports.ImageSize = Viewer_1.ImageSize;
22989 exports.Viewer = Viewer_1.Viewer;
22990 var Component_1 = require("./Component");
22991 exports.SliderMode = Component_1.SliderMode;
22992 var TagComponent = require("./component/tag/Tag");
22993 exports.TagComponent = TagComponent;
22994 var MarkerComponent = require("./component/marker/Marker");
22995 exports.MarkerComponent = MarkerComponent;
22996 var PopupComponent = require("./component/popup/Popup");
22997 exports.PopupComponent = PopupComponent;
22999 },{"./Component":290,"./Edge":291,"./Error":292,"./Render":296,"./State":297,"./Support":298,"./Viewer":301,"./component/marker/Marker":330,"./component/popup/Popup":343,"./component/tag/Tag":353}],296:[function(require,module,exports){
23001 Object.defineProperty(exports, "__esModule", { value: true });
23002 var DOMRenderer_1 = require("./render/DOMRenderer");
23003 exports.DOMRenderer = DOMRenderer_1.DOMRenderer;
23004 var GLRenderer_1 = require("./render/GLRenderer");
23005 exports.GLRenderer = GLRenderer_1.GLRenderer;
23006 var GLRenderStage_1 = require("./render/GLRenderStage");
23007 exports.GLRenderStage = GLRenderStage_1.GLRenderStage;
23008 var RenderCamera_1 = require("./render/RenderCamera");
23009 exports.RenderCamera = RenderCamera_1.RenderCamera;
23010 var RenderMode_1 = require("./render/RenderMode");
23011 exports.RenderMode = RenderMode_1.RenderMode;
23012 var RenderService_1 = require("./render/RenderService");
23013 exports.RenderService = RenderService_1.RenderService;
23015 },{"./render/DOMRenderer":410,"./render/GLRenderStage":411,"./render/GLRenderer":412,"./render/RenderCamera":413,"./render/RenderMode":414,"./render/RenderService":415}],297:[function(require,module,exports){
23017 Object.defineProperty(exports, "__esModule", { value: true });
23018 var RotationDelta_1 = require("./state/RotationDelta");
23019 exports.RotationDelta = RotationDelta_1.RotationDelta;
23020 var State_1 = require("./state/State");
23021 exports.State = State_1.State;
23022 var StateBase_1 = require("./state/states/StateBase");
23023 exports.StateBase = StateBase_1.StateBase;
23024 var StateContext_1 = require("./state/StateContext");
23025 exports.StateContext = StateContext_1.StateContext;
23026 var StateService_1 = require("./state/StateService");
23027 exports.StateService = StateService_1.StateService;
23028 var TransitionMode_1 = require("./state/TransitionMode");
23029 exports.TransitionMode = TransitionMode_1.TransitionMode;
23030 var InteractiveStateBase_1 = require("./state/states/InteractiveStateBase");
23031 exports.InteractiveStateBase = InteractiveStateBase_1.InteractiveStateBase;
23032 var InteractiveWaitingState_1 = require("./state/states/InteractiveWaitingState");
23033 exports.InteractiveWaitingState = InteractiveWaitingState_1.InteractiveWaitingState;
23034 var TraversingState_1 = require("./state/states/TraversingState");
23035 exports.TraversingState = TraversingState_1.TraversingState;
23036 var WaitingState_1 = require("./state/states/WaitingState");
23037 exports.WaitingState = WaitingState_1.WaitingState;
23039 },{"./state/RotationDelta":416,"./state/State":417,"./state/StateContext":418,"./state/StateService":419,"./state/TransitionMode":420,"./state/states/InteractiveStateBase":421,"./state/states/InteractiveWaitingState":422,"./state/states/StateBase":423,"./state/states/TraversingState":424,"./state/states/WaitingState":425}],298:[function(require,module,exports){
23041 Object.defineProperty(exports, "__esModule", { value: true });
23042 var support = require("./utils/Support");
23044 * Test whether the current browser supports the full
23045 * functionality of MapillaryJS.
23047 * @description The full functionality includes WebGL rendering.
23049 * @return {boolean}
23051 * @example `var supported = Mapillary.isSupported();`
23053 function isSupported() {
23054 return isFallbackSupported() &&
23055 support.isWebGLSupportedCached();
23057 exports.isSupported = isSupported;
23059 * Test whether the current browser supports the fallback
23060 * functionality of MapillaryJS.
23062 * @description The fallback functionality does not include WebGL
23063 * rendering, only 2D canvas rendering.
23065 * @return {boolean}
23067 * @example `var fallbackSupported = Mapillary.isFallbackSupported();`
23069 function isFallbackSupported() {
23070 return support.isBrowser() &&
23071 support.isBlobSupported() &&
23072 support.isArraySupported() &&
23073 support.isFunctionSupported() &&
23074 support.isJSONSupported() &&
23075 support.isObjectSupported();
23077 exports.isFallbackSupported = isFallbackSupported;
23079 },{"./utils/Support":433}],299:[function(require,module,exports){
23081 Object.defineProperty(exports, "__esModule", { value: true });
23082 var ImageTileLoader_1 = require("./tiles/ImageTileLoader");
23083 exports.ImageTileLoader = ImageTileLoader_1.ImageTileLoader;
23084 var ImageTileStore_1 = require("./tiles/ImageTileStore");
23085 exports.ImageTileStore = ImageTileStore_1.ImageTileStore;
23086 var TextureProvider_1 = require("./tiles/TextureProvider");
23087 exports.TextureProvider = TextureProvider_1.TextureProvider;
23088 var RegionOfInterestCalculator_1 = require("./tiles/RegionOfInterestCalculator");
23089 exports.RegionOfInterestCalculator = RegionOfInterestCalculator_1.RegionOfInterestCalculator;
23091 },{"./tiles/ImageTileLoader":426,"./tiles/ImageTileStore":427,"./tiles/RegionOfInterestCalculator":428,"./tiles/TextureProvider":429}],300:[function(require,module,exports){
23093 function __export(m) {
23094 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
23096 Object.defineProperty(exports, "__esModule", { value: true });
23097 var DOM_1 = require("./utils/DOM");
23098 exports.DOM = DOM_1.DOM;
23099 var EventEmitter_1 = require("./utils/EventEmitter");
23100 exports.EventEmitter = EventEmitter_1.EventEmitter;
23101 var Settings_1 = require("./utils/Settings");
23102 exports.Settings = Settings_1.Settings;
23103 __export(require("./utils/Support"));
23104 var Urls_1 = require("./utils/Urls");
23105 exports.Urls = Urls_1.Urls;
23107 },{"./utils/DOM":430,"./utils/EventEmitter":431,"./utils/Settings":432,"./utils/Support":433,"./utils/Urls":434}],301:[function(require,module,exports){
23109 Object.defineProperty(exports, "__esModule", { value: true });
23110 var Alignment_1 = require("./viewer/Alignment");
23111 exports.Alignment = Alignment_1.Alignment;
23112 var CacheService_1 = require("./viewer/CacheService");
23113 exports.CacheService = CacheService_1.CacheService;
23114 var ComponentController_1 = require("./viewer/ComponentController");
23115 exports.ComponentController = ComponentController_1.ComponentController;
23116 var Container_1 = require("./viewer/Container");
23117 exports.Container = Container_1.Container;
23118 var Observer_1 = require("./viewer/Observer");
23119 exports.Observer = Observer_1.Observer;
23120 var ImageSize_1 = require("./viewer/ImageSize");
23121 exports.ImageSize = ImageSize_1.ImageSize;
23122 var KeyboardService_1 = require("./viewer/KeyboardService");
23123 exports.KeyboardService = KeyboardService_1.KeyboardService;
23124 var LoadingService_1 = require("./viewer/LoadingService");
23125 exports.LoadingService = LoadingService_1.LoadingService;
23126 var MouseService_1 = require("./viewer/MouseService");
23127 exports.MouseService = MouseService_1.MouseService;
23128 var Navigator_1 = require("./viewer/Navigator");
23129 exports.Navigator = Navigator_1.Navigator;
23130 var PlayService_1 = require("./viewer/PlayService");
23131 exports.PlayService = PlayService_1.PlayService;
23132 var Projection_1 = require("./viewer/Projection");
23133 exports.Projection = Projection_1.Projection;
23134 var SpriteService_1 = require("./viewer/SpriteService");
23135 exports.SpriteService = SpriteService_1.SpriteService;
23136 var TouchService_1 = require("./viewer/TouchService");
23137 exports.TouchService = TouchService_1.TouchService;
23138 var Viewer_1 = require("./viewer/Viewer");
23139 exports.Viewer = Viewer_1.Viewer;
23141 },{"./viewer/Alignment":435,"./viewer/CacheService":436,"./viewer/ComponentController":437,"./viewer/Container":438,"./viewer/ImageSize":439,"./viewer/KeyboardService":440,"./viewer/LoadingService":441,"./viewer/MouseService":442,"./viewer/Navigator":443,"./viewer/Observer":444,"./viewer/PlayService":445,"./viewer/Projection":446,"./viewer/SpriteService":447,"./viewer/TouchService":448,"./viewer/Viewer":449}],302:[function(require,module,exports){
23143 /// <reference path="../../typings/index.d.ts" />
23144 Object.defineProperty(exports, "__esModule", { value: true });
23145 var Observable_1 = require("rxjs/Observable");
23146 var API_1 = require("../API");
23150 * @classdesc Provides methods for access of API v3.
23152 var APIv3 = /** @class */ (function () {
23154 * Create a new api v3 instance.
23156 * @param {number} clientId - Client id for API requests.
23157 * @param {number} [token] - Optional bearer token for API requests of
23158 * protected resources.
23159 * @param {ModelCreator} [creator] - Optional model creator instance.
23161 function APIv3(clientId, token, creator) {
23162 this._clientId = clientId;
23163 this._modelCreator = creator != null ? creator : new API_1.ModelCreator();
23164 this._model = this._modelCreator.createModel(clientId, token);
23165 this._pageCount = 999;
23166 this._pathImageByKey = "imageByKey";
23167 this._pathImageCloseTo = "imageCloseTo";
23168 this._pathImagesByH = "imagesByH";
23169 this._pathImageViewAdd = "imageViewAdd";
23170 this._pathSequenceByKey = "sequenceByKey";
23171 this._pathSequenceViewAdd = "sequenceViewAdd";
23172 this._propertiesCore = [
23177 this._propertiesFill = [
23179 "captured_with_camera_uuid",
23181 "organization_key",
23185 this._propertiesKey = [
23188 this._propertiesSequence = [
23191 this._propertiesSpatial = [
23205 this._propertiesUser = [
23209 APIv3.prototype.imageByKeyFill$ = function (keys) {
23210 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
23211 this._pathImageByKey,
23213 this._propertiesKey
23214 .concat(this._propertiesFill)
23215 .concat(this._propertiesSpatial),
23216 this._propertiesKey
23217 .concat(this._propertiesUser)
23219 .map(function (value) {
23221 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
23223 return value.json.imageByKey;
23224 }), this._pathImageByKey, keys);
23226 APIv3.prototype.imageByKeyFull$ = function (keys) {
23227 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
23228 this._pathImageByKey,
23230 this._propertiesKey
23231 .concat(this._propertiesCore)
23232 .concat(this._propertiesFill)
23233 .concat(this._propertiesSpatial),
23234 this._propertiesKey
23235 .concat(this._propertiesUser)
23237 .map(function (value) {
23239 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
23241 return value.json.imageByKey;
23242 }), this._pathImageByKey, keys);
23244 APIv3.prototype.imageCloseTo$ = function (lat, lon) {
23245 var lonLat = lon + ":" + lat;
23246 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
23247 this._pathImageCloseTo,
23249 this._propertiesKey
23250 .concat(this._propertiesCore)
23251 .concat(this._propertiesFill)
23252 .concat(this._propertiesSpatial),
23253 this._propertiesKey
23254 .concat(this._propertiesUser)
23256 .map(function (value) {
23257 return value != null ? value.json.imageCloseTo[lonLat] : null;
23258 }), this._pathImageCloseTo, [lonLat]);
23260 APIv3.prototype.imagesByH$ = function (hs) {
23262 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
23263 this._pathImagesByH,
23265 { from: 0, to: this._pageCount },
23266 this._propertiesKey
23267 .concat(this._propertiesCore)
23269 .map(function (value) {
23271 value = { json: { imagesByH: {} } };
23272 for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) {
23274 value.json.imagesByH[h] = {};
23275 for (var i = 0; i <= _this._pageCount; i++) {
23276 value.json.imagesByH[h][i] = null;
23280 return value.json.imagesByH;
23281 }), this._pathImagesByH, hs);
23283 APIv3.prototype.imageViewAdd$ = function (keys) {
23284 return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys);
23286 APIv3.prototype.invalidateImageByKey = function (keys) {
23287 this._invalidateGet(this._pathImageByKey, keys);
23289 APIv3.prototype.invalidateImagesByH = function (hs) {
23290 this._invalidateGet(this._pathImagesByH, hs);
23292 APIv3.prototype.invalidateSequenceByKey = function (sKeys) {
23293 this._invalidateGet(this._pathSequenceByKey, sKeys);
23295 APIv3.prototype.setToken = function (token) {
23296 this._model.invalidate([]);
23297 this._model = null;
23298 this._model = this._modelCreator.createModel(this._clientId, token);
23300 APIv3.prototype.sequenceByKey$ = function (sequenceKeys) {
23301 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
23302 this._pathSequenceByKey,
23304 this._propertiesKey
23305 .concat(this._propertiesSequence)
23307 .map(function (value) {
23309 value = { json: { sequenceByKey: {} } };
23311 for (var _i = 0, sequenceKeys_1 = sequenceKeys; _i < sequenceKeys_1.length; _i++) {
23312 var sequenceKey = sequenceKeys_1[_i];
23313 if (!(sequenceKey in value.json.sequenceByKey)) {
23314 console.warn("Sequence data missing (" + sequenceKey + ")");
23315 value.json.sequenceByKey[sequenceKey] = { key: sequenceKey, keys: [] };
23318 return value.json.sequenceByKey;
23319 }), this._pathSequenceByKey, sequenceKeys);
23321 APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) {
23322 return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys);
23324 Object.defineProperty(APIv3.prototype, "clientId", {
23326 return this._clientId;
23331 APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) {
23334 .catch(function (error) {
23335 _this._invalidateGet(path, paths);
23339 APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) {
23342 .catch(function (error) {
23343 _this._invalidateCall(path, paths);
23347 APIv3.prototype._invalidateGet = function (path, paths) {
23348 this._model.invalidate([path, paths]);
23350 APIv3.prototype._invalidateCall = function (path, paths) {
23351 this._model.invalidate([path], [paths]);
23353 APIv3.prototype._wrapPromise$ = function (promise) {
23354 return Observable_1.Observable.defer(function () { return Observable_1.Observable.fromPromise(promise); });
23358 exports.APIv3 = APIv3;
23359 exports.default = APIv3;
23361 },{"../API":289,"rxjs/Observable":29}],303:[function(require,module,exports){
23363 /// <reference path="../../typings/index.d.ts" />
23364 Object.defineProperty(exports, "__esModule", { value: true });
23365 var falcor = require("falcor");
23366 var HttpDataSource = require("falcor-http-datasource");
23367 var Utils_1 = require("../Utils");
23369 * @class ModelCreator
23371 * @classdesc Creates API models.
23373 var ModelCreator = /** @class */ (function () {
23374 function ModelCreator() {
23377 * Creates a Falcor model.
23379 * @description Max cache size will be set to 16 MB. Authorization
23380 * header will be added if bearer token is supplied.
23382 * @param {number} clientId - Client id for API requests.
23383 * @param {number} [token] - Optional bearer token for API requests of
23384 * protected resources.
23385 * @returns {falcor.Model} Falcor model for HTTP requests.
23387 ModelCreator.prototype.createModel = function (clientId, token) {
23388 var configuration = {
23390 withCredentials: false,
23392 if (token != null) {
23393 configuration.headers = { "Authorization": "Bearer " + token };
23395 return new falcor.Model({
23396 maxSize: 16 * 1024 * 1024,
23397 source: new HttpDataSource(Utils_1.Urls.falcorModel(clientId), configuration),
23400 return ModelCreator;
23402 exports.ModelCreator = ModelCreator;
23403 exports.default = ModelCreator;
23405 },{"../Utils":300,"falcor":15,"falcor-http-datasource":10}],304:[function(require,module,exports){
23407 /// <reference path="../../typings/index.d.ts" />
23408 var __extends = (this && this.__extends) || (function () {
23409 var extendStatics = Object.setPrototypeOf ||
23410 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23411 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23412 return function (d, b) {
23413 extendStatics(d, b);
23414 function __() { this.constructor = d; }
23415 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23418 Object.defineProperty(exports, "__esModule", { value: true });
23419 var vd = require("virtual-dom");
23420 var Observable_1 = require("rxjs/Observable");
23421 var Component_1 = require("../Component");
23422 var Utils_1 = require("../Utils");
23423 var AttributionComponent = /** @class */ (function (_super) {
23424 __extends(AttributionComponent, _super);
23425 function AttributionComponent(name, container, navigator) {
23426 return _super.call(this, name, container, navigator) || this;
23428 AttributionComponent.prototype._activate = function () {
23430 this._disposable = Observable_1.Observable
23431 .combineLatest(this._navigator.stateService.currentNode$, this._container.renderService.size$)
23432 .map(function (_a) {
23433 var node = _a[0], size = _a[1];
23436 vnode: _this._getAttributionNode(node.username, node.key, node.capturedAt, size.width),
23439 .subscribe(this._container.domRenderer.render$);
23441 AttributionComponent.prototype._deactivate = function () {
23442 this._disposable.unsubscribe();
23444 AttributionComponent.prototype._getDefaultConfiguration = function () {
23447 AttributionComponent.prototype._getAttributionNode = function (username, key, capturedAt, width) {
23448 var compact = width <= 640;
23449 var mapillaryIcon = vd.h("div.AttributionMapillaryLogo", []);
23450 var mapillaryLink = vd.h("a.AttributionIconContainer", { href: Utils_1.Urls.explore, target: "_blank" }, [mapillaryIcon]);
23451 var imageBy = compact ? "" + username : "image by " + username;
23452 var imageByContent = vd.h("div.AttributionUsername", { textContent: imageBy }, []);
23453 var date = new Date(capturedAt).toDateString().split(" ");
23454 var formatted = (date.length > 3 ?
23457 [date[1], date[2] + ",", date[3]] :
23459 var dateContent = vd.h("div.AttributionDate", { textContent: formatted }, []);
23460 var imageLink = vd.h("a.AttributionImageContainer", { href: Utils_1.Urls.exporeImage(key), target: "_blank" }, [imageByContent, dateContent]);
23461 var compactClass = compact ? ".AttributionCompact" : "";
23462 return vd.h("div.AttributionContainer" + compactClass, {}, [mapillaryLink, imageLink]);
23464 AttributionComponent.componentName = "attribution";
23465 return AttributionComponent;
23466 }(Component_1.Component));
23467 exports.AttributionComponent = AttributionComponent;
23468 Component_1.ComponentService.register(AttributionComponent);
23469 exports.default = AttributionComponent;
23471 },{"../Component":290,"../Utils":300,"rxjs/Observable":29,"virtual-dom":246}],305:[function(require,module,exports){
23473 /// <reference path="../../typings/index.d.ts" />
23474 var __extends = (this && this.__extends) || (function () {
23475 var extendStatics = Object.setPrototypeOf ||
23476 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23477 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23478 return function (d, b) {
23479 extendStatics(d, b);
23480 function __() { this.constructor = d; }
23481 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23484 Object.defineProperty(exports, "__esModule", { value: true });
23485 var vd = require("virtual-dom");
23486 var Component_1 = require("../Component");
23487 var BackgroundComponent = /** @class */ (function (_super) {
23488 __extends(BackgroundComponent, _super);
23489 function BackgroundComponent(name, container, navigator) {
23490 return _super.call(this, name, container, navigator) || this;
23492 BackgroundComponent.prototype._activate = function () {
23493 this._container.domRenderer.render$
23494 .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given image.") });
23496 BackgroundComponent.prototype._deactivate = function () {
23499 BackgroundComponent.prototype._getDefaultConfiguration = function () {
23502 BackgroundComponent.prototype._getBackgroundNode = function (notice) {
23503 // todo: add condition for when to display the DOM node
23504 return vd.h("div.BackgroundWrapper", {}, [
23505 vd.h("p", { textContent: notice }, []),
23508 BackgroundComponent.componentName = "background";
23509 return BackgroundComponent;
23510 }(Component_1.Component));
23511 exports.BackgroundComponent = BackgroundComponent;
23512 Component_1.ComponentService.register(BackgroundComponent);
23513 exports.default = BackgroundComponent;
23515 },{"../Component":290,"virtual-dom":246}],306:[function(require,module,exports){
23517 /// <reference path="../../typings/index.d.ts" />
23518 var __extends = (this && this.__extends) || (function () {
23519 var extendStatics = Object.setPrototypeOf ||
23520 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23521 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23522 return function (d, b) {
23523 extendStatics(d, b);
23524 function __() { this.constructor = d; }
23525 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23528 Object.defineProperty(exports, "__esModule", { value: true });
23529 var vd = require("virtual-dom");
23530 var Component_1 = require("../Component");
23531 var Geo_1 = require("../Geo");
23532 var BearingComponent = /** @class */ (function (_super) {
23533 __extends(BearingComponent, _super);
23534 function BearingComponent(name, container, navigator) {
23535 var _this = _super.call(this, name, container, navigator) || this;
23536 _this._spatial = new Geo_1.Spatial();
23537 _this._svgNamespace = "http://www.w3.org/2000/svg";
23538 _this._distinctThreshold = Math.PI / 360;
23541 BearingComponent.prototype._activate = function () {
23543 var cameraBearingFov$ = this._container.renderService.renderCamera$
23544 .map(function (rc) {
23545 var vFov = _this._spatial.degToRad(rc.perspective.fov);
23546 var hFov = rc.perspective.aspect === Number.POSITIVE_INFINITY ?
23548 Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2;
23549 return [_this._spatial.azimuthalToBearing(rc.rotation.phi), hFov];
23551 .distinctUntilChanged(function (a1, a2) {
23552 return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
23553 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
23555 this._renderSubscription = cameraBearingFov$
23556 .map(function (_a) {
23557 var bearing = _a[0], fov = _a[1];
23558 var background = vd.h("div.BearingIndicatorBackground", {}, []);
23559 var backgroundCircle = vd.h("div.BearingIndicatorBackgroundCircle", {}, []);
23560 var north = _this._createNorth(bearing);
23561 var cameraSector = _this._createCircleSectorCompass(_this._createCircleSector(Math.max(Math.PI / 20, fov), "#FFF"));
23564 vnode: vd.h("div.BearingIndicatorContainer", { oncontextmenu: function (event) { event.preventDefault(); } }, [
23572 .subscribe(this._container.domRenderer.render$);
23574 BearingComponent.prototype._deactivate = function () {
23575 this._renderSubscription.unsubscribe();
23577 BearingComponent.prototype._getDefaultConfiguration = function () {
23580 BearingComponent.prototype._createCircleSectorCompass = function (cameraSector) {
23581 var group = vd.h("g", {
23582 attributes: { transform: "translate(1,1)" },
23583 namespace: this._svgNamespace,
23584 }, [cameraSector]);
23585 var svg = vd.h("svg", {
23586 attributes: { viewBox: "0 0 2 2" },
23587 namespace: this._svgNamespace,
23591 position: "absolute",
23598 BearingComponent.prototype._createCircleSector = function (fov, fill) {
23599 if (fov > 2 * Math.PI - Math.PI / 90) {
23600 return vd.h("circle", {
23601 attributes: { cx: "0", cy: "0", fill: fill, r: "1" },
23602 namespace: this._svgNamespace,
23605 var arcStart = -Math.PI / 2 - fov / 2;
23606 var arcEnd = arcStart + fov;
23607 var startX = Math.cos(arcStart);
23608 var startY = Math.sin(arcStart);
23609 var endX = Math.cos(arcEnd);
23610 var endY = Math.sin(arcEnd);
23611 var largeArc = fov >= Math.PI ? 1 : 0;
23612 var description = "M 0 0 " + startX + " " + startY + " A 1 1 0 " + largeArc + " 1 " + endX + " " + endY;
23613 return vd.h("path", {
23614 attributes: { d: description, fill: fill },
23615 namespace: this._svgNamespace,
23618 BearingComponent.prototype._createNorth = function (bearing) {
23619 var north = vd.h("div.BearingNorth", []);
23620 var container = vd.h("div.BearingNorthContainer", { style: { transform: "rotateZ(" + -bearing * 180 / Math.PI + "deg)" } }, [north]);
23623 BearingComponent.componentName = "bearing";
23624 return BearingComponent;
23625 }(Component_1.Component));
23626 exports.BearingComponent = BearingComponent;
23627 Component_1.ComponentService.register(BearingComponent);
23628 exports.default = BearingComponent;
23630 },{"../Component":290,"../Geo":293,"virtual-dom":246}],307:[function(require,module,exports){
23632 var __extends = (this && this.__extends) || (function () {
23633 var extendStatics = Object.setPrototypeOf ||
23634 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23635 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23636 return function (d, b) {
23637 extendStatics(d, b);
23638 function __() { this.constructor = d; }
23639 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23642 Object.defineProperty(exports, "__esModule", { value: true });
23643 var Observable_1 = require("rxjs/Observable");
23644 var Edge_1 = require("../Edge");
23645 var Component_1 = require("../Component");
23646 var CacheComponent = /** @class */ (function (_super) {
23647 __extends(CacheComponent, _super);
23648 function CacheComponent(name, container, navigator) {
23649 return _super.call(this, name, container, navigator) || this;
23652 * Set the cache depth.
23654 * Configures the cache depth. The cache depth can be different for
23655 * different edge direction types.
23657 * @param {ICacheDepth} depth - Cache depth structure.
23659 CacheComponent.prototype.setDepth = function (depth) {
23660 this.configure({ depth: depth });
23662 CacheComponent.prototype._activate = function () {
23664 this._sequenceSubscription = Observable_1.Observable
23665 .combineLatest(this._navigator.stateService.currentNode$
23666 .switchMap(function (node) {
23667 return node.sequenceEdges$;
23669 .filter(function (status) {
23670 return status.cached;
23671 }), this._configuration$)
23672 .switchMap(function (nc) {
23673 var status = nc[0];
23674 var configuration = nc[1];
23675 var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence));
23676 var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth);
23677 var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth);
23678 return Observable_1.Observable
23679 .merge(next$, prev$)
23680 .catch(function (error, caught) {
23681 console.error("Failed to cache sequence edges.", error);
23682 return Observable_1.Observable.empty();
23685 .subscribe(function () { });
23686 this._spatialSubscription = this._navigator.stateService.currentNode$
23687 .switchMap(function (node) {
23688 return Observable_1.Observable
23689 .combineLatest(Observable_1.Observable.of(node), node.spatialEdges$
23690 .filter(function (status) {
23691 return status.cached;
23694 .combineLatest(this._configuration$, function (ns, configuration) {
23695 return [ns[0], ns[1], configuration];
23697 .switchMap(function (args) {
23698 var node = args[0];
23699 var edges = args[1].edges;
23700 var depth = args[2].depth;
23701 var panoDepth = Math.max(0, Math.min(2, depth.pano));
23702 var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step));
23703 var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn));
23704 var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth);
23705 var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth);
23706 var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth);
23707 var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth);
23708 var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth);
23709 var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth);
23710 var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth);
23711 var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth);
23712 return Observable_1.Observable
23713 .merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$)
23714 .catch(function (error, caught) {
23715 console.error("Failed to cache spatial edges.", error);
23716 return Observable_1.Observable.empty();
23719 .subscribe(function () { });
23721 CacheComponent.prototype._deactivate = function () {
23722 this._sequenceSubscription.unsubscribe();
23723 this._spatialSubscription.unsubscribe();
23725 CacheComponent.prototype._getDefaultConfiguration = function () {
23726 return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } };
23728 CacheComponent.prototype._cache$ = function (edges, direction, depth) {
23730 return Observable_1.Observable
23731 .zip(Observable_1.Observable.of(edges), Observable_1.Observable.of(depth))
23732 .expand(function (ed) {
23735 var edgesDepths$ = [];
23737 for (var _i = 0, es_1 = es; _i < es_1.length; _i++) {
23738 var edge = es_1[_i];
23739 if (edge.data.direction === direction) {
23740 edgesDepths$.push(Observable_1.Observable
23741 .zip(_this._navigator.graphService.cacheNode$(edge.to)
23742 .mergeMap(function (n) {
23743 return _this._nodeToEdges$(n, direction);
23744 }), Observable_1.Observable.of(d - 1)));
23748 return Observable_1.Observable
23749 .from(edgesDepths$)
23754 CacheComponent.prototype._nodeToEdges$ = function (node, direction) {
23755 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
23756 node.sequenceEdges$ :
23757 node.spatialEdges$)
23758 .first(function (status) {
23759 return status.cached;
23761 .map(function (status) {
23762 return status.edges;
23765 CacheComponent.componentName = "cache";
23766 return CacheComponent;
23767 }(Component_1.Component));
23768 exports.CacheComponent = CacheComponent;
23769 Component_1.ComponentService.register(CacheComponent);
23770 exports.default = CacheComponent;
23772 },{"../Component":290,"../Edge":291,"rxjs/Observable":29}],308:[function(require,module,exports){
23774 var __extends = (this && this.__extends) || (function () {
23775 var extendStatics = Object.setPrototypeOf ||
23776 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23777 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23778 return function (d, b) {
23779 extendStatics(d, b);
23780 function __() { this.constructor = d; }
23781 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23784 Object.defineProperty(exports, "__esModule", { value: true });
23785 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
23786 var Subject_1 = require("rxjs/Subject");
23787 var Utils_1 = require("../Utils");
23788 var Component = /** @class */ (function (_super) {
23789 __extends(Component, _super);
23790 function Component(name, container, navigator) {
23791 var _this = _super.call(this) || this;
23792 _this._activated$ = new BehaviorSubject_1.BehaviorSubject(false);
23793 _this._configurationSubject$ = new Subject_1.Subject();
23794 _this._activated = false;
23795 _this._container = container;
23796 _this._name = name;
23797 _this._navigator = navigator;
23798 _this._configuration$ =
23799 _this._configurationSubject$
23800 .startWith(_this.defaultConfiguration)
23801 .scan(function (conf, newConf) {
23802 for (var key in newConf) {
23803 if (newConf.hasOwnProperty(key)) {
23804 conf[key] = newConf[key];
23811 _this._configuration$.subscribe(function () { });
23814 Object.defineProperty(Component.prototype, "activated", {
23816 return this._activated;
23821 Object.defineProperty(Component.prototype, "activated$", {
23823 return this._activated$;
23828 Object.defineProperty(Component.prototype, "defaultConfiguration", {
23830 * Get default configuration.
23832 * @returns {TConfiguration} Default configuration for component.
23835 return this._getDefaultConfiguration();
23840 Object.defineProperty(Component.prototype, "configuration$", {
23842 return this._configuration$;
23847 Object.defineProperty(Component.prototype, "name", {
23854 Component.prototype.activate = function (conf) {
23855 if (this._activated) {
23858 if (conf !== undefined) {
23859 this._configurationSubject$.next(conf);
23861 this._activated = true;
23863 this._activated$.next(true);
23865 Component.prototype.configure = function (conf) {
23866 this._configurationSubject$.next(conf);
23868 Component.prototype.deactivate = function () {
23869 if (!this._activated) {
23872 this._activated = false;
23873 this._deactivate();
23874 this._container.domRenderer.clear(this._name);
23875 this._container.glRenderer.clear(this._name);
23876 this._activated$.next(false);
23879 * Detect the viewer's new width and height and resize the component's
23880 * rendered elements accordingly if applicable.
23882 Component.prototype.resize = function () { return; };
23884 * Component name. Used when interacting with component through the Viewer's API.
23886 Component.componentName = "not_worthy";
23888 }(Utils_1.EventEmitter));
23889 exports.Component = Component;
23890 exports.default = Component;
23892 },{"../Utils":300,"rxjs/BehaviorSubject":26,"rxjs/Subject":34}],309:[function(require,module,exports){
23894 /// <reference path="../../typings/index.d.ts" />
23895 Object.defineProperty(exports, "__esModule", { value: true });
23896 var _ = require("underscore");
23897 var Error_1 = require("../Error");
23898 var ComponentService = /** @class */ (function () {
23899 function ComponentService(container, navigator) {
23900 this._components = {};
23901 for (var _i = 0, _a = _.values(ComponentService.registeredComponents); _i < _a.length; _i++) {
23902 var component = _a[_i];
23903 this._components[component.componentName] = {
23905 component: new component(component.componentName, container, navigator),
23908 this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator);
23909 this._coverComponent.activate();
23910 this._coverActivated = true;
23912 ComponentService.register = function (component) {
23913 if (ComponentService.registeredComponents[component.componentName] === undefined) {
23914 ComponentService.registeredComponents[component.componentName] = component;
23917 ComponentService.registerCover = function (coverComponent) {
23918 ComponentService.registeredCoverComponent = coverComponent;
23920 Object.defineProperty(ComponentService.prototype, "coverActivated", {
23922 return this._coverActivated;
23927 ComponentService.prototype.activateCover = function () {
23928 if (this._coverActivated) {
23931 this._coverActivated = true;
23932 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
23933 var component = _a[_i];
23934 if (component.active) {
23935 component.component.deactivate();
23940 ComponentService.prototype.deactivateCover = function () {
23941 if (!this._coverActivated) {
23944 this._coverActivated = false;
23945 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
23946 var component = _a[_i];
23947 if (component.active) {
23948 component.component.activate();
23953 ComponentService.prototype.activate = function (name) {
23954 this._checkName(name);
23955 this._components[name].active = true;
23956 if (!this._coverActivated) {
23957 this.get(name).activate();
23960 ComponentService.prototype.configure = function (name, conf) {
23961 this._checkName(name);
23962 this.get(name).configure(conf);
23964 ComponentService.prototype.deactivate = function (name) {
23965 this._checkName(name);
23966 this._components[name].active = false;
23967 if (!this._coverActivated) {
23968 this.get(name).deactivate();
23971 ComponentService.prototype.resize = function () {
23972 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
23973 var component = _a[_i];
23974 component.component.resize();
23977 ComponentService.prototype.get = function (name) {
23978 return this._components[name].component;
23980 ComponentService.prototype.getCover = function () {
23981 return this._coverComponent;
23983 ComponentService.prototype._checkName = function (name) {
23984 if (!(name in this._components)) {
23985 throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name);
23988 ComponentService.registeredComponents = {};
23989 return ComponentService;
23991 exports.ComponentService = ComponentService;
23992 exports.default = ComponentService;
23994 },{"../Error":292,"underscore":242}],310:[function(require,module,exports){
23996 /// <reference path="../../typings/index.d.ts" />
23997 var __extends = (this && this.__extends) || (function () {
23998 var extendStatics = Object.setPrototypeOf ||
23999 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24000 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24001 return function (d, b) {
24002 extendStatics(d, b);
24003 function __() { this.constructor = d; }
24004 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24007 Object.defineProperty(exports, "__esModule", { value: true });
24008 var vd = require("virtual-dom");
24009 var Observable_1 = require("rxjs/Observable");
24010 var Component_1 = require("../Component");
24011 var Utils_1 = require("../Utils");
24012 var Viewer_1 = require("../Viewer");
24013 var CoverComponent = /** @class */ (function (_super) {
24014 __extends(CoverComponent, _super);
24015 function CoverComponent(name, container, navigator) {
24016 return _super.call(this, name, container, navigator) || this;
24018 CoverComponent.prototype._activate = function () {
24020 this._configuration$
24021 .distinctUntilChanged(undefined, function (configuration) {
24022 return configuration.state;
24024 .switchMap(function (configuration) {
24025 return Observable_1.Observable
24026 .combineLatest(Observable_1.Observable.of(configuration.state), _this._navigator.stateService.currentNode$);
24028 .switchMap(function (_a) {
24029 var state = _a[0], node = _a[1];
24030 var keySrc$ = Observable_1.Observable
24031 .combineLatest(Observable_1.Observable.of(node.key), node.image$
24032 .map(function (image) {
24035 return state === Component_1.CoverState.Visible ? keySrc$.first() : keySrc$;
24037 .distinctUntilChanged(function (_a, _b) {
24038 var k1 = _a[0], s1 = _a[1];
24039 var k2 = _b[0], s2 = _b[1];
24040 return k1 === k2 && s1 === s2;
24042 .map(function (_a) {
24043 var key = _a[0], src = _a[1];
24044 return { key: key, src: src };
24046 .subscribe(this._configurationSubject$);
24047 this._renderSubscription = Observable_1.Observable
24048 .combineLatest(this._configuration$, this._container.renderService.size$)
24049 .map(function (_a) {
24050 var configuration = _a[0], size = _a[1];
24051 if (!configuration.key) {
24052 return { name: _this._name, vnode: vd.h("div", []) };
24054 var compactClass = size.width <= 640 || size.height <= 480 ? ".CoverCompact" : "";
24055 if (configuration.state === Component_1.CoverState.Hidden) {
24056 var doneContainer = vd.h("div.CoverContainer.CoverDone" + compactClass, [_this._getCoverBackgroundVNode(configuration)]);
24057 return { name: _this._name, vnode: doneContainer };
24059 var container = vd.h("div.CoverContainer" + compactClass, [_this._getCoverButtonVNode(configuration)]);
24060 return { name: _this._name, vnode: container };
24062 .subscribe(this._container.domRenderer.render$);
24064 CoverComponent.prototype._deactivate = function () {
24065 this._renderSubscription.unsubscribe();
24066 this._keySubscription.unsubscribe();
24068 CoverComponent.prototype._getDefaultConfiguration = function () {
24069 return { state: Component_1.CoverState.Visible };
24071 CoverComponent.prototype._getCoverButtonVNode = function (configuration) {
24073 var cover = configuration.state === Component_1.CoverState.Loading ? "div.Cover.CoverLoading" : "div.Cover";
24074 var coverButton = vd.h("div.CoverButton", { onclick: function () { _this.configure({ state: Component_1.CoverState.Loading }); } }, [vd.h("div.CoverButtonIcon", [])]);
24075 var coverLogo = vd.h("a.CoverLogo", { href: Utils_1.Urls.explore, target: "_blank" }, []);
24076 return vd.h(cover, [this._getCoverBackgroundVNode(configuration), coverButton, coverLogo]);
24078 CoverComponent.prototype._getCoverBackgroundVNode = function (conf) {
24079 var url = conf.src != null ?
24080 conf.src : Utils_1.Urls.thumbnail(conf.key, Viewer_1.ImageSize.Size640);
24081 var properties = { style: { backgroundImage: "url(" + url + ")" } };
24083 if (conf.state === Component_1.CoverState.Loading) {
24084 children.push(vd.h("div.Spinner", {}, []));
24086 return vd.h("div.CoverBackground", properties, children);
24088 CoverComponent.componentName = "cover";
24089 return CoverComponent;
24090 }(Component_1.Component));
24091 exports.CoverComponent = CoverComponent;
24092 Component_1.ComponentService.registerCover(CoverComponent);
24093 exports.default = CoverComponent;
24095 },{"../Component":290,"../Utils":300,"../Viewer":301,"rxjs/Observable":29,"virtual-dom":246}],311:[function(require,module,exports){
24097 /// <reference path="../../typings/index.d.ts" />
24098 var __extends = (this && this.__extends) || (function () {
24099 var extendStatics = Object.setPrototypeOf ||
24100 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24101 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24102 return function (d, b) {
24103 extendStatics(d, b);
24104 function __() { this.constructor = d; }
24105 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24108 Object.defineProperty(exports, "__esModule", { value: true });
24109 var _ = require("underscore");
24110 var vd = require("virtual-dom");
24111 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
24112 var Component_1 = require("../Component");
24113 var DebugComponent = /** @class */ (function (_super) {
24114 __extends(DebugComponent, _super);
24115 function DebugComponent() {
24116 var _this = _super !== null && _super.apply(this, arguments) || this;
24117 _this._open$ = new BehaviorSubject_1.BehaviorSubject(false);
24120 DebugComponent.prototype._activate = function () {
24122 this._disposable = this._navigator.stateService.currentState$
24123 .combineLatest(this._open$, this._navigator.imageLoadingService.loadstatus$, function (frame, open, loadStatus) {
24124 return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) };
24126 .subscribe(this._container.domRenderer.render$);
24128 DebugComponent.prototype._deactivate = function () {
24129 this._disposable.unsubscribe();
24131 DebugComponent.prototype._getDefaultConfiguration = function () {
24134 DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) {
24136 ret.push(vd.h("h2", "Node"));
24137 if (frame.state.currentNode) {
24138 ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key));
24140 if (frame.state.previousNode) {
24141 ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key));
24143 ret.push(vd.h("h2", "Loading"));
24147 for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
24148 var loadStat = _a[_i];
24149 total += loadStat.loaded;
24150 if (loadStat.loaded !== loadStat.total) {
24157 ret.push(vd.h("p", "Loaded Images: " + loaded));
24158 ret.push(vd.h("p", "Loading Images: " + loading));
24159 ret.push(vd.h("p", "Total bytes loaded: " + total));
24160 ret.push(vd.h("h2", "Camera"));
24161 ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x));
24162 ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y));
24163 ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z));
24164 ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x));
24165 ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y));
24166 ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z));
24167 ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x));
24168 ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y));
24169 ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z));
24172 DebugComponent.prototype._getDebugVNode = function (open, info) {
24174 return vd.h("div.Debug", {}, [
24175 vd.h("h2", {}, ["Debug"]),
24176 this._getDebugVNodeButton(open),
24177 vd.h("pre", {}, info),
24181 return this._getDebugVNodeButton(open);
24184 DebugComponent.prototype._getDebugVNodeButton = function (open) {
24185 var buttonText = open ? "Disable Debug" : "D";
24186 var buttonCssClass = open ? "" : ".DebugButtonFixed";
24188 return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]);
24191 return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]);
24194 DebugComponent.prototype._closeDebugElement = function (open) {
24195 this._open$.next(false);
24197 DebugComponent.prototype._openDebugElement = function () {
24198 this._open$.next(true);
24200 DebugComponent.componentName = "debug";
24201 return DebugComponent;
24202 }(Component_1.Component));
24203 exports.DebugComponent = DebugComponent;
24204 Component_1.ComponentService.register(DebugComponent);
24205 exports.default = DebugComponent;
24207 },{"../Component":290,"rxjs/BehaviorSubject":26,"underscore":242,"virtual-dom":246}],312:[function(require,module,exports){
24209 /// <reference path="../../typings/index.d.ts" />
24210 var __extends = (this && this.__extends) || (function () {
24211 var extendStatics = Object.setPrototypeOf ||
24212 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24213 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24214 return function (d, b) {
24215 extendStatics(d, b);
24216 function __() { this.constructor = d; }
24217 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24220 Object.defineProperty(exports, "__esModule", { value: true });
24221 var vd = require("virtual-dom");
24222 var Observable_1 = require("rxjs/Observable");
24223 var Component_1 = require("../Component");
24224 var Utils_1 = require("../Utils");
24225 var ImageComponent = /** @class */ (function (_super) {
24226 __extends(ImageComponent, _super);
24227 function ImageComponent(name, container, navigator, dom) {
24228 var _this = _super.call(this, name, container, navigator) || this;
24229 _this._canvasId = container.id + "-" + _this._name;
24230 _this._dom = !!dom ? dom : new Utils_1.DOM();
24233 ImageComponent.prototype._activate = function () {
24235 var canvasSize$ = this._container.domRenderer.element$
24236 .map(function (element) {
24237 return _this._dom.document.getElementById(_this._canvasId);
24239 .filter(function (canvas) {
24242 .map(function (canvas) {
24243 var adaptableDomRenderer = canvas.parentElement;
24244 var width = adaptableDomRenderer.offsetWidth;
24245 var height = adaptableDomRenderer.offsetHeight;
24246 return [canvas, { height: height, width: width }];
24248 .distinctUntilChanged(function (s1, s2) {
24249 return s1.height === s2.height && s1.width === s2.width;
24251 var canvas = _a[0], size = _a[1];
24254 this.drawSubscription = Observable_1.Observable
24255 .combineLatest(canvasSize$, this._navigator.stateService.currentNode$)
24256 .subscribe(function (_a) {
24257 var _b = _a[0], canvas = _b[0], size = _b[1], node = _a[1];
24258 canvas.width = size.width;
24259 canvas.height = size.height;
24262 .drawImage(node.image, 0, 0, size.width, size.height);
24264 this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) });
24266 ImageComponent.prototype._deactivate = function () {
24267 this.drawSubscription.unsubscribe();
24269 ImageComponent.prototype._getDefaultConfiguration = function () {
24272 ImageComponent.componentName = "image";
24273 return ImageComponent;
24274 }(Component_1.Component));
24275 exports.ImageComponent = ImageComponent;
24276 Component_1.ComponentService.register(ImageComponent);
24277 exports.default = ImageComponent;
24279 },{"../Component":290,"../Utils":300,"rxjs/Observable":29,"virtual-dom":246}],313:[function(require,module,exports){
24281 /// <reference path="../../typings/index.d.ts" />
24282 var __extends = (this && this.__extends) || (function () {
24283 var extendStatics = Object.setPrototypeOf ||
24284 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24285 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24286 return function (d, b) {
24287 extendStatics(d, b);
24288 function __() { this.constructor = d; }
24289 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24292 Object.defineProperty(exports, "__esModule", { value: true });
24293 var _ = require("underscore");
24294 var vd = require("virtual-dom");
24295 var Observable_1 = require("rxjs/Observable");
24296 var Component_1 = require("../Component");
24297 var LoadingComponent = /** @class */ (function (_super) {
24298 __extends(LoadingComponent, _super);
24299 function LoadingComponent(name, container, navigator) {
24300 return _super.call(this, name, container, navigator) || this;
24302 LoadingComponent.prototype._activate = function () {
24304 this._loadingSubscription = this._navigator.loadingService.loading$
24305 .switchMap(function (loading) {
24307 _this._navigator.imageLoadingService.loadstatus$ :
24308 Observable_1.Observable.of({});
24310 .map(function (loadStatus) {
24313 for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
24314 var loadStat = _a[_i];
24315 if (loadStat.loaded !== loadStat.total) {
24316 loaded += loadStat.loaded;
24317 total += loadStat.total;
24320 var percentage = 100;
24322 percentage = (loaded / total) * 100;
24324 return { name: _this._name, vnode: _this._getBarVNode(percentage) };
24326 .subscribe(this._container.domRenderer.render$);
24328 LoadingComponent.prototype._deactivate = function () {
24329 this._loadingSubscription.unsubscribe();
24331 LoadingComponent.prototype._getDefaultConfiguration = function () {
24334 LoadingComponent.prototype._getBarVNode = function (percentage) {
24335 var loadingBarStyle = {};
24336 var loadingContainerStyle = {};
24337 if (percentage !== 100) {
24338 loadingBarStyle.width = percentage.toFixed(0) + "%";
24339 loadingBarStyle.opacity = "1";
24342 loadingBarStyle.width = "100%";
24343 loadingBarStyle.opacity = "0";
24345 return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]);
24347 LoadingComponent.componentName = "loading";
24348 return LoadingComponent;
24349 }(Component_1.Component));
24350 exports.LoadingComponent = LoadingComponent;
24351 Component_1.ComponentService.register(LoadingComponent);
24352 exports.default = LoadingComponent;
24354 },{"../Component":290,"rxjs/Observable":29,"underscore":242,"virtual-dom":246}],314:[function(require,module,exports){
24356 /// <reference path="../../typings/index.d.ts" />
24357 var __extends = (this && this.__extends) || (function () {
24358 var extendStatics = Object.setPrototypeOf ||
24359 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24360 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24361 return function (d, b) {
24362 extendStatics(d, b);
24363 function __() { this.constructor = d; }
24364 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24367 Object.defineProperty(exports, "__esModule", { value: true });
24368 var vd = require("virtual-dom");
24369 var Observable_1 = require("rxjs/Observable");
24370 var Edge_1 = require("../Edge");
24371 var Error_1 = require("../Error");
24372 var Component_1 = require("../Component");
24374 * @class NavigationComponent
24376 * @classdesc Fallback navigation component for environments without WebGL support.
24378 * Replaces the functionality in the Direction and Sequence components.
24380 var NavigationComponent = /** @class */ (function (_super) {
24381 __extends(NavigationComponent, _super);
24382 function NavigationComponent(name, container, navigator) {
24383 var _this = _super.call(this, name, container, navigator) || this;
24384 _this._seqNames = {};
24385 _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Prev]] = "Prev";
24386 _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Next]] = "Next";
24387 _this._spaTopNames = {};
24388 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnLeft]] = "Turnleft";
24389 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepLeft]] = "Left";
24390 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepForward]] = "Forward";
24391 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepRight]] = "Right";
24392 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnRight]] = "Turnright";
24393 _this._spaBottomNames = {};
24394 _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnU]] = "Turnaround";
24395 _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepBackward]] = "Backward";
24398 NavigationComponent.prototype._activate = function () {
24400 this._renderSubscription = Observable_1.Observable
24401 .combineLatest(this._navigator.stateService.currentNode$, this._configuration$)
24402 .switchMap(function (_a) {
24403 var node = _a[0], configuration = _a[1];
24404 var sequenceEdges$ = configuration.sequence ?
24405 node.sequenceEdges$
24406 .map(function (status) {
24407 return status.edges
24408 .map(function (edge) {
24409 return edge.data.direction;
24412 Observable_1.Observable.of([]);
24413 var spatialEdges$ = !node.pano && configuration.spatial ?
24415 .map(function (status) {
24416 return status.edges
24417 .map(function (edge) {
24418 return edge.data.direction;
24421 Observable_1.Observable.of([]);
24422 return Observable_1.Observable
24423 .combineLatest(sequenceEdges$, spatialEdges$)
24424 .map(function (_a) {
24425 var seq = _a[0], spa = _a[1];
24426 return seq.concat(spa);
24429 .map(function (edgeDirections) {
24430 var seqs = _this._createArrowRow(_this._seqNames, edgeDirections);
24431 var spaTops = _this._createArrowRow(_this._spaTopNames, edgeDirections);
24432 var spaBottoms = _this._createArrowRow(_this._spaBottomNames, edgeDirections);
24433 var seqContainer = vd.h("div.NavigationSequence", seqs);
24434 var spaTopContainer = vd.h("div.NavigationSpatialTop", spaTops);
24435 var spaBottomContainer = vd.h("div.NavigationSpatialBottom", spaBottoms);
24436 var spaContainer = vd.h("div.NavigationSpatial", [spaTopContainer, spaBottomContainer]);
24437 return { name: _this._name, vnode: vd.h("div.NavigationContainer", [seqContainer, spaContainer]) };
24439 .subscribe(this._container.domRenderer.render$);
24441 NavigationComponent.prototype._deactivate = function () {
24442 this._renderSubscription.unsubscribe();
24444 NavigationComponent.prototype._getDefaultConfiguration = function () {
24445 return { sequence: true, spatial: true };
24447 NavigationComponent.prototype._createArrowRow = function (arrowNames, edgeDirections) {
24449 for (var arrowName in arrowNames) {
24450 if (!(arrowNames.hasOwnProperty(arrowName))) {
24453 var direction = Edge_1.EdgeDirection[arrowName];
24454 if (edgeDirections.indexOf(direction) !== -1) {
24455 arrows.push(this._createVNode(direction, arrowNames[arrowName], "visible"));
24458 arrows.push(this._createVNode(direction, arrowNames[arrowName], "hidden"));
24463 NavigationComponent.prototype._createVNode = function (direction, name, visibility) {
24465 return vd.h("span.Direction.Direction" + name, {
24466 onclick: function (ev) {
24467 _this._navigator.moveDir$(direction)
24468 .subscribe(undefined, function (error) {
24469 if (!(error instanceof Error_1.AbortMapillaryError)) {
24470 console.error(error);
24475 visibility: visibility,
24479 NavigationComponent.componentName = "navigation";
24480 return NavigationComponent;
24481 }(Component_1.Component));
24482 exports.NavigationComponent = NavigationComponent;
24483 Component_1.ComponentService.register(NavigationComponent);
24484 exports.default = NavigationComponent;
24486 },{"../Component":290,"../Edge":291,"../Error":292,"rxjs/Observable":29,"virtual-dom":246}],315:[function(require,module,exports){
24488 /// <reference path="../../typings/index.d.ts" />
24489 var __extends = (this && this.__extends) || (function () {
24490 var extendStatics = Object.setPrototypeOf ||
24491 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24492 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24493 return function (d, b) {
24494 extendStatics(d, b);
24495 function __() { this.constructor = d; }
24496 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24499 Object.defineProperty(exports, "__esModule", { value: true });
24500 var _ = require("underscore");
24501 var vd = require("virtual-dom");
24502 var Observable_1 = require("rxjs/Observable");
24503 var Component_1 = require("../Component");
24504 var DescriptionState = /** @class */ (function () {
24505 function DescriptionState() {
24507 return DescriptionState;
24509 var RouteState = /** @class */ (function () {
24510 function RouteState() {
24514 var RouteTrack = /** @class */ (function () {
24515 function RouteTrack() {
24516 this.nodeInstructions = [];
24517 this.nodeInstructionsOrdered = [];
24521 var RouteComponent = /** @class */ (function (_super) {
24522 __extends(RouteComponent, _super);
24523 function RouteComponent(name, container, navigator) {
24524 return _super.call(this, name, container, navigator) || this;
24526 RouteComponent.prototype._activate = function () {
24528 var _slowedStream$;
24529 _slowedStream$ = this._navigator.stateService.currentState$.filter(function (frame) {
24530 return (frame.id % 2) === 0;
24531 }).filter(function (frame) {
24532 return frame.state.nodesAhead < 15;
24533 }).distinctUntilChanged(undefined, function (frame) {
24534 return frame.state.lastNode.key;
24537 _routeTrack$ = this.configuration$.mergeMap(function (conf) {
24538 return Observable_1.Observable.from(conf.paths);
24539 }).distinct(function (p) {
24540 return p.sequenceKey;
24541 }).mergeMap(function (path) {
24542 return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey])
24543 .map(function (sequenceByKey) {
24544 return sequenceByKey[path.sequenceKey];
24546 }).combineLatest(this.configuration$, function (sequence, conf) {
24548 var instructionPlaces = [];
24549 for (var _i = 0, _a = conf.paths; _i < _a.length; _i++) {
24551 if (path.sequenceKey === sequence.key) {
24552 var nodeInstructions = [];
24553 var saveKey = false;
24554 for (var _b = 0, _c = sequence.keys; _b < _c.length; _b++) {
24556 if (path.startKey === key) {
24560 var description = null;
24561 for (var _d = 0, _e = path.infoKeys; _d < _e.length; _d++) {
24562 var infoKey = _e[_d];
24563 if (infoKey.key === key) {
24564 description = infoKey.description;
24567 nodeInstructions.push({ description: description, key: key });
24569 if (path.stopKey === key) {
24573 instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i });
24577 return instructionPlaces;
24578 }).scan(function (routeTrack, instructionPlaces) {
24579 for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) {
24580 var instructionPlace = instructionPlaces_1[_i];
24581 routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions;
24583 routeTrack.nodeInstructions = _.flatten(routeTrack.nodeInstructionsOrdered);
24585 }, new RouteTrack());
24586 this._disposable = _slowedStream$
24587 .combineLatest(_routeTrack$, this.configuration$, function (frame, routeTrack, conf) {
24588 return { conf: conf, frame: frame, routeTrack: routeTrack };
24589 }).scan(function (routeState, rtAndFrame) {
24590 if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) {
24591 routeState.routeTrack = rtAndFrame.routeTrack;
24592 routeState.currentNode = rtAndFrame.frame.state.currentNode;
24593 routeState.lastNode = rtAndFrame.frame.state.lastNode;
24594 routeState.playing = true;
24597 _this._navigator.stateService.cutNodes();
24598 routeState.playing = false;
24601 }, new RouteState())
24602 .filter(function (routeState) {
24603 return routeState.playing;
24604 }).filter(function (routeState) {
24605 for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
24606 var nodeInstruction = _a[_i];
24607 if (!nodeInstruction) {
24610 if (nodeInstruction.key === routeState.lastNode.key) {
24615 }).distinctUntilChanged(undefined, function (routeState) {
24616 return routeState.lastNode.key;
24617 }).mergeMap(function (routeState) {
24619 for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
24620 var nodeInstruction = _a[_i];
24621 if (nodeInstruction.key === routeState.lastNode.key) {
24626 var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1];
24627 if (!nextInstruction) {
24628 return Observable_1.Observable.of(null);
24630 return _this._navigator.graphService.cacheNode$(nextInstruction.key);
24631 }).combineLatest(this.configuration$, function (node, conf) {
24632 return { conf: conf, node: node };
24633 }).filter(function (cAN) {
24634 return cAN.node !== null && cAN.conf.playing;
24635 }).pluck("node").subscribe(this._navigator.stateService.appendNode$);
24636 this._disposableDescription = this._navigator.stateService.currentNode$
24637 .combineLatest(_routeTrack$, this.configuration$, function (node, routeTrack, conf) {
24638 if (conf.playing !== undefined && !conf.playing) {
24641 var description = null;
24642 for (var _i = 0, _a = routeTrack.nodeInstructions; _i < _a.length; _i++) {
24643 var nodeInstruction = _a[_i];
24644 if (nodeInstruction.key === node.key) {
24645 description = nodeInstruction.description;
24649 return description;
24650 }).scan(function (descriptionState, description) {
24651 if (description !== descriptionState.description && description !== null) {
24652 descriptionState.description = description;
24653 descriptionState.showsLeft = 6;
24656 descriptionState.showsLeft--;
24658 if (description === "quit") {
24659 descriptionState.description = null;
24661 return descriptionState;
24662 }, new DescriptionState()).map(function (descriptionState) {
24663 if (descriptionState.showsLeft > 0 && descriptionState.description) {
24664 return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) };
24667 return { name: _this._name, vnode: vd.h("div", []) };
24669 }).subscribe(this._container.domRenderer.render$);
24671 RouteComponent.prototype._deactivate = function () {
24672 this._disposable.unsubscribe();
24673 this._disposableDescription.unsubscribe();
24675 RouteComponent.prototype._getDefaultConfiguration = function () {
24678 RouteComponent.prototype.play = function () {
24679 this.configure({ playing: true });
24681 RouteComponent.prototype.stop = function () {
24682 this.configure({ playing: false });
24684 RouteComponent.prototype._getRouteAnnotationNode = function (description) {
24685 return vd.h("div.RouteFrame", {}, [
24686 vd.h("p", { textContent: description }, []),
24689 RouteComponent.componentName = "route";
24690 return RouteComponent;
24691 }(Component_1.Component));
24692 exports.RouteComponent = RouteComponent;
24693 Component_1.ComponentService.register(RouteComponent);
24694 exports.default = RouteComponent;
24696 },{"../Component":290,"rxjs/Observable":29,"underscore":242,"virtual-dom":246}],316:[function(require,module,exports){
24698 var __extends = (this && this.__extends) || (function () {
24699 var extendStatics = Object.setPrototypeOf ||
24700 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24701 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24702 return function (d, b) {
24703 extendStatics(d, b);
24704 function __() { this.constructor = d; }
24705 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24708 Object.defineProperty(exports, "__esModule", { value: true });
24709 var Observable_1 = require("rxjs/Observable");
24710 var Component_1 = require("../Component");
24711 var StatsComponent = /** @class */ (function (_super) {
24712 __extends(StatsComponent, _super);
24713 function StatsComponent(name, container, navigator) {
24714 return _super.call(this, name, container, navigator) || this;
24716 StatsComponent.prototype._activate = function () {
24718 this._sequenceSubscription = this._navigator.stateService.currentNode$
24719 .scan(function (keys, node) {
24720 var sKey = node.sequenceKey;
24722 if (!(sKey in keys.reported)) {
24723 keys.report = [sKey];
24724 keys.reported[sKey] = true;
24727 }, { report: [], reported: {} })
24728 .filter(function (keys) {
24729 return keys.report.length > 0;
24731 .mergeMap(function (keys) {
24732 return _this._navigator.apiV3.sequenceViewAdd$(keys.report)
24733 .catch(function (error, caught) {
24734 console.error("Failed to report sequence stats (" + keys.report + ")", error);
24735 return Observable_1.Observable.empty();
24738 .subscribe(function () { });
24739 this._imageSubscription = this._navigator.stateService.currentNode$
24740 .map(function (node) {
24743 .buffer(this._navigator.stateService.currentNode$.debounceTime(5000))
24744 .scan(function (keys, newKeys) {
24746 for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
24747 var key = newKeys_1[_i];
24748 if (!(key in keys.reported)) {
24749 keys.report.push(key);
24750 keys.reported[key] = true;
24754 }, { report: [], reported: {} })
24755 .filter(function (keys) {
24756 return keys.report.length > 0;
24758 .mergeMap(function (keys) {
24759 return _this._navigator.apiV3.imageViewAdd$(keys.report)
24760 .catch(function (error, caught) {
24761 console.error("Failed to report image stats (" + keys.report + ")", error);
24762 return Observable_1.Observable.empty();
24765 .subscribe(function () { });
24767 StatsComponent.prototype._deactivate = function () {
24768 this._sequenceSubscription.unsubscribe();
24769 this._imageSubscription.unsubscribe();
24771 StatsComponent.prototype._getDefaultConfiguration = function () {
24774 StatsComponent.componentName = "stats";
24775 return StatsComponent;
24776 }(Component_1.Component));
24777 exports.StatsComponent = StatsComponent;
24778 Component_1.ComponentService.register(StatsComponent);
24779 exports.default = StatsComponent;
24781 },{"../Component":290,"rxjs/Observable":29}],317:[function(require,module,exports){
24783 /// <reference path="../../../typings/index.d.ts" />
24784 var __extends = (this && this.__extends) || (function () {
24785 var extendStatics = Object.setPrototypeOf ||
24786 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24787 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24788 return function (d, b) {
24789 extendStatics(d, b);
24790 function __() { this.constructor = d; }
24791 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24794 Object.defineProperty(exports, "__esModule", { value: true });
24795 var vd = require("virtual-dom");
24796 var Observable_1 = require("rxjs/Observable");
24797 var Subject_1 = require("rxjs/Subject");
24798 var Component_1 = require("../../Component");
24800 * @class DirectionComponent
24801 * @classdesc Component showing navigation arrows for steps and turns.
24803 var DirectionComponent = /** @class */ (function (_super) {
24804 __extends(DirectionComponent, _super);
24805 function DirectionComponent(name, container, navigator, directionDOMRenderer) {
24806 var _this = _super.call(this, name, container, navigator) || this;
24807 _this._renderer = !!directionDOMRenderer ?
24808 directionDOMRenderer :
24809 new Component_1.DirectionDOMRenderer(_this.defaultConfiguration, container.element);
24810 _this._hoveredKeySubject$ = new Subject_1.Subject();
24811 _this._hoveredKey$ = _this._hoveredKeySubject$.share();
24814 Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", {
24816 * Get hovered key observable.
24818 * @description An observable emitting the key of the node for the direction
24819 * arrow that is being hovered. When the mouse leaves a direction arrow null
24822 * @returns {Observable<string>}
24825 return this._hoveredKey$;
24831 * Set highlight key.
24833 * @description The arrow pointing towards the node corresponding to the
24834 * highlight key will be highlighted.
24836 * @param {string} highlightKey Key of node to be highlighted if existing
24839 DirectionComponent.prototype.setHighlightKey = function (highlightKey) {
24840 this.configure({ highlightKey: highlightKey });
24843 * Set min width of container element.
24845 * @description Set min width of the non transformed container element holding
24846 * the navigation arrows. If the min width is larger than the max width the
24847 * min width value will be used.
24849 * The container element is automatically resized when the resize
24850 * method on the Viewer class is called.
24852 * @param {number} minWidth
24854 DirectionComponent.prototype.setMinWidth = function (minWidth) {
24855 this.configure({ minWidth: minWidth });
24858 * Set max width of container element.
24860 * @description Set max width of the non transformed container element holding
24861 * the navigation arrows. If the min width is larger than the max width the
24862 * min width value will be used.
24864 * The container element is automatically resized when the resize
24865 * method on the Viewer class is called.
24867 * @param {number} minWidth
24869 DirectionComponent.prototype.setMaxWidth = function (maxWidth) {
24870 this.configure({ maxWidth: maxWidth });
24873 DirectionComponent.prototype.resize = function () {
24874 this._renderer.resize(this._container.element);
24876 DirectionComponent.prototype._activate = function () {
24878 this._configurationSubscription = this._configuration$
24879 .subscribe(function (configuration) {
24880 _this._renderer.setConfiguration(configuration);
24882 this._nodeSubscription = this._navigator.stateService.currentNode$
24883 .do(function (node) {
24884 _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) });
24885 _this._renderer.setNode(node);
24887 .withLatestFrom(this._configuration$)
24888 .switchMap(function (_a) {
24889 var node = _a[0], configuration = _a[1];
24890 return Observable_1.Observable
24891 .combineLatest(node.spatialEdges$, configuration.distinguishSequence ?
24892 _this._navigator.graphService
24893 .cacheSequence$(node.sequenceKey)
24894 .catch(function (error, caught) {
24895 console.error("Failed to cache sequence (" + node.sequenceKey + ")", error);
24896 return Observable_1.Observable.of(null);
24898 Observable_1.Observable.of(null));
24900 .subscribe(function (_a) {
24901 var edgeStatus = _a[0], sequence = _a[1];
24902 _this._renderer.setEdges(edgeStatus, sequence);
24904 this._renderCameraSubscription = this._container.renderService.renderCameraFrame$
24905 .do(function (renderCamera) {
24906 _this._renderer.setRenderCamera(renderCamera);
24908 .map(function (renderCamera) {
24909 return _this._renderer;
24911 .filter(function (renderer) {
24912 return renderer.needsRender;
24914 .map(function (renderer) {
24915 return { name: _this._name, vnode: renderer.render(_this._navigator) };
24917 .subscribe(this._container.domRenderer.render$);
24918 this._hoveredKeySubscription = Observable_1.Observable
24920 this._container.domRenderer.element$,
24921 this._container.renderService.renderCamera$,
24922 this._container.mouseService.mouseMove$.startWith(null),
24923 this._container.mouseService.mouseUp$.startWith(null),
24924 ], function (e, rc, mm, mu) {
24927 .map(function (element) {
24928 var elements = element.getElementsByClassName("DirectionsPerspective");
24929 for (var i = 0; i < elements.length; i++) {
24930 var hovered = elements.item(i).querySelector(":hover");
24931 if (hovered != null && hovered.hasAttribute("data-key")) {
24932 return hovered.getAttribute("data-key");
24937 .distinctUntilChanged()
24938 .subscribe(this._hoveredKeySubject$);
24940 DirectionComponent.prototype._deactivate = function () {
24941 this._configurationSubscription.unsubscribe();
24942 this._nodeSubscription.unsubscribe();
24943 this._renderCameraSubscription.unsubscribe();
24944 this._hoveredKeySubscription.unsubscribe();
24946 DirectionComponent.prototype._getDefaultConfiguration = function () {
24948 distinguishSequence: false,
24954 DirectionComponent.componentName = "direction";
24955 return DirectionComponent;
24956 }(Component_1.Component));
24957 exports.DirectionComponent = DirectionComponent;
24958 Component_1.ComponentService.register(DirectionComponent);
24959 exports.default = DirectionComponent;
24961 },{"../../Component":290,"rxjs/Observable":29,"rxjs/Subject":34,"virtual-dom":246}],318:[function(require,module,exports){
24963 Object.defineProperty(exports, "__esModule", { value: true });
24964 var Geo_1 = require("../../Geo");
24966 * @class DirectionDOMCalculator
24967 * @classdesc Helper class for calculating DOM CSS properties.
24969 var DirectionDOMCalculator = /** @class */ (function () {
24970 function DirectionDOMCalculator(configuration, element) {
24971 this._spatial = new Geo_1.Spatial();
24972 this._minThresholdWidth = 320;
24973 this._maxThresholdWidth = 1480;
24974 this._minThresholdHeight = 240;
24975 this._maxThresholdHeight = 820;
24976 this._configure(configuration);
24977 this._resize(element);
24980 Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", {
24982 return this._minWidth;
24987 Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", {
24989 return this._maxWidth;
24994 Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", {
24996 return this._containerWidth;
25001 Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", {
25003 return this._containerWidthCss;
25008 Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", {
25010 return this._containerMarginCss;
25015 Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", {
25017 return this._containerLeftCss;
25022 Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", {
25024 return this._containerHeight;
25029 Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", {
25031 return this._containerHeightCss;
25036 Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", {
25038 return this._containerBottomCss;
25043 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", {
25045 return this._stepCircleSize;
25050 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", {
25052 return this._stepCircleSizeCss;
25057 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", {
25059 return this._stepCircleMarginCss;
25064 Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", {
25066 return this._turnCircleSize;
25071 Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", {
25073 return this._turnCircleSizeCss;
25078 Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", {
25080 return this._outerRadius;
25085 Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", {
25087 return this._innerRadius;
25092 Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", {
25094 return this._shadowOffset;
25100 * Configures the min and max width values.
25102 * @param {IDirectionConfiguration} configuration Configuration
25103 * with min and max width values.
25105 DirectionDOMCalculator.prototype.configure = function (configuration) {
25106 this._configure(configuration);
25110 * Resizes all properties according to the width and height
25113 * @param {HTMLElement} element The container element from which to extract
25114 * the width and height.
25116 DirectionDOMCalculator.prototype.resize = function (element) {
25117 this._resize(element);
25121 * Calculates the coordinates on the unit circle for an angle.
25123 * @param {number} angle Angle in radians.
25124 * @returns {Array<number>} The x and y coordinates on the unit circle.
25126 DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) {
25127 return [Math.cos(angle), Math.sin(angle)];
25130 * Calculates the coordinates on the unit circle for the
25131 * relative angle between the first and second angle.
25133 * @param {number} first Angle in radians.
25134 * @param {number} second Angle in radians.
25135 * @returns {Array<number>} The x and y coordinates on the unit circle
25136 * for the relative angle between the first and second angle.
25138 DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) {
25139 var relativeAngle = this._spatial.wrapAngle(first - second);
25140 return this.angleToCoordinates(relativeAngle);
25142 DirectionDOMCalculator.prototype._configure = function (configuration) {
25143 this._minWidth = configuration.minWidth;
25144 this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth);
25146 DirectionDOMCalculator.prototype._resize = function (element) {
25147 this._elementWidth = element.offsetWidth;
25148 this._elementHeight = element.offsetHeight;
25150 DirectionDOMCalculator.prototype._reset = function () {
25151 this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight);
25152 this._containerHeight = this._getContainerHeight(this.containerWidth);
25153 this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight);
25154 this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight);
25155 this._outerRadius = this._getOuterRadius(this._containerHeight);
25156 this._innerRadius = this._getInnerRadius(this._containerHeight);
25157 this._shadowOffset = 3;
25158 this._containerWidthCss = this._numberToCssPixels(this._containerWidth);
25159 this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth);
25160 this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth));
25161 this._containerHeightCss = this._numberToCssPixels(this._containerHeight);
25162 this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight));
25163 this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize);
25164 this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize);
25165 this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize);
25167 DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) {
25168 var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
25169 var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
25170 var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
25171 coeff = 0.04 * Math.round(25 * coeff);
25172 return this._minWidth + coeff * (this._maxWidth - this._minWidth);
25174 DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) {
25175 return 0.77 * containerWidth;
25177 DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) {
25178 return 0.34 * containerHeight;
25180 DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) {
25181 return 0.3 * containerHeight;
25183 DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) {
25184 return 0.31 * containerHeight;
25186 DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) {
25187 return 0.125 * containerHeight;
25189 DirectionDOMCalculator.prototype._numberToCssPixels = function (value) {
25190 return value + "px";
25192 DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) {
25193 return value > minWidth ? value : minWidth;
25195 return DirectionDOMCalculator;
25197 exports.DirectionDOMCalculator = DirectionDOMCalculator;
25198 exports.default = DirectionDOMCalculator;
25200 },{"../../Geo":293}],319:[function(require,module,exports){
25202 /// <reference path="../../../typings/index.d.ts" />
25203 Object.defineProperty(exports, "__esModule", { value: true });
25204 var vd = require("virtual-dom");
25205 var Component_1 = require("../../Component");
25206 var Edge_1 = require("../../Edge");
25207 var Error_1 = require("../../Error");
25208 var Geo_1 = require("../../Geo");
25210 * @class DirectionDOMRenderer
25211 * @classdesc DOM renderer for direction arrows.
25213 var DirectionDOMRenderer = /** @class */ (function () {
25214 function DirectionDOMRenderer(configuration, element) {
25215 this._isEdge = false;
25216 this._spatial = new Geo_1.Spatial();
25217 this._calculator = new Component_1.DirectionDOMCalculator(configuration, element);
25219 this._rotation = { phi: 0, theta: 0 };
25220 this._epsilon = 0.5 * Math.PI / 180;
25221 this._highlightKey = null;
25222 this._distinguishSequence = false;
25223 this._needsRender = false;
25224 this._stepEdges = [];
25225 this._turnEdges = [];
25226 this._panoEdges = [];
25227 this._sequenceEdgeKeys = [];
25228 this._stepDirections = [
25229 Edge_1.EdgeDirection.StepForward,
25230 Edge_1.EdgeDirection.StepBackward,
25231 Edge_1.EdgeDirection.StepLeft,
25232 Edge_1.EdgeDirection.StepRight,
25234 this._turnDirections = [
25235 Edge_1.EdgeDirection.TurnLeft,
25236 Edge_1.EdgeDirection.TurnRight,
25237 Edge_1.EdgeDirection.TurnU,
25239 this._turnNames = {};
25240 this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft";
25241 this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight";
25242 this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround";
25243 // detects IE 8-11, then Edge 20+.
25244 var isIE = !!document.documentMode;
25245 this._isEdge = !isIE && !!window.StyleMedia;
25247 Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", {
25249 * Get needs render.
25251 * @returns {boolean} Value indicating whether render should be called.
25254 return this._needsRender;
25260 * Renders virtual DOM elements.
25262 * @description Calling render resets the needs render property.
25264 DirectionDOMRenderer.prototype.render = function (navigator) {
25265 this._needsRender = false;
25266 var rotation = this._rotation;
25269 if (this._node.pano) {
25270 steps = steps.concat(this._createPanoArrows(navigator, rotation));
25273 steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation));
25274 steps = steps.concat(this._createStepArrows(navigator, rotation));
25275 turns = turns.concat(this._createTurnArrows(navigator));
25277 return this._getContainer(steps, turns, rotation);
25279 DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) {
25280 this._setEdges(edgeStatus, sequence);
25281 this._setNeedsRender();
25284 * Set node for which to show edges.
25286 * @param {Node} node
25288 DirectionDOMRenderer.prototype.setNode = function (node) {
25290 this._clearEdges();
25291 this._setNeedsRender();
25294 * Set the render camera to use for calculating rotations.
25296 * @param {RenderCamera} renderCamera
25298 DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) {
25299 var rotation = renderCamera.rotation;
25300 if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) {
25303 this._rotation = rotation;
25304 this._setNeedsRender();
25307 * Set configuration values.
25309 * @param {IDirectionConfiguration} configuration
25311 DirectionDOMRenderer.prototype.setConfiguration = function (configuration) {
25312 var needsRender = false;
25313 if (this._highlightKey !== configuration.highlightKey ||
25314 this._distinguishSequence !== configuration.distinguishSequence) {
25315 this._highlightKey = configuration.highlightKey;
25316 this._distinguishSequence = configuration.distinguishSequence;
25317 needsRender = true;
25319 if (this._calculator.minWidth !== configuration.minWidth ||
25320 this._calculator.maxWidth !== configuration.maxWidth) {
25321 this._calculator.configure(configuration);
25322 needsRender = true;
25325 this._setNeedsRender();
25329 * Detect the element's width and height and resize
25330 * elements accordingly.
25332 * @param {HTMLElement} element Viewer container element.
25334 DirectionDOMRenderer.prototype.resize = function (element) {
25335 this._calculator.resize(element);
25336 this._setNeedsRender();
25338 DirectionDOMRenderer.prototype._setNeedsRender = function () {
25339 if (this._node != null) {
25340 this._needsRender = true;
25343 DirectionDOMRenderer.prototype._clearEdges = function () {
25344 this._stepEdges = [];
25345 this._turnEdges = [];
25346 this._panoEdges = [];
25347 this._sequenceEdgeKeys = [];
25349 DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) {
25350 this._stepEdges = [];
25351 this._turnEdges = [];
25352 this._panoEdges = [];
25353 this._sequenceEdgeKeys = [];
25354 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
25356 var direction = edge.data.direction;
25357 if (this._stepDirections.indexOf(direction) > -1) {
25358 this._stepEdges.push(edge);
25361 if (this._turnDirections.indexOf(direction) > -1) {
25362 this._turnEdges.push(edge);
25365 if (edge.data.direction === Edge_1.EdgeDirection.Pano) {
25366 this._panoEdges.push(edge);
25369 if (this._distinguishSequence && sequence != null) {
25370 var edges = this._panoEdges
25371 .concat(this._stepEdges)
25372 .concat(this._turnEdges);
25373 for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) {
25374 var edge = edges_1[_b];
25375 var edgeKey = edge.to;
25376 for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
25377 var sequenceKey = _d[_c];
25378 if (sequenceKey === edgeKey) {
25379 this._sequenceEdgeKeys.push(edgeKey);
25386 DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) {
25388 for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
25389 var panoEdge = _a[_i];
25390 arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano"));
25392 for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) {
25393 var stepEdge = _c[_b];
25394 arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
25398 DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) {
25399 var threshold = Math.PI / 8;
25400 var relativePhi = rotation.phi;
25401 switch (direction) {
25402 case Edge_1.EdgeDirection.StepBackward:
25403 relativePhi = rotation.phi - Math.PI;
25405 case Edge_1.EdgeDirection.StepLeft:
25406 relativePhi = rotation.phi + Math.PI / 2;
25408 case Edge_1.EdgeDirection.StepRight:
25409 relativePhi = rotation.phi - Math.PI / 2;
25414 if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) {
25415 return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep");
25417 return this._createVNodeDisabled(key, azimuth, rotation);
25419 DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) {
25421 for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
25422 var panoEdge = _a[_i];
25423 arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true));
25427 DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) {
25429 for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) {
25430 var stepEdge = _a[_i];
25431 arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
25435 DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) {
25437 for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) {
25438 var turnEdge = _a[_i];
25439 var direction = turnEdge.data.direction;
25440 var name_1 = this._turnNames[direction];
25441 turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction));
25445 DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) {
25446 var onClick = function (e) {
25447 navigator.moveToKey$(key)
25448 .subscribe(undefined, function (error) {
25449 if (!(error instanceof Error_1.AbortMapillaryError)) {
25450 console.error(error);
25454 return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically);
25456 DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) {
25457 var onClick = function (e) {
25458 navigator.moveDir$(direction)
25459 .subscribe(undefined, function (error) {
25460 if (!(error instanceof Error_1.AbortMapillaryError)) {
25461 console.error(error);
25465 return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick);
25467 DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) {
25468 var onClick = function (e) {
25469 navigator.moveDir$(direction)
25470 .subscribe(undefined, function (error) {
25471 if (!(error instanceof Error_1.AbortMapillaryError)) {
25472 console.error(error);
25477 height: this._calculator.turnCircleSizeCss,
25478 transform: "rotate(0)",
25479 width: this._calculator.turnCircleSizeCss,
25481 switch (direction) {
25482 case Edge_1.EdgeDirection.TurnLeft:
25483 style.left = "5px";
25486 case Edge_1.EdgeDirection.TurnRight:
25487 style.right = "5px";
25490 case Edge_1.EdgeDirection.TurnU:
25491 style.left = "5px";
25492 style.bottom = "5px";
25497 var circleProperties = {
25504 var circleClassName = "TurnCircle";
25505 if (this._sequenceEdgeKeys.indexOf(key) > -1) {
25506 circleClassName += "Sequence";
25508 if (this._highlightKey === key) {
25509 circleClassName += "Highlight";
25511 var turn = vd.h("div." + className, {}, []);
25512 return vd.h("div." + circleClassName, circleProperties, [turn]);
25514 DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) {
25515 return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled");
25517 DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) {
25518 var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi);
25519 // rotate 90 degrees clockwise and flip over X-axis
25520 var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth);
25521 var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight);
25522 var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi);
25523 var shadowOffset = this._calculator.shadowOffset;
25524 var shadowTranslationX = -shadowOffset * shadowTranslation[1];
25525 var shadowTranslationY = shadowOffset * shadowTranslation[0];
25526 var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))";
25529 "-webkit-filter": filter,
25533 var chevron = vd.h("div." + className, properties, []);
25534 var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi);
25535 var circleTransform = shiftVertically ?
25536 "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" :
25537 "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)";
25538 var circleProperties = {
25539 attributes: { "data-key": key },
25542 height: this._calculator.stepCircleSizeCss,
25543 marginLeft: this._calculator.stepCircleMarginCss,
25544 marginTop: this._calculator.stepCircleMarginCss,
25545 transform: circleTransform,
25546 width: this._calculator.stepCircleSizeCss,
25549 if (this._sequenceEdgeKeys.indexOf(key) > -1) {
25550 circleClassName += "Sequence";
25552 if (this._highlightKey === key) {
25553 circleClassName += "Highlight";
25555 return vd.h("div." + circleClassName, circleProperties, [chevron]);
25557 DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) {
25558 // edge does not handle hover on perspective transforms.
25559 var transform = this._isEdge ?
25561 "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)";
25563 oncontextmenu: function (event) { event.preventDefault(); },
25565 bottom: this._calculator.containerBottomCss,
25566 height: this._calculator.containerHeightCss,
25567 left: this._calculator.containerLeftCss,
25568 marginLeft: this._calculator.containerMarginCss,
25569 transform: transform,
25570 width: this._calculator.containerWidthCss,
25573 return vd.h("div.DirectionsPerspective", properties, turns.concat(steps));
25575 return DirectionDOMRenderer;
25577 exports.DirectionDOMRenderer = DirectionDOMRenderer;
25578 exports.default = DirectionDOMRenderer;
25580 },{"../../Component":290,"../../Edge":291,"../../Error":292,"../../Geo":293,"virtual-dom":246}],320:[function(require,module,exports){
25582 var __extends = (this && this.__extends) || (function () {
25583 var extendStatics = Object.setPrototypeOf ||
25584 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25585 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25586 return function (d, b) {
25587 extendStatics(d, b);
25588 function __() { this.constructor = d; }
25589 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25592 Object.defineProperty(exports, "__esModule", { value: true });
25593 var Observable_1 = require("rxjs/Observable");
25594 var Subject_1 = require("rxjs/Subject");
25595 var Component_1 = require("../../Component");
25596 var Render_1 = require("../../Render");
25597 var Tiles_1 = require("../../Tiles");
25598 var Utils_1 = require("../../Utils");
25599 var ImagePlaneComponent = /** @class */ (function (_super) {
25600 __extends(ImagePlaneComponent, _super);
25601 function ImagePlaneComponent(name, container, navigator) {
25602 var _this = _super.call(this, name, container, navigator) || this;
25603 _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
25604 _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
25605 _this._rendererOperation$ = new Subject_1.Subject();
25606 _this._rendererCreator$ = new Subject_1.Subject();
25607 _this._rendererDisposer$ = new Subject_1.Subject();
25608 _this._renderer$ = _this._rendererOperation$
25609 .scan(function (renderer, operation) {
25610 return operation(renderer);
25612 .filter(function (renderer) {
25613 return renderer != null;
25615 .distinctUntilChanged(undefined, function (renderer) {
25616 return renderer.frameId;
25618 _this._rendererCreator$
25620 return function (renderer) {
25621 if (renderer != null) {
25622 throw new Error("Multiple image plane states can not be created at the same time");
25624 return new Component_1.ImagePlaneGLRenderer();
25627 .subscribe(_this._rendererOperation$);
25628 _this._rendererDisposer$
25630 return function (renderer) {
25631 renderer.dispose();
25635 .subscribe(_this._rendererOperation$);
25638 ImagePlaneComponent.prototype._activate = function () {
25640 this._rendererSubscription = this._renderer$
25641 .map(function (renderer) {
25645 frameId: renderer.frameId,
25646 needsRender: renderer.needsRender,
25647 render: renderer.render.bind(renderer),
25648 stage: Render_1.GLRenderStage.Background,
25651 renderer.clearNeedsRender();
25654 .subscribe(this._container.glRenderer.render$);
25655 this._rendererCreator$.next(null);
25656 this._stateSubscription = this._navigator.stateService.currentState$
25657 .map(function (frame) {
25658 return function (renderer) {
25659 renderer.updateFrame(frame);
25663 .subscribe(this._rendererOperation$);
25664 var textureProvider$ = this._navigator.stateService.currentState$
25665 .distinctUntilChanged(undefined, function (frame) {
25666 return frame.state.currentNode.key;
25668 .combineLatest(this._configuration$)
25669 .filter(function (args) {
25670 return args[1].imageTiling === true;
25672 .map(function (args) {
25675 .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$)
25676 .map(function (_a) {
25677 var frame = _a[0], renderer = _a[1], size = _a[2];
25678 var state = frame.state;
25679 var viewportSize = Math.max(size.width, size.height);
25680 var currentNode = state.currentNode;
25681 var currentTransform = state.currentTransform;
25682 var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
25683 return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
25687 this._textureProviderSubscription = textureProvider$.subscribe(function () { });
25688 this._setTextureProviderSubscription = textureProvider$
25689 .map(function (provider) {
25690 return function (renderer) {
25691 renderer.setTextureProvider(provider.key, provider);
25695 .subscribe(this._rendererOperation$);
25696 this._setTileSizeSubscription = this._container.renderService.size$
25697 .switchMap(function (size) {
25698 return Observable_1.Observable
25699 .combineLatest(textureProvider$, Observable_1.Observable.of(size))
25702 .subscribe(function (_a) {
25703 var provider = _a[0], size = _a[1];
25704 var viewportSize = Math.max(size.width, size.height);
25705 var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
25706 provider.setTileSize(tileSize);
25708 this._abortTextureProviderSubscription = textureProvider$
25710 .subscribe(function (pair) {
25711 var previous = pair[0];
25714 var roiTrigger$ = Observable_1.Observable
25715 .combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.debounceTime(250))
25716 .map(function (_a) {
25717 var camera = _a[0], size = _a[1];
25719 camera.camera.position.clone(),
25720 camera.camera.lookat.clone(),
25721 camera.zoom.valueOf(),
25722 size.height.valueOf(),
25723 size.width.valueOf()
25727 .skipWhile(function (pls) {
25728 return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
25730 .map(function (pls) {
25731 var samePosition = pls[0][0].equals(pls[1][0]);
25732 var sameLookat = pls[0][1].equals(pls[1][1]);
25733 var sameZoom = pls[0][2] === pls[1][2];
25734 var sameHeight = pls[0][3] === pls[1][3];
25735 var sameWidth = pls[0][4] === pls[1][4];
25736 return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
25738 .distinctUntilChanged()
25739 .filter(function (stalled) {
25742 .switchMap(function (stalled) {
25743 return _this._container.renderService.renderCameraFrame$
25746 .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$);
25747 this._setRegionOfInterestSubscription = textureProvider$
25748 .switchMap(function (provider) {
25750 .map(function (_a) {
25751 var camera = _a[0], size = _a[1], transform = _a[2];
25753 _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
25758 .filter(function (args) {
25759 return !args[1].disposed;
25761 .subscribe(function (args) {
25763 var provider = args[1];
25764 provider.setRegionOfInterest(roi);
25766 var hasTexture$ = textureProvider$
25767 .switchMap(function (provider) {
25768 return provider.hasTexture$;
25773 this._hasTextureSubscription = hasTexture$.subscribe(function () { });
25774 var nodeImage$ = this._navigator.stateService.currentState$
25775 .filter(function (frame) {
25776 return frame.state.nodesAhead === 0;
25778 .map(function (frame) {
25779 return frame.state.currentNode;
25781 .distinctUntilChanged(undefined, function (node) {
25784 .debounceTime(1000)
25785 .withLatestFrom(hasTexture$)
25786 .filter(function (args) {
25789 .map(function (args) {
25792 .filter(function (node) {
25794 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
25795 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
25797 .switchMap(function (node) {
25798 var baseImageSize = node.pano ?
25799 Utils_1.Settings.basePanoramaSize :
25800 Utils_1.Settings.baseImageSize;
25801 if (Math.max(node.image.width, node.image.height) > baseImageSize) {
25802 return Observable_1.Observable.empty();
25805 .cacheImage$(Utils_1.Settings.maxImageSize)
25806 .map(function (n) {
25807 return [n.image, n];
25810 .takeUntil(hasTexture$
25811 .filter(function (hasTexture) {
25814 .catch(function (error, caught) {
25815 console.error("Failed to fetch high res image (" + node.key + ")", error);
25816 return Observable_1.Observable.empty();
25821 this._updateBackgroundSubscription = nodeImage$
25822 .withLatestFrom(textureProvider$)
25823 .subscribe(function (args) {
25824 if (args[0][1].key !== args[1].key ||
25825 args[1].disposed) {
25828 args[1].updateBackground(args[0][0]);
25830 this._updateTextureImageSubscription = nodeImage$
25831 .map(function (imn) {
25832 return function (renderer) {
25833 renderer.updateTextureImage(imn[0], imn[1]);
25837 .subscribe(this._rendererOperation$);
25839 ImagePlaneComponent.prototype._deactivate = function () {
25840 this._rendererDisposer$.next(null);
25841 this._abortTextureProviderSubscription.unsubscribe();
25842 this._hasTextureSubscription.unsubscribe();
25843 this._rendererSubscription.unsubscribe();
25844 this._setRegionOfInterestSubscription.unsubscribe();
25845 this._setTextureProviderSubscription.unsubscribe();
25846 this._setTileSizeSubscription.unsubscribe();
25847 this._stateSubscription.unsubscribe();
25848 this._textureProviderSubscription.unsubscribe();
25849 this._updateBackgroundSubscription.unsubscribe();
25850 this._updateTextureImageSubscription.unsubscribe();
25852 ImagePlaneComponent.prototype._getDefaultConfiguration = function () {
25853 return { imageTiling: false };
25855 ImagePlaneComponent.componentName = "imagePlane";
25856 return ImagePlaneComponent;
25857 }(Component_1.Component));
25858 exports.ImagePlaneComponent = ImagePlaneComponent;
25859 Component_1.ComponentService.register(ImagePlaneComponent);
25860 exports.default = ImagePlaneComponent;
25862 },{"../../Component":290,"../../Render":296,"../../Tiles":299,"../../Utils":300,"rxjs/Observable":29,"rxjs/Subject":34}],321:[function(require,module,exports){
25864 /// <reference path="../../../typings/index.d.ts" />
25865 Object.defineProperty(exports, "__esModule", { value: true });
25866 var Component_1 = require("../../Component");
25867 var ImagePlaneGLRenderer = /** @class */ (function () {
25868 function ImagePlaneGLRenderer() {
25869 this._factory = new Component_1.MeshFactory();
25870 this._scene = new Component_1.MeshScene();
25872 this._alphaOld = 0;
25873 this._fadeOutSpeed = 0.05;
25874 this._currentKey = null;
25875 this._previousKey = null;
25876 this._providerDisposers = {};
25878 this._needsRender = false;
25880 Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", {
25882 return this._frameId;
25887 Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", {
25889 return this._needsRender;
25894 ImagePlaneGLRenderer.prototype.indicateNeedsRender = function () {
25895 this._needsRender = true;
25897 ImagePlaneGLRenderer.prototype.updateFrame = function (frame) {
25898 this._updateFrameId(frame.id);
25899 this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender;
25900 this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender;
25901 this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender;
25903 ImagePlaneGLRenderer.prototype.setTextureProvider = function (key, provider) {
25905 if (key !== this._currentKey) {
25908 var createdSubscription = provider.textureCreated$
25909 .subscribe(function (texture) {
25910 _this._updateTexture(texture);
25912 var updatedSubscription = provider.textureUpdated$
25913 .subscribe(function (updated) {
25914 _this._needsRender = true;
25916 var dispose = function () {
25917 createdSubscription.unsubscribe();
25918 updatedSubscription.unsubscribe();
25919 provider.dispose();
25921 if (key in this._providerDisposers) {
25922 var disposeProvider = this._providerDisposers[key];
25924 delete this._providerDisposers[key];
25926 this._providerDisposers[key] = dispose;
25928 ImagePlaneGLRenderer.prototype._updateTexture = function (texture) {
25929 this._needsRender = true;
25930 for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) {
25931 var plane = _a[_i];
25932 var material = plane.material;
25933 var oldTexture = material.uniforms.projectorTex.value;
25934 material.uniforms.projectorTex.value = null;
25935 oldTexture.dispose();
25936 material.uniforms.projectorTex.value = texture;
25939 ImagePlaneGLRenderer.prototype.updateTextureImage = function (image, node) {
25940 if (this._currentKey !== node.key) {
25943 this._needsRender = true;
25944 for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) {
25945 var plane = _a[_i];
25946 var material = plane.material;
25947 var texture = material.uniforms.projectorTex.value;
25948 texture.image = image;
25949 texture.needsUpdate = true;
25952 ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
25953 var planeAlpha = this._scene.imagePlanesOld.length ? 1 : this._alpha;
25954 for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) {
25955 var plane = _a[_i];
25956 plane.material.uniforms.opacity.value = planeAlpha;
25958 for (var _b = 0, _c = this._scene.imagePlanesOld; _b < _c.length; _b++) {
25959 var plane = _c[_b];
25960 plane.material.uniforms.opacity.value = this._alphaOld;
25962 renderer.render(this._scene.scene, perspectiveCamera);
25963 renderer.render(this._scene.sceneOld, perspectiveCamera);
25964 for (var _d = 0, _e = this._scene.imagePlanes; _d < _e.length; _d++) {
25965 var plane = _e[_d];
25966 plane.material.uniforms.opacity.value = this._alpha;
25968 renderer.render(this._scene.scene, perspectiveCamera);
25970 ImagePlaneGLRenderer.prototype.clearNeedsRender = function () {
25971 this._needsRender = false;
25973 ImagePlaneGLRenderer.prototype.dispose = function () {
25974 this._scene.clear();
25976 ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) {
25977 this._frameId = frameId;
25979 ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) {
25980 if (alpha === this._alpha) {
25983 this._alpha = alpha;
25986 ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) {
25987 if (alpha < 1 || this._alphaOld === 0) {
25990 this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed);
25993 ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) {
25994 if (state.currentNode == null || state.currentNode.key === this._currentKey) {
25997 var previousKey = state.previousNode != null ? state.previousNode.key : null;
25998 var currentKey = state.currentNode.key;
25999 if (this._previousKey !== previousKey &&
26000 this._previousKey !== currentKey &&
26001 this._previousKey in this._providerDisposers) {
26002 var disposeProvider = this._providerDisposers[this._previousKey];
26004 delete this._providerDisposers[this._previousKey];
26006 if (previousKey != null) {
26007 if (previousKey !== this._currentKey && previousKey !== this._previousKey) {
26008 var previousMesh = this._factory.createMesh(state.previousNode, state.previousTransform);
26009 this._scene.updateImagePlanes([previousMesh]);
26011 this._previousKey = previousKey;
26013 this._currentKey = currentKey;
26014 var currentMesh = this._factory.createMesh(state.currentNode, state.currentTransform);
26015 this._scene.updateImagePlanes([currentMesh]);
26016 this._alphaOld = 1;
26019 return ImagePlaneGLRenderer;
26021 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer;
26022 exports.default = ImagePlaneGLRenderer;
26024 },{"../../Component":290}],322:[function(require,module,exports){
26026 Object.defineProperty(exports, "__esModule", { value: true });
26028 (function (CoverState) {
26029 CoverState[CoverState["Hidden"] = 0] = "Hidden";
26030 CoverState[CoverState["Loading"] = 1] = "Loading";
26031 CoverState[CoverState["Visible"] = 2] = "Visible";
26032 })(CoverState = exports.CoverState || (exports.CoverState = {}));
26034 },{}],323:[function(require,module,exports){
26036 Object.defineProperty(exports, "__esModule", { value: true });
26038 * Enumeration for slider mode.
26043 * @description Modes for specifying how transitions
26044 * between nodes are performed in slider mode. Only
26045 * applicable when the slider component determines
26046 * that transitions with motion is possilble. When it
26047 * is not, the stationary mode will be applied.
26050 (function (SliderMode) {
26052 * Transitions with motion.
26054 * @description The slider component moves the
26055 * camera between the node origins.
26057 * In this mode it is not possible to zoom or pan.
26059 * The slider component falls back to stationary
26060 * mode when it determines that the pair of nodes
26061 * does not have a strong enough relation.
26063 SliderMode[SliderMode["Motion"] = 0] = "Motion";
26065 * Stationary transitions.
26067 * @description The camera is stationary.
26069 * In this mode it is possible to zoom and pan.
26071 SliderMode[SliderMode["Stationary"] = 1] = "Stationary";
26072 })(SliderMode = exports.SliderMode || (exports.SliderMode = {}));
26074 },{}],324:[function(require,module,exports){
26076 Object.defineProperty(exports, "__esModule", { value: true });
26077 var ICoverConfiguration_1 = require("./ICoverConfiguration");
26078 exports.CoverState = ICoverConfiguration_1.CoverState;
26079 var ISliderConfiguration_1 = require("./ISliderConfiguration");
26080 exports.SliderMode = ISliderConfiguration_1.SliderMode;
26082 },{"./ICoverConfiguration":322,"./ISliderConfiguration":323}],325:[function(require,module,exports){
26084 /// <reference path="../../../typings/index.d.ts" />
26085 var __extends = (this && this.__extends) || (function () {
26086 var extendStatics = Object.setPrototypeOf ||
26087 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26088 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26089 return function (d, b) {
26090 extendStatics(d, b);
26091 function __() { this.constructor = d; }
26092 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26095 Object.defineProperty(exports, "__esModule", { value: true });
26096 var Component_1 = require("../../Component");
26097 var Edge_1 = require("../../Edge");
26099 * The `KeyPlayHandler` allows the user to control the play behavior
26100 * using the following key commands:
26102 * `Spacebar`: Start or stop playing.
26103 * `SHIFT` + `D`: Switch direction.
26104 * `<`: Decrease speed.
26105 * `>`: Increase speed.
26109 * var keyboardComponent = viewer.getComponent("keyboard");
26111 * keyboardComponent.keyPlay.disable();
26112 * keyboardComponent.keyPlay.enable();
26114 * var isEnabled = keyboardComponent.keyPlay.isEnabled;
26117 var KeyPlayHandler = /** @class */ (function (_super) {
26118 __extends(KeyPlayHandler, _super);
26119 function KeyPlayHandler() {
26120 return _super !== null && _super.apply(this, arguments) || this;
26122 KeyPlayHandler.prototype._enable = function () {
26124 this._keyDownSubscription = this._container.keyboardService.keyDown$
26125 .withLatestFrom(this._navigator.playService.playing$, this._navigator.playService.direction$, this._navigator.playService.speed$, this._navigator.stateService.currentNode$
26126 .switchMap(function (node) {
26127 return node.sequenceEdges$;
26129 .subscribe(function (_a) {
26130 var event = _a[0], playing = _a[1], direction = _a[2], speed = _a[3], status = _a[4];
26131 if (event.altKey || event.ctrlKey || event.metaKey) {
26134 switch (event.key) {
26136 if (!event.shiftKey) {
26139 var newDirection = playing ?
26140 null : direction === Edge_1.EdgeDirection.Next ?
26141 Edge_1.EdgeDirection.Prev : direction === Edge_1.EdgeDirection.Prev ?
26142 Edge_1.EdgeDirection.Next : null;
26143 if (newDirection != null) {
26144 _this._navigator.playService.setDirection(newDirection);
26148 if (event.shiftKey) {
26152 _this._navigator.playService.stop();
26155 for (var _i = 0, _b = status.edges; _i < _b.length; _i++) {
26157 if (edge.data.direction === direction) {
26158 _this._navigator.playService.play();
26164 _this._navigator.playService.setSpeed(speed - 0.05);
26167 _this._navigator.playService.setSpeed(speed + 0.05);
26172 event.preventDefault();
26175 KeyPlayHandler.prototype._disable = function () {
26176 this._keyDownSubscription.unsubscribe();
26178 KeyPlayHandler.prototype._getConfiguration = function (enable) {
26179 return { keyZoom: enable };
26181 return KeyPlayHandler;
26182 }(Component_1.HandlerBase));
26183 exports.KeyPlayHandler = KeyPlayHandler;
26184 exports.default = KeyPlayHandler;
26186 },{"../../Component":290,"../../Edge":291}],326:[function(require,module,exports){
26188 /// <reference path="../../../typings/index.d.ts" />
26189 var __extends = (this && this.__extends) || (function () {
26190 var extendStatics = Object.setPrototypeOf ||
26191 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26192 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26193 return function (d, b) {
26194 extendStatics(d, b);
26195 function __() { this.constructor = d; }
26196 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26199 Object.defineProperty(exports, "__esModule", { value: true });
26200 var Component_1 = require("../../Component");
26201 var Edge_1 = require("../../Edge");
26202 var Error_1 = require("../../Error");
26204 * The `KeySequenceNavigationHandler` allows the user to navigate through a sequence using the
26205 * following key commands:
26207 * `ALT` + `Up Arrow`: Navigate to next image in the sequence.
26208 * `ALT` + `Down Arrow`: Navigate to previous image in sequence.
26212 * var keyboardComponent = viewer.getComponent("keyboard");
26214 * keyboardComponent.keySequenceNavigation.disable();
26215 * keyboardComponent.keySequenceNavigation.enable();
26217 * var isEnabled = keyboardComponent.keySequenceNavigation.isEnabled;
26220 var KeySequenceNavigationHandler = /** @class */ (function (_super) {
26221 __extends(KeySequenceNavigationHandler, _super);
26222 function KeySequenceNavigationHandler() {
26223 return _super !== null && _super.apply(this, arguments) || this;
26225 KeySequenceNavigationHandler.prototype._enable = function () {
26227 var sequenceEdges$ = this._navigator.stateService.currentNode$
26228 .switchMap(function (node) {
26229 return node.sequenceEdges$;
26231 this._keyDownSubscription = this._container.keyboardService.keyDown$
26232 .withLatestFrom(sequenceEdges$)
26233 .subscribe(function (_a) {
26234 var event = _a[0], edgeStatus = _a[1];
26235 var direction = null;
26236 switch (event.keyCode) {
26238 direction = Edge_1.EdgeDirection.Next;
26241 direction = Edge_1.EdgeDirection.Prev;
26246 event.preventDefault();
26247 if (!event.altKey || event.shiftKey || !edgeStatus.cached) {
26250 for (var _i = 0, _b = edgeStatus.edges; _i < _b.length; _i++) {
26252 if (edge.data.direction === direction) {
26253 _this._navigator.moveToKey$(edge.to)
26254 .subscribe(undefined, function (error) {
26255 if (!(error instanceof Error_1.AbortMapillaryError)) {
26256 console.error(error);
26264 KeySequenceNavigationHandler.prototype._disable = function () {
26265 this._keyDownSubscription.unsubscribe();
26267 KeySequenceNavigationHandler.prototype._getConfiguration = function (enable) {
26268 return { keySequenceNavigation: enable };
26270 return KeySequenceNavigationHandler;
26271 }(Component_1.HandlerBase));
26272 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler;
26273 exports.default = KeySequenceNavigationHandler;
26275 },{"../../Component":290,"../../Edge":291,"../../Error":292}],327:[function(require,module,exports){
26277 /// <reference path="../../../typings/index.d.ts" />
26278 var __extends = (this && this.__extends) || (function () {
26279 var extendStatics = Object.setPrototypeOf ||
26280 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26281 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26282 return function (d, b) {
26283 extendStatics(d, b);
26284 function __() { this.constructor = d; }
26285 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26288 Object.defineProperty(exports, "__esModule", { value: true });
26289 var Component_1 = require("../../Component");
26290 var Edge_1 = require("../../Edge");
26291 var Error_1 = require("../../Error");
26293 * The `KeySpatialNavigationHandler` allows the user to navigate through a sequence using the
26294 * following key commands:
26296 * `Up Arrow`: Step forward.
26297 * `Down Arrow`: Step backward.
26298 * `Left Arrow`: Step to the left.
26299 * `Rigth Arrow`: Step to the right.
26300 * `SHIFT` + `Down Arrow`: Turn around.
26301 * `SHIFT` + `Left Arrow`: Turn to the left.
26302 * `SHIFT` + `Rigth Arrow`: Turn to the right.
26306 * var keyboardComponent = viewer.getComponent("keyboard");
26308 * keyboardComponent.keySpatialNavigation.disable();
26309 * keyboardComponent.keySpatialNavigation.enable();
26311 * var isEnabled = keyboardComponent.keySpatialNavigation.isEnabled;
26314 var KeySpatialNavigationHandler = /** @class */ (function (_super) {
26315 __extends(KeySpatialNavigationHandler, _super);
26316 function KeySpatialNavigationHandler(component, container, navigator, spatial) {
26317 var _this = _super.call(this, component, container, navigator) || this;
26318 _this._spatial = spatial;
26321 KeySpatialNavigationHandler.prototype._enable = function () {
26323 var spatialEdges$ = this._navigator.stateService.currentNode$
26324 .switchMap(function (node) {
26325 return node.spatialEdges$;
26327 this._keyDownSubscription = this._container.keyboardService.keyDown$
26328 .withLatestFrom(spatialEdges$, this._navigator.stateService.currentState$)
26329 .subscribe(function (_a) {
26330 var event = _a[0], edgeStatus = _a[1], frame = _a[2];
26331 var pano = frame.state.currentNode.pano;
26332 var direction = null;
26333 switch (event.keyCode) {
26335 direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft;
26338 direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward;
26341 direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight;
26344 direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward;
26349 event.preventDefault();
26350 if (event.altKey || !edgeStatus.cached ||
26351 (event.shiftKey && pano)) {
26355 _this._moveDir(direction, edgeStatus);
26359 shifts[Edge_1.EdgeDirection.StepBackward] = Math.PI;
26360 shifts[Edge_1.EdgeDirection.StepForward] = 0;
26361 shifts[Edge_1.EdgeDirection.StepLeft] = Math.PI / 2;
26362 shifts[Edge_1.EdgeDirection.StepRight] = -Math.PI / 2;
26363 var phi = _this._rotationFromCamera(frame.state.camera).phi;
26364 var navigationAngle = _this._spatial.wrapAngle(phi + shifts[direction]);
26365 var threshold = Math.PI / 4;
26366 var edges = edgeStatus.edges.filter(function (e) {
26367 return e.data.direction === Edge_1.EdgeDirection.Pano || e.data.direction === direction;
26369 var smallestAngle = Number.MAX_VALUE;
26371 for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
26372 var edge = edges_1[_i];
26373 var angle = Math.abs(_this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle));
26374 if (angle < Math.min(smallestAngle, threshold)) {
26375 smallestAngle = angle;
26379 if (toKey == null) {
26382 _this._moveToKey(toKey);
26386 KeySpatialNavigationHandler.prototype._disable = function () {
26387 this._keyDownSubscription.unsubscribe();
26389 KeySpatialNavigationHandler.prototype._getConfiguration = function (enable) {
26390 return { keySpatialNavigation: enable };
26392 KeySpatialNavigationHandler.prototype._moveDir = function (direction, edgeStatus) {
26393 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
26395 if (edge.data.direction === direction) {
26396 this._moveToKey(edge.to);
26401 KeySpatialNavigationHandler.prototype._moveToKey = function (key) {
26402 this._navigator.moveToKey$(key)
26403 .subscribe(undefined, function (error) {
26404 if (!(error instanceof Error_1.AbortMapillaryError)) {
26405 console.error(error);
26409 KeySpatialNavigationHandler.prototype._rotationFromCamera = function (camera) {
26410 var direction = camera.lookat.clone().sub(camera.position);
26411 var upProjection = direction.clone().dot(camera.up);
26412 var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection));
26413 var phi = Math.atan2(planeProjection.y, planeProjection.x);
26414 var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
26415 return { phi: phi, theta: theta };
26417 return KeySpatialNavigationHandler;
26418 }(Component_1.HandlerBase));
26419 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler;
26420 exports.default = KeySpatialNavigationHandler;
26422 },{"../../Component":290,"../../Edge":291,"../../Error":292}],328:[function(require,module,exports){
26424 /// <reference path="../../../typings/index.d.ts" />
26425 var __extends = (this && this.__extends) || (function () {
26426 var extendStatics = Object.setPrototypeOf ||
26427 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26428 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26429 return function (d, b) {
26430 extendStatics(d, b);
26431 function __() { this.constructor = d; }
26432 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26435 Object.defineProperty(exports, "__esModule", { value: true });
26436 var Component_1 = require("../../Component");
26438 * The `KeyZoomHandler` allows the user to zoom in and out using the
26439 * following key commands:
26446 * var keyboardComponent = viewer.getComponent("keyboard");
26448 * keyboardComponent.keyZoom.disable();
26449 * keyboardComponent.keyZoom.enable();
26451 * var isEnabled = keyboardComponent.keyZoom.isEnabled;
26454 var KeyZoomHandler = /** @class */ (function (_super) {
26455 __extends(KeyZoomHandler, _super);
26456 function KeyZoomHandler(component, container, navigator, viewportCoords) {
26457 var _this = _super.call(this, component, container, navigator) || this;
26458 _this._viewportCoords = viewportCoords;
26461 KeyZoomHandler.prototype._enable = function () {
26463 this._keyDownSubscription = this._container.keyboardService.keyDown$
26464 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
26465 .subscribe(function (_a) {
26466 var event = _a[0], render = _a[1], transform = _a[2];
26467 if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
26471 switch (event.key) {
26481 event.preventDefault();
26482 var unprojected = _this._viewportCoords.unprojectFromViewport(0, 0, render.perspective);
26483 var reference = transform.projectBasic(unprojected.toArray());
26484 _this._navigator.stateService.zoomIn(delta, reference);
26487 KeyZoomHandler.prototype._disable = function () {
26488 this._keyDownSubscription.unsubscribe();
26490 KeyZoomHandler.prototype._getConfiguration = function (enable) {
26491 return { keyZoom: enable };
26493 return KeyZoomHandler;
26494 }(Component_1.HandlerBase));
26495 exports.KeyZoomHandler = KeyZoomHandler;
26496 exports.default = KeyZoomHandler;
26498 },{"../../Component":290}],329:[function(require,module,exports){
26500 var __extends = (this && this.__extends) || (function () {
26501 var extendStatics = Object.setPrototypeOf ||
26502 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26503 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26504 return function (d, b) {
26505 extendStatics(d, b);
26506 function __() { this.constructor = d; }
26507 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26510 Object.defineProperty(exports, "__esModule", { value: true });
26511 var Component_1 = require("../../Component");
26512 var Geo_1 = require("../../Geo");
26514 * @class KeyboardComponent
26516 * @classdesc Component for keyboard event handling.
26518 * To retrive and use the keyboard component
26522 * var viewer = new Mapillary.Viewer(
26527 * var keyboardComponent = viewer.getComponent("keyboard");
26530 var KeyboardComponent = /** @class */ (function (_super) {
26531 __extends(KeyboardComponent, _super);
26532 function KeyboardComponent(name, container, navigator) {
26533 var _this = _super.call(this, name, container, navigator) || this;
26534 _this._keyPlayHandler = new Component_1.KeyPlayHandler(_this, container, navigator);
26535 _this._keySequenceNavigationHandler = new Component_1.KeySequenceNavigationHandler(_this, container, navigator);
26536 _this._keySpatialNavigationHandler = new Component_1.KeySpatialNavigationHandler(_this, container, navigator, new Geo_1.Spatial());
26537 _this._keyZoomHandler = new Component_1.KeyZoomHandler(_this, container, navigator, new Geo_1.ViewportCoords());
26540 Object.defineProperty(KeyboardComponent.prototype, "keyPlay", {
26544 * @returns {KeyPlayHandler} The key play handler.
26547 return this._keyPlayHandler;
26552 Object.defineProperty(KeyboardComponent.prototype, "keySequenceNavigation", {
26554 * Get key sequence navigation.
26556 * @returns {KeySequenceNavigationHandler} The key sequence navigation handler.
26559 return this._keySequenceNavigationHandler;
26564 Object.defineProperty(KeyboardComponent.prototype, "keySpatialNavigation", {
26568 * @returns {KeySpatialNavigationHandler} The spatial handler.
26571 return this._keySpatialNavigationHandler;
26576 Object.defineProperty(KeyboardComponent.prototype, "keyZoom", {
26580 * @returns {KeyZoomHandler} The key zoom handler.
26583 return this._keyZoomHandler;
26588 KeyboardComponent.prototype._activate = function () {
26590 this._configurationSubscription = this._configuration$
26591 .subscribe(function (configuration) {
26592 if (configuration.keyPlay) {
26593 _this._keyPlayHandler.enable();
26596 _this._keyPlayHandler.disable();
26598 if (configuration.keySequenceNavigation) {
26599 _this._keySequenceNavigationHandler.enable();
26602 _this._keySequenceNavigationHandler.disable();
26604 if (configuration.keySpatialNavigation) {
26605 _this._keySpatialNavigationHandler.enable();
26608 _this._keySpatialNavigationHandler.disable();
26610 if (configuration.keyZoom) {
26611 _this._keyZoomHandler.enable();
26614 _this._keyZoomHandler.disable();
26618 KeyboardComponent.prototype._deactivate = function () {
26619 this._configurationSubscription.unsubscribe();
26620 this._keyPlayHandler.disable();
26621 this._keySequenceNavigationHandler.disable();
26622 this._keySpatialNavigationHandler.disable();
26623 this._keyZoomHandler.disable();
26625 KeyboardComponent.prototype._getDefaultConfiguration = function () {
26626 return { keyPlay: true, keySequenceNavigation: true, keySpatialNavigation: true, keyZoom: true };
26628 KeyboardComponent.componentName = "keyboard";
26629 return KeyboardComponent;
26630 }(Component_1.Component));
26631 exports.KeyboardComponent = KeyboardComponent;
26632 Component_1.ComponentService.register(KeyboardComponent);
26633 exports.default = KeyboardComponent;
26635 },{"../../Component":290,"../../Geo":293}],330:[function(require,module,exports){
26637 Object.defineProperty(exports, "__esModule", { value: true });
26638 var MarkerComponent_1 = require("./MarkerComponent");
26639 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
26640 var SimpleMarker_1 = require("./marker/SimpleMarker");
26641 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
26642 var CircleMarker_1 = require("./marker/CircleMarker");
26643 exports.CircleMarker = CircleMarker_1.CircleMarker;
26645 },{"./MarkerComponent":331,"./marker/CircleMarker":334,"./marker/SimpleMarker":336}],331:[function(require,module,exports){
26647 /// <reference path="../../../typings/index.d.ts" />
26648 var __extends = (this && this.__extends) || (function () {
26649 var extendStatics = Object.setPrototypeOf ||
26650 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26651 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26652 return function (d, b) {
26653 extendStatics(d, b);
26654 function __() { this.constructor = d; }
26655 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26658 Object.defineProperty(exports, "__esModule", { value: true });
26659 var THREE = require("three");
26660 var when = require("when");
26661 var Observable_1 = require("rxjs/Observable");
26662 var Component_1 = require("../../Component");
26663 var Render_1 = require("../../Render");
26664 var Graph_1 = require("../../Graph");
26665 var Geo_1 = require("../../Geo");
26667 * @class MarkerComponent
26669 * @classdesc Component for showing and editing 3D marker objects.
26671 * The `add` method is used for adding new markers or replacing
26672 * markers already in the set.
26674 * If a marker already in the set has the same
26675 * id as one of the markers added, the old marker will be removed and
26676 * the added marker will take its place.
26678 * It is not possible to update markers in the set by updating any properties
26679 * directly on the marker object. Markers need to be replaced by
26680 * re-adding them for updates to geographic position or configuration
26683 * Markers added to the marker component can be either interactive
26684 * or non-interactive. Different marker types define their behavior.
26685 * Markers with interaction support can be configured with options
26686 * to respond to dragging inside the viewer and be detected when
26687 * retrieving markers from pixel points with the `getMarkerIdAt` method.
26689 * To retrive and use the marker component
26693 * var viewer = new Mapillary.Viewer(
26697 * { component: { marker: true } });
26699 * var markerComponent = viewer.getComponent("marker");
26702 var MarkerComponent = /** @class */ (function (_super) {
26703 __extends(MarkerComponent, _super);
26704 function MarkerComponent(name, container, navigator) {
26705 var _this = _super.call(this, name, container, navigator) || this;
26706 _this._relativeGroundAltitude = -2;
26707 _this._geoCoords = new Geo_1.GeoCoords();
26708 _this._graphCalculator = new Graph_1.GraphCalculator();
26709 _this._markerScene = new Component_1.MarkerScene();
26710 _this._markerSet = new Component_1.MarkerSet();
26711 _this._viewportCoords = new Geo_1.ViewportCoords();
26715 * Add markers to the marker set or replace markers in the marker set.
26717 * @description If a marker already in the set has the same
26718 * id as one of the markers added, the old marker will be removed
26719 * the added marker will take its place.
26721 * Any marker inside the visible bounding bbox
26722 * will be initialized and placed in the viewer.
26724 * @param {Array<Marker>} markers - Markers to add.
26726 * @example ```markerComponent.add([marker1, marker2]);```
26728 MarkerComponent.prototype.add = function (markers) {
26729 this._markerSet.add(markers);
26732 * Returns the marker in the marker set with the specified id, or
26733 * undefined if the id matches no marker.
26735 * @param {string} markerId - Id of the marker.
26737 * @example ```var marker = markerComponent.get("markerId");```
26740 MarkerComponent.prototype.get = function (markerId) {
26741 return this._markerSet.get(markerId);
26744 * Returns an array of all markers.
26746 * @example ```var markers = markerComponent.getAll();```
26748 MarkerComponent.prototype.getAll = function () {
26749 return this._markerSet.getAll();
26752 * Returns the id of the interactive marker closest to the current camera
26753 * position at the specified point.
26755 * @description Notice that the pixelPoint argument requires x, y
26756 * coordinates from pixel space.
26758 * With this function, you can use the coordinates provided by mouse
26759 * events to get information out of the marker component.
26761 * If no interactive geometry of an interactive marker exist at the pixel
26762 * point, `null` will be returned.
26764 * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
26765 * @returns {string} Id of the interactive marker closest to the camera. If no
26766 * interactive marker exist at the pixel point, `null` will be returned.
26770 * markerComponent.getMarkerIdAt([100, 100])
26771 * .then((markerId) => { console.log(markerId); });
26774 MarkerComponent.prototype.getMarkerIdAt = function (pixelPoint) {
26776 return when.promise(function (resolve, reject) {
26777 _this._container.renderService.renderCamera$
26779 .map(function (render) {
26780 var viewport = _this._viewportCoords
26781 .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
26782 var id = _this._markerScene.intersectObjects(viewport, render.perspective);
26785 .subscribe(function (id) {
26787 }, function (error) {
26793 * Check if a marker exist in the marker set.
26795 * @param {string} markerId - Id of the marker.
26797 * @example ```var markerExists = markerComponent.has("markerId");```
26799 MarkerComponent.prototype.has = function (markerId) {
26800 return this._markerSet.has(markerId);
26803 * Remove markers with the specified ids from the marker set.
26805 * @param {Array<string>} markerIds - Ids for markers to remove.
26807 * @example ```markerComponent.remove(["id-1", "id-2"]);```
26809 MarkerComponent.prototype.remove = function (markerIds) {
26810 this._markerSet.remove(markerIds);
26813 * Remove all markers from the marker set.
26815 * @example ```markerComponent.removeAll();```
26817 MarkerComponent.prototype.removeAll = function () {
26818 this._markerSet.removeAll();
26820 MarkerComponent.prototype._activate = function () {
26822 var groundAltitude$ = this._navigator.stateService.currentState$
26823 .map(function (frame) {
26824 return frame.state.camera.position.z + _this._relativeGroundAltitude;
26826 .distinctUntilChanged(function (a1, a2) {
26827 return Math.abs(a1 - a2) < 0.01;
26831 var geoInitiated$ = Observable_1.Observable
26832 .combineLatest(groundAltitude$, this._navigator.stateService.reference$)
26834 .map(function () { })
26837 var clampedConfiguration$ = this._configuration$
26838 .map(function (configuration) {
26839 return { visibleBBoxSize: Math.max(1, Math.min(200, configuration.visibleBBoxSize)) };
26841 var currentlatLon$ = this._navigator.stateService.currentNode$
26842 .map(function (node) { return node.latLon; })
26845 var visibleBBox$ = Observable_1.Observable
26846 .combineLatest(clampedConfiguration$, currentlatLon$)
26847 .map(function (_a) {
26848 var configuration = _a[0], latLon = _a[1];
26849 return _this._graphCalculator
26850 .boundingBoxCorners(latLon, configuration.visibleBBoxSize / 2);
26854 var visibleMarkers$ = Observable_1.Observable
26855 .combineLatest(Observable_1.Observable
26856 .of(this._markerSet)
26857 .concat(this._markerSet.changed$), visibleBBox$)
26858 .map(function (_a) {
26859 var set = _a[0], bbox = _a[1];
26860 return set.search(bbox);
26862 this._setChangedSubscription = geoInitiated$
26863 .switchMap(function () {
26864 return visibleMarkers$
26865 .withLatestFrom(_this._navigator.stateService.reference$, groundAltitude$);
26867 .subscribe(function (_a) {
26868 var markers = _a[0], reference = _a[1], alt = _a[2];
26869 var geoCoords = _this._geoCoords;
26870 var markerScene = _this._markerScene;
26871 var sceneMarkers = markerScene.markers;
26872 var markersToRemove = Object.assign({}, sceneMarkers);
26873 for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
26874 var marker = markers_1[_i];
26875 if (marker.id in sceneMarkers) {
26876 delete markersToRemove[marker.id];
26879 var point3d = geoCoords
26880 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
26881 markerScene.add(marker, point3d);
26884 for (var id in markersToRemove) {
26885 if (!markersToRemove.hasOwnProperty(id)) {
26888 markerScene.remove(id);
26891 this._markersUpdatedSubscription = geoInitiated$
26892 .switchMap(function () {
26893 return _this._markerSet.updated$
26894 .withLatestFrom(visibleBBox$, _this._navigator.stateService.reference$, groundAltitude$);
26896 .subscribe(function (_a) {
26897 var markers = _a[0], _b = _a[1], sw = _b[0], ne = _b[1], reference = _a[2], alt = _a[3];
26898 var geoCoords = _this._geoCoords;
26899 var markerScene = _this._markerScene;
26900 for (var _i = 0, markers_2 = markers; _i < markers_2.length; _i++) {
26901 var marker = markers_2[_i];
26902 var exists = markerScene.has(marker.id);
26903 var visible = marker.latLon.lat > sw.lat &&
26904 marker.latLon.lat < ne.lat &&
26905 marker.latLon.lon > sw.lon &&
26906 marker.latLon.lon < ne.lon;
26908 var point3d = geoCoords
26909 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
26910 markerScene.add(marker, point3d);
26912 else if (!visible && exists) {
26913 markerScene.remove(marker.id);
26917 this._referenceSubscription = this._navigator.stateService.reference$
26919 .withLatestFrom(groundAltitude$)
26920 .subscribe(function (_a) {
26921 var reference = _a[0], alt = _a[1];
26922 var geoCoords = _this._geoCoords;
26923 var markerScene = _this._markerScene;
26924 for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
26925 var marker = _b[_i];
26926 var point3d = geoCoords
26927 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
26928 markerScene.update(marker.id, point3d);
26931 this._adjustHeightSubscription = groundAltitude$
26933 .withLatestFrom(this._navigator.stateService.reference$, currentlatLon$)
26934 .subscribe(function (_a) {
26935 var alt = _a[0], reference = _a[1], latLon = _a[2];
26936 var geoCoords = _this._geoCoords;
26937 var markerScene = _this._markerScene;
26938 var position = geoCoords
26939 .geodeticToEnu(latLon.lat, latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
26940 for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
26941 var marker = _b[_i];
26942 var point3d = geoCoords
26943 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
26944 var distanceX = point3d[0] - position[0];
26945 var distanceY = point3d[1] - position[1];
26946 var groundDistance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
26947 if (groundDistance > 50) {
26950 markerScene.lerpAltitude(marker.id, alt, Math.min(1, Math.max(0, 1.2 - 1.2 * groundDistance / 50)));
26953 this._renderSubscription = this._navigator.stateService.currentState$
26954 .map(function (frame) {
26955 var scene = _this._markerScene;
26960 needsRender: scene.needsRender,
26961 render: scene.render.bind(scene),
26962 stage: Render_1.GLRenderStage.Foreground,
26966 .subscribe(this._container.glRenderer.render$);
26967 var hoveredMarkerId$ = Observable_1.Observable
26968 .combineLatest(this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$)
26969 .map(function (_a) {
26970 var render = _a[0], event = _a[1];
26971 var element = _this._container.element;
26972 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
26973 var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element);
26974 var markerId = _this._markerScene.intersectObjects(viewport, render.perspective);
26979 var draggingStarted$ = this._container.mouseService
26980 .filtered$(this._name, this._container.mouseService.mouseDragStart$)
26981 .map(function (event) {
26984 var draggingStopped$ = this._container.mouseService
26985 .filtered$(this._name, this._container.mouseService.mouseDragEnd$)
26986 .map(function (event) {
26989 var filteredDragging$ = Observable_1.Observable
26990 .merge(draggingStarted$, draggingStopped$)
26992 this._dragEventSubscription = draggingStarted$
26993 .withLatestFrom(hoveredMarkerId$)
26994 .merge(Observable_1.Observable
26995 .combineLatest(draggingStopped$, Observable_1.Observable.of(null)))
26996 .startWith([false, null])
26998 .subscribe(function (_a) {
26999 var previous = _a[0], current = _a[1];
27000 var dragging = current[0];
27001 var eventType = dragging ? MarkerComponent.dragstart : MarkerComponent.dragend;
27002 var id = dragging ? current[1] : previous[1];
27003 var marker = _this._markerScene.get(id);
27004 var markerEvent = { marker: marker, target: _this, type: eventType };
27005 _this.fire(eventType, markerEvent);
27007 var mouseDown$ = Observable_1.Observable
27008 .merge(this._container.mouseService.mouseDown$
27009 .map(function (event) { return true; }), this._container.mouseService.documentMouseUp$
27010 .map(function (event) { return false; }))
27012 this._mouseClaimSubscription = Observable_1.Observable
27013 .combineLatest(this._container.mouseService.active$, hoveredMarkerId$.distinctUntilChanged(), mouseDown$, filteredDragging$)
27014 .map(function (_a) {
27015 var active = _a[0], markerId = _a[1], mouseDown = _a[2], filteredDragging = _a[3];
27016 return (!active && markerId != null && mouseDown) || filteredDragging;
27018 .distinctUntilChanged()
27019 .subscribe(function (claim) {
27021 _this._container.mouseService.claimMouse(_this._name, 1);
27022 _this._container.mouseService.claimWheel(_this._name, 1);
27025 _this._container.mouseService.unclaimMouse(_this._name);
27026 _this._container.mouseService.unclaimWheel(_this._name);
27029 var offset$ = this._container.mouseService
27030 .filtered$(this._name, this._container.mouseService.mouseDragStart$)
27031 .withLatestFrom(hoveredMarkerId$, this._container.renderService.renderCamera$)
27032 .map(function (_a) {
27033 var e = _a[0], id = _a[1], r = _a[2];
27034 var marker = _this._markerScene.get(id);
27035 var element = _this._container.element;
27036 var _b = _this._viewportCoords.projectToCanvas(marker.geometry.position.toArray(), element, r.perspective), groundCanvasX = _b[0], groundCanvasY = _b[1];
27037 var _c = _this._viewportCoords.canvasPosition(e, element), canvasX = _c[0], canvasY = _c[1];
27038 var offset = [canvasX - groundCanvasX, canvasY - groundCanvasY];
27039 return [marker, offset, r];
27043 this._updateMarkerSubscription = this._container.mouseService
27044 .filtered$(this._name, this._container.mouseService.mouseDrag$)
27045 .withLatestFrom(offset$, this._navigator.stateService.reference$, clampedConfiguration$)
27046 .subscribe(function (_a) {
27047 var event = _a[0], _b = _a[1], marker = _b[0], offset = _b[1], render = _b[2], reference = _a[2], configuration = _a[3];
27048 if (!_this._markerScene.has(marker.id)) {
27051 var element = _this._container.element;
27052 var _c = _this._viewportCoords.canvasPosition(event, element), canvasX = _c[0], canvasY = _c[1];
27053 var groundX = canvasX - offset[0];
27054 var groundY = canvasY - offset[1];
27055 var _d = _this._viewportCoords
27056 .canvasToViewport(groundX, groundY, element), viewportX = _d[0], viewportY = _d[1];
27057 var direction = new THREE.Vector3(viewportX, viewportY, 1)
27058 .unproject(render.perspective)
27059 .sub(render.perspective.position)
27061 var distance = Math.min(_this._relativeGroundAltitude / direction.z, configuration.visibleBBoxSize / 2 - 0.1);
27062 if (distance < 0) {
27065 var intersection = direction
27067 .multiplyScalar(distance)
27068 .add(render.perspective.position);
27069 intersection.z = render.perspective.position.z + _this._relativeGroundAltitude;
27070 var _e = _this._geoCoords
27071 .enuToGeodetic(intersection.x, intersection.y, intersection.z, reference.lat, reference.lon, reference.alt), lat = _e[0], lon = _e[1];
27072 _this._markerScene.update(marker.id, intersection.toArray(), { lat: lat, lon: lon });
27073 _this._markerSet.update(marker);
27074 var markerEvent = { marker: marker, target: _this, type: MarkerComponent.changed };
27075 _this.fire(MarkerComponent.changed, markerEvent);
27078 MarkerComponent.prototype._deactivate = function () {
27079 this._adjustHeightSubscription.unsubscribe();
27080 this._dragEventSubscription.unsubscribe();
27081 this._markersUpdatedSubscription.unsubscribe();
27082 this._mouseClaimSubscription.unsubscribe();
27083 this._referenceSubscription.unsubscribe();
27084 this._renderSubscription.unsubscribe();
27085 this._setChangedSubscription.unsubscribe();
27086 this._updateMarkerSubscription.unsubscribe();
27087 this._markerScene.clear();
27089 MarkerComponent.prototype._getDefaultConfiguration = function () {
27090 return { visibleBBoxSize: 100 };
27092 MarkerComponent.componentName = "marker";
27094 * Fired when the position of a marker is changed.
27096 * @type {IMarkerEvent} markerEvent - Marker event data.
27099 * markerComponent.on("changed", function(e) {
27100 * console.log(e.marker.id, e.marker.latLon);
27104 MarkerComponent.changed = "changed";
27106 * Fired when a marker drag interaction starts.
27108 * @type {IMarkerEvent} markerEvent - Marker event data.
27111 * markerComponent.on("dragstart", function(e) {
27112 * console.log(e.marker.id, e.marker.latLon);
27116 MarkerComponent.dragstart = "dragstart";
27118 * Fired when a marker drag interaction ends.
27120 * @type {IMarkerEvent} markerEvent - Marker event data.
27123 * markerComponent.on("dragend", function(e) {
27124 * console.log(e.marker.id, e.marker.latLon);
27128 MarkerComponent.dragend = "dragend";
27129 return MarkerComponent;
27130 }(Component_1.Component));
27131 exports.MarkerComponent = MarkerComponent;
27132 Component_1.ComponentService.register(MarkerComponent);
27133 exports.default = MarkerComponent;
27135 },{"../../Component":290,"../../Geo":293,"../../Graph":294,"../../Render":296,"rxjs/Observable":29,"three":240,"when":287}],332:[function(require,module,exports){
27137 /// <reference path="../../../typings/index.d.ts" />
27138 Object.defineProperty(exports, "__esModule", { value: true });
27139 var THREE = require("three");
27140 var MarkerScene = /** @class */ (function () {
27141 function MarkerScene(scene, raycaster) {
27142 this._needsRender = false;
27143 this._interactiveObjects = [];
27144 this._markers = {};
27145 this._objectMarkers = {};
27146 this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
27147 this._scene = !!scene ? scene : new THREE.Scene();
27149 Object.defineProperty(MarkerScene.prototype, "markers", {
27151 return this._markers;
27156 Object.defineProperty(MarkerScene.prototype, "needsRender", {
27158 return this._needsRender;
27163 MarkerScene.prototype.add = function (marker, position) {
27164 if (marker.id in this._markers) {
27165 this._dispose(marker.id);
27167 marker.createGeometry(position);
27168 this._scene.add(marker.geometry);
27169 this._markers[marker.id] = marker;
27170 for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
27171 var interactiveObject = _a[_i];
27172 this._interactiveObjects.push(interactiveObject);
27173 this._objectMarkers[interactiveObject.uuid] = marker.id;
27175 this._needsRender = true;
27177 MarkerScene.prototype.clear = function () {
27178 for (var id in this._markers) {
27179 if (!this._markers.hasOwnProperty) {
27184 this._needsRender = true;
27186 MarkerScene.prototype.get = function (id) {
27187 return this._markers[id];
27189 MarkerScene.prototype.getAll = function () {
27192 .keys(this._markers)
27193 .map(function (id) { return _this._markers[id]; });
27195 MarkerScene.prototype.has = function (id) {
27196 return id in this._markers;
27198 MarkerScene.prototype.intersectObjects = function (_a, camera) {
27199 var viewportX = _a[0], viewportY = _a[1];
27200 this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
27201 var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
27202 for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
27203 var intersect = intersects_1[_i];
27204 if (intersect.object.uuid in this._objectMarkers) {
27205 return this._objectMarkers[intersect.object.uuid];
27210 MarkerScene.prototype.lerpAltitude = function (id, alt, alpha) {
27211 if (!(id in this._markers)) {
27214 this._markers[id].lerpAltitude(alt, alpha);
27215 this._needsRender = true;
27217 MarkerScene.prototype.remove = function (id) {
27218 if (!(id in this._markers)) {
27222 this._needsRender = true;
27224 MarkerScene.prototype.render = function (perspectiveCamera, renderer) {
27225 renderer.render(this._scene, perspectiveCamera);
27226 this._needsRender = false;
27228 MarkerScene.prototype.update = function (id, position, latLon) {
27229 if (!(id in this._markers)) {
27232 var marker = this._markers[id];
27233 marker.updatePosition(position, latLon);
27234 this._needsRender = true;
27236 MarkerScene.prototype._dispose = function (id) {
27237 var marker = this._markers[id];
27238 this._scene.remove(marker.geometry);
27239 for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
27240 var interactiveObject = _a[_i];
27241 var index = this._interactiveObjects.indexOf(interactiveObject);
27242 if (index !== -1) {
27243 this._interactiveObjects.splice(index, 1);
27246 console.warn("Object does not exist (" + interactiveObject.id + ") for " + id);
27248 delete this._objectMarkers[interactiveObject.uuid];
27250 marker.disposeGeometry();
27251 delete this._markers[id];
27253 return MarkerScene;
27255 exports.MarkerScene = MarkerScene;
27256 exports.default = MarkerScene;
27258 },{"three":240}],333:[function(require,module,exports){
27260 /// <reference path="../../../typings/index.d.ts" />
27261 Object.defineProperty(exports, "__esModule", { value: true });
27262 var rbush = require("rbush");
27263 var Subject_1 = require("rxjs/Subject");
27264 var MarkerSet = /** @class */ (function () {
27265 function MarkerSet() {
27267 this._index = rbush(16, [".lon", ".lat", ".lon", ".lat"]);
27268 this._indexChanged$ = new Subject_1.Subject();
27269 this._updated$ = new Subject_1.Subject();
27271 Object.defineProperty(MarkerSet.prototype, "changed$", {
27273 return this._indexChanged$;
27278 Object.defineProperty(MarkerSet.prototype, "updated$", {
27280 return this._updated$;
27285 MarkerSet.prototype.add = function (markers) {
27287 var hash = this._hash;
27288 var index = this._index;
27289 for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
27290 var marker = markers_1[_i];
27291 var id = marker.id;
27293 index.remove(hash[id]);
27294 updated.push(marker);
27297 lat: marker.latLon.lat,
27298 lon: marker.latLon.lon,
27302 index.insert(item);
27304 if (updated.length > 0) {
27305 this._updated$.next(updated);
27307 if (markers.length > updated.length) {
27308 this._indexChanged$.next(this);
27311 MarkerSet.prototype.has = function (id) {
27312 return id in this._hash;
27314 MarkerSet.prototype.get = function (id) {
27315 return this.has(id) ? this._hash[id].marker : undefined;
27317 MarkerSet.prototype.getAll = function () {
27320 .map(function (indexItem) {
27321 return indexItem.marker;
27324 MarkerSet.prototype.remove = function (ids) {
27325 var hash = this._hash;
27326 var index = this._index;
27327 var changed = false;
27328 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
27329 var id = ids_1[_i];
27330 if (!(id in hash)) {
27333 var item = hash[id];
27334 index.remove(item);
27339 this._indexChanged$.next(this);
27342 MarkerSet.prototype.removeAll = function () {
27344 this._index.clear();
27345 this._indexChanged$.next(this);
27347 MarkerSet.prototype.search = function (_a) {
27348 var sw = _a[0], ne = _a[1];
27350 .search({ maxX: ne.lon, maxY: ne.lat, minX: sw.lon, minY: sw.lat })
27351 .map(function (indexItem) {
27352 return indexItem.marker;
27355 MarkerSet.prototype.update = function (marker) {
27356 var hash = this._hash;
27357 var index = this._index;
27358 var id = marker.id;
27359 if (!(id in hash)) {
27362 index.remove(hash[id]);
27364 lat: marker.latLon.lat,
27365 lon: marker.latLon.lon,
27369 index.insert(item);
27373 exports.MarkerSet = MarkerSet;
27374 exports.default = MarkerSet;
27376 },{"rbush":25,"rxjs/Subject":34}],334:[function(require,module,exports){
27378 /// <reference path="../../../../typings/index.d.ts" />
27379 var __extends = (this && this.__extends) || (function () {
27380 var extendStatics = Object.setPrototypeOf ||
27381 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27382 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27383 return function (d, b) {
27384 extendStatics(d, b);
27385 function __() { this.constructor = d; }
27386 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27389 Object.defineProperty(exports, "__esModule", { value: true });
27390 var THREE = require("three");
27391 var Component_1 = require("../../../Component");
27393 * @class CircleMarker
27395 * @classdesc Non-interactive marker with a flat circle shape. The circle
27396 * marker can not be configured to be interactive.
27398 * Circle marker properties can not be updated after creation.
27400 * To create and add one `CircleMarker` with default configuration
27401 * and one with configuration use
27405 * var defaultMarker = new Mapillary.MarkerComponent.CircleMarker(
27407 * { lat: 0, lon: 0, });
27409 * var configuredMarker = new Mapillary.MarkerComponent.CircleMarker(
27411 * { lat: 0, lon: 0, },
27418 * markerComponent.add([defaultMarker, configuredMarker]);
27421 var CircleMarker = /** @class */ (function (_super) {
27422 __extends(CircleMarker, _super);
27423 function CircleMarker(id, latLon, options) {
27424 var _this = _super.call(this, id, latLon) || this;
27425 options = !!options ? options : {};
27426 _this._color = options.color != null ? options.color : 0xffffff;
27427 _this._opacity = options.opacity != null ? options.opacity : 0.4;
27428 _this._radius = options.radius != null ? options.radius : 1;
27431 CircleMarker.prototype._createGeometry = function (position) {
27432 var circle = new THREE.Mesh(new THREE.CircleGeometry(this._radius, 16), new THREE.MeshBasicMaterial({
27433 color: this._color,
27434 opacity: this._opacity,
27437 circle.up.fromArray([0, 0, 1]);
27438 circle.renderOrder = -1;
27439 var group = new THREE.Object3D();
27441 group.position.fromArray(position);
27442 this._geometry = group;
27444 CircleMarker.prototype._disposeGeometry = function () {
27445 for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
27447 mesh.geometry.dispose();
27448 mesh.material.dispose();
27451 CircleMarker.prototype._getInteractiveObjects = function () {
27454 return CircleMarker;
27455 }(Component_1.Marker));
27456 exports.CircleMarker = CircleMarker;
27457 exports.default = CircleMarker;
27459 },{"../../../Component":290,"three":240}],335:[function(require,module,exports){
27461 /// <reference path="../../../../typings/index.d.ts" />
27462 Object.defineProperty(exports, "__esModule", { value: true });
27466 * @classdesc Represents an abstract marker class that should be extended
27467 * by marker implementations used in the marker component.
27469 var Marker = /** @class */ (function () {
27470 function Marker(id, latLon) {
27472 this._latLon = latLon;
27474 Object.defineProperty(Marker.prototype, "id", {
27477 * @returns {string} The id of the marker.
27485 Object.defineProperty(Marker.prototype, "geometry", {
27487 return this._geometry;
27492 Object.defineProperty(Marker.prototype, "latLon", {
27495 * @returns {ILatLon} The geographic coordinates of the marker.
27498 return this._latLon;
27503 Marker.prototype.createGeometry = function (position) {
27504 if (!!this._geometry) {
27507 this._createGeometry(position);
27508 // update matrix world if raycasting occurs before first render
27509 this._geometry.updateMatrixWorld(true);
27511 Marker.prototype.disposeGeometry = function () {
27512 if (!this._geometry) {
27515 this._disposeGeometry();
27516 this._geometry = undefined;
27518 Marker.prototype.getInteractiveObjects = function () {
27519 if (!this._geometry) {
27522 return this._getInteractiveObjects();
27524 Marker.prototype.lerpAltitude = function (alt, alpha) {
27525 if (!this._geometry) {
27528 this._geometry.position.z = (1 - alpha) * this._geometry.position.z + alpha * alt;
27530 Marker.prototype.updatePosition = function (position, latLon) {
27532 this._latLon.lat = latLon.lat;
27533 this._latLon.lon = latLon.lon;
27535 if (!this._geometry) {
27538 this._geometry.position.fromArray(position);
27539 this._geometry.updateMatrixWorld(true);
27543 exports.Marker = Marker;
27544 exports.default = Marker;
27546 },{}],336:[function(require,module,exports){
27548 /// <reference path="../../../../typings/index.d.ts" />
27549 var __extends = (this && this.__extends) || (function () {
27550 var extendStatics = Object.setPrototypeOf ||
27551 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27552 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27553 return function (d, b) {
27554 extendStatics(d, b);
27555 function __() { this.constructor = d; }
27556 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27559 Object.defineProperty(exports, "__esModule", { value: true });
27560 var THREE = require("three");
27561 var Component_1 = require("../../../Component");
27563 * @class SimpleMarker
27565 * @classdesc Interactive marker with ice cream shape. The sphere
27566 * inside the ice cream can be configured to be interactive.
27568 * Simple marker properties can not be updated after creation.
27570 * To create and add one `SimpleMarker` with default configuration
27571 * (non-interactive) and one interactive with configuration use
27575 * var defaultMarker = new Mapillary.MarkerComponent.SimpleMarker(
27577 * { lat: 0, lon: 0, });
27579 * var interactiveMarker = new Mapillary.MarkerComponent.SimpleMarker(
27581 * { lat: 0, lon: 0, },
27583 * ballColor: "#00f",
27584 * ballOpacity: 0.5,
27586 * interactive: true,
27591 * markerComponent.add([defaultMarker, interactiveMarker]);
27594 var SimpleMarker = /** @class */ (function (_super) {
27595 __extends(SimpleMarker, _super);
27596 function SimpleMarker(id, latLon, options) {
27597 var _this = _super.call(this, id, latLon) || this;
27598 options = !!options ? options : {};
27599 _this._ballColor = options.ballColor != null ? options.ballColor : 0xff0000;
27600 _this._ballOpacity = options.ballOpacity != null ? options.ballOpacity : 0.8;
27601 _this._circleToRayAngle = 2;
27602 _this._color = options.color != null ? options.color : 0xff0000;
27603 _this._interactive = !!options.interactive;
27604 _this._opacity = options.opacity != null ? options.opacity : 0.4;
27605 _this._radius = options.radius != null ? options.radius : 1;
27608 SimpleMarker.prototype._createGeometry = function (position) {
27609 var radius = this._radius;
27610 var cone = new THREE.Mesh(this._markerGeometry(radius, 8, 8), new THREE.MeshBasicMaterial({
27611 color: this._color,
27612 opacity: this._opacity,
27615 cone.renderOrder = 1;
27616 var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 8, 8), new THREE.MeshBasicMaterial({
27617 color: this._ballColor,
27618 opacity: this._ballOpacity,
27621 ball.position.z = this._markerHeight(radius);
27622 var group = new THREE.Object3D();
27625 group.position.fromArray(position);
27626 this._geometry = group;
27628 SimpleMarker.prototype._disposeGeometry = function () {
27629 for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
27631 mesh.geometry.dispose();
27632 mesh.material.dispose();
27635 SimpleMarker.prototype._getInteractiveObjects = function () {
27636 return this._interactive ? [this._geometry.children[0]] : [];
27638 SimpleMarker.prototype._markerHeight = function (radius) {
27639 var t = Math.tan(Math.PI - this._circleToRayAngle);
27640 return radius * Math.sqrt(1 + t * t);
27642 SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) {
27643 var geometry = new THREE.Geometry();
27644 widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
27645 heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
27646 var height = this._markerHeight(radius);
27648 for (var y = 0; y <= heightSegments; ++y) {
27649 var verticesRow = [];
27650 for (var x = 0; x <= widthSegments; ++x) {
27651 var u = x / widthSegments * Math.PI * 2;
27652 var v = y / heightSegments * Math.PI;
27654 if (v < this._circleToRayAngle) {
27658 var t = Math.tan(v - this._circleToRayAngle);
27659 r = radius * Math.sqrt(1 + t * t);
27661 var vertex = new THREE.Vector3();
27662 vertex.x = r * Math.cos(u) * Math.sin(v);
27663 vertex.y = r * Math.sin(u) * Math.sin(v);
27664 vertex.z = r * Math.cos(v) + height;
27665 geometry.vertices.push(vertex);
27666 verticesRow.push(geometry.vertices.length - 1);
27668 vertices.push(verticesRow);
27670 for (var y = 0; y < heightSegments; ++y) {
27671 for (var x = 0; x < widthSegments; ++x) {
27672 var v1 = vertices[y][x + 1];
27673 var v2 = vertices[y][x];
27674 var v3 = vertices[y + 1][x];
27675 var v4 = vertices[y + 1][x + 1];
27676 var n1 = geometry.vertices[v1].clone().normalize();
27677 var n2 = geometry.vertices[v2].clone().normalize();
27678 var n3 = geometry.vertices[v3].clone().normalize();
27679 var n4 = geometry.vertices[v4].clone().normalize();
27680 geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4]));
27681 geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()]));
27684 geometry.computeFaceNormals();
27685 geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height);
27688 return SimpleMarker;
27689 }(Component_1.Marker));
27690 exports.SimpleMarker = SimpleMarker;
27691 exports.default = SimpleMarker;
27693 },{"../../../Component":290,"three":240}],337:[function(require,module,exports){
27695 /// <reference path="../../../typings/index.d.ts" />
27696 var __extends = (this && this.__extends) || (function () {
27697 var extendStatics = Object.setPrototypeOf ||
27698 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27699 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27700 return function (d, b) {
27701 extendStatics(d, b);
27702 function __() { this.constructor = d; }
27703 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27706 Object.defineProperty(exports, "__esModule", { value: true });
27707 var Observable_1 = require("rxjs/Observable");
27708 var Component_1 = require("../../Component");
27710 * The `BounceHandler` ensures that the viewer bounces back to the image
27711 * when drag panning outside of the image edge.
27713 var BounceHandler = /** @class */ (function (_super) {
27714 __extends(BounceHandler, _super);
27715 function BounceHandler(component, container, navigator, viewportCoords, spatial) {
27716 var _this = _super.call(this, component, container, navigator) || this;
27717 _this._spatial = spatial;
27718 _this._viewportCoords = viewportCoords;
27719 _this._basicDistanceThreshold = 1e-3;
27720 _this._basicRotationThreshold = 5e-2;
27721 _this._bounceCoeff = 1e-1;
27724 BounceHandler.prototype._enable = function () {
27726 var inTransition$ = this._navigator.stateService.currentState$
27727 .map(function (frame) {
27728 return frame.state.alpha < 1;
27730 this._bounceSubscription = Observable_1.Observable
27731 .combineLatest(inTransition$, this._navigator.stateService.inTranslation$, this._container.mouseService.active$, this._container.touchService.active$)
27732 .map(function (noForce) {
27733 return noForce[0] || noForce[1] || noForce[2] || noForce[3];
27735 .distinctUntilChanged()
27736 .switchMap(function (noForce) {
27738 Observable_1.Observable.empty() :
27739 Observable_1.Observable.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$.first());
27741 .subscribe(function (args) {
27742 var renderCamera = args[0];
27743 var perspectiveCamera = renderCamera.perspective;
27744 var transform = args[1];
27745 if (!transform.hasValidScale && renderCamera.camera.focal < 0.1) {
27748 if (renderCamera.perspective.aspect === 0 || renderCamera.perspective.aspect === Number.POSITIVE_INFINITY) {
27751 var distanceThreshold = _this._basicDistanceThreshold / Math.pow(2, renderCamera.zoom);
27752 var basicCenter = _this._viewportCoords.viewportToBasic(0, 0, transform, perspectiveCamera);
27753 if (Math.abs(basicCenter[0] - 0.5) < distanceThreshold && Math.abs(basicCenter[1] - 0.5) < distanceThreshold) {
27756 var basicDistances = _this._viewportCoords.getBasicDistances(transform, perspectiveCamera);
27759 if (basicDistances[0] < distanceThreshold && basicDistances[1] < distanceThreshold &&
27760 basicDistances[2] < distanceThreshold && basicDistances[3] < distanceThreshold) {
27763 if (Math.abs(basicDistances[0] - basicDistances[2]) < distanceThreshold &&
27764 Math.abs(basicDistances[1] - basicDistances[3]) < distanceThreshold) {
27767 var coeff = _this._bounceCoeff;
27768 if (basicDistances[1] > 0 && basicDistances[3] === 0) {
27769 basicX = -coeff * basicDistances[1];
27771 else if (basicDistances[1] === 0 && basicDistances[3] > 0) {
27772 basicX = coeff * basicDistances[3];
27774 else if (basicDistances[1] > 0 && basicDistances[3] > 0) {
27775 basicX = coeff * (basicDistances[3] - basicDistances[1]) / 2;
27777 if (basicDistances[0] > 0 && basicDistances[2] === 0) {
27778 basicY = coeff * basicDistances[0];
27780 else if (basicDistances[0] === 0 && basicDistances[2] > 0) {
27781 basicY = -coeff * basicDistances[2];
27783 else if (basicDistances[0] > 0 && basicDistances[2] > 0) {
27784 basicY = coeff * (basicDistances[0] - basicDistances[2]) / 2;
27786 var rotationThreshold = _this._basicRotationThreshold;
27787 basicX = _this._spatial.clamp(basicX, -rotationThreshold, rotationThreshold);
27788 basicY = _this._spatial.clamp(basicY, -rotationThreshold, rotationThreshold);
27789 _this._navigator.stateService.rotateBasicUnbounded([basicX, basicY]);
27792 BounceHandler.prototype._disable = function () {
27793 this._bounceSubscription.unsubscribe();
27795 BounceHandler.prototype._getConfiguration = function (enable) {
27798 return BounceHandler;
27799 }(Component_1.HandlerBase));
27800 exports.BounceHandler = BounceHandler;
27801 exports.default = BounceHandler;
27803 },{"../../Component":290,"rxjs/Observable":29}],338:[function(require,module,exports){
27805 var __extends = (this && this.__extends) || (function () {
27806 var extendStatics = Object.setPrototypeOf ||
27807 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27808 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27809 return function (d, b) {
27810 extendStatics(d, b);
27811 function __() { this.constructor = d; }
27812 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27815 Object.defineProperty(exports, "__esModule", { value: true });
27816 var Observable_1 = require("rxjs/Observable");
27817 var Component_1 = require("../../Component");
27819 * The `DoubleClickZoomHandler` allows the user to zoom the viewer image at a point by double clicking.
27823 * var mouseComponent = viewer.getComponent("mouse");
27825 * mouseComponent.doubleClickZoom.disable();
27826 * mouseComponent.doubleClickZoom.enable();
27828 * var isEnabled = mouseComponent.doubleClickZoom.isEnabled;
27831 var DoubleClickZoomHandler = /** @class */ (function (_super) {
27832 __extends(DoubleClickZoomHandler, _super);
27833 function DoubleClickZoomHandler(component, container, navigator, viewportCoords) {
27834 var _this = _super.call(this, component, container, navigator) || this;
27835 _this._viewportCoords = viewportCoords;
27838 DoubleClickZoomHandler.prototype._enable = function () {
27840 this._zoomSubscription = Observable_1.Observable
27841 .merge(this._container.mouseService
27842 .filtered$(this._component.name, this._container.mouseService.dblClick$), this._container.touchService.doubleTap$
27843 .map(function (e) {
27844 var touch = e.touches[0];
27845 return { clientX: touch.clientX, clientY: touch.clientY, shiftKey: e.shiftKey };
27847 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
27848 .subscribe(function (_a) {
27849 var event = _a[0], render = _a[1], transform = _a[2];
27850 var element = _this._container.element;
27851 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
27852 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
27853 var reference = transform.projectBasic(unprojected.toArray());
27854 var delta = !!event.shiftKey ? -1 : 1;
27855 _this._navigator.stateService.zoomIn(delta, reference);
27858 DoubleClickZoomHandler.prototype._disable = function () {
27859 this._zoomSubscription.unsubscribe();
27861 DoubleClickZoomHandler.prototype._getConfiguration = function (enable) {
27862 return { doubleClickZoom: enable };
27864 return DoubleClickZoomHandler;
27865 }(Component_1.HandlerBase));
27866 exports.DoubleClickZoomHandler = DoubleClickZoomHandler;
27867 exports.default = DoubleClickZoomHandler;
27869 },{"../../Component":290,"rxjs/Observable":29}],339:[function(require,module,exports){
27871 /// <reference path="../../../typings/index.d.ts" />
27872 var __extends = (this && this.__extends) || (function () {
27873 var extendStatics = Object.setPrototypeOf ||
27874 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27875 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27876 return function (d, b) {
27877 extendStatics(d, b);
27878 function __() { this.constructor = d; }
27879 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27882 Object.defineProperty(exports, "__esModule", { value: true });
27883 var THREE = require("three");
27884 var Observable_1 = require("rxjs/Observable");
27885 var Component_1 = require("../../Component");
27887 * The `DragPanHandler` allows the user to pan the viewer image by clicking and dragging the cursor.
27891 * var mouseComponent = viewer.getComponent("mouse");
27893 * mouseComponent.dragPan.disable();
27894 * mouseComponent.dragPan.enable();
27896 * var isEnabled = mouseComponent.dragPan.isEnabled;
27899 var DragPanHandler = /** @class */ (function (_super) {
27900 __extends(DragPanHandler, _super);
27901 function DragPanHandler(component, container, navigator, viewportCoords, spatial) {
27902 var _this = _super.call(this, component, container, navigator) || this;
27903 _this._spatial = spatial;
27904 _this._viewportCoords = viewportCoords;
27905 _this._basicRotationThreshold = 5e-2;
27906 _this._forceCoeff = 2e-1;
27909 DragPanHandler.prototype._enable = function () {
27911 var draggingStarted$ = this._container.mouseService
27912 .filtered$(this._component.name, this._container.mouseService.mouseDragStart$)
27913 .map(function (event) {
27917 var draggingStopped$ = this._container.mouseService
27918 .filtered$(this._component.name, this._container.mouseService.mouseDragEnd$)
27919 .map(function (event) {
27923 this._activeMouseSubscription = Observable_1.Observable
27924 .merge(draggingStarted$, draggingStopped$)
27925 .subscribe(this._container.mouseService.activate$);
27926 this._preventDefaultSubscription = Observable_1.Observable
27927 .merge(draggingStarted$, draggingStopped$)
27928 .switchMap(function (dragging) {
27930 _this._container.mouseService.documentMouseMove$ :
27931 Observable_1.Observable.empty();
27933 .merge(this._container.touchService.touchMove$)
27934 .subscribe(function (event) {
27935 event.preventDefault(); // prevent selection of content outside the viewer
27937 var touchMovingStarted$ = this._container.touchService.singleTouchDragStart$
27938 .map(function (event) {
27941 var touchMovingStopped$ = this._container.touchService.singleTouchDragEnd$
27942 .map(function (event) {
27945 this._activeTouchSubscription = Observable_1.Observable
27946 .merge(touchMovingStarted$, touchMovingStopped$)
27947 .subscribe(this._container.touchService.activate$);
27948 var basicRotation$ = this._navigator.stateService.currentState$
27949 .map(function (frame) {
27950 return frame.state.currentNode.fullPano || frame.state.nodesAhead < 1;
27952 .distinctUntilChanged()
27953 .switchMap(function (enable) {
27955 return Observable_1.Observable.empty();
27957 var mouseDrag$ = _this._container.mouseService
27958 .filtered$(_this._component.name, _this._container.mouseService.mouseDragStart$)
27959 .switchMap(function (mouseDragStart) {
27960 return Observable_1.Observable
27961 .of(mouseDragStart)
27962 .concat(_this._container.mouseService
27963 .filtered$(_this._component.name, _this._container.mouseService.mouseDrag$))
27964 .merge(_this._container.mouseService
27965 .filtered$(_this._component.name, _this._container.mouseService.mouseDragEnd$)
27966 .map(function (e) {
27969 .takeWhile(function (e) {
27975 .filter(function (pair) {
27976 return pair[0] != null && pair[1] != null;
27978 var singleTouchDrag$ = Observable_1.Observable
27979 .merge(_this._container.touchService.singleTouchDragStart$, _this._container.touchService.singleTouchDrag$, _this._container.touchService.singleTouchDragEnd$.map(function (t) { return null; }))
27980 .map(function (event) {
27981 return event != null && event.touches.length > 0 ?
27982 event.touches[0] : null;
27985 .filter(function (pair) {
27986 return pair[0] != null && pair[1] != null;
27988 return Observable_1.Observable
27989 .merge(mouseDrag$, singleTouchDrag$);
27991 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.stateService.currentCamera$)
27992 .map(function (_a) {
27993 var events = _a[0], render = _a[1], transform = _a[2], c = _a[3];
27994 var camera = c.clone();
27995 var previousEvent = events[0];
27996 var event = events[1];
27997 var movementX = event.clientX - previousEvent.clientX;
27998 var movementY = event.clientY - previousEvent.clientY;
27999 var element = _this._container.element;
28000 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
28001 var currentDirection = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective)
28002 .sub(render.perspective.position);
28003 var directionX = _this._viewportCoords.unprojectFromCanvas(canvasX - movementX, canvasY, element, render.perspective)
28004 .sub(render.perspective.position);
28005 var directionY = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY - movementY, element, render.perspective)
28006 .sub(render.perspective.position);
28007 var deltaPhi = (movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection);
28008 var deltaTheta = (movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection);
28009 var upQuaternion = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
28010 var upQuaternionInverse = upQuaternion.clone().inverse();
28011 var offset = new THREE.Vector3();
28012 offset.copy(camera.lookat).sub(camera.position);
28013 offset.applyQuaternion(upQuaternion);
28014 var length = offset.length();
28015 var phi = Math.atan2(offset.y, offset.x);
28017 var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
28018 theta += deltaTheta;
28019 theta = Math.max(0.01, Math.min(Math.PI - 0.01, theta));
28020 offset.x = Math.sin(theta) * Math.cos(phi);
28021 offset.y = Math.sin(theta) * Math.sin(phi);
28022 offset.z = Math.cos(theta);
28023 offset.applyQuaternion(upQuaternionInverse);
28024 var lookat = new THREE.Vector3().copy(camera.position).add(offset.multiplyScalar(length));
28025 var basic = transform.projectBasic(lookat.toArray());
28026 var original = transform.projectBasic(camera.lookat.toArray());
28027 var x = basic[0] - original[0];
28028 var y = basic[1] - original[1];
28029 if (Math.abs(x) > 1) {
28032 else if (x > 0.5) {
28035 else if (x < -0.5) {
28038 var rotationThreshold = _this._basicRotationThreshold;
28039 x = _this._spatial.clamp(x, -rotationThreshold, rotationThreshold);
28040 y = _this._spatial.clamp(y, -rotationThreshold, rotationThreshold);
28041 if (transform.fullPano) {
28044 var pixelDistances = _this._viewportCoords.getPixelDistances(_this._container.element, transform, render.perspective);
28045 var coeff = _this._forceCoeff;
28046 if (pixelDistances[0] > 0 && y < 0 && basic[1] < 0.5) {
28047 y /= Math.max(1, coeff * pixelDistances[0]);
28049 if (pixelDistances[1] > 0 && x > 0 && basic[0] > 0.5) {
28050 x /= Math.max(1, coeff * pixelDistances[1]);
28052 if (pixelDistances[2] > 0 && y > 0 && basic[1] > 0.5) {
28053 y /= Math.max(1, coeff * pixelDistances[2]);
28055 if (pixelDistances[3] > 0 && x < 0 && basic[0] < 0.5) {
28056 x /= Math.max(1, coeff * pixelDistances[3]);
28061 this._rotateBasicWithoutInertiaSubscription = basicRotation$
28062 .subscribe(function (basicRotation) {
28063 _this._navigator.stateService.rotateBasicWithoutInertia(basicRotation);
28065 this._rotateBasicSubscription = basicRotation$
28066 .scan(function (rotationBuffer, rotation) {
28067 _this._drainBuffer(rotationBuffer);
28068 rotationBuffer.push([Date.now(), rotation]);
28069 return rotationBuffer;
28071 .sample(Observable_1.Observable
28072 .merge(this._container.mouseService.filtered$(this._component.name, this._container.mouseService.mouseDragEnd$), this._container.touchService.singleTouchDragEnd$))
28073 .map(function (rotationBuffer) {
28074 var drainedBuffer = _this._drainBuffer(rotationBuffer.slice());
28075 var basicRotation = [0, 0];
28076 for (var _i = 0, drainedBuffer_1 = drainedBuffer; _i < drainedBuffer_1.length; _i++) {
28077 var rotation = drainedBuffer_1[_i];
28078 basicRotation[0] += rotation[1][0];
28079 basicRotation[1] += rotation[1][1];
28081 var count = drainedBuffer.length;
28083 basicRotation[0] /= count;
28084 basicRotation[1] /= count;
28086 return basicRotation;
28088 .subscribe(function (basicRotation) {
28089 _this._navigator.stateService.rotateBasic(basicRotation);
28092 DragPanHandler.prototype._disable = function () {
28093 this._activeMouseSubscription.unsubscribe();
28094 this._activeTouchSubscription.unsubscribe();
28095 this._preventDefaultSubscription.unsubscribe();
28096 this._rotateBasicSubscription.unsubscribe();
28097 this._rotateBasicWithoutInertiaSubscription.unsubscribe();
28098 this._activeMouseSubscription = null;
28099 this._activeTouchSubscription = null;
28100 this._preventDefaultSubscription = null;
28101 this._rotateBasicSubscription = null;
28103 DragPanHandler.prototype._getConfiguration = function (enable) {
28104 return { dragPan: enable };
28106 DragPanHandler.prototype._drainBuffer = function (buffer) {
28108 var now = Date.now();
28109 while (buffer.length > 0 && now - buffer[0][0] > cutoff) {
28114 return DragPanHandler;
28115 }(Component_1.HandlerBase));
28116 exports.DragPanHandler = DragPanHandler;
28117 exports.default = DragPanHandler;
28119 },{"../../Component":290,"rxjs/Observable":29,"three":240}],340:[function(require,module,exports){
28121 var __extends = (this && this.__extends) || (function () {
28122 var extendStatics = Object.setPrototypeOf ||
28123 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28124 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28125 return function (d, b) {
28126 extendStatics(d, b);
28127 function __() { this.constructor = d; }
28128 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28131 Object.defineProperty(exports, "__esModule", { value: true });
28132 var Component_1 = require("../../Component");
28133 var Geo_1 = require("../../Geo");
28135 * @class MouseComponent
28137 * @classdesc Component handling mouse and touch events for camera movement.
28139 * To retrive and use the mouse component
28143 * var viewer = new Mapillary.Viewer(
28148 * var mouseComponent = viewer.getComponent("mouse");
28151 var MouseComponent = /** @class */ (function (_super) {
28152 __extends(MouseComponent, _super);
28153 function MouseComponent(name, container, navigator) {
28154 var _this = _super.call(this, name, container, navigator) || this;
28155 var spatial = new Geo_1.Spatial();
28156 var viewportCoords = new Geo_1.ViewportCoords();
28157 _this._bounceHandler = new Component_1.BounceHandler(_this, container, navigator, viewportCoords, spatial);
28158 _this._doubleClickZoomHandler = new Component_1.DoubleClickZoomHandler(_this, container, navigator, viewportCoords);
28159 _this._dragPanHandler = new Component_1.DragPanHandler(_this, container, navigator, viewportCoords, spatial);
28160 _this._scrollZoomHandler = new Component_1.ScrollZoomHandler(_this, container, navigator, viewportCoords);
28161 _this._touchZoomHandler = new Component_1.TouchZoomHandler(_this, container, navigator, viewportCoords);
28164 Object.defineProperty(MouseComponent.prototype, "doubleClickZoom", {
28166 * Get double click zoom.
28168 * @returns {DoubleClickZoomHandler} The double click zoom handler.
28171 return this._doubleClickZoomHandler;
28176 Object.defineProperty(MouseComponent.prototype, "dragPan", {
28180 * @returns {DragPanHandler} The drag pan handler.
28183 return this._dragPanHandler;
28188 Object.defineProperty(MouseComponent.prototype, "scrollZoom", {
28192 * @returns {ScrollZoomHandler} The scroll zoom handler.
28195 return this._scrollZoomHandler;
28200 Object.defineProperty(MouseComponent.prototype, "touchZoom", {
28204 * @returns {TouchZoomHandler} The touch zoom handler.
28207 return this._touchZoomHandler;
28212 MouseComponent.prototype._activate = function () {
28214 this._bounceHandler.enable();
28215 this._configurationSubscription = this._configuration$
28216 .subscribe(function (configuration) {
28217 if (configuration.doubleClickZoom) {
28218 _this._doubleClickZoomHandler.enable();
28221 _this._doubleClickZoomHandler.disable();
28223 if (configuration.dragPan) {
28224 _this._dragPanHandler.enable();
28227 _this._dragPanHandler.disable();
28229 if (configuration.scrollZoom) {
28230 _this._scrollZoomHandler.enable();
28233 _this._scrollZoomHandler.disable();
28235 if (configuration.touchZoom) {
28236 _this._touchZoomHandler.enable();
28239 _this._touchZoomHandler.disable();
28242 this._container.mouseService.claimMouse(this._name, 0);
28244 MouseComponent.prototype._deactivate = function () {
28245 this._container.mouseService.unclaimMouse(this._name);
28246 this._configurationSubscription.unsubscribe();
28247 this._bounceHandler.disable();
28248 this._doubleClickZoomHandler.disable();
28249 this._dragPanHandler.disable();
28250 this._scrollZoomHandler.disable();
28251 this._touchZoomHandler.disable();
28253 MouseComponent.prototype._getDefaultConfiguration = function () {
28254 return { doubleClickZoom: false, dragPan: true, scrollZoom: true, touchZoom: true };
28257 MouseComponent.componentName = "mouse";
28258 return MouseComponent;
28259 }(Component_1.Component));
28260 exports.MouseComponent = MouseComponent;
28261 Component_1.ComponentService.register(MouseComponent);
28262 exports.default = MouseComponent;
28264 },{"../../Component":290,"../../Geo":293}],341:[function(require,module,exports){
28266 var __extends = (this && this.__extends) || (function () {
28267 var extendStatics = Object.setPrototypeOf ||
28268 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28269 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28270 return function (d, b) {
28271 extendStatics(d, b);
28272 function __() { this.constructor = d; }
28273 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28276 Object.defineProperty(exports, "__esModule", { value: true });
28277 var Component_1 = require("../../Component");
28279 * The `ScrollZoomHandler` allows the user to zoom the viewer image by scrolling.
28283 * var mouseComponent = viewer.getComponent("mouse");
28285 * mouseComponent.scrollZoom.disable();
28286 * mouseComponent.scrollZoom.enable();
28288 * var isEnabled = mouseComponent.scrollZoom.isEnabled;
28291 var ScrollZoomHandler = /** @class */ (function (_super) {
28292 __extends(ScrollZoomHandler, _super);
28293 function ScrollZoomHandler(component, container, navigator, viewportCoords) {
28294 var _this = _super.call(this, component, container, navigator) || this;
28295 _this._viewportCoords = viewportCoords;
28298 ScrollZoomHandler.prototype._enable = function () {
28300 this._container.mouseService.claimWheel(this._component.name, 0);
28301 this._preventDefaultSubscription = this._container.mouseService.mouseWheel$
28302 .subscribe(function (event) {
28303 event.preventDefault();
28305 this._zoomSubscription = this._container.mouseService
28306 .filteredWheel$(this._component.name, this._container.mouseService.mouseWheel$)
28307 .withLatestFrom(this._navigator.stateService.currentState$, function (w, f) {
28310 .filter(function (args) {
28311 var state = args[1].state;
28312 return state.currentNode.fullPano || state.nodesAhead < 1;
28314 .map(function (args) {
28317 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) {
28320 .subscribe(function (args) {
28321 var event = args[0];
28322 var render = args[1];
28323 var transform = args[2];
28324 var element = _this._container.element;
28325 var _a = _this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
28326 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
28327 var reference = transform.projectBasic(unprojected.toArray());
28328 var deltaY = event.deltaY;
28329 if (event.deltaMode === 1) {
28330 deltaY = 40 * deltaY;
28332 else if (event.deltaMode === 2) {
28333 deltaY = 800 * deltaY;
28335 var canvasSize = _this._viewportCoords.containerToCanvas(element);
28336 var zoom = -3 * deltaY / canvasSize[1];
28337 _this._navigator.stateService.zoomIn(zoom, reference);
28340 ScrollZoomHandler.prototype._disable = function () {
28341 this._container.mouseService.unclaimWheel(this._component.name);
28342 this._preventDefaultSubscription.unsubscribe();
28343 this._zoomSubscription.unsubscribe();
28344 this._preventDefaultSubscription = null;
28345 this._zoomSubscription = null;
28347 ScrollZoomHandler.prototype._getConfiguration = function (enable) {
28348 return { scrollZoom: enable };
28350 return ScrollZoomHandler;
28351 }(Component_1.HandlerBase));
28352 exports.ScrollZoomHandler = ScrollZoomHandler;
28353 exports.default = ScrollZoomHandler;
28355 },{"../../Component":290}],342:[function(require,module,exports){
28357 /// <reference path="../../../typings/index.d.ts" />
28358 var __extends = (this && this.__extends) || (function () {
28359 var extendStatics = Object.setPrototypeOf ||
28360 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28361 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28362 return function (d, b) {
28363 extendStatics(d, b);
28364 function __() { this.constructor = d; }
28365 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28368 Object.defineProperty(exports, "__esModule", { value: true });
28369 var Observable_1 = require("rxjs/Observable");
28370 var Component_1 = require("../../Component");
28372 * The `TouchZoomHandler` allows the user to zoom the viewer image by pinching on a touchscreen.
28376 * var mouseComponent = viewer.getComponent("mouse");
28378 * mouseComponent.touchZoom.disable();
28379 * mouseComponent.touchZoom.enable();
28381 * var isEnabled = mouseComponent.touchZoom.isEnabled;
28384 var TouchZoomHandler = /** @class */ (function (_super) {
28385 __extends(TouchZoomHandler, _super);
28386 function TouchZoomHandler(component, container, navigator, viewportCoords) {
28387 var _this = _super.call(this, component, container, navigator) || this;
28388 _this._viewportCoords = viewportCoords;
28391 TouchZoomHandler.prototype._enable = function () {
28393 this._preventDefaultSubscription = this._container.touchService.pinch$
28394 .subscribe(function (pinch) {
28395 pinch.originalEvent.preventDefault();
28397 var pinchStarted$ = this._container.touchService.pinchStart$
28398 .map(function (event) {
28401 var pinchStopped$ = this._container.touchService.pinchEnd$
28402 .map(function (event) {
28405 this._activeSubscription = Observable_1.Observable
28406 .merge(pinchStarted$, pinchStopped$)
28407 .subscribe(this._container.touchService.activate$);
28408 this._zoomSubscription = this._container.touchService.pinch$
28409 .withLatestFrom(this._navigator.stateService.currentState$)
28410 .filter(function (args) {
28411 var state = args[1].state;
28412 return state.currentNode.fullPano || state.nodesAhead < 1;
28414 .map(function (args) {
28417 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
28418 .subscribe(function (_a) {
28419 var pinch = _a[0], render = _a[1], transform = _a[2];
28420 var element = _this._container.element;
28421 var _b = _this._viewportCoords.canvasPosition(pinch, element), canvasX = _b[0], canvasY = _b[1];
28422 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
28423 var reference = transform.projectBasic(unprojected.toArray());
28424 var _c = _this._viewportCoords.containerToCanvas(element), canvasWidth = _c[0], canvasHeight = _c[1];
28425 var zoom = 3 * pinch.distanceChange / Math.min(canvasWidth, canvasHeight);
28426 _this._navigator.stateService.zoomIn(zoom, reference);
28429 TouchZoomHandler.prototype._disable = function () {
28430 this._activeSubscription.unsubscribe();
28431 this._preventDefaultSubscription.unsubscribe();
28432 this._zoomSubscription.unsubscribe();
28433 this._preventDefaultSubscription = null;
28434 this._zoomSubscription = null;
28436 TouchZoomHandler.prototype._getConfiguration = function (enable) {
28437 return { touchZoom: enable };
28439 return TouchZoomHandler;
28440 }(Component_1.HandlerBase));
28441 exports.TouchZoomHandler = TouchZoomHandler;
28442 exports.default = TouchZoomHandler;
28444 },{"../../Component":290,"rxjs/Observable":29}],343:[function(require,module,exports){
28446 Object.defineProperty(exports, "__esModule", { value: true });
28447 var Popup_1 = require("./popup/Popup");
28448 exports.Popup = Popup_1.Popup;
28449 var PopupComponent_1 = require("./PopupComponent");
28450 exports.PopupComponent = PopupComponent_1.PopupComponent;
28452 },{"./PopupComponent":344,"./popup/Popup":345}],344:[function(require,module,exports){
28454 var __extends = (this && this.__extends) || (function () {
28455 var extendStatics = Object.setPrototypeOf ||
28456 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28457 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28458 return function (d, b) {
28459 extendStatics(d, b);
28460 function __() { this.constructor = d; }
28461 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28464 Object.defineProperty(exports, "__esModule", { value: true });
28465 var Observable_1 = require("rxjs/Observable");
28466 var Subject_1 = require("rxjs/Subject");
28467 var Component_1 = require("../../Component");
28468 var Utils_1 = require("../../Utils");
28470 * @class PopupComponent
28472 * @classdesc Component for showing HTML popup objects.
28474 * The `add` method is used for adding new popups. Popups are removed by reference.
28476 * It is not possible to update popups in the set by updating any properties
28477 * directly on the popup object. Popups need to be replaced by
28478 * removing them and creating new ones with relevant changed properties and
28479 * adding those instead.
28481 * Popups are only relevant to a single image because they are based on
28482 * 2D basic image coordinates. Popups related to a certain image should
28483 * be removed when the viewer is moved to another node.
28485 * To retrive and use the popup component
28489 * var viewer = new Mapillary.Viewer(
28493 * { component: { popup: true } });
28495 * var popupComponent = viewer.getComponent("popup");
28498 var PopupComponent = /** @class */ (function (_super) {
28499 __extends(PopupComponent, _super);
28500 function PopupComponent(name, container, navigator, dom) {
28501 var _this = _super.call(this, name, container, navigator) || this;
28502 _this._dom = !!dom ? dom : new Utils_1.DOM();
28503 _this._popups = [];
28504 _this._added$ = new Subject_1.Subject();
28505 _this._popups$ = new Subject_1.Subject();
28509 * Add popups to the popups set.
28511 * @description Adding a new popup never replaces an old one
28512 * because they are stored by reference. Adding an already
28513 * existing popup has no effect.
28515 * @param {Array<Popup>} popups - Popups to add.
28517 * @example ```popupComponent.add([popup1, popup2]);```
28519 PopupComponent.prototype.add = function (popups) {
28520 for (var _i = 0, popups_1 = popups; _i < popups_1.length; _i++) {
28521 var popup = popups_1[_i];
28522 if (this._popups.indexOf(popup) !== -1) {
28525 this._popups.push(popup);
28526 if (this._activated) {
28527 popup.setParentContainer(this._popupContainer);
28530 this._added$.next(popups);
28531 this._popups$.next(this._popups);
28534 * Returns an array of all popups.
28536 * @example ```var popups = popupComponent.getAll();```
28538 PopupComponent.prototype.getAll = function () {
28539 return this._popups.slice();
28542 * Remove popups based on reference from the popup set.
28544 * @param {Array<Popup>} popups - Popups to remove.
28546 * @example ```popupComponent.remove([popup1, popup2]);```
28548 PopupComponent.prototype.remove = function (popups) {
28549 for (var _i = 0, popups_2 = popups; _i < popups_2.length; _i++) {
28550 var popup = popups_2[_i];
28551 this._remove(popup);
28553 this._popups$.next(this._popups);
28556 * Remove all popups from the popup set.
28558 * @example ```popupComponent.removeAll();```
28560 PopupComponent.prototype.removeAll = function () {
28561 for (var _i = 0, _a = this._popups.slice(); _i < _a.length; _i++) {
28562 var popup = _a[_i];
28563 this._remove(popup);
28565 this._popups$.next(this._popups);
28567 PopupComponent.prototype._activate = function () {
28569 this._popupContainer = this._dom.createElement("div", "mapillary-js-popup-container", this._container.element);
28570 for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
28571 var popup = _a[_i];
28572 popup.setParentContainer(this._popupContainer);
28574 this._updateAllSubscription = Observable_1.Observable
28575 .combineLatest(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
28576 .subscribe(function (_a) {
28577 var renderCamera = _a[0], size = _a[1], transform = _a[2];
28578 for (var _i = 0, _b = _this._popups; _i < _b.length; _i++) {
28579 var popup = _b[_i];
28580 popup.update(renderCamera, size, transform);
28583 var changed$ = this._popups$
28584 .startWith(this._popups)
28585 .switchMap(function (popups) {
28586 return Observable_1.Observable
28588 .mergeMap(function (popup) {
28589 return popup.changed$;
28592 .map(function (popup) {
28595 this._updateAddedChangedSubscription = this._added$
28597 .withLatestFrom(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
28598 .subscribe(function (_a) {
28599 var popups = _a[0], renderCamera = _a[1], size = _a[2], transform = _a[3];
28600 for (var _i = 0, popups_3 = popups; _i < popups_3.length; _i++) {
28601 var popup = popups_3[_i];
28602 popup.update(renderCamera, size, transform);
28606 PopupComponent.prototype._deactivate = function () {
28607 this._updateAllSubscription.unsubscribe();
28608 this._updateAddedChangedSubscription.unsubscribe();
28609 for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
28610 var popup = _a[_i];
28613 this._container.element.removeChild(this._popupContainer);
28614 delete this._popupContainer;
28616 PopupComponent.prototype._getDefaultConfiguration = function () {
28619 PopupComponent.prototype._remove = function (popup) {
28620 var index = this._popups.indexOf(popup);
28621 if (index === -1) {
28624 var removed = this._popups.splice(index, 1)[0];
28625 if (this._activated) {
28629 PopupComponent.componentName = "popup";
28630 return PopupComponent;
28631 }(Component_1.Component));
28632 exports.PopupComponent = PopupComponent;
28633 Component_1.ComponentService.register(PopupComponent);
28634 exports.default = PopupComponent;
28636 },{"../../Component":290,"../../Utils":300,"rxjs/Observable":29,"rxjs/Subject":34}],345:[function(require,module,exports){
28638 /// <reference path="../../../../typings/index.d.ts" />
28639 Object.defineProperty(exports, "__esModule", { value: true });
28640 var Subject_1 = require("rxjs/Subject");
28641 var Geo_1 = require("../../../Geo");
28642 var Utils_1 = require("../../../Utils");
28643 var Viewer_1 = require("../../../Viewer");
28647 * @classdesc Popup instance for rendering custom HTML content
28648 * on top of images. Popups are based on 2D basic image coordinates
28649 * (see the {@link Viewer} class documentation for more information about coordinate
28650 * systems) and a certain popup is therefore only relevant to a single image.
28651 * Popups related to a certain image should be removed when moving
28652 * to another image.
28654 * A popup must have both its content and its point or rect set to be
28655 * rendered. Popup options can not be updated after creation but the
28656 * basic point or rect as well as its content can be changed by calling
28657 * the appropriate methods.
28659 * To create and add one `Popup` with default configuration
28660 * (tooltip visuals and automatic float) and one with specific options
28665 * var defaultSpan = document.createElement('span');
28666 * defaultSpan.innerHTML = 'hello default';
28668 * var defaultPopup = new Mapillary.PopupComponent.Popup();
28669 * defaultPopup.setDOMContent(defaultSpan);
28670 * defaultPopup.setBasicPoint([0.3, 0.3]);
28672 * var cleanSpan = document.createElement('span');
28673 * cleanSpan.innerHTML = 'hello clean';
28675 * var cleanPopup = new Mapillary.PopupComponent.Popup({
28677 * float: Mapillary.Alignment.Top,
28682 * cleanPopup.setDOMContent(cleanSpan);
28683 * cleanPopup.setBasicPoint([0.6, 0.6]);
28685 * popupComponent.add([defaultPopup, cleanPopup]);
28688 * @description Implementation of API methods and API documentation inspired
28689 * by/used from https://github.com/mapbox/mapbox-gl-js/blob/v0.38.0/src/ui/popup.js
28691 var Popup = /** @class */ (function () {
28692 function Popup(options, viewportCoords, dom) {
28693 this._options = {};
28695 this._options.capturePointer = options.capturePointer == null ? true : options.capturePointer;
28696 this._options.clean = options.clean;
28697 this._options.float = options.float;
28698 this._options.offset = options.offset;
28699 this._options.opacity = options.opacity;
28700 this._options.position = options.position;
28702 this._dom = !!dom ? dom : new Utils_1.DOM();
28703 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
28704 this._notifyChanged$ = new Subject_1.Subject();
28706 Object.defineProperty(Popup.prototype, "changed$", {
28710 * @description Internal observable used by the component to
28711 * render the popup when its position or content has changed.
28714 return this._notifyChanged$;
28722 * @description Internal method used by the component to
28723 * remove all references to the popup.
28725 Popup.prototype.remove = function () {
28726 if (this._content && this._content.parentNode) {
28727 this._content.parentNode.removeChild(this._content);
28729 if (this._container) {
28730 this._container.parentNode.removeChild(this._container);
28731 delete this._container;
28733 if (this._parentContainer) {
28734 delete this._parentContainer;
28738 * Sets a 2D basic image coordinates point to the popup's anchor, and
28739 * moves the popup to it.
28741 * @description Overwrites any previously set point or rect.
28743 * @param {Array<number>} basicPoint - Point in 2D basic image coordinates.
28747 * var popup = new Mapillary.PopupComponent.Popup();
28748 * popup.setText('hello image');
28749 * popup.setBasicPoint([0.3, 0.3]);
28751 * popupComponent.add([popup]);
28754 Popup.prototype.setBasicPoint = function (basicPoint) {
28755 this._point = basicPoint.slice();
28757 this._notifyChanged$.next(this);
28760 * Sets a 2D basic image coordinates rect to the popup's anchor, and
28761 * moves the popup to it.
28763 * @description Overwrites any previously set point or rect.
28765 * @param {Array<number>} basicRect - Rect in 2D basic image
28766 * coordinates ([topLeftX, topLeftY, bottomRightX, bottomRightY]) .
28770 * var popup = new Mapillary.PopupComponent.Popup();
28771 * popup.setText('hello image');
28772 * popup.setBasicRect([0.3, 0.3, 0.5, 0.6]);
28774 * popupComponent.add([popup]);
28777 Popup.prototype.setBasicRect = function (basicRect) {
28778 this._rect = basicRect.slice();
28779 this._point = null;
28780 this._notifyChanged$.next(this);
28783 * Sets the popup's content to the element provided as a DOM node.
28785 * @param {Node} htmlNode - A DOM node to be used as content for the popup.
28789 * var div = document.createElement('div');
28790 * div.innerHTML = 'hello image';
28792 * var popup = new Mapillary.PopupComponent.Popup();
28793 * popup.setDOMContent(div);
28794 * popup.setBasicPoint([0.3, 0.3]);
28796 * popupComponent.add([popup]);
28799 Popup.prototype.setDOMContent = function (htmlNode) {
28800 if (this._content && this._content.parentNode) {
28801 this._content.parentNode.removeChild(this._content);
28803 var className = "mapillaryjs-popup-content" +
28804 (this._options.clean === true ? "-clean" : "") +
28805 (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : "");
28806 this._content = this._dom.createElement("div", className, this._container);
28807 this._content.appendChild(htmlNode);
28808 this._notifyChanged$.next(this);
28811 * Sets the popup's content to the HTML provided as a string.
28813 * @description This method does not perform HTML filtering or sanitization,
28814 * and must be used only with trusted content. Consider Popup#setText if the
28815 * content is an untrusted text string.
28817 * @param {string} html - A string representing HTML content for the popup.
28821 * var popup = new Mapillary.PopupComponent.Popup();
28822 * popup.setHTML('<div>hello image</div>');
28823 * popup.setBasicPoint([0.3, 0.3]);
28825 * popupComponent.add([popup]);
28828 Popup.prototype.setHTML = function (html) {
28829 var frag = this._dom.document.createDocumentFragment();
28830 var temp = this._dom.createElement("body");
28832 temp.innerHTML = html;
28834 child = temp.firstChild;
28838 frag.appendChild(child);
28840 this.setDOMContent(frag);
28843 * Sets the popup's content to a string of text.
28845 * @description This function creates a Text node in the DOM, so it cannot insert raw HTML.
28846 * Use this method for security against XSS if the popup content is user-provided.
28848 * @param {string} text - Textual content for the popup.
28852 * var popup = new Mapillary.PopupComponent.Popup();
28853 * popup.setText('hello image');
28854 * popup.setBasicPoint([0.3, 0.3]);
28856 * popupComponent.add([popup]);
28859 Popup.prototype.setText = function (text) {
28860 this.setDOMContent(this._dom.document.createTextNode(text));
28865 * @description Internal method for attaching the popup to
28866 * its parent container so that it is rendered in the DOM tree.
28868 Popup.prototype.setParentContainer = function (parentContainer) {
28869 this._parentContainer = parentContainer;
28874 * @description Internal method for updating the rendered
28875 * position of the popup called by the popup component.
28877 Popup.prototype.update = function (renderCamera, size, transform) {
28878 if (!this._parentContainer || !this._content) {
28881 if (!this._point && !this._rect) {
28884 if (!this._container) {
28885 this._container = this._dom.createElement("div", "mapillaryjs-popup", this._parentContainer);
28886 var showTip = this._options.clean !== true &&
28887 this._options.float !== Viewer_1.Alignment.Center;
28889 var tipClassName = "mapillaryjs-popup-tip" +
28890 (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : "");
28891 this._tip = this._dom.createElement("div", tipClassName, this._container);
28892 this._dom.createElement("div", "mapillaryjs-popup-tip-inner", this._tip);
28894 this._container.appendChild(this._content);
28895 this._parentContainer.appendChild(this._container);
28896 if (this._options.opacity != null) {
28897 this._container.style.opacity = this._options.opacity.toString();
28900 var pointPixel = null;
28901 var position = this._alignmentToPopupAligment(this._options.position);
28902 var float = this._alignmentToPopupAligment(this._options.float);
28903 var classList = this._container.classList;
28904 if (this._point != null) {
28906 this._viewportCoords.basicToCanvasSafe(this._point[0], this._point[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
28909 var alignments = ["center", "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right"];
28910 var appliedPosition = null;
28911 for (var _i = 0, alignments_1 = alignments; _i < alignments_1.length; _i++) {
28912 var alignment = alignments_1[_i];
28913 if (classList.contains("mapillaryjs-popup-float-" + alignment)) {
28914 appliedPosition = alignment;
28918 _a = this._rectToPixel(this._rect, position, appliedPosition, renderCamera, size, transform), pointPixel = _a[0], position = _a[1];
28923 if (pointPixel == null) {
28924 this._container.style.visibility = "hidden";
28927 this._container.style.visibility = "visible";
28929 var width = this._container.offsetWidth;
28930 var height = this._container.offsetHeight;
28931 var floats = this._pixelToFloats(pointPixel, size, width, height);
28932 float = floats.length === 0 ? "top" : floats.join("-");
28934 var offset = this._normalizeOffset(this._options.offset);
28935 pointPixel = [pointPixel[0] + offset[float][0], pointPixel[1] + offset[float][1]];
28936 pointPixel = [Math.round(pointPixel[0]), Math.round(pointPixel[1])];
28937 var floatTranslate = {
28938 "bottom": "translate(-50%,0)",
28939 "bottom-left": "translate(-100%,0)",
28940 "bottom-right": "translate(0,0)",
28941 "center": "translate(-50%,-50%)",
28942 "left": "translate(-100%,-50%)",
28943 "right": "translate(0,-50%)",
28944 "top": "translate(-50%,-100%)",
28945 "top-left": "translate(-100%,-100%)",
28946 "top-right": "translate(0,-100%)",
28948 for (var key in floatTranslate) {
28949 if (!floatTranslate.hasOwnProperty(key)) {
28952 classList.remove("mapillaryjs-popup-float-" + key);
28954 classList.add("mapillaryjs-popup-float-" + float);
28955 this._container.style.transform = floatTranslate[float] + " translate(" + pointPixel[0] + "px," + pointPixel[1] + "px)";
28958 Popup.prototype._rectToPixel = function (rect, position, appliedPosition, renderCamera, size, transform) {
28960 var width = this._container.offsetWidth;
28961 var height = this._container.offsetHeight;
28962 var floatOffsets = {
28963 "bottom": [0, height / 2],
28964 "bottom-left": [-width / 2, height / 2],
28965 "bottom-right": [width / 2, height / 2],
28966 "left": [-width / 2, 0],
28967 "right": [width / 2, 0],
28968 "top": [0, -height / 2],
28969 "top-left": [-width / 2, -height / 2],
28970 "top-right": [width / 2, -height / 2],
28972 var automaticPositions = ["top", "bottom", "left", "right"];
28973 var largestVisibleArea = [0, null, null];
28974 for (var _i = 0, automaticPositions_1 = automaticPositions; _i < automaticPositions_1.length; _i++) {
28975 var automaticPosition = automaticPositions_1[_i];
28976 var autoPointBasic = this._pointFromRectPosition(rect, automaticPosition);
28977 var autoPointPixel = this._viewportCoords.basicToCanvasSafe(autoPointBasic[0], autoPointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
28978 if (autoPointPixel == null) {
28981 var floatOffset = floatOffsets[automaticPosition];
28982 var offsetedPosition = [autoPointPixel[0] + floatOffset[0], autoPointPixel[1] + floatOffset[1]];
28983 var staticCoeff = appliedPosition != null && appliedPosition === automaticPosition ? 1 : 0.7;
28984 var floats = this._pixelToFloats(offsetedPosition, size, width / staticCoeff, height / (2 * staticCoeff));
28985 if (floats.length === 0 &&
28986 autoPointPixel[0] > 0 &&
28987 autoPointPixel[0] < size.width &&
28988 autoPointPixel[1] > 0 &&
28989 autoPointPixel[1] < size.height) {
28990 return [autoPointPixel, automaticPosition];
28992 var minX = Math.max(offsetedPosition[0] - width / 2, 0);
28993 var maxX = Math.min(offsetedPosition[0] + width / 2, size.width);
28994 var minY = Math.max(offsetedPosition[1] - height / 2, 0);
28995 var maxY = Math.min(offsetedPosition[1] + height / 2, size.height);
28996 var visibleX = Math.max(0, maxX - minX);
28997 var visibleY = Math.max(0, maxY - minY);
28998 var visibleArea = staticCoeff * visibleX * visibleY;
28999 if (visibleArea > largestVisibleArea[0]) {
29000 largestVisibleArea[0] = visibleArea;
29001 largestVisibleArea[1] = autoPointPixel;
29002 largestVisibleArea[2] = automaticPosition;
29005 if (largestVisibleArea[0] > 0) {
29006 return [largestVisibleArea[1], largestVisibleArea[2]];
29009 var pointBasic = this._pointFromRectPosition(rect, position);
29010 var pointPixel = this._viewportCoords.basicToCanvasSafe(pointBasic[0], pointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
29011 return [pointPixel, position != null ? position : "top"];
29013 Popup.prototype._alignmentToPopupAligment = function (float) {
29015 case Viewer_1.Alignment.Bottom:
29017 case Viewer_1.Alignment.BottomLeft:
29018 return "bottom-left";
29019 case Viewer_1.Alignment.BottomRight:
29020 return "bottom-right";
29021 case Viewer_1.Alignment.Center:
29023 case Viewer_1.Alignment.Left:
29025 case Viewer_1.Alignment.Right:
29027 case Viewer_1.Alignment.Top:
29029 case Viewer_1.Alignment.TopLeft:
29031 case Viewer_1.Alignment.TopRight:
29032 return "top-right";
29037 Popup.prototype._normalizeOffset = function (offset) {
29038 if (offset == null) {
29039 return this._normalizeOffset(0);
29041 if (typeof offset === "number") {
29042 // input specifies a radius
29043 var sideOffset = offset;
29044 var sign = sideOffset >= 0 ? 1 : -1;
29045 var cornerOffset = sign * Math.round(Math.sqrt(0.5 * Math.pow(sideOffset, 2)));
29047 "bottom": [0, sideOffset],
29048 "bottom-left": [-cornerOffset, cornerOffset],
29049 "bottom-right": [cornerOffset, cornerOffset],
29051 "left": [-sideOffset, 0],
29052 "right": [sideOffset, 0],
29053 "top": [0, -sideOffset],
29054 "top-left": [-cornerOffset, -cornerOffset],
29055 "top-right": [cornerOffset, -cornerOffset],
29059 // input specifes a value for each position
29061 "bottom": offset.bottom || [0, 0],
29062 "bottom-left": offset.bottomLeft || [0, 0],
29063 "bottom-right": offset.bottomRight || [0, 0],
29064 "center": offset.center || [0, 0],
29065 "left": offset.left || [0, 0],
29066 "right": offset.right || [0, 0],
29067 "top": offset.top || [0, 0],
29068 "top-left": offset.topLeft || [0, 0],
29069 "top-right": offset.topRight || [0, 0],
29073 Popup.prototype._pixelToFloats = function (pointPixel, size, width, height) {
29075 if (pointPixel[1] < height) {
29076 floats.push("bottom");
29078 else if (pointPixel[1] > size.height - height) {
29079 floats.push("top");
29081 if (pointPixel[0] < width / 2) {
29082 floats.push("right");
29084 else if (pointPixel[0] > size.width - width / 2) {
29085 floats.push("left");
29089 Popup.prototype._pointFromRectPosition = function (rect, position) {
29091 var x1 = rect[0] < rect[2] ? rect[2] : rect[2] + 1;
29094 switch (position) {
29096 return [(x0 + x1) / 2, y1];
29097 case "bottom-left":
29099 case "bottom-right":
29102 return [(x0 + x1) / 2, (y0 + y1) / 2];
29104 return [x0, (y0 + y1) / 2];
29106 return [x1, (y0 + y1) / 2];
29108 return [(x0 + x1) / 2, y0];
29114 return [(x0 + x1) / 2, y1];
29119 exports.Popup = Popup;
29120 exports.default = Popup;
29122 },{"../../../Geo":293,"../../../Utils":300,"../../../Viewer":301,"rxjs/Subject":34}],346:[function(require,module,exports){
29124 /// <reference path="../../../typings/index.d.ts" />
29125 var __extends = (this && this.__extends) || (function () {
29126 var extendStatics = Object.setPrototypeOf ||
29127 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29128 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29129 return function (d, b) {
29130 extendStatics(d, b);
29131 function __() { this.constructor = d; }
29132 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29135 Object.defineProperty(exports, "__esModule", { value: true });
29136 var Observable_1 = require("rxjs/Observable");
29137 var Subject_1 = require("rxjs/Subject");
29138 var Component_1 = require("../../Component");
29139 var Edge_1 = require("../../Edge");
29140 var Graph_1 = require("../../Graph");
29142 * @class SequenceComponent
29143 * @classdesc Component showing navigation arrows for sequence directions
29144 * as well as playing button. Exposes an API to start and stop play.
29146 var SequenceComponent = /** @class */ (function (_super) {
29147 __extends(SequenceComponent, _super);
29148 function SequenceComponent(name, container, navigator, renderer, scheduler) {
29149 var _this = _super.call(this, name, container, navigator) || this;
29150 _this._sequenceDOMRenderer = !!renderer ? renderer : new Component_1.SequenceDOMRenderer(container);
29151 _this._scheduler = scheduler;
29152 _this._containerWidth$ = new Subject_1.Subject();
29153 _this._hoveredKeySubject$ = new Subject_1.Subject();
29154 _this._hoveredKey$ = _this._hoveredKeySubject$.share();
29155 _this._navigator.playService.playing$
29157 .withLatestFrom(_this._configuration$)
29158 .subscribe(function (_a) {
29159 var playing = _a[0], configuration = _a[1];
29160 _this.fire(SequenceComponent.playingchanged, playing);
29161 if (playing === configuration.playing) {
29171 _this._navigator.playService.direction$
29173 .withLatestFrom(_this._configuration$)
29174 .subscribe(function (_a) {
29175 var direction = _a[0], configuration = _a[1];
29176 if (direction !== configuration.direction) {
29177 _this.setDirection(direction);
29182 Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", {
29184 * Get hovered key observable.
29186 * @description An observable emitting the key of the node for the direction
29187 * arrow that is being hovered. When the mouse leaves a direction arrow null
29190 * @returns {Observable<string>}
29193 return this._hoveredKey$;
29201 * @fires PlayerComponent#playingchanged
29203 SequenceComponent.prototype.play = function () {
29204 this.configure({ playing: true });
29209 * @fires PlayerComponent#playingchanged
29211 SequenceComponent.prototype.stop = function () {
29212 this.configure({ playing: false });
29215 * Set the direction to follow when playing.
29217 * @param {EdgeDirection} direction - The direction that will be followed when playing.
29219 SequenceComponent.prototype.setDirection = function (direction) {
29220 this.configure({ direction: direction });
29223 * Set highlight key.
29225 * @description The arrow pointing towards the node corresponding to the
29226 * highlight key will be highlighted.
29228 * @param {string} highlightKey Key of node to be highlighted if existing.
29230 SequenceComponent.prototype.setHighlightKey = function (highlightKey) {
29231 this.configure({ highlightKey: highlightKey });
29234 * Set max width of container element.
29236 * @description Set max width of the container element holding
29237 * the sequence navigation elements. If the min width is larger than the
29238 * max width the min width value will be used.
29240 * The container element is automatically resized when the resize
29241 * method on the Viewer class is called.
29243 * @param {number} minWidth
29245 SequenceComponent.prototype.setMaxWidth = function (maxWidth) {
29246 this.configure({ maxWidth: maxWidth });
29249 * Set min width of container element.
29251 * @description Set min width of the container element holding
29252 * the sequence navigation elements. If the min width is larger than the
29253 * max width the min width value will be used.
29255 * The container element is automatically resized when the resize
29256 * method on the Viewer class is called.
29258 * @param {number} minWidth
29260 SequenceComponent.prototype.setMinWidth = function (minWidth) {
29261 this.configure({ minWidth: minWidth });
29264 * Set the value indicating whether the sequence UI elements should be visible.
29266 * @param {boolean} visible
29268 SequenceComponent.prototype.setVisible = function (visible) {
29269 this.configure({ visible: visible });
29272 SequenceComponent.prototype.resize = function () {
29274 this._configuration$
29276 .map(function (configuration) {
29277 return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
29279 .subscribe(function (containerWidth) {
29280 _this._containerWidth$.next(containerWidth);
29283 SequenceComponent.prototype._activate = function () {
29285 this._sequenceDOMRenderer.activate();
29286 var edgeStatus$ = this._navigator.stateService.currentNode$
29287 .switchMap(function (node) {
29288 return node.sequenceEdges$;
29292 var sequence$ = this._navigator.stateService.currentNode$
29293 .distinctUntilChanged(undefined, function (node) {
29294 return node.sequenceKey;
29296 .switchMap(function (node) {
29297 return Observable_1.Observable
29298 .concat(Observable_1.Observable.of(null), _this._navigator.graphService.cacheSequence$(node.sequenceKey)
29300 .catch(function (e) {
29301 console.error("Failed to cache sequence", e);
29302 return Observable_1.Observable.of(null);
29308 this._sequenceSubscription = sequence$.subscribe();
29309 var rendererKey$ = this._sequenceDOMRenderer.index$
29310 .withLatestFrom(sequence$)
29311 .map(function (_a) {
29312 var index = _a[0], sequence = _a[1];
29313 return sequence != null ? sequence.keys[index] : null;
29315 .filter(function (key) {
29318 .distinctUntilChanged()
29321 this._moveSubscription = Observable_1.Observable
29322 .merge(rendererKey$.debounceTime(100, this._scheduler), rendererKey$.auditTime(400, this._scheduler))
29323 .distinctUntilChanged()
29324 .switchMap(function (key) {
29325 return _this._navigator.moveToKey$(key)
29326 .catch(function (e) {
29327 return Observable_1.Observable.empty();
29331 this._setSequenceGraphModeSubscription = this._sequenceDOMRenderer.changingPositionChanged$
29332 .filter(function (changing) {
29335 .subscribe(function () {
29336 _this._navigator.graphService.setGraphMode(Graph_1.GraphMode.Sequence);
29338 this._setSpatialGraphModeSubscription = this._sequenceDOMRenderer.changingPositionChanged$
29339 .filter(function (changing) {
29342 .subscribe(function () {
29343 _this._navigator.graphService.setGraphMode(Graph_1.GraphMode.Spatial);
29345 this._navigator.graphService.graphMode$
29346 .switchMap(function (mode) {
29347 return mode === Graph_1.GraphMode.Spatial ?
29348 _this._navigator.stateService.currentNode$
29350 Observable_1.Observable.empty();
29352 .filter(function (node) {
29353 return !node.spatialEdges.cached;
29355 .switchMap(function (node) {
29356 return _this._navigator.graphService.cacheNode$(node.key)
29357 .catch(function (e) {
29358 return Observable_1.Observable.empty();
29362 this._stopSubscription = this._sequenceDOMRenderer.changingPositionChanged$
29363 .filter(function (changing) {
29366 .subscribe(function () {
29367 _this._navigator.playService.stop();
29369 this._cacheSequenceNodesSubscription = Observable_1.Observable
29370 .combineLatest(this._navigator.graphService.graphMode$, this._sequenceDOMRenderer.changingPositionChanged$
29372 .distinctUntilChanged())
29373 .withLatestFrom(this._navigator.stateService.currentNode$)
29374 .switchMap(function (_a) {
29375 var _b = _a[0], mode = _b[0], changing = _b[1], node = _a[1];
29376 return changing && mode === Graph_1.GraphMode.Sequence ?
29377 _this._navigator.graphService.cacheSequenceNodes$(node.sequenceKey, node.key)
29379 .catch(function (error) {
29380 console.error("Failed to cache sequence nodes.", error);
29381 return Observable_1.Observable.empty();
29383 Observable_1.Observable.empty();
29386 var position$ = sequence$
29387 .switchMap(function (sequence) {
29389 return Observable_1.Observable.of({ index: null, max: null });
29391 var firstCurrentKey = true;
29392 return _this._sequenceDOMRenderer.changingPositionChanged$
29394 .distinctUntilChanged()
29395 .switchMap(function (changingPosition) {
29396 var skip = !changingPosition && firstCurrentKey ? 0 : 1;
29397 firstCurrentKey = false;
29398 return changingPosition ?
29400 _this._navigator.stateService.currentNode$
29401 .map(function (node) {
29404 .distinctUntilChanged()
29407 .map(function (key) {
29408 var index = sequence.keys.indexOf(key);
29409 if (index === -1) {
29410 return { index: null, max: null };
29412 return { index: index, max: sequence.keys.length - 1 };
29415 this._renderSubscription = Observable_1.Observable
29416 .combineLatest(edgeStatus$, this._configuration$, this._containerWidth$, this._sequenceDOMRenderer.changed$.startWith(this._sequenceDOMRenderer), this._navigator.playService.speed$, position$)
29417 .map(function (_a) {
29418 var edgeStatus = _a[0], configuration = _a[1], containerWidth = _a[2], renderer = _a[3], speed = _a[4], position = _a[5];
29419 var vNode = _this._sequenceDOMRenderer
29420 .render(edgeStatus, configuration, containerWidth, speed, position.index, position.max, _this, _this._navigator);
29421 return { name: _this._name, vnode: vNode };
29423 .subscribe(this._container.domRenderer.render$);
29424 this._setSpeedSubscription = this._sequenceDOMRenderer.speed$
29425 .subscribe(function (speed) {
29426 _this._navigator.playService.setSpeed(speed);
29428 this._setDirectionSubscription = this._configuration$
29429 .map(function (configuration) {
29430 return configuration.direction;
29432 .distinctUntilChanged()
29433 .subscribe(function (direction) {
29434 _this._navigator.playService.setDirection(direction);
29436 this._containerWidthSubscription = this._configuration$
29437 .distinctUntilChanged(function (value1, value2) {
29438 return value1[0] === value2[0] && value1[1] === value2[1];
29439 }, function (configuration) {
29440 return [configuration.minWidth, configuration.maxWidth];
29442 .map(function (configuration) {
29443 return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
29445 .subscribe(this._containerWidth$);
29446 this._playingSubscription = this._configuration$
29447 .map(function (configuration) {
29448 return configuration.playing;
29450 .distinctUntilChanged()
29451 .subscribe(function (playing) {
29453 _this._navigator.playService.play();
29456 _this._navigator.playService.stop();
29459 this._hoveredKeySubscription = this._sequenceDOMRenderer.mouseEnterDirection$
29460 .switchMap(function (direction) {
29462 .map(function (edgeStatus) {
29463 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
29465 if (edge.data.direction === direction) {
29471 .takeUntil(_this._sequenceDOMRenderer.mouseLeaveDirection$)
29472 .concat(Observable_1.Observable.of(null));
29474 .distinctUntilChanged()
29475 .subscribe(this._hoveredKeySubject$);
29477 SequenceComponent.prototype._deactivate = function () {
29478 this._renderSubscription.unsubscribe();
29479 this._playingSubscription.unsubscribe();
29480 this._containerWidthSubscription.unsubscribe();
29481 this._hoveredKeySubscription.unsubscribe();
29482 this._setSpeedSubscription.unsubscribe();
29483 this._setDirectionSubscription.unsubscribe();
29484 this._setSequenceGraphModeSubscription.unsubscribe();
29485 this._setSpatialGraphModeSubscription.unsubscribe();
29486 this._sequenceSubscription.unsubscribe();
29487 this._moveSubscription.unsubscribe();
29488 this._cacheSequenceNodesSubscription.unsubscribe();
29489 this._stopSubscription.unsubscribe();
29490 this._sequenceDOMRenderer.deactivate();
29492 SequenceComponent.prototype._getDefaultConfiguration = function () {
29494 direction: Edge_1.EdgeDirection.Next,
29502 SequenceComponent.componentName = "sequence";
29504 * Event fired when playing starts or stops.
29506 * @event PlayerComponent#playingchanged
29507 * @type {boolean} Indicates whether the player is playing.
29509 SequenceComponent.playingchanged = "playingchanged";
29510 return SequenceComponent;
29511 }(Component_1.Component));
29512 exports.SequenceComponent = SequenceComponent;
29513 Component_1.ComponentService.register(SequenceComponent);
29514 exports.default = SequenceComponent;
29516 },{"../../Component":290,"../../Edge":291,"../../Graph":294,"rxjs/Observable":29,"rxjs/Subject":34}],347:[function(require,module,exports){
29518 /// <reference path="../../../typings/index.d.ts" />
29519 Object.defineProperty(exports, "__esModule", { value: true });
29520 var vd = require("virtual-dom");
29521 var Observable_1 = require("rxjs/Observable");
29522 var Subject_1 = require("rxjs/Subject");
29523 var Component_1 = require("../../Component");
29524 var Edge_1 = require("../../Edge");
29525 var Error_1 = require("../../Error");
29526 var SequenceDOMRenderer = /** @class */ (function () {
29527 function SequenceDOMRenderer(container) {
29528 this._container = container;
29529 this._minThresholdWidth = 320;
29530 this._maxThresholdWidth = 1480;
29531 this._minThresholdHeight = 240;
29532 this._maxThresholdHeight = 820;
29533 this._stepperDefaultWidth = 108;
29534 this._controlsDefaultWidth = 88;
29535 this._defaultHeight = 30;
29536 this._expandControls = false;
29537 this._mode = Component_1.SequenceMode.Default;
29539 this._changingSpeed = false;
29540 this._index = null;
29541 this._changingPosition = false;
29542 this._mouseEnterDirection$ = new Subject_1.Subject();
29543 this._mouseLeaveDirection$ = new Subject_1.Subject();
29544 this._notifyChanged$ = new Subject_1.Subject();
29545 this._notifyChangingPositionChanged$ = new Subject_1.Subject();
29546 this._notifySpeedChanged$ = new Subject_1.Subject();
29547 this._notifyIndexChanged$ = new Subject_1.Subject();
29549 Object.defineProperty(SequenceDOMRenderer.prototype, "changed$", {
29551 return this._notifyChanged$;
29556 Object.defineProperty(SequenceDOMRenderer.prototype, "changingPositionChanged$", {
29558 return this._notifyChangingPositionChanged$;
29563 Object.defineProperty(SequenceDOMRenderer.prototype, "speed$", {
29565 return this._notifySpeedChanged$;
29570 Object.defineProperty(SequenceDOMRenderer.prototype, "index$", {
29572 return this._notifyIndexChanged$;
29577 Object.defineProperty(SequenceDOMRenderer.prototype, "mouseEnterDirection$", {
29579 return this._mouseEnterDirection$;
29584 Object.defineProperty(SequenceDOMRenderer.prototype, "mouseLeaveDirection$", {
29586 return this._mouseLeaveDirection$;
29591 SequenceDOMRenderer.prototype.activate = function () {
29593 if (!!this._changingSubscription) {
29596 this._changingSubscription = Observable_1.Observable
29597 .merge(this._container.mouseService.documentMouseUp$, this._container.touchService.touchEnd$
29598 .filter(function (touchEvent) {
29599 return touchEvent.touches.length === 0;
29601 .subscribe(function (event) {
29602 if (_this._changingSpeed) {
29603 _this._changingSpeed = false;
29605 if (_this._changingPosition) {
29606 _this._setChangingPosition(false);
29610 SequenceDOMRenderer.prototype.deactivate = function () {
29611 if (!this._changingSubscription) {
29614 this._changingSpeed = false;
29615 this._changingPosition = false;
29616 this._expandControls = false;
29617 this._mode = Component_1.SequenceMode.Default;
29618 this._changingSubscription.unsubscribe();
29619 this._changingSubscription = null;
29621 SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, speed, index, max, component, navigator) {
29622 if (configuration.visible === false) {
29623 return vd.h("div.SequenceContainer", {}, []);
29625 var stepper = this._createStepper(edgeStatus, configuration, containerWidth, component, navigator);
29626 var controls = this._createSequenceControls(containerWidth);
29627 var playback = this._createPlaybackControls(containerWidth, speed, component, configuration);
29628 var timeline = this._createTimelineControls(containerWidth, index, max);
29629 return vd.h("div.SequenceContainer", [stepper, controls, playback, timeline]);
29631 SequenceDOMRenderer.prototype.getContainerWidth = function (element, configuration) {
29632 var elementWidth = element.offsetWidth;
29633 var elementHeight = element.offsetHeight;
29634 var minWidth = configuration.minWidth;
29635 var maxWidth = configuration.maxWidth;
29636 if (maxWidth < minWidth) {
29637 maxWidth = minWidth;
29639 var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
29640 var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
29641 var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
29642 return minWidth + coeff * (maxWidth - minWidth);
29644 SequenceDOMRenderer.prototype._createPositionInput = function (index, max) {
29646 this._index = index;
29647 var onPosition = function (e) {
29648 _this._index = Number(e.target.value);
29649 _this._notifyIndexChanged$.next(_this._index);
29651 var boundingRect = this._container.domContainer.getBoundingClientRect();
29652 var width = Math.max(276, Math.min(410, 5 + 0.8 * boundingRect.width)) - 65;
29653 var onStart = function (e) {
29654 e.stopPropagation();
29655 _this._setChangingPosition(true);
29657 var onMove = function (e) {
29658 if (_this._changingPosition === true) {
29659 e.stopPropagation();
29662 var onKeyDown = function (e) {
29663 if (e.key === "ArrowDown" || e.key === "ArrowLeft" ||
29664 e.key === "ArrowRight" || e.key === "ArrowUp") {
29665 e.preventDefault();
29668 var positionInputProperties = {
29669 max: max != null ? max : 1,
29671 onchange: onPosition,
29672 oninput: onPosition,
29673 onkeydown: onKeyDown,
29674 onmousedown: onStart,
29675 onmousemove: onMove,
29676 ontouchmove: onMove,
29677 ontouchstart: onStart,
29679 width: width + "px",
29682 value: index != null ? index : 0,
29684 var disabled = index == null || max == null || max <= 1;
29686 positionInputProperties.disabled = "true";
29688 var positionInput = vd.h("input.SequencePosition", positionInputProperties, []);
29689 var positionContainerClass = disabled ? ".SequencePositionContainerDisabled" : ".SequencePositionContainer";
29690 return vd.h("div" + positionContainerClass, [positionInput]);
29692 SequenceDOMRenderer.prototype._createSpeedInput = function (speed) {
29694 this._speed = speed;
29695 var onSpeed = function (e) {
29696 _this._speed = Number(e.target.value) / 1000;
29697 _this._notifySpeedChanged$.next(_this._speed);
29699 var boundingRect = this._container.domContainer.getBoundingClientRect();
29700 var width = Math.max(276, Math.min(410, 5 + 0.8 * boundingRect.width)) - 160;
29701 var onStart = function (e) {
29702 _this._changingSpeed = true;
29703 e.stopPropagation();
29705 var onMove = function (e) {
29706 if (_this._changingSpeed === true) {
29707 e.stopPropagation();
29710 var onKeyDown = function (e) {
29711 if (e.key === "ArrowDown" || e.key === "ArrowLeft" ||
29712 e.key === "ArrowRight" || e.key === "ArrowUp") {
29713 e.preventDefault();
29716 var speedInput = vd.h("input.SequenceSpeed", {
29721 onkeydown: onKeyDown,
29722 onmousedown: onStart,
29723 onmousemove: onMove,
29724 ontouchmove: onMove,
29725 ontouchstart: onStart,
29727 width: width + "px",
29730 value: 1000 * speed,
29732 return vd.h("div.SequenceSpeedContainer", [speedInput]);
29734 SequenceDOMRenderer.prototype._createPlaybackControls = function (containerWidth, speed, component, configuration) {
29736 if (this._mode !== Component_1.SequenceMode.Playback) {
29737 return vd.h("div.SequencePlayback", []);
29739 var switchIcon = vd.h("div.SequenceSwitchIcon.SequenceIconVisible", []);
29740 var direction = configuration.direction === Edge_1.EdgeDirection.Next ?
29741 Edge_1.EdgeDirection.Prev : Edge_1.EdgeDirection.Next;
29742 var playing = configuration.playing;
29743 var switchButtonProperties = {
29744 onclick: function () {
29746 component.setDirection(direction);
29750 var switchButtonClassName = configuration.playing ? ".SequenceSwitchButtonDisabled" : ".SequenceSwitchButton";
29751 var switchButton = vd.h("div" + switchButtonClassName, switchButtonProperties, [switchIcon]);
29752 var slowIcon = vd.h("div.SequenceSlowIcon.SequenceIconVisible", []);
29753 var slowContainer = vd.h("div.SequenceSlowContainer", [slowIcon]);
29754 var fastIcon = vd.h("div.SequenceFastIcon.SequenceIconVisible", []);
29755 var fastContainer = vd.h("div.SequenceFastContainer", [fastIcon]);
29756 var closeIcon = vd.h("div.SequenceCloseIcon.SequenceIconVisible", []);
29757 var closeButtonProperties = {
29758 onclick: function () {
29759 _this._mode = Component_1.SequenceMode.Default;
29760 _this._notifyChanged$.next(_this);
29763 var closeButton = vd.h("div.SequenceCloseButton", closeButtonProperties, [closeIcon]);
29764 var speedInput = this._createSpeedInput(speed);
29765 var playbackChildren = [switchButton, slowContainer, speedInput, fastContainer, closeButton];
29766 var top = Math.round(containerWidth / this._stepperDefaultWidth * this._defaultHeight + 10);
29767 var playbackProperties = { style: { top: top + "px" } };
29768 return vd.h("div.SequencePlayback", playbackProperties, playbackChildren);
29770 SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) {
29771 var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null ||
29772 configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null;
29773 var onclick = configuration.playing ?
29774 function (e) { component.stop(); } :
29775 canPlay ? function (e) { component.play(); } : null;
29776 var buttonProperties = { onclick: onclick };
29777 var iconClass = configuration.playing ?
29779 canPlay ? "Play" : "PlayDisabled";
29780 var iconProperties = { className: iconClass };
29781 if (configuration.direction === Edge_1.EdgeDirection.Prev) {
29782 iconProperties.style = {
29783 transform: "rotate(180deg) translate(50%, 50%)",
29786 var icon = vd.h("div.SequenceComponentIcon", iconProperties, []);
29787 var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled";
29788 return vd.h("div." + buttonClass, buttonProperties, [icon]);
29790 SequenceDOMRenderer.prototype._createSequenceControls = function (containerWidth) {
29792 var borderRadius = Math.round(8 / this._stepperDefaultWidth * containerWidth);
29793 var expanderProperties = {
29794 onclick: function () {
29795 _this._expandControls = !_this._expandControls;
29796 _this._mode = Component_1.SequenceMode.Default;
29797 _this._notifyChanged$.next(_this);
29800 "border-bottom-right-radius": borderRadius + "px",
29801 "border-top-right-radius": borderRadius + "px",
29804 var expanderBar = vd.h("div.SequenceExpanderBar", []);
29805 var expander = vd.h("div.SequenceExpanderButton", expanderProperties, [expanderBar]);
29806 var fastIconClassName = this._mode === Component_1.SequenceMode.Playback ?
29807 ".SequenceFastIconGrey.SequenceIconVisible" : ".SequenceFastIcon";
29808 var fastIcon = vd.h("div" + fastIconClassName, []);
29809 var playbackProperties = {
29810 onclick: function () {
29811 _this._mode = _this._mode === Component_1.SequenceMode.Playback ?
29812 Component_1.SequenceMode.Default :
29813 Component_1.SequenceMode.Playback;
29814 _this._notifyChanged$.next(_this);
29817 var playback = vd.h("div.SequencePlaybackButton", playbackProperties, [fastIcon]);
29818 var timelineIconClassName = this._mode === Component_1.SequenceMode.Timeline ?
29819 ".SequenceTimelineIconGrey.SequenceIconVisible" : ".SequenceTimelineIcon";
29820 var timelineIcon = vd.h("div" + timelineIconClassName, []);
29821 var timelineProperties = {
29822 onclick: function () {
29823 _this._mode = _this._mode === Component_1.SequenceMode.Timeline ?
29824 Component_1.SequenceMode.Default :
29825 Component_1.SequenceMode.Timeline;
29826 _this._notifyChanged$.next(_this);
29829 var timeline = vd.h("div.SequenceTimelineButton", timelineProperties, [timelineIcon]);
29832 height: (this._defaultHeight / this._stepperDefaultWidth * containerWidth) + "px",
29833 transform: "translate(" + (containerWidth / 2 + 2) + "px, 0)",
29834 width: (this._controlsDefaultWidth / this._stepperDefaultWidth * containerWidth) + "px",
29837 var className = ".SequenceControls" +
29838 (this._expandControls ? ".SequenceControlsExpanded" : "");
29839 return vd.h("div" + className, properties, [playback, timeline, expander]);
29841 SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, containerWidth, configuration, navigator) {
29843 var nextProperties = {
29844 onclick: nextKey != null ?
29846 navigator.moveDir$(Edge_1.EdgeDirection.Next)
29847 .subscribe(undefined, function (error) {
29848 if (!(error instanceof Error_1.AbortMapillaryError)) {
29849 console.error(error);
29854 onmouseenter: function (e) { _this._mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); },
29855 onmouseleave: function (e) { _this._mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); },
29857 var borderRadius = Math.round(8 / this._stepperDefaultWidth * containerWidth);
29858 var prevProperties = {
29859 onclick: prevKey != null ?
29861 navigator.moveDir$(Edge_1.EdgeDirection.Prev)
29862 .subscribe(undefined, function (error) {
29863 if (!(error instanceof Error_1.AbortMapillaryError)) {
29864 console.error(error);
29869 onmouseenter: function (e) { _this._mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); },
29870 onmouseleave: function (e) { _this._mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); },
29872 "border-bottom-left-radius": borderRadius + "px",
29873 "border-top-left-radius": borderRadius + "px",
29876 var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey);
29877 var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey);
29878 var nextIcon = vd.h("div.SequenceComponentIcon", []);
29879 var prevIcon = vd.h("div.SequenceComponentIcon", []);
29881 vd.h("div." + prevClass, prevProperties, [prevIcon]),
29882 vd.h("div." + nextClass, nextProperties, [nextIcon]),
29885 SequenceDOMRenderer.prototype._createStepper = function (edgeStatus, configuration, containerWidth, component, navigator) {
29886 var nextKey = null;
29887 var prevKey = null;
29888 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
29890 if (edge.data.direction === Edge_1.EdgeDirection.Next) {
29893 if (edge.data.direction === Edge_1.EdgeDirection.Prev) {
29897 var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component);
29898 var buttons = this._createSequenceArrows(nextKey, prevKey, containerWidth, configuration, navigator);
29899 buttons.splice(1, 0, playingButton);
29900 var containerProperties = {
29901 oncontextmenu: function (event) { event.preventDefault(); },
29903 height: (this._defaultHeight / this._stepperDefaultWidth * containerWidth) + "px",
29904 width: containerWidth + "px",
29907 return vd.h("div.SequenceStepper", containerProperties, buttons);
29909 SequenceDOMRenderer.prototype._createTimelineControls = function (containerWidth, index, max) {
29911 if (this._mode !== Component_1.SequenceMode.Timeline) {
29912 return vd.h("div.SequenceTimeline", []);
29914 var positionInput = this._createPositionInput(index, max);
29915 var closeIcon = vd.h("div.SequenceCloseIcon.SequenceIconVisible", []);
29916 var closeButtonProperties = {
29917 onclick: function () {
29918 _this._mode = Component_1.SequenceMode.Default;
29919 _this._notifyChanged$.next(_this);
29922 var closeButton = vd.h("div.SequenceCloseButton", closeButtonProperties, [closeIcon]);
29923 var top = Math.round(containerWidth / this._stepperDefaultWidth * this._defaultHeight + 10);
29924 var playbackProperties = { style: { top: top + "px" } };
29925 return vd.h("div.SequenceTimeline", playbackProperties, [positionInput, closeButton]);
29927 SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) {
29928 var className = direction === Edge_1.EdgeDirection.Next ?
29929 "SequenceStepNext" :
29930 "SequenceStepPrev";
29932 className += "Disabled";
29935 if (highlightKey === key) {
29936 className += "Highlight";
29941 SequenceDOMRenderer.prototype._setChangingPosition = function (value) {
29942 this._changingPosition = value;
29943 this._notifyChangingPositionChanged$.next(value);
29945 return SequenceDOMRenderer;
29947 exports.SequenceDOMRenderer = SequenceDOMRenderer;
29948 exports.default = SequenceDOMRenderer;
29950 },{"../../Component":290,"../../Edge":291,"../../Error":292,"rxjs/Observable":29,"rxjs/Subject":34,"virtual-dom":246}],348:[function(require,module,exports){
29952 Object.defineProperty(exports, "__esModule", { value: true });
29954 (function (SequenceMode) {
29955 SequenceMode[SequenceMode["Default"] = 0] = "Default";
29956 SequenceMode[SequenceMode["Playback"] = 1] = "Playback";
29957 SequenceMode[SequenceMode["Timeline"] = 2] = "Timeline";
29958 })(SequenceMode = exports.SequenceMode || (exports.SequenceMode = {}));
29959 exports.default = SequenceMode;
29961 },{}],349:[function(require,module,exports){
29963 /// <reference path="../../../typings/index.d.ts" />
29964 Object.defineProperty(exports, "__esModule", { value: true });
29966 var path = require("path");
29967 var Shaders = /** @class */ (function () {
29968 function Shaders() {
29970 Shaders.equirectangular = {
29971 fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform float phiLength;\nuniform float phiShift;\nuniform float thetaLength;\nuniform float thetaShift;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vec3 b = normalize(vRstq.xyz);\n float lat = -asin(b.y);\n float lon = atan(b.x, b.z);\n float x = (lon - phiShift) / phiLength + 0.5;\n float y = (lat - thetaShift) / thetaLength + 0.5;\n vec4 baseColor = texture2D(projectorTex, vec2(x, y));\n baseColor.a = opacity;\n gl_FragColor = baseColor;\n}",
29972 vertex: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform mat4 projectorMat;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vRstq = projectorMat * vec4(position, 1.0);\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}",
29974 Shaders.equirectangularCurtain = {
29975 fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float curtain;\nuniform float opacity;\nuniform float phiLength;\nuniform float phiShift;\nuniform float thetaLength;\nuniform float thetaShift;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vec3 b = normalize(vRstq.xyz);\n float lat = -asin(b.y);\n float lon = atan(b.x, b.z);\n float x = (lon - phiShift) / phiLength + 0.5;\n float y = (lat - thetaShift) / thetaLength + 0.5;\n\n bool inverted = curtain < 0.5;\n\n float curtainMin = inverted ? curtain + 0.5 : curtain - 0.5;\n float curtainMax = curtain;\n\n bool insideCurtain = inverted ?\n x > curtainMin || x < curtainMax :\n x > curtainMin && x < curtainMax;\n\n vec4 baseColor;\n if (insideCurtain) {\n baseColor = texture2D(projectorTex, vec2(x, y));\n baseColor.a = opacity;\n } else {\n baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n }\n\n gl_FragColor = baseColor;\n}",
29976 vertex: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform mat4 projectorMat;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vRstq = projectorMat * vec4(position, 1.0);\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}",
29978 Shaders.perspective = {
29979 fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform vec4 bbox;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n float x = vRstq.x / vRstq.w;\n float y = vRstq.y / vRstq.w;\n\n vec4 baseColor = texture2D(projectorTex, vec2(x, y));\n baseColor.a = opacity;\n\n gl_FragColor = baseColor;\n}",
29980 vertex: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform mat4 projectorMat;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vRstq = projectorMat * vec4(position, 1.0);\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}",
29982 Shaders.perspectiveCurtain = {
29983 fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform float curtain;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n float x = vRstq.x / vRstq.w;\n float y = vRstq.y / vRstq.w;\n\n vec4 baseColor;\n if (x < curtain || curtain >= 1.0) {\n baseColor = texture2D(projectorTex, vec2(x, y));\n baseColor.a = opacity;\n } else {\n baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n }\n\n gl_FragColor = baseColor;\n}\n",
29984 vertex: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform mat4 projectorMat;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vRstq = projectorMat * vec4(position, 1.0);\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}",
29988 exports.Shaders = Shaders;
29990 },{"path":22}],350:[function(require,module,exports){
29992 /// <reference path="../../../typings/index.d.ts" />
29993 var __extends = (this && this.__extends) || (function () {
29994 var extendStatics = Object.setPrototypeOf ||
29995 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29996 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29997 return function (d, b) {
29998 extendStatics(d, b);
29999 function __() { this.constructor = d; }
30000 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30003 Object.defineProperty(exports, "__esModule", { value: true });
30004 var Observable_1 = require("rxjs/Observable");
30005 var Subject_1 = require("rxjs/Subject");
30006 var Component_1 = require("../../Component");
30007 var Geo_1 = require("../../Geo");
30008 var State_1 = require("../../State");
30009 var Render_1 = require("../../Render");
30010 var Tiles_1 = require("../../Tiles");
30011 var Utils_1 = require("../../Utils");
30013 * @class SliderComponent
30015 * @classdesc Component for comparing pairs of images. Renders
30016 * a slider for adjusting the curtain of the first image.
30018 * Deactivate the sequence, direction and image plane
30019 * components when activating the slider component to avoid
30020 * interfering UI elements.
30022 * To retrive and use the marker component
30026 * var viewer = new Mapillary.Viewer(
30031 * viewer.deactivateComponent("imagePlane");
30032 * viewer.deactivateComponent("direction");
30033 * viewer.deactivateComponent("sequence");
30035 * viewer.activateComponent("slider");
30037 * var sliderComponent = viewer.getComponent("marker");
30040 var SliderComponent = /** @class */ (function (_super) {
30041 __extends(SliderComponent, _super);
30042 function SliderComponent(name, container, navigator, viewportCoords) {
30043 var _this = _super.call(this, name, container, navigator) || this;
30044 _this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
30045 _this._domRenderer = new Component_1.SliderDOMRenderer(container);
30046 _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
30047 _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
30048 _this._spatial = new Geo_1.Spatial();
30049 _this._glRendererOperation$ = new Subject_1.Subject();
30050 _this._glRendererCreator$ = new Subject_1.Subject();
30051 _this._glRendererDisposer$ = new Subject_1.Subject();
30052 _this._glRenderer$ = _this._glRendererOperation$
30053 .scan(function (glRenderer, operation) {
30054 return operation(glRenderer);
30056 .filter(function (glRenderer) {
30057 return glRenderer != null;
30059 .distinctUntilChanged(undefined, function (glRenderer) {
30060 return glRenderer.frameId;
30062 _this._glRendererCreator$
30064 return function (glRenderer) {
30065 if (glRenderer != null) {
30066 throw new Error("Multiple slider states can not be created at the same time");
30068 return new Component_1.SliderGLRenderer();
30071 .subscribe(_this._glRendererOperation$);
30072 _this._glRendererDisposer$
30074 return function (glRenderer) {
30075 glRenderer.dispose();
30079 .subscribe(_this._glRendererOperation$);
30083 * Set the initial position.
30085 * @description Configures the intial position of the slider.
30086 * The inital position value will be used when the component
30089 * @param {number} initialPosition - Initial slider position.
30091 SliderComponent.prototype.setInitialPosition = function (initialPosition) {
30092 this.configure({ initialPosition: initialPosition });
30095 * Set the image keys.
30097 * @description Configures the component to show the image
30098 * planes for the supplied image keys.
30100 * @param {ISliderKeys} keys - Slider keys object specifying
30101 * the images to be shown in the foreground and the background.
30103 SliderComponent.prototype.setKeys = function (keys) {
30104 this.configure({ keys: keys });
30107 * Set the slider mode.
30109 * @description Configures the mode for transitions between
30112 * @param {SliderMode} mode - Slider mode to be set.
30114 SliderComponent.prototype.setSliderMode = function (mode) {
30115 this.configure({ mode: mode });
30118 * Set the value controlling if the slider is visible.
30120 * @param {boolean} sliderVisible - Value indicating if
30121 * the slider should be visible or not.
30123 SliderComponent.prototype.setSliderVisible = function (sliderVisible) {
30124 this.configure({ sliderVisible: sliderVisible });
30126 SliderComponent.prototype._activate = function () {
30128 this._modeSubcription = this._domRenderer.mode$
30129 .subscribe(function (mode) {
30130 _this.setSliderMode(mode);
30132 this._glRenderSubscription = this._glRenderer$
30133 .map(function (glRenderer) {
30137 frameId: glRenderer.frameId,
30138 needsRender: glRenderer.needsRender,
30139 render: glRenderer.render.bind(glRenderer),
30140 stage: Render_1.GLRenderStage.Background,
30145 .subscribe(this._container.glRenderer.render$);
30146 var position$ = this.configuration$
30147 .map(function (configuration) {
30148 return configuration.initialPosition != null ?
30149 configuration.initialPosition : 1;
30152 .concat(this._domRenderer.position$);
30153 var mode$ = this.configuration$
30154 .map(function (configuration) {
30155 return configuration.mode;
30157 .distinctUntilChanged();
30158 var motionless$ = this._navigator.stateService.currentState$
30159 .map(function (frame) {
30160 return frame.state.motionless;
30162 .distinctUntilChanged();
30163 var fullPano$ = this._navigator.stateService.currentState$
30164 .map(function (frame) {
30165 return frame.state.currentNode.fullPano;
30167 .distinctUntilChanged();
30168 var sliderVisible$ = Observable_1.Observable
30169 .combineLatest(this._configuration$
30170 .map(function (configuration) {
30171 return configuration.sliderVisible;
30172 }), this._navigator.stateService.currentState$
30173 .map(function (frame) {
30174 return !(frame.state.currentNode == null ||
30175 frame.state.previousNode == null ||
30176 (frame.state.currentNode.pano && !frame.state.currentNode.fullPano) ||
30177 (frame.state.previousNode.pano && !frame.state.previousNode.fullPano) ||
30178 (frame.state.currentNode.fullPano && !frame.state.previousNode.fullPano));
30180 .distinctUntilChanged())
30181 .map(function (_a) {
30182 var sliderVisible = _a[0], enabledState = _a[1];
30183 return sliderVisible && enabledState;
30185 .distinctUntilChanged();
30186 this._waitSubscription = Observable_1.Observable
30187 .combineLatest(mode$, motionless$, fullPano$, sliderVisible$)
30188 .withLatestFrom(this._navigator.stateService.state$)
30189 .subscribe(function (_a) {
30190 var _b = _a[0], mode = _b[0], motionless = _b[1], fullPano = _b[2], sliderVisible = _b[3], state = _a[1];
30191 var interactive = sliderVisible &&
30192 (motionless || mode === Component_1.SliderMode.Stationary || fullPano);
30193 if (interactive && state !== State_1.State.WaitingInteractively) {
30194 _this._navigator.stateService.waitInteractively();
30196 else if (!interactive && state !== State_1.State.Waiting) {
30197 _this._navigator.stateService.wait();
30200 this._moveSubscription = Observable_1.Observable
30201 .combineLatest(position$, mode$, motionless$, fullPano$, sliderVisible$)
30202 .subscribe(function (_a) {
30203 var position = _a[0], mode = _a[1], motionless = _a[2], fullPano = _a[3], sliderVisible = _a[4];
30204 if (motionless || mode === Component_1.SliderMode.Stationary || fullPano) {
30205 _this._navigator.stateService.moveTo(1);
30208 _this._navigator.stateService.moveTo(position);
30211 this._domRenderSubscription = Observable_1.Observable
30212 .combineLatest(position$, mode$, motionless$, fullPano$, sliderVisible$, this._container.renderService.size$)
30213 .map(function (_a) {
30214 var position = _a[0], mode = _a[1], motionless = _a[2], fullPano = _a[3], sliderVisible = _a[4], size = _a[5];
30217 vnode: _this._domRenderer.render(position, mode, motionless, fullPano, sliderVisible),
30220 .subscribe(this._container.domRenderer.render$);
30221 this._glRendererCreator$.next(null);
30222 this._updateCurtainSubscription = Observable_1.Observable
30223 .combineLatest(position$, fullPano$, sliderVisible$, this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
30224 .map(function (_a) {
30225 var position = _a[0], fullPano = _a[1], visible = _a[2], render = _a[3], transform = _a[4];
30227 return visible ? position : 1;
30229 var basicMin = _this._viewportCoords.viewportToBasic(-1.15, 0, transform, render.perspective);
30230 var basicMax = _this._viewportCoords.viewportToBasic(1.15, 0, transform, render.perspective);
30231 var shiftedMax = basicMax[0] < basicMin[0] ? basicMax[0] + 1 : basicMax[0];
30232 var basicPosition = basicMin[0] + position * (shiftedMax - basicMin[0]);
30233 return basicPosition > 1 ? basicPosition - 1 : basicPosition;
30235 .map(function (position) {
30236 return function (glRenderer) {
30237 glRenderer.updateCurtain(position);
30241 .subscribe(this._glRendererOperation$);
30242 this._stateSubscription = Observable_1.Observable
30243 .combineLatest(this._navigator.stateService.currentState$, mode$)
30244 .map(function (_a) {
30245 var frame = _a[0], mode = _a[1];
30246 return function (glRenderer) {
30247 glRenderer.update(frame, mode);
30251 .subscribe(this._glRendererOperation$);
30252 this._setKeysSubscription = this._configuration$
30253 .filter(function (configuration) {
30254 return configuration.keys != null;
30256 .switchMap(function (configuration) {
30257 return Observable_1.Observable
30258 .zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground))
30259 .map(function (nodes) {
30260 return { background: nodes[0], foreground: nodes[1] };
30262 .zip(_this._navigator.stateService.currentState$.first())
30263 .map(function (nf) {
30264 return { nodes: nf[0], state: nf[1].state };
30267 .subscribe(function (co) {
30268 if (co.state.currentNode != null &&
30269 co.state.previousNode != null &&
30270 co.state.currentNode.key === co.nodes.foreground.key &&
30271 co.state.previousNode.key === co.nodes.background.key) {
30274 if (co.state.currentNode.key === co.nodes.background.key) {
30275 _this._navigator.stateService.setNodes([co.nodes.foreground]);
30278 if (co.state.currentNode.key === co.nodes.foreground.key &&
30279 co.state.trajectory.length === 1) {
30280 _this._navigator.stateService.prependNodes([co.nodes.background]);
30283 _this._navigator.stateService.setNodes([co.nodes.background]);
30284 _this._navigator.stateService.setNodes([co.nodes.foreground]);
30288 var previousNode$ = this._navigator.stateService.currentState$
30289 .map(function (frame) {
30290 return frame.state.previousNode;
30292 .filter(function (node) {
30293 return node != null;
30295 .distinctUntilChanged(undefined, function (node) {
30298 var textureProvider$ = this._navigator.stateService.currentState$
30299 .distinctUntilChanged(undefined, function (frame) {
30300 return frame.state.currentNode.key;
30302 .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$)
30303 .map(function (_a) {
30304 var frame = _a[0], renderer = _a[1], size = _a[2];
30305 var state = frame.state;
30306 var viewportSize = Math.max(size.width, size.height);
30307 var currentNode = state.currentNode;
30308 var currentTransform = state.currentTransform;
30309 var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
30310 return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
30314 this._textureProviderSubscription = textureProvider$.subscribe(function () { });
30315 this._setTextureProviderSubscription = textureProvider$
30316 .map(function (provider) {
30317 return function (renderer) {
30318 renderer.setTextureProvider(provider.key, provider);
30322 .subscribe(this._glRendererOperation$);
30323 this._setTileSizeSubscription = this._container.renderService.size$
30324 .switchMap(function (size) {
30325 return Observable_1.Observable
30326 .combineLatest(textureProvider$, Observable_1.Observable.of(size))
30329 .subscribe(function (_a) {
30330 var provider = _a[0], size = _a[1];
30331 var viewportSize = Math.max(size.width, size.height);
30332 var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
30333 provider.setTileSize(tileSize);
30335 this._abortTextureProviderSubscription = textureProvider$
30337 .subscribe(function (pair) {
30338 var previous = pair[0];
30341 var roiTrigger$ = Observable_1.Observable
30342 .combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.debounceTime(250))
30343 .map(function (_a) {
30344 var camera = _a[0], size = _a[1];
30346 camera.camera.position.clone(),
30347 camera.camera.lookat.clone(),
30348 camera.zoom.valueOf(),
30349 size.height.valueOf(),
30350 size.width.valueOf()
30354 .skipWhile(function (pls) {
30355 return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
30357 .map(function (pls) {
30358 var samePosition = pls[0][0].equals(pls[1][0]);
30359 var sameLookat = pls[0][1].equals(pls[1][1]);
30360 var sameZoom = pls[0][2] === pls[1][2];
30361 var sameHeight = pls[0][3] === pls[1][3];
30362 var sameWidth = pls[0][4] === pls[1][4];
30363 return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
30365 .distinctUntilChanged()
30366 .filter(function (stalled) {
30369 .switchMap(function (stalled) {
30370 return _this._container.renderService.renderCameraFrame$
30373 .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$);
30374 this._setRegionOfInterestSubscription = textureProvider$
30375 .switchMap(function (provider) {
30377 .map(function (_a) {
30378 var camera = _a[0], size = _a[1], transform = _a[2];
30380 _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
30385 .filter(function (args) {
30386 return !args[1].disposed;
30388 .subscribe(function (args) {
30390 var provider = args[1];
30391 provider.setRegionOfInterest(roi);
30393 var hasTexture$ = textureProvider$
30394 .switchMap(function (provider) {
30395 return provider.hasTexture$;
30400 this._hasTextureSubscription = hasTexture$.subscribe(function () { });
30401 var nodeImage$ = this._navigator.stateService.currentState$
30402 .filter(function (frame) {
30403 return frame.state.nodesAhead === 0;
30405 .map(function (frame) {
30406 return frame.state.currentNode;
30408 .distinctUntilChanged(undefined, function (node) {
30411 .debounceTime(1000)
30412 .withLatestFrom(hasTexture$)
30413 .filter(function (args) {
30416 .map(function (args) {
30419 .filter(function (node) {
30421 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
30422 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
30424 .switchMap(function (node) {
30425 var baseImageSize = node.pano ?
30426 Utils_1.Settings.basePanoramaSize :
30427 Utils_1.Settings.baseImageSize;
30428 if (Math.max(node.image.width, node.image.height) > baseImageSize) {
30429 return Observable_1.Observable.empty();
30432 .cacheImage$(Utils_1.Settings.maxImageSize)
30433 .map(function (n) {
30434 return [n.image, n];
30437 .takeUntil(hasTexture$
30438 .filter(function (hasTexture) {
30441 .catch(function (error, caught) {
30442 console.error("Failed to fetch high res image (" + node.key + ")", error);
30443 return Observable_1.Observable.empty();
30448 this._updateBackgroundSubscription = nodeImage$
30449 .withLatestFrom(textureProvider$)
30450 .subscribe(function (args) {
30451 if (args[0][1].key !== args[1].key ||
30452 args[1].disposed) {
30455 args[1].updateBackground(args[0][0]);
30457 this._updateTextureImageSubscription = nodeImage$
30458 .map(function (imn) {
30459 return function (renderer) {
30460 renderer.updateTextureImage(imn[0], imn[1]);
30464 .subscribe(this._glRendererOperation$);
30465 var textureProviderPrev$ = this._navigator.stateService.currentState$
30466 .filter(function (frame) {
30467 return !!frame.state.previousNode;
30469 .distinctUntilChanged(undefined, function (frame) {
30470 return frame.state.previousNode.key;
30472 .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$)
30473 .map(function (_a) {
30474 var frame = _a[0], renderer = _a[1], size = _a[2];
30475 var state = frame.state;
30476 var viewportSize = Math.max(size.width, size.height);
30477 var previousNode = state.previousNode;
30478 var previousTransform = state.previousTransform;
30479 var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
30480 return new Tiles_1.TextureProvider(previousNode.key, previousTransform.basicWidth, previousTransform.basicHeight, tileSize, previousNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
30484 this._textureProviderSubscriptionPrev = textureProviderPrev$.subscribe(function () { });
30485 this._setTextureProviderSubscriptionPrev = textureProviderPrev$
30486 .map(function (provider) {
30487 return function (renderer) {
30488 renderer.setTextureProviderPrev(provider.key, provider);
30492 .subscribe(this._glRendererOperation$);
30493 this._setTileSizeSubscriptionPrev = this._container.renderService.size$
30494 .switchMap(function (size) {
30495 return Observable_1.Observable
30496 .combineLatest(textureProviderPrev$, Observable_1.Observable.of(size))
30499 .subscribe(function (_a) {
30500 var provider = _a[0], size = _a[1];
30501 var viewportSize = Math.max(size.width, size.height);
30502 var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
30503 provider.setTileSize(tileSize);
30505 this._abortTextureProviderSubscriptionPrev = textureProviderPrev$
30507 .subscribe(function (pair) {
30508 var previous = pair[0];
30511 var roiTriggerPrev$ = Observable_1.Observable
30512 .combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.debounceTime(250))
30513 .map(function (_a) {
30514 var camera = _a[0], size = _a[1];
30516 camera.camera.position.clone(),
30517 camera.camera.lookat.clone(),
30518 camera.zoom.valueOf(),
30519 size.height.valueOf(),
30520 size.width.valueOf()
30524 .skipWhile(function (pls) {
30525 return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
30527 .map(function (pls) {
30528 var samePosition = pls[0][0].equals(pls[1][0]);
30529 var sameLookat = pls[0][1].equals(pls[1][1]);
30530 var sameZoom = pls[0][2] === pls[1][2];
30531 var sameHeight = pls[0][3] === pls[1][3];
30532 var sameWidth = pls[0][4] === pls[1][4];
30533 return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
30535 .distinctUntilChanged()
30536 .filter(function (stalled) {
30539 .switchMap(function (stalled) {
30540 return _this._container.renderService.renderCameraFrame$
30543 .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$);
30544 this._setRegionOfInterestSubscriptionPrev = textureProviderPrev$
30545 .switchMap(function (provider) {
30546 return roiTriggerPrev$
30547 .map(function (_a) {
30548 var camera = _a[0], size = _a[1], transform = _a[2];
30550 _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
30555 .filter(function (args) {
30556 return !args[1].disposed;
30558 .withLatestFrom(this._navigator.stateService.currentState$)
30559 .subscribe(function (_a) {
30560 var _b = _a[0], roi = _b[0], provider = _b[1], frame = _a[1];
30561 var shiftedRoi = null;
30562 if (frame.state.previousNode.fullPano) {
30563 if (frame.state.currentNode.fullPano) {
30564 var currentViewingDirection = _this._spatial.viewingDirection(frame.state.currentNode.rotation);
30565 var previousViewingDirection = _this._spatial.viewingDirection(frame.state.previousNode.rotation);
30566 var directionDiff = _this._spatial.angleBetweenVector2(currentViewingDirection.x, currentViewingDirection.y, previousViewingDirection.x, previousViewingDirection.y);
30567 var shift = directionDiff / (2 * Math.PI);
30569 maxX: _this._spatial.wrap(roi.bbox.maxX + shift, 0, 1),
30570 maxY: roi.bbox.maxY,
30571 minX: _this._spatial.wrap(roi.bbox.minX + shift, 0, 1),
30572 minY: roi.bbox.minY,
30576 pixelHeight: roi.pixelHeight,
30577 pixelWidth: roi.pixelWidth,
30581 var currentViewingDirection = _this._spatial.viewingDirection(frame.state.currentNode.rotation);
30582 var previousViewingDirection = _this._spatial.viewingDirection(frame.state.previousNode.rotation);
30583 var directionDiff = _this._spatial.angleBetweenVector2(currentViewingDirection.x, currentViewingDirection.y, previousViewingDirection.x, previousViewingDirection.y);
30584 var shiftX = directionDiff / (2 * Math.PI);
30585 var a1 = _this._spatial.angleToPlane(currentViewingDirection.toArray(), [0, 0, 1]);
30586 var a2 = _this._spatial.angleToPlane(previousViewingDirection.toArray(), [0, 0, 1]);
30587 var shiftY = (a2 - a1) / (2 * Math.PI);
30588 var currentTransform = frame.state.currentTransform;
30589 var size = Math.max(currentTransform.basicWidth, currentTransform.basicHeight);
30590 var hFov = size > 0 ?
30591 2 * Math.atan(0.5 * currentTransform.basicWidth / (size * currentTransform.focal)) :
30593 var vFov = size > 0 ?
30594 2 * Math.atan(0.5 * currentTransform.basicHeight / (size * currentTransform.focal)) :
30596 var spanningWidth = hFov / (2 * Math.PI);
30597 var spanningHeight = vFov / Math.PI;
30598 var basicWidth = (roi.bbox.maxX - roi.bbox.minX) * spanningWidth;
30599 var basicHeight = (roi.bbox.maxY - roi.bbox.minY) * spanningHeight;
30600 var pixelWidth = roi.pixelWidth * spanningWidth;
30601 var pixelHeight = roi.pixelHeight * spanningHeight;
30602 var zoomShiftX = (roi.bbox.minX + roi.bbox.maxX) / 2 - 0.5;
30603 var zoomShiftY = (roi.bbox.minY + roi.bbox.maxY) / 2 - 0.5;
30604 var minX = 0.5 + shiftX + spanningWidth * zoomShiftX - basicWidth / 2;
30605 var maxX = 0.5 + shiftX + spanningWidth * zoomShiftX + basicWidth / 2;
30606 var minY = 0.5 + shiftY + spanningHeight * zoomShiftY - basicHeight / 2;
30607 var maxY = 0.5 + shiftY + spanningHeight * zoomShiftY + basicHeight / 2;
30609 maxX: _this._spatial.wrap(maxX, 0, 1),
30611 minX: _this._spatial.wrap(minX, 0, 1),
30616 pixelHeight: pixelHeight,
30617 pixelWidth: pixelWidth,
30622 var currentBasicAspect = frame.state.currentTransform.basicAspect;
30623 var previousBasicAspect = frame.state.previousTransform.basicAspect;
30624 var _c = _this._getBasicCorners(currentBasicAspect, previousBasicAspect), _d = _c[0], cornerMinX = _d[0], cornerMinY = _d[1], _e = _c[1], cornerMaxX = _e[0], cornerMaxY = _e[1];
30625 var basicWidth = cornerMaxX - cornerMinX;
30626 var basicHeight = cornerMaxY - cornerMinY;
30627 var pixelWidth = roi.pixelWidth / basicWidth;
30628 var pixelHeight = roi.pixelHeight / basicHeight;
30629 var minX = (basicWidth - 1) / (2 * basicWidth) + roi.bbox.minX / basicWidth;
30630 var maxX = (basicWidth - 1) / (2 * basicWidth) + roi.bbox.maxX / basicWidth;
30631 var minY = (basicHeight - 1) / (2 * basicHeight) + roi.bbox.minY / basicHeight;
30632 var maxY = (basicHeight - 1) / (2 * basicHeight) + roi.bbox.maxY / basicHeight;
30639 _this._clipBoundingBox(bbox);
30642 pixelHeight: pixelHeight,
30643 pixelWidth: pixelWidth,
30646 provider.setRegionOfInterest(shiftedRoi);
30648 var hasTexturePrev$ = textureProviderPrev$
30649 .switchMap(function (provider) {
30650 return provider.hasTexture$;
30655 this._hasTextureSubscriptionPrev = hasTexturePrev$.subscribe(function () { });
30656 var nodeImagePrev$ = this._navigator.stateService.currentState$
30657 .filter(function (frame) {
30658 return frame.state.nodesAhead === 0 && !!frame.state.previousNode;
30660 .map(function (frame) {
30661 return frame.state.previousNode;
30663 .distinctUntilChanged(undefined, function (node) {
30666 .debounceTime(1000)
30667 .withLatestFrom(hasTexturePrev$)
30668 .filter(function (args) {
30671 .map(function (args) {
30674 .filter(function (node) {
30676 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
30677 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
30679 .switchMap(function (node) {
30680 var baseImageSize = node.pano ?
30681 Utils_1.Settings.basePanoramaSize :
30682 Utils_1.Settings.baseImageSize;
30683 if (Math.max(node.image.width, node.image.height) > baseImageSize) {
30684 return Observable_1.Observable.empty();
30687 .cacheImage$(Utils_1.Settings.maxImageSize)
30688 .map(function (n) {
30689 return [n.image, n];
30692 .takeUntil(hasTexturePrev$
30693 .filter(function (hasTexture) {
30696 .catch(function (error, caught) {
30697 console.error("Failed to fetch high res image (" + node.key + ")", error);
30698 return Observable_1.Observable.empty();
30703 this._updateBackgroundSubscriptionPrev = nodeImagePrev$
30704 .withLatestFrom(textureProviderPrev$)
30705 .subscribe(function (args) {
30706 if (args[0][1].key !== args[1].key ||
30707 args[1].disposed) {
30710 args[1].updateBackground(args[0][0]);
30712 this._updateTextureImageSubscriptionPrev = nodeImagePrev$
30713 .map(function (imn) {
30714 return function (renderer) {
30715 renderer.updateTextureImage(imn[0], imn[1]);
30719 .subscribe(this._glRendererOperation$);
30721 SliderComponent.prototype._deactivate = function () {
30723 this._waitSubscription.unsubscribe();
30724 this._navigator.stateService.state$
30726 .subscribe(function (state) {
30727 if (state !== State_1.State.Traversing) {
30728 _this._navigator.stateService.traverse();
30731 this._glRendererDisposer$.next(null);
30732 this._domRenderer.deactivate();
30733 this._modeSubcription.unsubscribe();
30734 this._setKeysSubscription.unsubscribe();
30735 this._stateSubscription.unsubscribe();
30736 this._glRenderSubscription.unsubscribe();
30737 this._domRenderSubscription.unsubscribe();
30738 this._moveSubscription.unsubscribe();
30739 this.configure({ keys: null });
30741 SliderComponent.prototype._getDefaultConfiguration = function () {
30743 initialPosition: 1,
30744 mode: Component_1.SliderMode.Motion,
30745 sliderVisible: true,
30748 SliderComponent.prototype._catchCacheNode$ = function (key) {
30749 return this._navigator.graphService.cacheNode$(key)
30750 .catch(function (error, caught) {
30751 console.error("Failed to cache slider node (" + key + ")", error);
30752 return Observable_1.Observable.empty();
30755 SliderComponent.prototype._getBasicCorners = function (currentAspect, previousAspect) {
30758 if (currentAspect > previousAspect) {
30760 offsetY = 0.5 * currentAspect / previousAspect;
30763 offsetX = 0.5 * previousAspect / currentAspect;
30766 return [[0.5 - offsetX, 0.5 - offsetY], [0.5 + offsetX, 0.5 + offsetY]];
30768 SliderComponent.prototype._clipBoundingBox = function (bbox) {
30769 bbox.minX = Math.max(0, Math.min(1, bbox.minX));
30770 bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
30771 bbox.minY = Math.max(0, Math.min(1, bbox.minY));
30772 bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
30774 SliderComponent.componentName = "slider";
30775 return SliderComponent;
30776 }(Component_1.Component));
30777 exports.SliderComponent = SliderComponent;
30778 Component_1.ComponentService.register(SliderComponent);
30779 exports.default = SliderComponent;
30781 },{"../../Component":290,"../../Geo":293,"../../Render":296,"../../State":297,"../../Tiles":299,"../../Utils":300,"rxjs/Observable":29,"rxjs/Subject":34}],351:[function(require,module,exports){
30783 /// <reference path="../../../typings/index.d.ts" />
30784 Object.defineProperty(exports, "__esModule", { value: true });
30785 var vd = require("virtual-dom");
30786 var Observable_1 = require("rxjs/Observable");
30787 var Subject_1 = require("rxjs/Subject");
30788 var Component_1 = require("../../Component");
30789 var SliderDOMRenderer = /** @class */ (function () {
30790 function SliderDOMRenderer(container) {
30791 this._container = container;
30792 this._interacting = false;
30793 this._notifyModeChanged$ = new Subject_1.Subject();
30794 this._notifyPositionChanged$ = new Subject_1.Subject();
30795 this._stopInteractionSubscription = null;
30797 Object.defineProperty(SliderDOMRenderer.prototype, "mode$", {
30799 return this._notifyModeChanged$;
30804 Object.defineProperty(SliderDOMRenderer.prototype, "position$", {
30806 return this._notifyPositionChanged$;
30811 SliderDOMRenderer.prototype.activate = function () {
30813 if (!!this._stopInteractionSubscription) {
30816 this._stopInteractionSubscription = Observable_1.Observable
30817 .merge(this._container.mouseService.documentMouseUp$, this._container.touchService.touchEnd$
30818 .filter(function (touchEvent) {
30819 return touchEvent.touches.length === 0;
30821 .subscribe(function (event) {
30822 if (_this._interacting) {
30823 _this._interacting = false;
30827 SliderDOMRenderer.prototype.deactivate = function () {
30828 if (!this._stopInteractionSubscription) {
30831 this._interacting = false;
30832 this._stopInteractionSubscription.unsubscribe();
30833 this._stopInteractionSubscription = null;
30835 SliderDOMRenderer.prototype.render = function (position, mode, motionless, pano, visible) {
30838 children.push(vd.h("div.SliderBorder", []));
30839 var modeVisible = !(motionless || pano);
30841 children.push(this._createModeButton(mode));
30843 children.push(this._createPositionInput(position, modeVisible));
30845 var boundingRect = this._container.domContainer.getBoundingClientRect();
30846 var width = Math.max(215, Math.min(400, boundingRect.width - 100));
30847 return vd.h("div.SliderContainer", { style: { width: width + "px" } }, children);
30849 SliderDOMRenderer.prototype._createModeButton = function (mode) {
30852 onclick: function () {
30853 _this._notifyModeChanged$.next(mode === Component_1.SliderMode.Motion ?
30854 Component_1.SliderMode.Stationary :
30855 Component_1.SliderMode.Motion);
30858 var className = mode === Component_1.SliderMode.Stationary ?
30859 "SliderModeButtonPressed" :
30860 "SliderModeButton";
30861 return vd.h("div." + className, properties, [vd.h("div.SliderModeIcon", [])]);
30863 SliderDOMRenderer.prototype._createPositionInput = function (position, modeVisible) {
30865 var onChange = function (e) {
30866 _this._notifyPositionChanged$.next(Number(e.target.value) / 1000);
30868 var onStart = function (e) {
30869 _this._interacting = true;
30870 e.stopPropagation();
30872 var onMove = function (e) {
30873 if (_this._interacting) {
30874 e.stopPropagation();
30877 var onKeyDown = function (e) {
30878 if (e.key === "ArrowDown" || e.key === "ArrowLeft" ||
30879 e.key === "ArrowRight" || e.key === "ArrowUp") {
30880 e.preventDefault();
30883 var boundingRect = this._container.domContainer.getBoundingClientRect();
30884 var width = Math.max(215, Math.min(400, boundingRect.width - 105)) - 68 + (modeVisible ? 0 : 36);
30885 var positionInput = vd.h("input.SliderPosition", {
30888 onchange: onChange,
30890 onkeydown: onKeyDown,
30891 onmousedown: onStart,
30892 onmousemove: onMove,
30893 ontouchmove: onMove,
30894 ontouchstart: onStart,
30896 width: width + "px",
30899 value: 1000 * position,
30901 return vd.h("div.SliderPositionContainer", [positionInput]);
30903 return SliderDOMRenderer;
30905 exports.SliderDOMRenderer = SliderDOMRenderer;
30906 exports.default = SliderDOMRenderer;
30908 },{"../../Component":290,"rxjs/Observable":29,"rxjs/Subject":34,"virtual-dom":246}],352:[function(require,module,exports){
30910 Object.defineProperty(exports, "__esModule", { value: true });
30911 var Component_1 = require("../../Component");
30912 var Geo_1 = require("../../Geo");
30913 var SliderGLRenderer = /** @class */ (function () {
30914 function SliderGLRenderer() {
30915 this._factory = new Component_1.MeshFactory();
30916 this._scene = new Component_1.MeshScene();
30917 this._spatial = new Geo_1.Spatial();
30918 this._currentKey = null;
30919 this._previousKey = null;
30920 this._disabled = false;
30923 this._needsRender = false;
30925 this._currentProviderDisposers = {};
30926 this._previousProviderDisposers = {};
30928 Object.defineProperty(SliderGLRenderer.prototype, "disabled", {
30930 return this._disabled;
30935 Object.defineProperty(SliderGLRenderer.prototype, "frameId", {
30937 return this._frameId;
30942 Object.defineProperty(SliderGLRenderer.prototype, "needsRender", {
30944 return this._needsRender;
30949 SliderGLRenderer.prototype.setTextureProvider = function (key, provider) {
30950 this._setTextureProvider(key, this._currentKey, provider, this._currentProviderDisposers, this._updateTexture.bind(this));
30952 SliderGLRenderer.prototype.setTextureProviderPrev = function (key, provider) {
30953 this._setTextureProvider(key, this._previousKey, provider, this._previousProviderDisposers, this._updateTexturePrev.bind(this));
30955 SliderGLRenderer.prototype.update = function (frame, mode) {
30956 this._updateFrameId(frame.id);
30957 this._updateImagePlanes(frame.state, mode);
30959 SliderGLRenderer.prototype.updateCurtain = function (curtain) {
30960 if (this._curtain === curtain) {
30963 this._curtain = curtain;
30964 this._updateCurtain();
30965 this._needsRender = true;
30967 SliderGLRenderer.prototype.updateTexture = function (image, node) {
30968 var imagePlanes = node.key === this._currentKey ?
30969 this._scene.imagePlanes :
30970 node.key === this._previousKey ?
30971 this._scene.imagePlanesOld :
30973 if (imagePlanes.length === 0) {
30976 this._needsRender = true;
30977 for (var _i = 0, imagePlanes_1 = imagePlanes; _i < imagePlanes_1.length; _i++) {
30978 var plane = imagePlanes_1[_i];
30979 var material = plane.material;
30980 var texture = material.uniforms.projectorTex.value;
30981 texture.image = image;
30982 texture.needsUpdate = true;
30985 SliderGLRenderer.prototype.updateTextureImage = function (image, node) {
30986 if (this._currentKey !== node.key) {
30989 this._needsRender = true;
30990 for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) {
30991 var plane = _a[_i];
30992 var material = plane.material;
30993 var texture = material.uniforms.projectorTex.value;
30994 texture.image = image;
30995 texture.needsUpdate = true;
30998 SliderGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
30999 if (!this.disabled) {
31000 renderer.render(this._scene.sceneOld, perspectiveCamera);
31002 renderer.render(this._scene.scene, perspectiveCamera);
31003 this._needsRender = false;
31005 SliderGLRenderer.prototype.dispose = function () {
31006 this._scene.clear();
31007 for (var key in this._currentProviderDisposers) {
31008 if (!this._currentProviderDisposers.hasOwnProperty(key)) {
31011 this._currentProviderDisposers[key]();
31013 for (var key in this._previousProviderDisposers) {
31014 if (!this._previousProviderDisposers.hasOwnProperty(key)) {
31017 this._previousProviderDisposers[key]();
31019 this._currentProviderDisposers = {};
31020 this._previousProviderDisposers = {};
31022 SliderGLRenderer.prototype._getBasicCorners = function (currentAspect, previousAspect) {
31025 if (currentAspect > previousAspect) {
31027 offsetY = 0.5 * currentAspect / previousAspect;
31030 offsetX = 0.5 * previousAspect / currentAspect;
31033 return [[0.5 - offsetX, 0.5 - offsetY], [0.5 + offsetX, 0.5 + offsetY]];
31035 SliderGLRenderer.prototype._setDisabled = function (state) {
31036 this._disabled = state.currentNode == null ||
31037 state.previousNode == null ||
31038 (state.currentNode.pano && !state.currentNode.fullPano) ||
31039 (state.previousNode.pano && !state.previousNode.fullPano) ||
31040 (state.currentNode.fullPano && !state.previousNode.fullPano);
31042 SliderGLRenderer.prototype._setTextureProvider = function (key, originalKey, provider, providerDisposers, updateTexture) {
31044 if (key !== originalKey) {
31047 var createdSubscription = provider.textureCreated$
31048 .subscribe(updateTexture);
31049 var updatedSubscription = provider.textureUpdated$
31050 .subscribe(function (updated) {
31051 _this._needsRender = true;
31053 var dispose = function () {
31054 createdSubscription.unsubscribe();
31055 updatedSubscription.unsubscribe();
31056 provider.dispose();
31058 if (key in providerDisposers) {
31059 var disposeProvider = providerDisposers[key];
31061 delete providerDisposers[key];
31063 providerDisposers[key] = dispose;
31065 SliderGLRenderer.prototype._updateCurtain = function () {
31066 for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) {
31067 var plane = _a[_i];
31068 var shaderMaterial = plane.material;
31069 if (!!shaderMaterial.uniforms.curtain) {
31070 shaderMaterial.uniforms.curtain.value = this._curtain;
31074 SliderGLRenderer.prototype._updateFrameId = function (frameId) {
31075 this._frameId = frameId;
31077 SliderGLRenderer.prototype._updateImagePlanes = function (state, mode) {
31078 var currentChanged = state.currentNode != null && this._currentKey !== state.currentNode.key;
31079 var previousChanged = state.previousNode != null && this._previousKey !== state.previousNode.key;
31080 var modeChanged = this._mode !== mode;
31081 if (!(currentChanged || previousChanged || modeChanged)) {
31084 this._setDisabled(state);
31085 this._needsRender = true;
31087 var motionless = state.motionless || mode === Component_1.SliderMode.Stationary || state.currentNode.pano;
31088 if (this.disabled || previousChanged) {
31089 if (this._previousKey in this._previousProviderDisposers) {
31090 this._previousProviderDisposers[this._previousKey]();
31091 delete this._previousProviderDisposers[this._previousKey];
31094 if (this.disabled) {
31095 this._scene.setImagePlanesOld([]);
31098 if (previousChanged || modeChanged) {
31099 var previousNode = state.previousNode;
31100 this._previousKey = previousNode.key;
31101 var elements = state.currentTransform.rt.elements;
31102 var translation = [elements[12], elements[13], elements[14]];
31103 var currentAspect = state.currentTransform.basicAspect;
31104 var previousAspect = state.previousTransform.basicAspect;
31105 var textureScale = currentAspect > previousAspect ?
31106 [1, previousAspect / currentAspect] :
31107 [currentAspect / previousAspect, 1];
31108 var rotation = state.currentNode.rotation;
31109 var width = state.currentNode.width;
31110 var height = state.currentNode.height;
31111 if (previousNode.fullPano) {
31112 rotation = state.previousNode.rotation;
31113 translation = this._spatial
31114 .rotate(this._spatial
31115 .opticalCenter(state.currentNode.rotation, translation)
31116 .toArray(), rotation)
31117 .multiplyScalar(-1)
31119 width = state.previousNode.width;
31120 height = state.previousNode.height;
31122 var transform = new Geo_1.Transform(state.currentNode.orientation, width, height, state.currentNode.focal, state.currentNode.scale, previousNode.gpano, rotation, translation, previousNode.image, textureScale);
31123 var mesh = undefined;
31124 if (previousNode.fullPano) {
31125 mesh = this._factory.createMesh(previousNode, motionless || state.currentNode.fullPano ? transform : state.previousTransform);
31129 var _a = this._getBasicCorners(currentAspect, previousAspect), _b = _a[0], basicX0 = _b[0], basicY0 = _b[1], _c = _a[1], basicX1 = _c[0], basicY1 = _c[1];
31130 mesh = this._factory.createFlatMesh(state.previousNode, transform, basicX0, basicX1, basicY0, basicY1);
31133 mesh = this._factory.createMesh(state.previousNode, state.previousTransform);
31136 this._scene.setImagePlanesOld([mesh]);
31139 if (currentChanged) {
31140 if (this._currentKey in this._currentProviderDisposers) {
31141 this._currentProviderDisposers[this._currentKey]();
31142 delete this._currentProviderDisposers[this._currentKey];
31144 this._currentKey = state.currentNode.key;
31145 var imagePlane = state.currentNode.pano && !state.currentNode.fullPano ?
31146 this._factory.createMesh(state.currentNode, state.currentTransform) :
31147 this._factory.createCurtainMesh(state.currentNode, state.currentTransform);
31148 this._scene.setImagePlanes([imagePlane]);
31149 this._updateCurtain();
31152 SliderGLRenderer.prototype._updateTexture = function (texture) {
31153 this._needsRender = true;
31154 for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) {
31155 var plane = _a[_i];
31156 var material = plane.material;
31157 var oldTexture = material.uniforms.projectorTex.value;
31158 material.uniforms.projectorTex.value = null;
31159 oldTexture.dispose();
31160 material.uniforms.projectorTex.value = texture;
31163 SliderGLRenderer.prototype._updateTexturePrev = function (texture) {
31164 this._needsRender = true;
31165 for (var _i = 0, _a = this._scene.imagePlanesOld; _i < _a.length; _i++) {
31166 var plane = _a[_i];
31167 var material = plane.material;
31168 var oldTexture = material.uniforms.projectorTex.value;
31169 material.uniforms.projectorTex.value = null;
31170 oldTexture.dispose();
31171 material.uniforms.projectorTex.value = texture;
31174 return SliderGLRenderer;
31176 exports.SliderGLRenderer = SliderGLRenderer;
31177 exports.default = SliderGLRenderer;
31179 },{"../../Component":290,"../../Geo":293}],353:[function(require,module,exports){
31181 Object.defineProperty(exports, "__esModule", { value: true });
31182 var GeometryTagError_1 = require("./error/GeometryTagError");
31183 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
31184 var PointGeometry_1 = require("./geometry/PointGeometry");
31185 exports.PointGeometry = PointGeometry_1.PointGeometry;
31186 var RectGeometry_1 = require("./geometry/RectGeometry");
31187 exports.RectGeometry = RectGeometry_1.RectGeometry;
31188 var PolygonGeometry_1 = require("./geometry/PolygonGeometry");
31189 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
31190 var OutlineTag_1 = require("./tag/OutlineTag");
31191 exports.OutlineTag = OutlineTag_1.OutlineTag;
31192 var SpotTag_1 = require("./tag/SpotTag");
31193 exports.SpotTag = SpotTag_1.SpotTag;
31194 var TagComponent_1 = require("./TagComponent");
31195 exports.TagComponent = TagComponent_1.TagComponent;
31196 var TagMode_1 = require("./TagMode");
31197 exports.TagMode = TagMode_1.TagMode;
31199 },{"./TagComponent":354,"./TagMode":357,"./error/GeometryTagError":361,"./geometry/PointGeometry":363,"./geometry/PolygonGeometry":364,"./geometry/RectGeometry":365,"./tag/OutlineTag":377,"./tag/SpotTag":380}],354:[function(require,module,exports){
31201 /// <reference path="../../../typings/index.d.ts" />
31202 var __extends = (this && this.__extends) || (function () {
31203 var extendStatics = Object.setPrototypeOf ||
31204 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31205 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31206 return function (d, b) {
31207 extendStatics(d, b);
31208 function __() { this.constructor = d; }
31209 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31212 Object.defineProperty(exports, "__esModule", { value: true });
31213 var when = require("when");
31214 var Observable_1 = require("rxjs/Observable");
31215 var Component_1 = require("../../Component");
31216 var Geo_1 = require("../../Geo");
31217 var Render_1 = require("../../Render");
31219 * @class TagComponent
31221 * @classdesc Component for showing and editing tags with different
31222 * geometries composed from 2D basic image coordinates (see the
31223 * {@link Viewer} class documentation for more information about coordinate
31226 * The `add` method is used for adding new tags or replacing
31227 * tags already in the set. Tags are removed by id.
31229 * If a tag already in the set has the same
31230 * id as one of the tags added, the old tag will be removed and
31231 * the added tag will take its place.
31233 * The tag component mode can be set to either be non interactive or
31234 * to be in creating mode of a certain geometry type.
31236 * The tag properties can be updated at any time and the change will
31237 * be visibile immediately.
31239 * Tags are only relevant to a single image because they are based on
31240 * 2D basic image coordinates. Tags related to a certain image should
31241 * be removed when the viewer is moved to another node.
31243 * To retrive and use the tag component
31247 * var viewer = new Mapillary.Viewer(
31251 * { component: { tag: true } });
31253 * var tagComponent = viewer.getComponent("tag");
31256 var TagComponent = /** @class */ (function (_super) {
31257 __extends(TagComponent, _super);
31258 function TagComponent(name, container, navigator) {
31259 var _this = _super.call(this, name, container, navigator) || this;
31260 _this._tagDomRenderer = new Component_1.TagDOMRenderer();
31261 _this._tagScene = new Component_1.TagScene();
31262 _this._tagSet = new Component_1.TagSet();
31263 _this._tagCreator = new Component_1.TagCreator(_this, navigator);
31264 _this._viewportCoords = new Geo_1.ViewportCoords();
31265 _this._createHandlers = {
31266 "CreatePoint": new Component_1.CreatePointHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
31267 "CreatePolygon": new Component_1.CreatePolygonHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
31268 "CreateRect": new Component_1.CreateRectHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
31269 "CreateRectDrag": new Component_1.CreateRectDragHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
31270 "Default": undefined,
31272 _this._editVertexHandler = new Component_1.EditVertexHandler(_this, container, navigator, _this._viewportCoords, _this._tagSet);
31273 _this._renderTags$ = _this._tagSet.changed$
31274 .map(function (tagSet) {
31275 var tags = tagSet.getAll();
31276 // ensure that tags are always rendered in the same order
31277 // to avoid hover tracking problems on first resize.
31278 tags.sort(function (t1, t2) {
31279 var id1 = t1.tag.id;
31280 var id2 = t2.tag.id;
31292 _this._tagChanged$ = _this._renderTags$
31293 .switchMap(function (tags) {
31294 return Observable_1.Observable
31296 .mergeMap(function (tag) {
31297 return Observable_1.Observable
31298 .merge(tag.tag.changed$, tag.tag.geometryChanged$);
31302 _this._renderTagGLChanged$ = _this._renderTags$
31303 .switchMap(function (tags) {
31304 return Observable_1.Observable
31306 .mergeMap(function (tag) {
31307 return tag.glObjectsChanged$;
31311 _this._createGeometryChanged$ = _this._tagCreator.tag$
31312 .switchMap(function (tag) {
31313 return tag != null ?
31314 tag.geometryChanged$ :
31315 Observable_1.Observable.empty();
31318 _this._createGLObjectsChanged$ = _this._tagCreator.tag$
31319 .switchMap(function (tag) {
31320 return tag != null ?
31321 tag.glObjectsChanged$ :
31322 Observable_1.Observable.empty();
31325 _this._creatingConfiguration$ = _this._configuration$
31326 .distinctUntilChanged(function (c1, c2) {
31327 return c1.mode === c2.mode;
31328 }, function (configuration) {
31330 createColor: configuration.createColor,
31331 mode: configuration.mode,
31336 _this._creatingConfiguration$
31337 .subscribe(function (configuration) {
31338 _this.fire(TagComponent.modechanged, configuration.mode);
31343 * Add tags to the tag set or replace tags in the tag set.
31345 * @description If a tag already in the set has the same
31346 * id as one of the tags added, the old tag will be removed
31347 * the added tag will take its place.
31349 * @param {Array<Tag>} tags - Tags to add.
31351 * @example ```tagComponent.add([tag1, tag2]);```
31353 TagComponent.prototype.add = function (tags) {
31355 if (this._activated) {
31356 this._navigator.stateService.currentTransform$
31358 .subscribe(function (transform) {
31359 _this._tagSet.add(tags, transform);
31360 var renderTags = tags
31361 .map(function (tag) {
31362 return _this._tagSet.get(tag.id);
31364 _this._tagScene.add(renderTags);
31368 this._tagSet.addDeactivated(tags);
31372 * Change the current tag mode.
31374 * @description Change the tag mode to one of the create modes for creating new geometries.
31376 * @param {TagMode} mode - New tag mode.
31378 * @fires TagComponent#modechanged
31380 * @example ```tagComponent.changeMode(Mapillary.TagComponent.TagMode.CreateRect);```
31382 TagComponent.prototype.changeMode = function (mode) {
31383 this.configure({ mode: mode });
31386 * Returns the tag in the tag set with the specified id, or
31387 * undefined if the id matches no tag.
31389 * @param {string} tagId - Id of the tag.
31391 * @example ```var tag = tagComponent.get("tagId");```
31393 TagComponent.prototype.get = function (tagId) {
31394 if (this._activated) {
31395 var renderTag = this._tagSet.get(tagId);
31396 return renderTag !== undefined ? renderTag.tag : undefined;
31399 return this._tagSet.getDeactivated(tagId);
31403 * Returns an array of all tags.
31405 * @example ```var tags = tagComponent.getAll();```
31407 TagComponent.prototype.getAll = function () {
31408 if (this.activated) {
31409 return this._tagSet
31411 .map(function (renderTag) {
31412 return renderTag.tag;
31416 return this._tagSet.getAllDeactivated();
31420 * Returns an array of tag ids for tags that contain the specified point.
31422 * @description The pixel point must lie inside the polygon or rectangle
31423 * of an added tag for the tag id to be returned. Tag ids for
31424 * tags that do not have a fill will also be returned if the point is inside
31425 * the geometry of the tag. Tags with point geometries can not be retrieved.
31427 * No tag ids will be returned for panoramas.
31429 * Notice that the pixelPoint argument requires x, y coordinates from pixel space.
31431 * With this function, you can use the coordinates provided by mouse
31432 * events to get information out of the tag component.
31434 * If no tag at exist the pixel point, an empty array will be returned.
31436 * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
31437 * @returns {Array<string>} Ids of the tags that contain the specified pixel point.
31441 * tagComponent.getTagIdsAt([100, 100])
31442 * .then((tagIds) => { console.log(tagIds); });
31445 TagComponent.prototype.getTagIdsAt = function (pixelPoint) {
31447 return when.promise(function (resolve, reject) {
31448 _this._container.renderService.renderCamera$
31450 .map(function (render) {
31451 var viewport = _this._viewportCoords
31452 .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
31453 var ids = _this._tagScene.intersectObjects(viewport, render.perspective);
31456 .subscribe(function (ids) {
31458 }, function (error) {
31464 * Check if a tag exist in the tag set.
31466 * @param {string} tagId - Id of the tag.
31468 * @example ```var tagExists = tagComponent.has("tagId");```
31470 TagComponent.prototype.has = function (tagId) {
31471 return this._activated ? this._tagSet.has(tagId) : this._tagSet.hasDeactivated(tagId);
31474 * Remove tags with the specified ids from the tag set.
31476 * @param {Array<string>} tagIds - Ids for tags to remove.
31478 * @example ```tagComponent.remove(["id-1", "id-2"]);```
31480 TagComponent.prototype.remove = function (tagIds) {
31481 if (this._activated) {
31482 this._tagSet.remove(tagIds);
31483 this._tagScene.remove(tagIds);
31486 this._tagSet.removeDeactivated(tagIds);
31490 * Remove all tags from the tag set.
31492 * @example ```tagComponent.removeAll();```
31494 TagComponent.prototype.removeAll = function () {
31495 if (this._activated) {
31496 this._tagSet.removeAll();
31497 this._tagScene.removeAll();
31500 this._tagSet.removeAllDeactivated();
31503 TagComponent.prototype._activate = function () {
31505 this._editVertexHandler.enable();
31506 var handlerGeometryCreated$ = Observable_1.Observable
31507 .from(Object.keys(this._createHandlers))
31508 .map(function (key) {
31509 return _this._createHandlers[key];
31511 .filter(function (handler) {
31514 .mergeMap(function (handler) {
31515 return handler.geometryCreated$;
31518 this._fireGeometryCreatedSubscription = handlerGeometryCreated$
31519 .subscribe(function (geometry) {
31520 _this.fire(TagComponent.geometrycreated, geometry);
31522 this._fireCreateGeometryEventSubscription = this._tagCreator.tag$
31523 .skipWhile(function (tag) {
31524 return tag == null;
31526 .distinctUntilChanged()
31527 .subscribe(function (tag) {
31528 var eventType = tag != null ?
31529 TagComponent.creategeometrystart :
31530 TagComponent.creategeometryend;
31531 _this.fire(eventType, _this);
31533 this._handlerStopCreateSubscription = handlerGeometryCreated$
31534 .subscribe(function () {
31535 _this.changeMode(Component_1.TagMode.Default);
31537 this._handlerEnablerSubscription = this._creatingConfiguration$
31538 .subscribe(function (configuration) {
31539 _this._disableCreateHandlers();
31540 var mode = Component_1.TagMode[configuration.mode];
31541 var handler = _this._createHandlers[mode];
31546 this._fireTagsChangedSubscription = this._renderTags$
31547 .subscribe(function (tags) {
31548 _this.fire(TagComponent.tagschanged, _this);
31550 this._stopCreateSubscription = this._tagCreator.tag$
31551 .switchMap(function (tag) {
31552 return tag != null ?
31554 .map(function (t) { return null; }) :
31555 Observable_1.Observable.empty();
31557 .subscribe(function () { _this.changeMode(Component_1.TagMode.Default); });
31558 this._setGLCreateTagSubscription = this._tagCreator.tag$
31559 .subscribe(function (tag) {
31560 if (_this._tagScene.hasCreateTag()) {
31561 _this._tagScene.removeCreateTag();
31564 _this._tagScene.addCreateTag(tag);
31567 this._createGLObjectsChangedSubscription = this._createGLObjectsChanged$
31568 .subscribe(function (tag) {
31569 _this._tagScene.updateCreateTagObjects(tag);
31571 this._updateGLObjectsSubscription = this._renderTagGLChanged$
31572 .subscribe(function (tag) {
31573 _this._tagScene.updateObjects(tag);
31575 this._updateTagSceneSubscription = this._tagChanged$
31576 .subscribe(function (tag) {
31577 _this._tagScene.update();
31579 this._domSubscription = this._renderTags$
31581 .do(function (tags) {
31582 _this._container.domRenderer.render$.next({
31584 vnode: _this._tagDomRenderer.clear(),
31587 .combineLatest(this._container.renderService.renderCamera$, this._container.spriteService.spriteAtlas$, this._container.renderService.size$, this._tagChanged$.startWith(null), this._tagCreator.tag$.merge(this._createGeometryChanged$).startWith(null), function (renderTags, rc, atlas, size, tag, ct) {
31588 return [rc, atlas, size, renderTags, tag, ct];
31590 .map(function (args) {
31593 vnode: _this._tagDomRenderer.render(args[3], args[5], args[1], args[0].perspective, args[2]),
31596 .subscribe(this._container.domRenderer.render$);
31597 this._glSubscription = this._navigator.stateService.currentState$
31598 .map(function (frame) {
31599 var tagScene = _this._tagScene;
31604 needsRender: tagScene.needsRender,
31605 render: tagScene.render.bind(tagScene),
31606 stage: Render_1.GLRenderStage.Foreground,
31610 .subscribe(this._container.glRenderer.render$);
31611 this._navigator.stateService.currentTransform$
31613 .subscribe(function (transform) {
31614 _this._tagSet.activate(transform);
31615 _this._tagScene.add(_this._tagSet.getAll());
31618 TagComponent.prototype._deactivate = function () {
31619 this._editVertexHandler.disable();
31620 this._disableCreateHandlers();
31621 this._tagScene.clear();
31622 this._tagSet.deactivate();
31623 this._tagCreator.delete$.next(null);
31624 this._updateGLObjectsSubscription.unsubscribe();
31625 this._updateTagSceneSubscription.unsubscribe();
31626 this._stopCreateSubscription.unsubscribe();
31627 this._setGLCreateTagSubscription.unsubscribe();
31628 this._createGLObjectsChangedSubscription.unsubscribe();
31629 this._domSubscription.unsubscribe();
31630 this._glSubscription.unsubscribe();
31631 this._fireCreateGeometryEventSubscription.unsubscribe();
31632 this._fireGeometryCreatedSubscription.unsubscribe();
31633 this._fireTagsChangedSubscription.unsubscribe();
31634 this._handlerStopCreateSubscription.unsubscribe();
31635 this._handlerEnablerSubscription.unsubscribe();
31636 this._container.element.classList.remove("component-tag-create");
31638 TagComponent.prototype._getDefaultConfiguration = function () {
31640 createColor: 0xFFFFFF,
31641 mode: Component_1.TagMode.Default,
31644 TagComponent.prototype._disableCreateHandlers = function () {
31645 var createHandlers = this._createHandlers;
31646 for (var key in createHandlers) {
31647 if (!createHandlers.hasOwnProperty(key)) {
31650 var handler = createHandlers[key];
31657 TagComponent.componentName = "tag";
31659 * Event fired when an interaction to create a geometry ends.
31661 * @description A create interaction can by a geometry being created
31662 * or by the creation being aborted.
31664 * @event TagComponent#creategeometryend
31665 * @type {TagComponent} Tag component.
31668 * tagComponent.on("creategeometryend", function(component) {
31669 * console.log(component);
31673 TagComponent.creategeometryend = "creategeometryend";
31675 * Event fired when an interaction to create a geometry starts.
31677 * @description A create interaction starts when the first vertex
31678 * is created in the geometry.
31680 * @event TagComponent#creategeometrystart
31681 * @type {TagComponent} Tag component.
31684 * tagComponent.on("creategeometrystart", function(component) {
31685 * console.log(component);
31689 TagComponent.creategeometrystart = "creategeometrystart";
31691 * Event fired when the create mode is changed.
31693 * @event TagComponent#modechanged
31694 * @type {TagMode} Tag mode
31697 * tagComponent.on("modechanged", function(mode) {
31698 * console.log(mode);
31702 TagComponent.modechanged = "modechanged";
31704 * Event fired when a geometry has been created.
31706 * @event TagComponent#geometrycreated
31707 * @type {Geometry} Created geometry.
31710 * tagComponent.on("geometrycreated", function(geometry) {
31711 * console.log(geometry);
31715 TagComponent.geometrycreated = "geometrycreated";
31717 * Event fired when the tags collection has changed.
31719 * @event TagComponent#tagschanged
31720 * @type {TagComponent} Tag component.
31723 * tagComponent.on("tagschanged", function(component) {
31724 * console.log(component.getAll());
31728 TagComponent.tagschanged = "tagschanged";
31729 return TagComponent;
31730 }(Component_1.Component));
31731 exports.TagComponent = TagComponent;
31732 Component_1.ComponentService.register(TagComponent);
31733 exports.default = TagComponent;
31735 },{"../../Component":290,"../../Geo":293,"../../Render":296,"rxjs/Observable":29,"when":287}],355:[function(require,module,exports){
31737 Object.defineProperty(exports, "__esModule", { value: true });
31738 var Subject_1 = require("rxjs/Subject");
31739 var Component_1 = require("../../Component");
31740 var TagCreator = /** @class */ (function () {
31741 function TagCreator(component, navigator) {
31742 this._component = component;
31743 this._navigator = navigator;
31744 this._tagOperation$ = new Subject_1.Subject();
31745 this._createPolygon$ = new Subject_1.Subject();
31746 this._createRect$ = new Subject_1.Subject();
31747 this._delete$ = new Subject_1.Subject();
31748 this._tag$ = this._tagOperation$
31749 .scan(function (tag, operation) {
31750 return operation(tag);
31754 .withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$)
31755 .map(function (_a) {
31756 var coord = _a[0], conf = _a[1], transform = _a[2];
31757 return function (tag) {
31758 var geometry = new Component_1.RectGeometry([
31764 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
31767 .subscribe(this._tagOperation$);
31768 this._createPolygon$
31769 .withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$)
31770 .map(function (_a) {
31771 var coord = _a[0], conf = _a[1], transform = _a[2];
31772 return function (tag) {
31773 var geometry = new Component_1.PolygonGeometry([
31774 [coord[0], coord[1]],
31775 [coord[0], coord[1]],
31776 [coord[0], coord[1]],
31778 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
31781 .subscribe(this._tagOperation$);
31784 return function (tag) {
31788 .subscribe(this._tagOperation$);
31790 Object.defineProperty(TagCreator.prototype, "createRect$", {
31792 return this._createRect$;
31797 Object.defineProperty(TagCreator.prototype, "createPolygon$", {
31799 return this._createPolygon$;
31804 Object.defineProperty(TagCreator.prototype, "delete$", {
31806 return this._delete$;
31811 Object.defineProperty(TagCreator.prototype, "tag$", {
31820 exports.TagCreator = TagCreator;
31821 exports.default = TagCreator;
31823 },{"../../Component":290,"rxjs/Subject":34}],356:[function(require,module,exports){
31825 /// <reference path="../../../typings/index.d.ts" />
31826 Object.defineProperty(exports, "__esModule", { value: true });
31827 var vd = require("virtual-dom");
31828 var TagDOMRenderer = /** @class */ (function () {
31829 function TagDOMRenderer() {
31831 TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, size) {
31833 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
31834 var tag = tags_1[_i];
31835 vNodes = vNodes.concat(tag.getDOMObjects(atlas, camera, size));
31837 if (createTag != null) {
31838 vNodes = vNodes.concat(createTag.getDOMObjects(camera, size));
31840 return vd.h("div.TagContainer", {}, vNodes);
31842 TagDOMRenderer.prototype.clear = function () {
31843 return vd.h("div", {}, []);
31845 return TagDOMRenderer;
31847 exports.TagDOMRenderer = TagDOMRenderer;
31849 },{"virtual-dom":246}],357:[function(require,module,exports){
31851 Object.defineProperty(exports, "__esModule", { value: true });
31853 * Enumeration for tag modes
31856 * @description Modes for the interaction in the tag component.
31859 (function (TagMode) {
31861 * Disables creating tags.
31863 TagMode[TagMode["Default"] = 0] = "Default";
31865 * Create a point geometry through a click.
31867 TagMode[TagMode["CreatePoint"] = 1] = "CreatePoint";
31869 * Create a polygon geometry through clicks.
31871 TagMode[TagMode["CreatePolygon"] = 2] = "CreatePolygon";
31873 * Create a rect geometry through clicks.
31875 TagMode[TagMode["CreateRect"] = 3] = "CreateRect";
31877 * Create a rect geometry through drag.
31879 * @description Claims the mouse which results in mouse handlers like
31880 * drag pan and scroll zoom becoming inactive.
31882 TagMode[TagMode["CreateRectDrag"] = 4] = "CreateRectDrag";
31883 })(TagMode = exports.TagMode || (exports.TagMode = {}));
31884 exports.default = TagMode;
31886 },{}],358:[function(require,module,exports){
31888 Object.defineProperty(exports, "__esModule", { value: true });
31890 (function (TagOperation) {
31891 TagOperation[TagOperation["None"] = 0] = "None";
31892 TagOperation[TagOperation["Centroid"] = 1] = "Centroid";
31893 TagOperation[TagOperation["Vertex"] = 2] = "Vertex";
31894 })(TagOperation = exports.TagOperation || (exports.TagOperation = {}));
31895 exports.default = TagOperation;
31897 },{}],359:[function(require,module,exports){
31899 /// <reference path="../../../typings/index.d.ts" />
31900 Object.defineProperty(exports, "__esModule", { value: true });
31901 var THREE = require("three");
31902 var TagScene = /** @class */ (function () {
31903 function TagScene(scene, raycaster) {
31904 this._createTag = null;
31905 this._needsRender = false;
31906 this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
31907 this._scene = !!scene ? scene : new THREE.Scene();
31908 this._objectTags = {};
31909 this._retrievableObjects = [];
31912 Object.defineProperty(TagScene.prototype, "needsRender", {
31914 return this._needsRender;
31919 TagScene.prototype.add = function (tags) {
31920 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
31921 var tag = tags_1[_i];
31922 if (tag.tag.id in this._tags) {
31923 this._remove(tag.tag.id);
31927 this._needsRender = true;
31929 TagScene.prototype.addCreateTag = function (tag) {
31930 for (var _i = 0, _a = tag.glObjects; _i < _a.length; _i++) {
31931 var object = _a[_i];
31932 this._scene.add(object);
31934 this._createTag = { tag: tag, objects: tag.glObjects };
31935 this._needsRender = true;
31937 TagScene.prototype.clear = function () {
31938 for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
31942 this._needsRender = false;
31944 TagScene.prototype.get = function (id) {
31945 return this.has(id) ? this._tags[id].tag : undefined;
31947 TagScene.prototype.has = function (id) {
31948 return id in this._tags;
31950 TagScene.prototype.hasCreateTag = function () {
31951 return this._createTag != null;
31953 TagScene.prototype.intersectObjects = function (_a, camera) {
31954 var viewportX = _a[0], viewportY = _a[1];
31955 this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
31956 var intersects = this._raycaster.intersectObjects(this._retrievableObjects);
31957 var intersectedIds = [];
31958 for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
31959 var intersect = intersects_1[_i];
31960 if (intersect.object.uuid in this._objectTags) {
31961 intersectedIds.push(this._objectTags[intersect.object.uuid]);
31964 return intersectedIds;
31966 TagScene.prototype.remove = function (ids) {
31967 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
31968 var id = ids_1[_i];
31971 this._needsRender = true;
31973 TagScene.prototype.removeAll = function () {
31974 for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
31978 this._needsRender = true;
31980 TagScene.prototype.removeCreateTag = function () {
31981 if (this._createTag == null) {
31984 for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
31985 var object = _a[_i];
31986 this._scene.remove(object);
31988 this._createTag.tag.dispose();
31989 this._createTag = null;
31990 this._needsRender = true;
31992 TagScene.prototype.render = function (perspectiveCamera, renderer) {
31993 renderer.render(this._scene, perspectiveCamera);
31994 this._needsRender = false;
31996 TagScene.prototype.update = function () {
31997 this._needsRender = true;
31999 TagScene.prototype.updateCreateTagObjects = function (tag) {
32000 if (this._createTag.tag !== tag) {
32001 throw new Error("Create tags do not have the same reference.");
32003 for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
32004 var object = _a[_i];
32005 this._scene.remove(object);
32007 for (var _b = 0, _c = tag.glObjects; _b < _c.length; _b++) {
32008 var object = _c[_b];
32009 this._scene.add(object);
32011 this._createTag.objects = tag.glObjects;
32012 this._needsRender = true;
32014 TagScene.prototype.updateObjects = function (tag) {
32015 var id = tag.tag.id;
32016 if (this._tags[id].tag !== tag) {
32017 throw new Error("Tags do not have the same reference.");
32019 var tagObjects = this._tags[id];
32020 this._removeObjects(tagObjects);
32021 delete this._tags[id];
32023 this._needsRender = true;
32025 TagScene.prototype._add = function (tag) {
32026 var id = tag.tag.id;
32027 var tagObjects = { tag: tag, objects: [], retrievableObjects: [] };
32028 this._tags[id] = tagObjects;
32029 for (var _i = 0, _a = tag.getGLObjects(); _i < _a.length; _i++) {
32030 var object = _a[_i];
32031 tagObjects.objects.push(object);
32032 this._scene.add(object);
32034 for (var _b = 0, _c = tag.getRetrievableObjects(); _b < _c.length; _b++) {
32035 var retrievableObject = _c[_b];
32036 tagObjects.retrievableObjects.push(retrievableObject);
32037 this._retrievableObjects.push(retrievableObject);
32038 this._objectTags[retrievableObject.uuid] = tag.tag.id;
32041 TagScene.prototype._remove = function (id) {
32042 var tagObjects = this._tags[id];
32043 this._removeObjects(tagObjects);
32044 tagObjects.tag.dispose();
32045 delete this._tags[id];
32047 TagScene.prototype._removeObjects = function (tagObjects) {
32048 for (var _i = 0, _a = tagObjects.objects; _i < _a.length; _i++) {
32049 var object = _a[_i];
32050 this._scene.remove(object);
32052 for (var _b = 0, _c = tagObjects.retrievableObjects; _b < _c.length; _b++) {
32053 var retrievableObject = _c[_b];
32054 var index = this._retrievableObjects.indexOf(retrievableObject);
32055 if (index !== -1) {
32056 this._retrievableObjects.splice(index, 1);
32062 exports.TagScene = TagScene;
32063 exports.default = TagScene;
32065 },{"three":240}],360:[function(require,module,exports){
32067 Object.defineProperty(exports, "__esModule", { value: true });
32068 var Subject_1 = require("rxjs/Subject");
32069 var Component_1 = require("../../Component");
32070 var TagSet = /** @class */ (function () {
32071 function TagSet() {
32072 this._active = false;
32074 this._hashDeactivated = {};
32075 this._notifyChanged$ = new Subject_1.Subject();
32077 Object.defineProperty(TagSet.prototype, "active", {
32079 return this._active;
32084 Object.defineProperty(TagSet.prototype, "changed$", {
32086 return this._notifyChanged$;
32091 TagSet.prototype.activate = function (transform) {
32092 if (this._active) {
32095 for (var id in this._hashDeactivated) {
32096 if (!this._hashDeactivated.hasOwnProperty(id)) {
32099 var tag = this._hashDeactivated[id];
32100 this._add(tag, transform);
32102 this._hashDeactivated = {};
32103 this._active = true;
32104 this._notifyChanged$.next(this);
32106 TagSet.prototype.deactivate = function () {
32107 if (!this._active) {
32110 for (var id in this._hash) {
32111 if (!this._hash.hasOwnProperty(id)) {
32114 this._hashDeactivated[id] = this._hash[id].tag;
32117 this._active = false;
32119 TagSet.prototype.add = function (tags, transform) {
32120 this._assertActivationState(true);
32121 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
32122 var tag = tags_1[_i];
32123 this._add(tag, transform);
32125 this._notifyChanged$.next(this);
32127 TagSet.prototype.addDeactivated = function (tags) {
32128 this._assertActivationState(false);
32129 for (var _i = 0, tags_2 = tags; _i < tags_2.length; _i++) {
32130 var tag = tags_2[_i];
32131 if (!(tag instanceof Component_1.OutlineTag || tag instanceof Component_1.SpotTag)) {
32132 throw new Error("Tag type not supported");
32134 this._hashDeactivated[tag.id] = tag;
32137 TagSet.prototype.get = function (id) {
32138 return this.has(id) ? this._hash[id] : undefined;
32140 TagSet.prototype.getAll = function () {
32141 var hash = this._hash;
32142 return Object.keys(hash)
32143 .map(function (id) {
32147 TagSet.prototype.getAllDeactivated = function () {
32148 var hashDeactivated = this._hashDeactivated;
32149 return Object.keys(hashDeactivated)
32150 .map(function (id) {
32151 return hashDeactivated[id];
32154 TagSet.prototype.getDeactivated = function (id) {
32155 return this.hasDeactivated(id) ? this._hashDeactivated[id] : undefined;
32157 TagSet.prototype.has = function (id) {
32158 return id in this._hash;
32160 TagSet.prototype.hasDeactivated = function (id) {
32161 return id in this._hashDeactivated;
32163 TagSet.prototype.remove = function (ids) {
32164 this._assertActivationState(true);
32165 var hash = this._hash;
32166 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
32167 var id = ids_1[_i];
32168 if (!(id in hash)) {
32173 this._notifyChanged$.next(this);
32175 TagSet.prototype.removeAll = function () {
32176 this._assertActivationState(true);
32178 this._notifyChanged$.next(this);
32180 TagSet.prototype.removeAllDeactivated = function () {
32181 this._assertActivationState(false);
32182 this._hashDeactivated = {};
32184 TagSet.prototype.removeDeactivated = function (ids) {
32185 this._assertActivationState(false);
32186 var hashDeactivated = this._hashDeactivated;
32187 for (var _i = 0, ids_2 = ids; _i < ids_2.length; _i++) {
32188 var id = ids_2[_i];
32189 if (!(id in hashDeactivated)) {
32192 delete hashDeactivated[id];
32195 TagSet.prototype._add = function (tag, transform) {
32196 if (tag instanceof Component_1.OutlineTag) {
32197 this._hash[tag.id] = new Component_1.OutlineRenderTag(tag, transform);
32199 else if (tag instanceof Component_1.SpotTag) {
32200 this._hash[tag.id] = new Component_1.SpotRenderTag(tag, transform);
32203 throw new Error("Tag type not supported");
32206 TagSet.prototype._assertActivationState = function (should) {
32207 if (should !== this._active) {
32208 throw new Error("Tag set not in correct state for operation.");
32213 exports.TagSet = TagSet;
32214 exports.default = TagSet;
32216 },{"../../Component":290,"rxjs/Subject":34}],361:[function(require,module,exports){
32218 var __extends = (this && this.__extends) || (function () {
32219 var extendStatics = Object.setPrototypeOf ||
32220 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32221 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32222 return function (d, b) {
32223 extendStatics(d, b);
32224 function __() { this.constructor = d; }
32225 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32228 Object.defineProperty(exports, "__esModule", { value: true });
32229 var Error_1 = require("../../../Error");
32230 var GeometryTagError = /** @class */ (function (_super) {
32231 __extends(GeometryTagError, _super);
32232 function GeometryTagError(message) {
32233 var _this = _super.call(this, message != null ? message : "The provided geometry value is incorrect") || this;
32234 _this.name = "GeometryTagError";
32237 return GeometryTagError;
32238 }(Error_1.MapillaryError));
32239 exports.GeometryTagError = GeometryTagError;
32240 exports.default = Error_1.MapillaryError;
32242 },{"../../../Error":292}],362:[function(require,module,exports){
32244 Object.defineProperty(exports, "__esModule", { value: true });
32245 var Subject_1 = require("rxjs/Subject");
32249 * @classdesc Represents a geometry.
32251 var Geometry = /** @class */ (function () {
32253 * Create a geometry.
32257 function Geometry() {
32258 this._notifyChanged$ = new Subject_1.Subject();
32260 Object.defineProperty(Geometry.prototype, "changed$", {
32262 * Get changed observable.
32264 * @description Emits the geometry itself every time the geometry
32267 * @returns {Observable<Geometry>} Observable emitting the geometry instance.
32271 return this._notifyChanged$;
32278 exports.Geometry = Geometry;
32279 exports.default = Geometry;
32281 },{"rxjs/Subject":34}],363:[function(require,module,exports){
32283 var __extends = (this && this.__extends) || (function () {
32284 var extendStatics = Object.setPrototypeOf ||
32285 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32286 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32287 return function (d, b) {
32288 extendStatics(d, b);
32289 function __() { this.constructor = d; }
32290 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32293 Object.defineProperty(exports, "__esModule", { value: true });
32294 var Component_1 = require("../../../Component");
32296 * @class PointGeometry
32298 * @classdesc Represents a point geometry in the 2D basic image coordinate system.
32302 * var basicPoint = [0.5, 0.7];
32303 * var pointGeometry = new Mapillary.TagComponent.PointGeometry(basicPoint);
32306 var PointGeometry = /** @class */ (function (_super) {
32307 __extends(PointGeometry, _super);
32309 * Create a point geometry.
32312 * @param {Array<number>} point - An array representing the basic coordinates of
32315 * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
32317 function PointGeometry(point) {
32318 var _this = _super.call(this) || this;
32321 if (x < 0 || x > 1 || y < 0 || y > 1) {
32322 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
32324 _this._point = point.slice();
32327 Object.defineProperty(PointGeometry.prototype, "point", {
32329 * Get point property.
32330 * @returns {Array<number>} Array representing the basic coordinates of the point.
32333 return this._point;
32339 * Get the 2D basic coordinates for the centroid of the point, i.e. the 2D
32340 * basic coordinates of the point itself.
32342 * @returns {Array<number>} 2D basic coordinates representing the centroid.
32344 PointGeometry.prototype.getCentroid2d = function () {
32345 return this._point.slice();
32348 * Get the 3D world coordinates for the centroid of the point, i.e. the 3D
32349 * world coordinates of the point itself.
32351 * @param {Transform} transform - The transform of the node related to the point.
32352 * @returns {Array<number>} 3D world coordinates representing the centroid.
32354 PointGeometry.prototype.getCentroid3d = function (transform) {
32355 return transform.unprojectBasic(this._point, 200);
32358 * Set the centroid of the point, i.e. the point coordinates.
32360 * @param {Array<number>} value - The new value of the centroid.
32361 * @param {Transform} transform - The transform of the node related to the point.
32363 PointGeometry.prototype.setCentroid2d = function (value, transform) {
32365 Math.max(0, Math.min(1, value[0])),
32366 Math.max(0, Math.min(1, value[1])),
32368 this._point[0] = changed[0];
32369 this._point[1] = changed[1];
32370 this._notifyChanged$.next(this);
32372 return PointGeometry;
32373 }(Component_1.Geometry));
32374 exports.PointGeometry = PointGeometry;
32376 },{"../../../Component":290}],364:[function(require,module,exports){
32378 var __extends = (this && this.__extends) || (function () {
32379 var extendStatics = Object.setPrototypeOf ||
32380 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32381 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32382 return function (d, b) {
32383 extendStatics(d, b);
32384 function __() { this.constructor = d; }
32385 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32388 Object.defineProperty(exports, "__esModule", { value: true });
32389 var Component_1 = require("../../../Component");
32391 * @class PolygonGeometry
32393 * @classdesc Represents a polygon geometry in the 2D basic image coordinate system.
32394 * All polygons and holes provided to the constructor needs to be closed.
32398 * var basicPolygon = [[0.5, 0.3], [0.7, 0.3], [0.6, 0.5], [0.5, 0.3]];
32399 * var polygonGeometry = new Mapillary.TagComponent.PointGeometry(basicPolygon);
32402 var PolygonGeometry = /** @class */ (function (_super) {
32403 __extends(PolygonGeometry, _super);
32405 * Create a polygon geometry.
32408 * @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
32409 * @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
32410 * Each array of holes vertices must be closed.
32412 * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
32414 function PolygonGeometry(polygon, holes) {
32415 var _this = _super.call(this) || this;
32416 var polygonLength = polygon.length;
32417 if (polygonLength < 3) {
32418 throw new Component_1.GeometryTagError("A polygon must have three or more positions.");
32420 if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
32421 polygon[0][1] !== polygon[polygonLength - 1][1]) {
32422 throw new Component_1.GeometryTagError("First and last positions must be equivalent.");
32424 _this._polygon = [];
32425 for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) {
32426 var vertex = polygon_1[_i];
32427 if (vertex[0] < 0 || vertex[0] > 1 ||
32428 vertex[1] < 0 || vertex[1] > 1) {
32429 throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
32431 _this._polygon.push(vertex.slice());
32434 if (holes == null) {
32437 for (var i = 0; i < holes.length; i++) {
32438 var hole = holes[i];
32439 var holeLength = hole.length;
32440 if (holeLength < 3) {
32441 throw new Component_1.GeometryTagError("A polygon hole must have three or more positions.");
32443 if (hole[0][0] !== hole[holeLength - 1][0] ||
32444 hole[0][1] !== hole[holeLength - 1][1]) {
32445 throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent.");
32447 _this._holes.push([]);
32448 for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) {
32449 var vertex = hole_1[_a];
32450 if (vertex[0] < 0 || vertex[0] > 1 ||
32451 vertex[1] < 0 || vertex[1] > 1) {
32452 throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
32454 _this._holes[i].push(vertex.slice());
32459 Object.defineProperty(PolygonGeometry.prototype, "polygon", {
32461 * Get polygon property.
32462 * @returns {Array<Array<number>>} Closed 2d polygon.
32465 return this._polygon;
32470 Object.defineProperty(PolygonGeometry.prototype, "holes", {
32472 * Get holes property.
32473 * @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
32476 return this._holes;
32482 * Add a vertex to the polygon by appending it after the last vertex.
32484 * @param {Array<number>} vertex - Vertex to add.
32486 PolygonGeometry.prototype.addVertex2d = function (vertex) {
32488 Math.max(0, Math.min(1, vertex[0])),
32489 Math.max(0, Math.min(1, vertex[1])),
32491 this._polygon.splice(this._polygon.length - 1, 0, clamped);
32492 this._notifyChanged$.next(this);
32495 * Get the coordinates of a vertex from the polygon representation of the geometry.
32497 * @description The first vertex represents the bottom-left corner with the rest of
32498 * the vertices following in clockwise order.
32500 * @param {number} index - Vertex index.
32501 * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
32503 PolygonGeometry.prototype.getVertex2d = function (index) {
32504 return this._polygon[index].slice();
32507 * Remove a vertex from the polygon.
32509 * @param {number} index - The index of the vertex to remove.
32511 PolygonGeometry.prototype.removeVertex2d = function (index) {
32513 index >= this._polygon.length ||
32514 this._polygon.length < 4) {
32515 throw new Component_1.GeometryTagError("Index for removed vertex must be valid.");
32517 if (index > 0 && index < this._polygon.length - 1) {
32518 this._polygon.splice(index, 1);
32521 this._polygon.splice(0, 1);
32522 this._polygon.pop();
32523 var closing = this._polygon[0].slice();
32524 this._polygon.push(closing);
32526 this._notifyChanged$.next(this);
32529 PolygonGeometry.prototype.setVertex2d = function (index, value, transform) {
32531 Math.max(0, Math.min(1, value[0])),
32532 Math.max(0, Math.min(1, value[1])),
32534 if (index === 0 || index === this._polygon.length - 1) {
32535 this._polygon[0] = changed.slice();
32536 this._polygon[this._polygon.length - 1] = changed.slice();
32539 this._polygon[index] = changed.slice();
32541 this._notifyChanged$.next(this);
32544 PolygonGeometry.prototype.setCentroid2d = function (value, transform) {
32545 var xs = this._polygon.map(function (point) { return point[0]; });
32546 var ys = this._polygon.map(function (point) { return point[1]; });
32547 var minX = Math.min.apply(Math, xs);
32548 var maxX = Math.max.apply(Math, xs);
32549 var minY = Math.min.apply(Math, ys);
32550 var maxY = Math.max.apply(Math, ys);
32551 var centroid = this.getCentroid2d();
32552 var minTranslationX = -minX;
32553 var maxTranslationX = 1 - maxX;
32554 var minTranslationY = -minY;
32555 var maxTranslationY = 1 - maxY;
32556 var translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
32557 var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
32558 for (var _i = 0, _a = this._polygon; _i < _a.length; _i++) {
32559 var point = _a[_i];
32560 point[0] += translationX;
32561 point[1] += translationY;
32563 this._notifyChanged$.next(this);
32566 PolygonGeometry.prototype.getPoints3d = function (transform) {
32567 return this.getVertices3d(transform);
32570 PolygonGeometry.prototype.getVertex3d = function (index, transform) {
32571 return transform.unprojectBasic(this._polygon[index], 200);
32574 PolygonGeometry.prototype.getVertices2d = function () {
32575 return this._polygon.slice();
32578 PolygonGeometry.prototype.getVertices3d = function (transform) {
32579 return this._polygon
32580 .map(function (point) {
32581 return transform.unprojectBasic(point, 200);
32585 * Get a polygon representation of the 3D coordinates for the vertices of each hole
32588 * @param {Transform} transform - The transform of the node related to the geometry.
32589 * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
32590 * representing the vertices of each hole of the geometry.
32592 PolygonGeometry.prototype.getHoleVertices3d = function (transform) {
32594 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
32597 .map(function (point) {
32598 return transform.unprojectBasic(point, 200);
32600 holes3d.push(hole3d);
32605 PolygonGeometry.prototype.getCentroid2d = function () {
32606 var polygon = this._polygon;
32610 for (var i = 0; i < polygon.length - 1; i++) {
32611 var xi = polygon[i][0];
32612 var yi = polygon[i][1];
32613 var xi1 = polygon[i + 1][0];
32614 var yi1 = polygon[i + 1][1];
32615 var a = xi * yi1 - xi1 * yi;
32617 centroidX += (xi + xi1) * a;
32618 centroidY += (yi + yi1) * a;
32621 centroidX /= 6 * area;
32622 centroidY /= 6 * area;
32623 return [centroidX, centroidY];
32626 PolygonGeometry.prototype.getCentroid3d = function (transform) {
32627 var centroid2d = this.getCentroid2d();
32628 return transform.unprojectBasic(centroid2d, 200);
32631 PolygonGeometry.prototype.getTriangles3d = function (transform) {
32632 return this._triangulate(this._polygon, this.getPoints3d(transform), this._holes, this.getHoleVertices3d(transform));
32635 PolygonGeometry.prototype.getPoleOfAccessibility2d = function () {
32636 return this._getPoleOfInaccessibility2d(this._polygon.slice());
32639 PolygonGeometry.prototype.getPoleOfAccessibility3d = function (transform) {
32640 var pole2d = this._getPoleOfInaccessibility2d(this._polygon.slice());
32641 return transform.unprojectBasic(pole2d, 200);
32643 return PolygonGeometry;
32644 }(Component_1.VertexGeometry));
32645 exports.PolygonGeometry = PolygonGeometry;
32646 exports.default = PolygonGeometry;
32648 },{"../../../Component":290}],365:[function(require,module,exports){
32650 var __extends = (this && this.__extends) || (function () {
32651 var extendStatics = Object.setPrototypeOf ||
32652 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32653 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32654 return function (d, b) {
32655 extendStatics(d, b);
32656 function __() { this.constructor = d; }
32657 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32660 Object.defineProperty(exports, "__esModule", { value: true });
32661 var Component_1 = require("../../../Component");
32663 * @class RectGeometry
32665 * @classdesc Represents a rectangle geometry in the 2D basic image coordinate system.
32669 * var basicRect = [0.5, 0.3, 0.7, 0.4];
32670 * var rectGeometry = new Mapillary.TagComponent.RectGeometry(basicRect);
32673 var RectGeometry = /** @class */ (function (_super) {
32674 __extends(RectGeometry, _super);
32676 * Create a rectangle geometry.
32679 * @param {Array<number>} rect - An array representing the top-left and bottom-right
32680 * corners of the rectangle in basic coordinates. Ordered according to [x0, y0, x1, y1].
32682 * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates.
32684 function RectGeometry(rect) {
32685 var _this = _super.call(this) || this;
32686 if (rect[1] > rect[3]) {
32687 throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted.");
32689 for (var _i = 0, rect_1 = rect; _i < rect_1.length; _i++) {
32690 var coord = rect_1[_i];
32691 if (coord < 0 || coord > 1) {
32692 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
32695 _this._anchorIndex = undefined;
32696 _this._rect = rect.slice(0, 4);
32697 _this._inverted = _this._rect[0] > _this._rect[2];
32700 Object.defineProperty(RectGeometry.prototype, "anchorIndex", {
32702 * Get anchor index property.
32704 * @returns {number} Index representing the current anchor property if
32705 * achoring indexing has been initialized. If anchor indexing has not been
32706 * initialized or has been terminated undefined will be returned.
32709 return this._anchorIndex;
32714 Object.defineProperty(RectGeometry.prototype, "inverted", {
32716 * Get inverted property.
32718 * @returns {boolean} Boolean determining whether the rect geometry is
32719 * inverted. For panoramas the rect geometrye may be inverted.
32722 return this._inverted;
32727 Object.defineProperty(RectGeometry.prototype, "rect", {
32729 * Get rect property.
32731 * @returns {Array<number>} Array representing the top-left and bottom-right
32732 * corners of the rectangle in basic coordinates.
32741 * Initialize anchor indexing to enable setting opposite vertex.
32743 * @param {number} [index] - The index of the vertex to use as anchor.
32745 * @throws {Error} If anchor indexing has already been initialized.
32746 * @throws {Error} If index is not valid (0 to 3).
32748 RectGeometry.prototype.initializeAnchorIndexing = function (index) {
32749 if (this._anchorIndex !== undefined) {
32750 throw new Error("Anchor indexing is already initialized.");
32752 if (index < 0 || index > 3) {
32753 throw new Error("Invalid anchor index: " + index + ".");
32755 this._anchorIndex = index === undefined ? 0 : index;
32758 * Terminate anchor indexing to disable setting pposite vertex.
32760 RectGeometry.prototype.terminateAnchorIndexing = function () {
32761 this._anchorIndex = undefined;
32764 * Set the value of the vertex opposite to the anchor in the polygon
32765 * representation of the rectangle.
32767 * @description Setting the opposite vertex may change the anchor index.
32769 * @param {Array<number>} opposite - The new value of the vertex opposite to the anchor.
32770 * @param {Transform} transform - The transform of the node related to the rectangle.
32772 * @throws {Error} When anchor indexing has not been initialized.
32774 RectGeometry.prototype.setOppositeVertex2d = function (opposite, transform) {
32775 if (this._anchorIndex === undefined) {
32776 throw new Error("Anchor indexing needs to be initialized.");
32779 Math.max(0, Math.min(1, opposite[0])),
32780 Math.max(0, Math.min(1, opposite[1])),
32782 var original = this._rect.slice();
32783 var anchor = this._anchorIndex === 0 ? [original[0], original[3]] :
32784 this._anchorIndex === 1 ? [original[0], original[1]] :
32785 this._anchorIndex === 2 ? [original[2], original[1]] :
32786 [original[2], original[3]];
32787 if (transform.fullPano) {
32788 var deltaX = this._anchorIndex < 2 ?
32789 changed[0] - original[2] :
32790 changed[0] - original[0];
32791 if (!this._inverted && this._anchorIndex < 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) {
32792 // right side passes boundary rightward
32793 this._inverted = true;
32794 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
32796 else if (!this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) {
32797 // left side passes right side and boundary rightward
32798 this._inverted = true;
32799 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
32801 else if (this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[0] > 0.75 && deltaX < -0.5) {
32802 this._inverted = false;
32803 if (anchor[0] > changed[0]) {
32804 // left side passes boundary rightward
32805 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
32808 // left side passes right side and boundary rightward
32809 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
32812 else if (!this._inverted && this._anchorIndex >= 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) {
32813 // left side passes boundary leftward
32814 this._inverted = true;
32815 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
32817 else if (!this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) {
32818 // right side passes left side and boundary leftward
32819 this._inverted = true;
32820 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
32822 else if (this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[2] < 0.25 && deltaX > 0.5) {
32823 this._inverted = false;
32824 if (anchor[0] > changed[0]) {
32825 // right side passes boundary leftward
32826 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
32829 // right side passes left side and boundary leftward
32830 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
32833 else if (this._inverted && this._anchorIndex < 2 && changed[0] > original[0]) {
32834 // inverted and right side passes left side completing a loop
32835 this._inverted = false;
32836 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
32838 else if (this._inverted && this._anchorIndex >= 2 && changed[0] < original[2]) {
32839 // inverted and left side passes right side completing a loop
32840 this._inverted = false;
32841 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
32843 else if (this._inverted) {
32844 // if still inverted only top and bottom can switch
32845 if (this._anchorIndex < 2) {
32846 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
32849 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
32853 // if still not inverted treat as non full pano
32854 if (anchor[0] <= changed[0] && anchor[1] > changed[1]) {
32855 this._anchorIndex = 0;
32857 else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) {
32858 this._anchorIndex = 1;
32860 else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) {
32861 this._anchorIndex = 2;
32864 this._anchorIndex = 3;
32868 if (this._anchorIndex === 0) {
32869 rect[0] = anchor[0];
32870 rect[1] = changed[1];
32871 rect[2] = changed[0];
32872 rect[3] = anchor[1];
32874 else if (this._anchorIndex === 1) {
32875 rect[0] = anchor[0];
32876 rect[1] = anchor[1];
32877 rect[2] = changed[0];
32878 rect[3] = changed[1];
32880 else if (this._anchorIndex === 2) {
32881 rect[0] = changed[0];
32882 rect[1] = anchor[1];
32883 rect[2] = anchor[0];
32884 rect[3] = changed[1];
32887 rect[0] = changed[0];
32888 rect[1] = changed[1];
32889 rect[2] = anchor[0];
32890 rect[3] = anchor[1];
32892 if (!this._inverted && rect[0] > rect[2] ||
32893 this._inverted && rect[0] < rect[2]) {
32894 rect[0] = original[0];
32895 rect[2] = original[2];
32897 if (rect[1] > rect[3]) {
32898 rect[1] = original[1];
32899 rect[3] = original[3];
32901 this._rect[0] = rect[0];
32902 this._rect[1] = rect[1];
32903 this._rect[2] = rect[2];
32904 this._rect[3] = rect[3];
32907 if (anchor[0] <= changed[0] && anchor[1] > changed[1]) {
32908 this._anchorIndex = 0;
32910 else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) {
32911 this._anchorIndex = 1;
32913 else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) {
32914 this._anchorIndex = 2;
32917 this._anchorIndex = 3;
32920 if (this._anchorIndex === 0) {
32921 rect[0] = anchor[0];
32922 rect[1] = changed[1];
32923 rect[2] = changed[0];
32924 rect[3] = anchor[1];
32926 else if (this._anchorIndex === 1) {
32927 rect[0] = anchor[0];
32928 rect[1] = anchor[1];
32929 rect[2] = changed[0];
32930 rect[3] = changed[1];
32932 else if (this._anchorIndex === 2) {
32933 rect[0] = changed[0];
32934 rect[1] = anchor[1];
32935 rect[2] = anchor[0];
32936 rect[3] = changed[1];
32939 rect[0] = changed[0];
32940 rect[1] = changed[1];
32941 rect[2] = anchor[0];
32942 rect[3] = anchor[1];
32944 if (rect[0] > rect[2]) {
32945 rect[0] = original[0];
32946 rect[2] = original[2];
32948 if (rect[1] > rect[3]) {
32949 rect[1] = original[1];
32950 rect[3] = original[3];
32952 this._rect[0] = rect[0];
32953 this._rect[1] = rect[1];
32954 this._rect[2] = rect[2];
32955 this._rect[3] = rect[3];
32957 this._notifyChanged$.next(this);
32960 * Set the value of a vertex in the polygon representation of the rectangle.
32962 * @description The polygon is defined to have the first vertex at the
32963 * bottom-left corner with the rest of the vertices following in clockwise order.
32965 * @param {number} index - The index of the vertex to be set.
32966 * @param {Array<number>} value - The new value of the vertex.
32967 * @param {Transform} transform - The transform of the node related to the rectangle.
32969 RectGeometry.prototype.setVertex2d = function (index, value, transform) {
32970 var original = this._rect.slice();
32972 Math.max(0, Math.min(1, value[0])),
32973 Math.max(0, Math.min(1, value[1])),
32977 rect[0] = changed[0];
32978 rect[1] = original[1];
32979 rect[2] = original[2];
32980 rect[3] = changed[1];
32982 else if (index === 1) {
32983 rect[0] = changed[0];
32984 rect[1] = changed[1];
32985 rect[2] = original[2];
32986 rect[3] = original[3];
32988 else if (index === 2) {
32989 rect[0] = original[0];
32990 rect[1] = changed[1];
32991 rect[2] = changed[0];
32992 rect[3] = original[3];
32994 else if (index === 3) {
32995 rect[0] = original[0];
32996 rect[1] = original[1];
32997 rect[2] = changed[0];
32998 rect[3] = changed[1];
33000 if (transform.fullPano) {
33001 var passingBoundaryLeftward = index < 2 && changed[0] > 0.75 && original[0] < 0.25 ||
33002 index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25;
33003 var passingBoundaryRightward = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 ||
33004 index >= 2 && changed[0] < 0.25 && original[2] > 0.75;
33005 if (passingBoundaryLeftward || passingBoundaryRightward) {
33006 this._inverted = !this._inverted;
33009 if (rect[0] - original[0] < -0.25) {
33010 rect[0] = original[0];
33012 if (rect[2] - original[2] > 0.25) {
33013 rect[2] = original[2];
33016 if (!this._inverted && rect[0] > rect[2] ||
33017 this._inverted && rect[0] < rect[2]) {
33018 rect[0] = original[0];
33019 rect[2] = original[2];
33023 if (rect[0] > rect[2]) {
33024 rect[0] = original[0];
33025 rect[2] = original[2];
33028 if (rect[1] > rect[3]) {
33029 rect[1] = original[1];
33030 rect[3] = original[3];
33032 this._rect[0] = rect[0];
33033 this._rect[1] = rect[1];
33034 this._rect[2] = rect[2];
33035 this._rect[3] = rect[3];
33036 this._notifyChanged$.next(this);
33039 RectGeometry.prototype.setCentroid2d = function (value, transform) {
33040 var original = this._rect.slice();
33041 var x0 = original[0];
33042 var x1 = this._inverted ? original[2] + 1 : original[2];
33043 var y0 = original[1];
33044 var y1 = original[3];
33045 var centerX = x0 + (x1 - x0) / 2;
33046 var centerY = y0 + (y1 - y0) / 2;
33047 var translationX = 0;
33048 if (transform.gpano != null &&
33049 transform.gpano.CroppedAreaImageWidthPixels === transform.gpano.FullPanoWidthPixels) {
33050 translationX = this._inverted ? value[0] + 1 - centerX : value[0] - centerX;
33053 var minTranslationX = -x0;
33054 var maxTranslationX = 1 - x1;
33055 translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centerX));
33057 var minTranslationY = -y0;
33058 var maxTranslationY = 1 - y1;
33059 var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centerY));
33060 this._rect[0] = original[0] + translationX;
33061 this._rect[1] = original[1] + translationY;
33062 this._rect[2] = original[2] + translationX;
33063 this._rect[3] = original[3] + translationY;
33064 if (this._rect[0] < 0) {
33065 this._rect[0] += 1;
33066 this._inverted = !this._inverted;
33068 else if (this._rect[0] > 1) {
33069 this._rect[0] -= 1;
33070 this._inverted = !this._inverted;
33072 if (this._rect[2] < 0) {
33073 this._rect[2] += 1;
33074 this._inverted = !this._inverted;
33076 else if (this._rect[2] > 1) {
33077 this._rect[2] -= 1;
33078 this._inverted = !this._inverted;
33080 this._notifyChanged$.next(this);
33083 * Get the 3D coordinates for the vertices of the rectangle with
33084 * interpolated points along the lines.
33086 * @param {Transform} transform - The transform of the node related to
33088 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates
33089 * representing the rectangle.
33091 RectGeometry.prototype.getPoints3d = function (transform) {
33092 return this._getPoints2d(transform)
33093 .map(function (point) {
33094 return transform.unprojectBasic(point, 200);
33098 * Get the coordinates of a vertex from the polygon representation of the geometry.
33100 * @description The first vertex represents the bottom-left corner with the rest of
33101 * the vertices following in clockwise order. The method shifts the right side
33102 * coordinates of the rectangle by one unit to ensure that the vertices are ordered
33105 * @param {number} index - Vertex index.
33106 * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
33108 RectGeometry.prototype.getVertex2d = function (index) {
33109 return this._rectToVertices2d(this._rect)[index];
33112 * Get the coordinates of a vertex from the polygon representation of the geometry.
33114 * @description The first vertex represents the bottom-left corner with the rest of
33115 * the vertices following in clockwise order. The coordinates will not be shifted
33116 * so they may not appear in clockwise order when layed out on the plane.
33118 * @param {number} index - Vertex index.
33119 * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
33121 RectGeometry.prototype.getNonAdjustedVertex2d = function (index) {
33122 return this._rectToNonAdjustedVertices2d(this._rect)[index];
33125 * Get a vertex from the polygon representation of the 3D coordinates for the
33126 * vertices of the geometry.
33128 * @description The first vertex represents the bottom-left corner with the rest of
33129 * the vertices following in clockwise order.
33131 * @param {number} index - Vertex index.
33132 * @param {Transform} transform - The transform of the node related to the geometry.
33133 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
33134 * the vertices of the geometry.
33136 RectGeometry.prototype.getVertex3d = function (index, transform) {
33137 return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200);
33140 * Get a polygon representation of the 2D basic coordinates for the vertices of the rectangle.
33142 * @description The first vertex represents the bottom-left corner with the rest of
33143 * the vertices following in clockwise order.
33145 * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates representing
33146 * the rectangle vertices.
33148 RectGeometry.prototype.getVertices2d = function () {
33149 return this._rectToVertices2d(this._rect);
33152 * Get a polygon representation of the 3D coordinates for the vertices of the rectangle.
33154 * @description The first vertex represents the bottom-left corner with the rest of
33155 * the vertices following in clockwise order.
33157 * @param {Transform} transform - The transform of the node related to the rectangle.
33158 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
33159 * the rectangle vertices.
33161 RectGeometry.prototype.getVertices3d = function (transform) {
33162 return this._rectToVertices2d(this._rect)
33163 .map(function (vertex) {
33164 return transform.unprojectBasic(vertex, 200);
33168 RectGeometry.prototype.getCentroid2d = function () {
33169 var rect = this._rect;
33171 var x1 = this._inverted ? rect[2] + 1 : rect[2];
33174 var centroidX = (x0 + x1) / 2;
33175 var centroidY = (y0 + y1) / 2;
33176 return [centroidX, centroidY];
33179 RectGeometry.prototype.getCentroid3d = function (transform) {
33180 var centroid2d = this.getCentroid2d();
33181 return transform.unprojectBasic(centroid2d, 200);
33184 RectGeometry.prototype.getPoleOfAccessibility2d = function () {
33185 return this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
33188 RectGeometry.prototype.getPoleOfAccessibility3d = function (transform) {
33189 var pole2d = this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
33190 return transform.unprojectBasic(pole2d, 200);
33193 RectGeometry.prototype.getTriangles3d = function (transform) {
33194 return this._triangulate(this._rectToVertices2d(this._rect), this.getVertices3d(transform));
33197 * Check if a particular bottom-right value is valid according to the current
33198 * rectangle coordinates.
33200 * @param {Array<number>} bottomRight - The bottom-right coordinates to validate
33201 * @returns {boolean} Value indicating whether the provided bottom-right coordinates
33204 RectGeometry.prototype.validate = function (bottomRight) {
33205 var rect = this._rect;
33206 if (!this._inverted && bottomRight[0] < rect[0] ||
33207 bottomRight[0] - rect[2] > 0.25 ||
33208 bottomRight[1] < rect[1]) {
33214 * Get the 2D coordinates for the vertices of the rectangle with
33215 * interpolated points along the lines.
33217 * @param {Transform} transform - The transform of the node related to
33219 * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates
33220 * representing the rectangle.
33222 RectGeometry.prototype._getPoints2d = function (transform) {
33223 var vertices2d = this._rectToVertices2d(this._rect);
33224 var sides = vertices2d.length - 1;
33227 for (var i = 0; i < sides; ++i) {
33228 var startX = vertices2d[i][0];
33229 var startY = vertices2d[i][1];
33230 var endX = vertices2d[i + 1][0];
33231 var endY = vertices2d[i + 1][1];
33232 var intervalX = (endX - startX) / (sections - 1);
33233 var intervalY = (endY - startY) / (sections - 1);
33234 for (var j = 0; j < sections; ++j) {
33236 startX + j * intervalX,
33237 startY + j * intervalY,
33239 points2d.push(point);
33245 * Convert the top-left, bottom-right representation of a rectangle to a polygon
33246 * representation of the vertices starting at the bottom-left corner going
33249 * @description The method shifts the right side coordinates of the rectangle
33250 * by one unit to ensure that the vertices are ordered clockwise.
33252 * @param {Array<number>} rect - Top-left, bottom-right representation of a
33254 * @returns {Array<Array<number>>} Polygon representation of the vertices of the
33257 RectGeometry.prototype._rectToVertices2d = function (rect) {
33259 [rect[0], rect[3]],
33260 [rect[0], rect[1]],
33261 [this._inverted ? rect[2] + 1 : rect[2], rect[1]],
33262 [this._inverted ? rect[2] + 1 : rect[2], rect[3]],
33263 [rect[0], rect[3]],
33267 * Convert the top-left, bottom-right representation of a rectangle to a polygon
33268 * representation of the vertices starting at the bottom-left corner going
33271 * @description The first vertex represents the bottom-left corner with the rest of
33272 * the vertices following in clockwise order. The coordinates will not be shifted
33273 * to ensure that the vertices are ordered clockwise when layed out on the plane.
33275 * @param {Array<number>} rect - Top-left, bottom-right representation of a
33277 * @returns {Array<Array<number>>} Polygon representation of the vertices of the
33280 RectGeometry.prototype._rectToNonAdjustedVertices2d = function (rect) {
33282 [rect[0], rect[3]],
33283 [rect[0], rect[1]],
33284 [rect[2], rect[1]],
33285 [rect[2], rect[3]],
33286 [rect[0], rect[3]],
33289 return RectGeometry;
33290 }(Component_1.VertexGeometry));
33291 exports.RectGeometry = RectGeometry;
33292 exports.default = RectGeometry;
33294 },{"../../../Component":290}],366:[function(require,module,exports){
33296 /// <reference path="../../../../typings/index.d.ts" />
33297 var __extends = (this && this.__extends) || (function () {
33298 var extendStatics = Object.setPrototypeOf ||
33299 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33300 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33301 return function (d, b) {
33302 extendStatics(d, b);
33303 function __() { this.constructor = d; }
33304 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33307 Object.defineProperty(exports, "__esModule", { value: true });
33308 var earcut = require("earcut");
33309 var polylabel = require("@mapbox/polylabel");
33310 var Component_1 = require("../../../Component");
33312 * @class VertexGeometry
33314 * @classdesc Represents a vertex geometry.
33316 var VertexGeometry = /** @class */ (function (_super) {
33317 __extends(VertexGeometry, _super);
33319 * Create a vertex geometry.
33323 function VertexGeometry() {
33324 return _super.call(this) || this;
33327 * Finds the polygon pole of inaccessibility, the most distant internal
33328 * point from the polygon outline.
33330 * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
33331 * @returns {Array<number>} Point of inaccessibility.
33334 VertexGeometry.prototype._getPoleOfInaccessibility2d = function (points2d) {
33335 var pole2d = polylabel([points2d], 3e-2);
33339 * Triangulates a 2d polygon and returns the triangle
33340 * representation as a flattened array of 3d points.
33342 * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
33343 * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points.
33344 * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate.
33345 * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points.
33346 * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles.
33349 VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) {
33350 var data = [points2d.slice(0, -1)];
33351 for (var _i = 0, _a = holes2d != null ? holes2d : []; _i < _a.length; _i++) {
33352 var hole2d = _a[_i];
33353 data.push(hole2d.slice(0, -1));
33355 var points = points3d.slice(0, -1);
33356 for (var _b = 0, _c = holes3d != null ? holes3d : []; _b < _c.length; _b++) {
33357 var hole3d = _c[_b];
33358 points = points.concat(hole3d.slice(0, -1));
33360 var flattened = earcut.flatten(data);
33361 var indices = earcut(flattened.vertices, flattened.holes, flattened.dimensions);
33362 var triangles = [];
33363 for (var i = 0; i < indices.length; ++i) {
33364 var point = points[indices[i]];
33365 triangles.push(point[0]);
33366 triangles.push(point[1]);
33367 triangles.push(point[2]);
33371 return VertexGeometry;
33372 }(Component_1.Geometry));
33373 exports.VertexGeometry = VertexGeometry;
33374 exports.default = VertexGeometry;
33376 },{"../../../Component":290,"@mapbox/polylabel":1,"earcut":8}],367:[function(require,module,exports){
33378 /// <reference path="../../../../typings/index.d.ts" />
33379 var __extends = (this && this.__extends) || (function () {
33380 var extendStatics = Object.setPrototypeOf ||
33381 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33382 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33383 return function (d, b) {
33384 extendStatics(d, b);
33385 function __() { this.constructor = d; }
33386 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33389 Object.defineProperty(exports, "__esModule", { value: true });
33390 var Subject_1 = require("rxjs/Subject");
33391 var Component_1 = require("../../../Component");
33392 var CreateHandlerBase = /** @class */ (function (_super) {
33393 __extends(CreateHandlerBase, _super);
33394 function CreateHandlerBase(component, container, navigator, viewportCoords, tagCreator) {
33395 var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
33396 _this._tagCreator = tagCreator;
33397 _this._geometryCreated$ = new Subject_1.Subject();
33400 Object.defineProperty(CreateHandlerBase.prototype, "geometryCreated$", {
33402 return this._geometryCreated$;
33407 CreateHandlerBase.prototype._enable = function () {
33408 this._enableCreate();
33409 this._container.element.classList.add("component-tag-create");
33411 CreateHandlerBase.prototype._disable = function () {
33412 this._container.element.classList.remove("component-tag-create");
33413 this._disableCreate();
33415 CreateHandlerBase.prototype._validateBasic = function (basic) {
33418 return 0 <= x && x <= 1 && 0 <= y && y <= 1;
33420 CreateHandlerBase.prototype._mouseEventToBasic$ = function (mouseEvent$) {
33423 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
33424 .map(function (_a) {
33425 var event = _a[0], camera = _a[1], transform = _a[2];
33426 return _this._mouseEventToBasic(event, _this._container.element, camera, transform);
33429 return CreateHandlerBase;
33430 }(Component_1.TagHandlerBase));
33431 exports.CreateHandlerBase = CreateHandlerBase;
33432 exports.default = CreateHandlerBase;
33434 },{"../../../Component":290,"rxjs/Subject":34}],368:[function(require,module,exports){
33436 var __extends = (this && this.__extends) || (function () {
33437 var extendStatics = Object.setPrototypeOf ||
33438 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33439 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33440 return function (d, b) {
33441 extendStatics(d, b);
33442 function __() { this.constructor = d; }
33443 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33446 Object.defineProperty(exports, "__esModule", { value: true });
33447 var Component_1 = require("../../../Component");
33448 var CreatePointHandler = /** @class */ (function (_super) {
33449 __extends(CreatePointHandler, _super);
33450 function CreatePointHandler() {
33451 return _super !== null && _super.apply(this, arguments) || this;
33453 CreatePointHandler.prototype._enableCreate = function () {
33454 this._container.mouseService.deferPixels(this._name, 4);
33455 this._geometryCreatedSubscription = this._mouseEventToBasic$(this._container.mouseService.proximateClick$)
33456 .filter(this._validateBasic)
33457 .map(function (basic) {
33458 return new Component_1.PointGeometry(basic);
33460 .subscribe(this._geometryCreated$);
33462 CreatePointHandler.prototype._disableCreate = function () {
33463 this._container.mouseService.undeferPixels(this._name);
33464 this._geometryCreatedSubscription.unsubscribe();
33466 CreatePointHandler.prototype._getNameExtension = function () {
33467 return "create-point";
33469 return CreatePointHandler;
33470 }(Component_1.CreateHandlerBase));
33471 exports.CreatePointHandler = CreatePointHandler;
33472 exports.default = CreatePointHandler;
33474 },{"../../../Component":290}],369:[function(require,module,exports){
33476 var __extends = (this && this.__extends) || (function () {
33477 var extendStatics = Object.setPrototypeOf ||
33478 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33479 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33480 return function (d, b) {
33481 extendStatics(d, b);
33482 function __() { this.constructor = d; }
33483 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33486 Object.defineProperty(exports, "__esModule", { value: true });
33487 var Component_1 = require("../../../Component");
33488 var CreatePolygonHandler = /** @class */ (function (_super) {
33489 __extends(CreatePolygonHandler, _super);
33490 function CreatePolygonHandler() {
33491 return _super !== null && _super.apply(this, arguments) || this;
33493 CreatePolygonHandler.prototype._addPoint = function (tag, basicPoint) {
33494 tag.addPoint(basicPoint);
33496 Object.defineProperty(CreatePolygonHandler.prototype, "_create$", {
33498 return this._tagCreator.createPolygon$;
33503 CreatePolygonHandler.prototype._getNameExtension = function () {
33504 return "create-polygon";
33506 CreatePolygonHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
33507 tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basicPoint, transform);
33509 return CreatePolygonHandler;
33510 }(Component_1.CreateVertexHandler));
33511 exports.CreatePolygonHandler = CreatePolygonHandler;
33512 exports.default = CreatePolygonHandler;
33514 },{"../../../Component":290}],370:[function(require,module,exports){
33516 var __extends = (this && this.__extends) || (function () {
33517 var extendStatics = Object.setPrototypeOf ||
33518 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33519 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33520 return function (d, b) {
33521 extendStatics(d, b);
33522 function __() { this.constructor = d; }
33523 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33526 Object.defineProperty(exports, "__esModule", { value: true });
33527 var Observable_1 = require("rxjs/Observable");
33528 var Component_1 = require("../../../Component");
33529 var CreateRectDragHandler = /** @class */ (function (_super) {
33530 __extends(CreateRectDragHandler, _super);
33531 function CreateRectDragHandler() {
33532 return _super !== null && _super.apply(this, arguments) || this;
33534 CreateRectDragHandler.prototype._enableCreate = function () {
33536 this._container.mouseService.claimMouse(this._name, 2);
33537 this._deleteSubscription = this._navigator.stateService.currentTransform$
33538 .map(function (transform) { return null; })
33540 .subscribe(this._tagCreator.delete$);
33541 this._createSubscription = this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDragStart$))
33542 .filter(this._validateBasic)
33543 .subscribe(this._tagCreator.createRect$);
33544 this._initializeAnchorIndexingSubscription = this._tagCreator.tag$
33545 .filter(function (tag) {
33548 .subscribe(function (tag) {
33549 tag.geometry.initializeAnchorIndexing();
33551 var basicMouse$ = Observable_1.Observable
33552 .merge(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseMove$), this._container.mouseService.filtered$(this._name, this._container.mouseService.domMouseMove$))
33553 .combineLatest(this._container.renderService.renderCamera$)
33554 .withLatestFrom(this._navigator.stateService.currentTransform$)
33555 .map(function (_a) {
33556 var _b = _a[0], event = _b[0], camera = _b[1], transform = _a[1];
33557 return _this._mouseEventToBasic(event, _this._container.element, camera, transform);
33559 this._setVertexSubscription = this._tagCreator.tag$
33560 .switchMap(function (tag) {
33562 Observable_1.Observable
33563 .combineLatest(Observable_1.Observable.of(tag), basicMouse$, _this._navigator.stateService.currentTransform$) :
33564 Observable_1.Observable.empty();
33566 .subscribe(function (_a) {
33567 var tag = _a[0], basicPoint = _a[1], transform = _a[2];
33568 tag.geometry.setOppositeVertex2d(basicPoint, transform);
33570 var basicMouseDragEnd$ = this._container.mouseService.mouseDragEnd$
33571 .withLatestFrom(this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDrag$))
33572 .filter(this._validateBasic), function (event, basicPoint) {
33576 this._addPointSubscription = this._tagCreator.tag$
33577 .switchMap(function (tag) {
33579 Observable_1.Observable
33580 .combineLatest(Observable_1.Observable.of(tag), basicMouseDragEnd$) :
33581 Observable_1.Observable.empty();
33583 .subscribe(function (_a) {
33584 var tag = _a[0], basicPoint = _a[1];
33585 var rectGeometry = tag.geometry;
33586 if (!rectGeometry.validate(basicPoint)) {
33587 basicPoint = rectGeometry.getNonAdjustedVertex2d(3);
33589 tag.addPoint(basicPoint);
33591 this._geometryCreatedSubscription = this._tagCreator.tag$
33592 .switchMap(function (tag) {
33595 .map(function (t) {
33598 Observable_1.Observable.empty();
33600 .subscribe(this._geometryCreated$);
33602 CreateRectDragHandler.prototype._disableCreate = function () {
33603 this._container.mouseService.unclaimMouse(this._name);
33604 this._tagCreator.delete$.next(null);
33605 this._addPointSubscription.unsubscribe();
33606 this._createSubscription.unsubscribe();
33607 this._deleteSubscription.unsubscribe();
33608 this._geometryCreatedSubscription.unsubscribe();
33609 this._initializeAnchorIndexingSubscription.unsubscribe();
33610 this._setVertexSubscription.unsubscribe();
33612 CreateRectDragHandler.prototype._getNameExtension = function () {
33613 return "create-rect-drag";
33615 return CreateRectDragHandler;
33616 }(Component_1.CreateHandlerBase));
33617 exports.CreateRectDragHandler = CreateRectDragHandler;
33618 exports.default = CreateRectDragHandler;
33620 },{"../../../Component":290,"rxjs/Observable":29}],371:[function(require,module,exports){
33622 var __extends = (this && this.__extends) || (function () {
33623 var extendStatics = Object.setPrototypeOf ||
33624 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33625 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33626 return function (d, b) {
33627 extendStatics(d, b);
33628 function __() { this.constructor = d; }
33629 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33632 Object.defineProperty(exports, "__esModule", { value: true });
33633 var Component_1 = require("../../../Component");
33634 var CreateRectHandler = /** @class */ (function (_super) {
33635 __extends(CreateRectHandler, _super);
33636 function CreateRectHandler() {
33637 return _super !== null && _super.apply(this, arguments) || this;
33639 Object.defineProperty(CreateRectHandler.prototype, "_create$", {
33641 return this._tagCreator.createRect$;
33646 CreateRectHandler.prototype._addPoint = function (tag, basicPoint) {
33647 var rectGeometry = tag.geometry;
33648 if (!rectGeometry.validate(basicPoint)) {
33649 basicPoint = rectGeometry.getNonAdjustedVertex2d(3);
33651 tag.addPoint(basicPoint);
33653 CreateRectHandler.prototype._enable = function () {
33654 _super.prototype._enable.call(this);
33655 this._initializeAnchorIndexingSubscription = this._tagCreator.tag$
33656 .filter(function (tag) {
33659 .subscribe(function (tag) {
33660 tag.geometry.initializeAnchorIndexing();
33663 CreateRectHandler.prototype._disable = function () {
33664 _super.prototype._disable.call(this);
33665 this._initializeAnchorIndexingSubscription.unsubscribe();
33667 CreateRectHandler.prototype._getNameExtension = function () {
33668 return "create-rect";
33670 CreateRectHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
33671 tag.geometry.setOppositeVertex2d(basicPoint, transform);
33673 return CreateRectHandler;
33674 }(Component_1.CreateVertexHandler));
33675 exports.CreateRectHandler = CreateRectHandler;
33676 exports.default = CreateRectHandler;
33678 },{"../../../Component":290}],372:[function(require,module,exports){
33680 var __extends = (this && this.__extends) || (function () {
33681 var extendStatics = Object.setPrototypeOf ||
33682 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33683 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33684 return function (d, b) {
33685 extendStatics(d, b);
33686 function __() { this.constructor = d; }
33687 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33690 Object.defineProperty(exports, "__esModule", { value: true });
33691 var Observable_1 = require("rxjs/Observable");
33692 var Component_1 = require("../../../Component");
33693 var CreateVertexHandler = /** @class */ (function (_super) {
33694 __extends(CreateVertexHandler, _super);
33695 function CreateVertexHandler() {
33696 return _super !== null && _super.apply(this, arguments) || this;
33698 CreateVertexHandler.prototype._enableCreate = function () {
33700 this._container.mouseService.deferPixels(this._name, 4);
33701 var transformChanged$ = this._navigator.stateService.currentTransform$
33702 .map(function (transform) { })
33705 this._deleteSubscription = transformChanged$
33707 .subscribe(this._tagCreator.delete$);
33708 var basicClick$ = this._mouseEventToBasic$(this._container.mouseService.proximateClick$).share();
33709 this._createSubscription = transformChanged$
33710 .switchMap(function () {
33712 .filter(_this._validateBasic)
33715 .subscribe(this._create$);
33716 this._setVertexSubscription = this._tagCreator.tag$
33717 .switchMap(function (tag) {
33719 Observable_1.Observable
33720 .combineLatest(Observable_1.Observable.of(tag), Observable_1.Observable
33721 .merge(_this._container.mouseService.mouseMove$, _this._container.mouseService.domMouseMove$), _this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$) :
33722 Observable_1.Observable.empty();
33724 .subscribe(function (_a) {
33725 var tag = _a[0], event = _a[1], camera = _a[2], transform = _a[3];
33726 var basicPoint = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
33727 _this._setVertex2d(tag, basicPoint, transform);
33729 this._addPointSubscription = this._tagCreator.tag$
33730 .switchMap(function (tag) {
33732 Observable_1.Observable
33733 .combineLatest(Observable_1.Observable.of(tag), basicClick$) :
33734 Observable_1.Observable.empty();
33736 .subscribe(function (_a) {
33737 var tag = _a[0], basicPoint = _a[1];
33738 _this._addPoint(tag, basicPoint);
33740 this._geometryCreateSubscription = this._tagCreator.tag$
33741 .switchMap(function (tag) {
33744 .map(function (t) {
33747 Observable_1.Observable.empty();
33749 .subscribe(this._geometryCreated$);
33751 CreateVertexHandler.prototype._disableCreate = function () {
33752 this._container.mouseService.undeferPixels(this._name);
33753 this._tagCreator.delete$.next(null);
33754 this._addPointSubscription.unsubscribe();
33755 this._createSubscription.unsubscribe();
33756 this._deleteSubscription.unsubscribe();
33757 this._geometryCreateSubscription.unsubscribe();
33758 this._setVertexSubscription.unsubscribe();
33760 return CreateVertexHandler;
33761 }(Component_1.CreateHandlerBase));
33762 exports.CreateVertexHandler = CreateVertexHandler;
33763 exports.default = CreateVertexHandler;
33765 },{"../../../Component":290,"rxjs/Observable":29}],373:[function(require,module,exports){
33767 var __extends = (this && this.__extends) || (function () {
33768 var extendStatics = Object.setPrototypeOf ||
33769 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33770 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33771 return function (d, b) {
33772 extendStatics(d, b);
33773 function __() { this.constructor = d; }
33774 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33777 Object.defineProperty(exports, "__esModule", { value: true });
33778 var Observable_1 = require("rxjs/Observable");
33779 var Component_1 = require("../../../Component");
33780 var EditVertexHandler = /** @class */ (function (_super) {
33781 __extends(EditVertexHandler, _super);
33782 function EditVertexHandler(component, container, navigator, viewportCoords, tagSet) {
33783 var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
33784 _this._tagSet = tagSet;
33787 EditVertexHandler.prototype._enable = function () {
33789 var interaction$ = this._tagSet.changed$
33790 .map(function (tagSet) {
33791 return tagSet.getAll();
33793 .switchMap(function (tags) {
33794 return Observable_1.Observable
33796 .mergeMap(function (tag) {
33797 return tag.interact$;
33800 .switchMap(function (interaction) {
33801 return Observable_1.Observable
33803 .concat(_this._container.mouseService.documentMouseUp$
33805 return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null };
33810 var mouseMove$ = Observable_1.Observable
33811 .merge(this._container.mouseService.mouseMove$, this._container.mouseService.domMouseMove$)
33813 this._claimMouseSubscription = interaction$
33814 .switchMap(function (interaction) {
33815 return !!interaction.tag ? _this._container.mouseService.domMouseDragStart$ : Observable_1.Observable.empty();
33817 .subscribe(function () {
33818 _this._container.mouseService.claimMouse(_this._name, 3);
33820 this._cursorSubscription = interaction$
33821 .map(function (interaction) {
33822 return interaction.cursor;
33824 .distinctUntilChanged()
33825 .subscribe(function (cursor) {
33826 var interactionCursors = ["crosshair", "move", "nesw-resize", "nwse-resize"];
33827 for (var _i = 0, interactionCursors_1 = interactionCursors; _i < interactionCursors_1.length; _i++) {
33828 var interactionCursor = interactionCursors_1[_i];
33829 _this._container.element.classList.remove("component-tag-edit-" + interactionCursor);
33832 _this._container.element.classList.add("component-tag-edit-" + cursor);
33835 this._unclaimMouseSubscription = this._container.mouseService
33836 .filtered$(this._name, this._container.mouseService.domMouseDragEnd$)
33837 .subscribe(function (e) {
33838 _this._container.mouseService.unclaimMouse(_this._name);
33840 this._preventDefaultSubscription = interaction$
33841 .switchMap(function (interaction) {
33842 return !!interaction.tag ?
33843 _this._container.mouseService.documentMouseMove$ :
33844 Observable_1.Observable.empty();
33846 .subscribe(function (event) {
33847 event.preventDefault(); // prevent selection of content outside the viewer
33849 this._updateGeometrySubscription = interaction$
33850 .withLatestFrom(mouseMove$)
33851 .switchMap(function (_a) {
33852 var interaction = _a[0], mouseMove = _a[1];
33853 if (interaction.operation === Component_1.TagOperation.None || !interaction.tag) {
33854 return Observable_1.Observable.empty();
33856 var mouseDrag$ = Observable_1.Observable
33858 .concat(_this._container.mouseService
33859 .filtered$(_this._name, _this._container.mouseService.domMouseDrag$)
33860 .filter(function (event) {
33861 return _this._viewportCoords.insideElement(event, _this._container.element);
33863 return Observable_1.Observable
33864 .combineLatest(mouseDrag$, _this._container.renderService.renderCamera$)
33865 .withLatestFrom(Observable_1.Observable.of(interaction), _this._navigator.stateService.currentTransform$, function (_a, i, transform) {
33866 var event = _a[0], render = _a[1];
33867 return [event, render, i, transform];
33870 .subscribe(function (_a) {
33871 var mouseEvent = _a[0], renderCamera = _a[1], interaction = _a[2], transform = _a[3];
33872 var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, interaction.offsetX, interaction.offsetY);
33873 var geometry = interaction.tag.geometry;
33874 if (interaction.operation === Component_1.TagOperation.Centroid) {
33875 geometry.setCentroid2d(basic, transform);
33877 else if (interaction.operation === Component_1.TagOperation.Vertex) {
33878 geometry.setVertex2d(interaction.vertexIndex, basic, transform);
33882 EditVertexHandler.prototype._disable = function () {
33883 this._claimMouseSubscription.unsubscribe();
33884 this._cursorSubscription.unsubscribe();
33885 this._preventDefaultSubscription.unsubscribe();
33886 this._unclaimMouseSubscription.unsubscribe();
33887 this._updateGeometrySubscription.unsubscribe();
33889 EditVertexHandler.prototype._getNameExtension = function () {
33890 return "edit-vertex";
33892 return EditVertexHandler;
33893 }(Component_1.TagHandlerBase));
33894 exports.EditVertexHandler = EditVertexHandler;
33895 exports.default = EditVertexHandler;
33897 },{"../../../Component":290,"rxjs/Observable":29}],374:[function(require,module,exports){
33899 /// <reference path="../../../../typings/index.d.ts" />
33900 var __extends = (this && this.__extends) || (function () {
33901 var extendStatics = Object.setPrototypeOf ||
33902 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33903 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33904 return function (d, b) {
33905 extendStatics(d, b);
33906 function __() { this.constructor = d; }
33907 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33910 Object.defineProperty(exports, "__esModule", { value: true });
33911 var Component_1 = require("../../../Component");
33912 var TagHandlerBase = /** @class */ (function (_super) {
33913 __extends(TagHandlerBase, _super);
33914 function TagHandlerBase(component, container, navigator, viewportCoords) {
33915 var _this = _super.call(this, component, container, navigator) || this;
33916 _this._name = _this._component.name + "-" + _this._getNameExtension();
33917 _this._viewportCoords = viewportCoords;
33920 TagHandlerBase.prototype._getConfiguration = function (enable) {
33923 TagHandlerBase.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) {
33924 offsetX = offsetX != null ? offsetX : 0;
33925 offsetY = offsetY != null ? offsetY : 0;
33926 var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
33927 var basic = this._viewportCoords.canvasToBasic(canvasX - offsetX, canvasY - offsetY, element, transform, camera.perspective);
33930 return TagHandlerBase;
33931 }(Component_1.HandlerBase));
33932 exports.TagHandlerBase = TagHandlerBase;
33933 exports.default = TagHandlerBase;
33935 },{"../../../Component":290}],375:[function(require,module,exports){
33937 /// <reference path="../../../../typings/index.d.ts" />
33938 Object.defineProperty(exports, "__esModule", { value: true });
33939 var THREE = require("three");
33940 var vd = require("virtual-dom");
33941 var Subject_1 = require("rxjs/Subject");
33942 var Component_1 = require("../../../Component");
33943 var Geo_1 = require("../../../Geo");
33944 var OutlineCreateTag = /** @class */ (function () {
33945 function OutlineCreateTag(geometry, options, transform, viewportCoords) {
33947 this._geometry = geometry;
33948 this._options = { color: options.color == null ? 0xFFFFFF : options.color };
33949 this._transform = transform;
33950 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
33951 this._outline = this._createOutine();
33952 this._glObjects = [this._outline];
33953 this._aborted$ = new Subject_1.Subject();
33954 this._created$ = new Subject_1.Subject();
33955 this._glObjectsChanged$ = new Subject_1.Subject();
33956 this._geometryChangedSubscription = this._geometry.changed$
33957 .subscribe(function (vertexGeometry) {
33958 _this._disposeOutline();
33959 _this._outline = _this._createOutine();
33960 _this._glObjects = [_this._outline];
33961 _this._glObjectsChanged$.next(_this);
33964 Object.defineProperty(OutlineCreateTag.prototype, "geometry", {
33966 return this._geometry;
33971 Object.defineProperty(OutlineCreateTag.prototype, "glObjects", {
33973 return this._glObjects;
33978 Object.defineProperty(OutlineCreateTag.prototype, "aborted$", {
33980 return this._aborted$;
33985 Object.defineProperty(OutlineCreateTag.prototype, "created$", {
33987 return this._created$;
33992 Object.defineProperty(OutlineCreateTag.prototype, "glObjectsChanged$", {
33994 return this._glObjectsChanged$;
33999 Object.defineProperty(OutlineCreateTag.prototype, "geometryChanged$", {
34002 return this._geometry.changed$
34003 .map(function (geometry) {
34010 OutlineCreateTag.prototype.dispose = function () {
34011 this._disposeOutline();
34012 this._geometryChangedSubscription.unsubscribe();
34014 OutlineCreateTag.prototype.getDOMObjects = function (camera, size) {
34018 offsetHeight: size.height, offsetWidth: size.width,
34020 var abort = function (e) {
34021 e.stopPropagation();
34022 _this._aborted$.next(_this);
34024 if (this._geometry instanceof Component_1.RectGeometry) {
34025 var anchorIndex = this._geometry.anchorIndex;
34026 var vertexIndex = anchorIndex === undefined ? 1 : anchorIndex;
34027 var _a = this._geometry.getVertex2d(vertexIndex), basicX = _a[0], basicY = _a[1];
34028 var canvasPoint = this._viewportCoords.basicToCanvasSafe(basicX, basicY, container, this._transform, camera);
34029 if (canvasPoint != null) {
34030 var background = this._colorToBackground(this._options.color);
34031 var transform = this._canvasToTransform(canvasPoint);
34032 var pointProperties = {
34033 style: { background: background, transform: transform },
34035 var completerProperties = {
34037 style: { transform: transform },
34039 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
34040 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
34043 else if (this._geometry instanceof Component_1.PolygonGeometry) {
34044 var polygonGeometry_1 = this._geometry;
34045 var _b = polygonGeometry_1.getVertex2d(0), firstVertexBasicX = _b[0], firstVertexBasicY = _b[1];
34046 var firstVertexCanvas = this._viewportCoords.basicToCanvasSafe(firstVertexBasicX, firstVertexBasicY, container, this._transform, camera);
34047 if (firstVertexCanvas != null) {
34048 var firstOnclick = polygonGeometry_1.polygon.length > 4 ?
34050 e.stopPropagation();
34051 polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 2);
34052 _this._created$.next(_this);
34055 var transform = this._canvasToTransform(firstVertexCanvas);
34056 var completerProperties = {
34057 onclick: firstOnclick,
34058 style: { transform: transform },
34060 var firstClass = polygonGeometry_1.polygon.length > 4 ?
34063 vNodes.push(vd.h("div." + firstClass, completerProperties, []));
34065 if (polygonGeometry_1.polygon.length > 3) {
34066 var _c = polygonGeometry_1.getVertex2d(polygonGeometry_1.polygon.length - 3), lastVertexBasicX = _c[0], lastVertexBasicY = _c[1];
34067 var lastVertexCanvas = this._viewportCoords.basicToCanvasSafe(lastVertexBasicX, lastVertexBasicY, container, this._transform, camera);
34068 if (lastVertexCanvas != null) {
34069 var remove = function (e) {
34070 e.stopPropagation();
34071 polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3);
34073 var transform = this._canvasToTransform(lastVertexCanvas);
34074 var completerProperties = {
34076 style: { transform: transform },
34078 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
34081 var verticesBasic = polygonGeometry_1.polygon.slice();
34082 verticesBasic.splice(-2, 2);
34083 for (var _i = 0, verticesBasic_1 = verticesBasic; _i < verticesBasic_1.length; _i++) {
34084 var vertexBasic = verticesBasic_1[_i];
34085 var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasic[0], vertexBasic[1], container, this._transform, camera);
34086 if (vertexCanvas != null) {
34087 var background = this._colorToBackground(this._options.color);
34088 var transform = this._canvasToTransform(vertexCanvas);
34089 var pointProperties = {
34091 background: background,
34092 transform: transform,
34095 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
34101 OutlineCreateTag.prototype.addPoint = function (point) {
34102 if (this._geometry instanceof Component_1.RectGeometry) {
34103 var rectGeometry = this._geometry;
34104 if (!rectGeometry.validate(point)) {
34107 this._created$.next(this);
34109 else if (this._geometry instanceof Component_1.PolygonGeometry) {
34110 var polygonGeometry = this._geometry;
34111 polygonGeometry.addVertex2d(point);
34114 OutlineCreateTag.prototype._canvasToTransform = function (canvas) {
34115 var canvasX = Math.round(canvas[0]);
34116 var canvasY = Math.round(canvas[1]);
34117 var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
34120 OutlineCreateTag.prototype._colorToBackground = function (color) {
34121 return "#" + ("000000" + color.toString(16)).substr(-6);
34123 OutlineCreateTag.prototype._createOutine = function () {
34124 var polygon3d = this._geometry.getPoints3d(this._transform);
34125 var positions = this._getLinePositions(polygon3d);
34126 var geometry = new THREE.BufferGeometry();
34127 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
34128 var material = new THREE.LineBasicMaterial({
34129 color: this._options.color,
34132 return new THREE.Line(geometry, material);
34134 OutlineCreateTag.prototype._disposeOutline = function () {
34135 if (this._outline == null) {
34138 var line = this._outline;
34139 line.geometry.dispose();
34140 line.material.dispose();
34141 this._outline = null;
34142 this._glObjects = [];
34144 OutlineCreateTag.prototype._getLinePositions = function (polygon3d) {
34145 var length = polygon3d.length;
34146 var positions = new Float32Array(length * 3);
34147 for (var i = 0; i < length; ++i) {
34149 var position = polygon3d[i];
34150 positions[index] = position[0];
34151 positions[index + 1] = position[1];
34152 positions[index + 2] = position[2];
34156 return OutlineCreateTag;
34158 exports.OutlineCreateTag = OutlineCreateTag;
34159 exports.default = OutlineCreateTag;
34161 },{"../../../Component":290,"../../../Geo":293,"rxjs/Subject":34,"three":240,"virtual-dom":246}],376:[function(require,module,exports){
34163 /// <reference path="../../../../typings/index.d.ts" />
34164 var __extends = (this && this.__extends) || (function () {
34165 var extendStatics = Object.setPrototypeOf ||
34166 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34167 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34168 return function (d, b) {
34169 extendStatics(d, b);
34170 function __() { this.constructor = d; }
34171 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34174 Object.defineProperty(exports, "__esModule", { value: true });
34175 var THREE = require("three");
34176 var vd = require("virtual-dom");
34177 var Component_1 = require("../../../Component");
34179 * @class OutlineRenderTag
34180 * @classdesc Tag visualizing the properties of an OutlineTag.
34182 var OutlineRenderTag = /** @class */ (function (_super) {
34183 __extends(OutlineRenderTag, _super);
34184 function OutlineRenderTag(tag, transform) {
34185 var _this = _super.call(this, tag, transform) || this;
34186 _this._fill = !transform.gpano ?
34187 _this._createFill() :
34189 _this._holes = _this._tag.lineWidth >= 1 ?
34190 _this._createHoles() :
34192 _this._outline = _this._tag.lineWidth >= 1 ?
34193 _this._createOutline() :
34195 _this._geometryChangedSubscription = _this._tag.geometry.changed$
34196 .subscribe(function (geometry) {
34197 if (_this._fill != null) {
34198 _this._updateFillGeometry();
34200 if (_this._holes.length > 0) {
34201 _this._updateHoleGeometries();
34203 if (_this._outline != null) {
34204 _this._updateOulineGeometry();
34207 _this._changedSubscription = _this._tag.changed$
34208 .subscribe(function (changedTag) {
34209 var glObjectsChanged = false;
34210 if (_this._fill != null) {
34211 _this._updateFillMaterial(_this._fill.material);
34213 if (_this._outline == null) {
34214 if (_this._tag.lineWidth >= 1) {
34215 _this._holes = _this._createHoles();
34216 _this._outline = _this._createOutline();
34217 glObjectsChanged = true;
34221 _this._updateHoleMaterials();
34222 _this._updateOutlineMaterial();
34224 if (glObjectsChanged) {
34225 _this._glObjectsChanged$.next(_this);
34230 OutlineRenderTag.prototype.dispose = function () {
34231 this._disposeFill();
34232 this._disposeHoles();
34233 this._disposeOutline();
34234 this._changedSubscription.unsubscribe();
34235 this._geometryChangedSubscription.unsubscribe();
34237 OutlineRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
34240 var isRect = this._tag.geometry instanceof Component_1.RectGeometry;
34241 var isPerspective = !this._transform.gpano;
34243 offsetHeight: size.height, offsetWidth: size.width,
34245 if (this._tag.icon != null && (isRect || isPerspective)) {
34246 var _a = this._tag.geometry instanceof Component_1.RectGeometry ?
34247 this._tag.geometry.getVertex2d(this._tag.iconIndex) :
34248 this._tag.geometry.getPoleOfAccessibility2d(), iconBasicX = _a[0], iconBasicY = _a[1];
34249 var iconCanvas = this._viewportCoords.basicToCanvasSafe(iconBasicX, iconBasicY, container, this._transform, camera);
34250 if (iconCanvas != null) {
34251 var interact = function (e) {
34252 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
34254 if (atlas.loaded) {
34255 var sprite = atlas.getDOMSprite(this._tag.icon, this._tag.iconFloat);
34256 var iconCanvasX = Math.round(iconCanvas[0]);
34257 var iconCanvasY = Math.round(iconCanvas[1]);
34258 var transform = "translate(" + iconCanvasX + "px," + iconCanvasY + "px)";
34259 var click = function (e) {
34260 e.stopPropagation();
34261 _this._tag.click$.next(_this._tag);
34265 onmousedown: interact,
34266 style: { transform: transform },
34268 vNodes.push(vd.h("div.TagSymbol", properties, [sprite]));
34272 else if (this._tag.text != null && (isRect || isPerspective)) {
34273 var _b = this._tag.geometry instanceof Component_1.RectGeometry ?
34274 this._tag.geometry.getVertex2d(3) :
34275 this._tag.geometry.getPoleOfAccessibility2d(), textBasicX = _b[0], textBasicY = _b[1];
34276 var textCanvas = this._viewportCoords.basicToCanvasSafe(textBasicX, textBasicY, container, this._transform, camera);
34277 if (textCanvas != null) {
34278 var textCanvasX = Math.round(textCanvas[0]);
34279 var textCanvasY = Math.round(textCanvas[1]);
34280 var transform = this._tag.geometry instanceof Component_1.RectGeometry ?
34281 "translate(" + textCanvasX + "px," + textCanvasY + "px)" :
34282 "translate(-50%, -50%) translate(" + textCanvasX + "px," + textCanvasY + "px)";
34283 var interact = function (e) {
34284 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
34287 onmousedown: interact,
34289 color: this._colorToCss(this._tag.textColor),
34290 transform: transform,
34292 textContent: this._tag.text,
34294 vNodes.push(vd.h("span.TagSymbol", properties, []));
34297 if (!this._tag.editable) {
34300 var lineColor = this._colorToCss(this._tag.lineColor);
34301 if (this._tag.geometry instanceof Component_1.RectGeometry) {
34302 var _c = this._tag.geometry.getCentroid2d(), centroidBasicX = _c[0], centroidBasicY = _c[1];
34303 var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
34304 if (centroidCanvas != null) {
34305 var interact = this._interact(Component_1.TagOperation.Centroid, "move");
34306 var centroidCanvasX = Math.round(centroidCanvas[0]);
34307 var centroidCanvasY = Math.round(centroidCanvas[1]);
34308 var transform = "translate(-50%, -50%) translate(" + centroidCanvasX + "px," + centroidCanvasY + "px)";
34310 onmousedown: interact,
34311 style: { background: lineColor, transform: transform },
34313 vNodes.push(vd.h("div.TagMover", properties, []));
34316 var vertices2d = this._tag.geometry.getVertices2d();
34317 for (var i = 0; i < vertices2d.length - 1; i++) {
34319 ((this._tag.icon != null && i === this._tag.iconIndex) ||
34320 (this._tag.icon == null && this._tag.text != null && i === 3))) {
34323 var _d = vertices2d[i], vertexBasicX = _d[0], vertexBasicY = _d[1];
34324 var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasicX, vertexBasicY, container, this._transform, camera);
34325 if (vertexCanvas == null) {
34328 var cursor = isRect ?
34329 i % 2 === 0 ? "nesw-resize" : "nwse-resize" :
34331 var interact = this._interact(Component_1.TagOperation.Vertex, cursor, i);
34332 var vertexCanvasX = Math.round(vertexCanvas[0]);
34333 var vertexCanvasY = Math.round(vertexCanvas[1]);
34334 var transform = "translate(-50%, -50%) translate(" + vertexCanvasX + "px," + vertexCanvasY + "px)";
34336 onmousedown: interact,
34337 style: { background: lineColor, transform: transform, cursor: cursor },
34339 vNodes.push(vd.h("div.TagResizer", properties, []));
34340 if (!this._tag.indicateVertices) {
34343 var pointProperties = {
34344 style: { background: lineColor, transform: transform },
34346 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
34350 OutlineRenderTag.prototype.getGLObjects = function () {
34351 var glObjects = [];
34352 if (this._fill != null) {
34353 glObjects.push(this._fill);
34355 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
34357 glObjects.push(hole);
34359 if (this._outline != null) {
34360 glObjects.push(this._outline);
34364 OutlineRenderTag.prototype.getRetrievableObjects = function () {
34365 return this._fill != null ? [this._fill] : [];
34367 OutlineRenderTag.prototype._colorToCss = function (color) {
34368 return "#" + ("000000" + color.toString(16)).substr(-6);
34370 OutlineRenderTag.prototype._createFill = function () {
34371 var triangles = this._tag.geometry.getTriangles3d(this._transform);
34372 var positions = new Float32Array(triangles);
34373 var geometry = new THREE.BufferGeometry();
34374 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
34375 geometry.computeBoundingSphere();
34376 var material = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, transparent: true });
34377 this._updateFillMaterial(material);
34378 return new THREE.Mesh(geometry, material);
34380 OutlineRenderTag.prototype._createHoles = function () {
34382 if (this._tag.geometry instanceof Component_1.PolygonGeometry) {
34383 var polygonGeometry = this._tag.geometry;
34384 var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
34385 for (var _i = 0, holes3d_1 = holes3d; _i < holes3d_1.length; _i++) {
34386 var holePoints3d = holes3d_1[_i];
34387 var hole = this._createLine(holePoints3d);
34393 OutlineRenderTag.prototype._createLine = function (points3d) {
34394 var positions = this._getLinePositions(points3d);
34395 var geometry = new THREE.BufferGeometry();
34396 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
34397 geometry.computeBoundingSphere();
34398 var material = new THREE.LineBasicMaterial();
34399 this._updateLineBasicMaterial(material);
34400 var line = new THREE.Line(geometry, material);
34401 line.renderOrder = 1;
34404 OutlineRenderTag.prototype._createOutline = function () {
34405 var points3d = this._tag.geometry.getPoints3d(this._transform);
34406 return this._createLine(points3d);
34408 OutlineRenderTag.prototype._disposeFill = function () {
34409 if (this._fill == null) {
34412 this._fill.geometry.dispose();
34413 this._fill.material.dispose();
34416 OutlineRenderTag.prototype._disposeHoles = function () {
34417 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
34419 hole.geometry.dispose();
34420 hole.material.dispose();
34424 OutlineRenderTag.prototype._disposeOutline = function () {
34425 if (this._outline == null) {
34428 this._outline.geometry.dispose();
34429 this._outline.material.dispose();
34430 this._outline = null;
34432 OutlineRenderTag.prototype._getLinePositions = function (points3d) {
34433 var length = points3d.length;
34434 var positions = new Float32Array(length * 3);
34435 for (var i = 0; i < length; ++i) {
34437 var position = points3d[i];
34438 positions[index + 0] = position[0];
34439 positions[index + 1] = position[1];
34440 positions[index + 2] = position[2];
34444 OutlineRenderTag.prototype._interact = function (operation, cursor, vertexIndex) {
34446 return function (e) {
34447 var offsetX = e.offsetX - e.target.offsetWidth / 2;
34448 var offsetY = e.offsetY - e.target.offsetHeight / 2;
34449 _this._interact$.next({
34453 operation: operation,
34455 vertexIndex: vertexIndex,
34459 OutlineRenderTag.prototype._updateFillGeometry = function () {
34460 var triangles = this._tag.geometry.getTriangles3d(this._transform);
34461 var positions = new Float32Array(triangles);
34462 var geometry = this._fill.geometry;
34463 var attribute = geometry.getAttribute("position");
34464 if (attribute.array.length === positions.length) {
34465 attribute.set(positions);
34466 attribute.needsUpdate = true;
34469 geometry.removeAttribute("position");
34470 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
34472 geometry.computeBoundingSphere();
34474 OutlineRenderTag.prototype._updateFillMaterial = function (material) {
34475 material.color = new THREE.Color(this._tag.fillColor);
34476 material.opacity = this._tag.fillOpacity;
34477 material.needsUpdate = true;
34479 OutlineRenderTag.prototype._updateHoleGeometries = function () {
34480 var polygonGeometry = this._tag.geometry;
34481 var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
34482 if (holes3d.length !== this._holes.length) {
34483 throw new Error("Changing the number of holes is not supported.");
34485 for (var i = 0; i < this._holes.length; i++) {
34486 var holePoints3d = holes3d[i];
34487 var hole = this._holes[i];
34488 this._updateLine(hole, holePoints3d);
34491 OutlineRenderTag.prototype._updateHoleMaterials = function () {
34492 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
34494 var material = hole.material;
34495 this._updateLineBasicMaterial(material);
34498 OutlineRenderTag.prototype._updateLine = function (line, points3d) {
34499 var positions = this._getLinePositions(points3d);
34500 var geometry = line.geometry;
34501 var attribute = geometry.getAttribute("position");
34502 attribute.set(positions);
34503 attribute.needsUpdate = true;
34504 geometry.computeBoundingSphere();
34506 OutlineRenderTag.prototype._updateOulineGeometry = function () {
34507 var points3d = this._tag.geometry.getPoints3d(this._transform);
34508 this._updateLine(this._outline, points3d);
34510 OutlineRenderTag.prototype._updateOutlineMaterial = function () {
34511 var material = this._outline.material;
34512 this._updateLineBasicMaterial(material);
34514 OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) {
34515 material.color = new THREE.Color(this._tag.lineColor);
34516 material.linewidth = Math.max(this._tag.lineWidth, 1);
34517 material.visible = this._tag.lineWidth >= 1 && this._tag.lineOpacity > 0;
34518 material.opacity = this._tag.lineOpacity;
34519 material.transparent = this._tag.lineOpacity < 1;
34520 material.needsUpdate = true;
34522 return OutlineRenderTag;
34523 }(Component_1.RenderTag));
34524 exports.OutlineRenderTag = OutlineRenderTag;
34526 },{"../../../Component":290,"three":240,"virtual-dom":246}],377:[function(require,module,exports){
34528 var __extends = (this && this.__extends) || (function () {
34529 var extendStatics = Object.setPrototypeOf ||
34530 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34531 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34532 return function (d, b) {
34533 extendStatics(d, b);
34534 function __() { this.constructor = d; }
34535 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34538 Object.defineProperty(exports, "__esModule", { value: true });
34539 var Subject_1 = require("rxjs/Subject");
34540 var Component_1 = require("../../../Component");
34541 var Viewer_1 = require("../../../Viewer");
34543 * @class OutlineTag
34545 * @classdesc Tag holding properties for visualizing a geometry outline.
34549 * var geometry = new Mapillary.TagComponent.RectGeometry([0.3, 0.3, 0.5, 0.4]);
34550 * var tag = new Mapillary.TagComponent.OutlineTag(
34553 * { editable: true, lineColor: 0xff0000 });
34555 * tagComponent.add([tag]);
34558 var OutlineTag = /** @class */ (function (_super) {
34559 __extends(OutlineTag, _super);
34561 * Create an outline tag.
34565 * @param {string} id - Unique identifier of the tag.
34566 * @param {VertexGeometry} geometry - Geometry defining vertices of tag.
34567 * @param {IOutlineTagOptions} options - Options defining the visual appearance and
34568 * behavior of the outline tag.
34570 function OutlineTag(id, geometry, options) {
34571 var _this = _super.call(this, id, geometry) || this;
34572 options = !!options ? options : {};
34573 _this._editable = options.editable == null ? false : options.editable;
34574 _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
34575 _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
34576 _this._icon = options.icon === undefined ? null : options.icon;
34577 _this._iconFloat = options.iconFloat == null ? Viewer_1.Alignment.Center : options.iconFloat;
34578 _this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
34579 _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
34580 _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
34581 _this._lineOpacity = options.lineOpacity == null ? 1 : options.lineOpacity;
34582 _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
34583 _this._text = options.text === undefined ? null : options.text;
34584 _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
34585 _this._click$ = new Subject_1.Subject();
34587 .subscribe(function (t) {
34588 _this.fire(OutlineTag.click, _this);
34592 Object.defineProperty(OutlineTag.prototype, "click$", {
34594 * Click observable.
34596 * @description An observable emitting the tag when the icon of the
34597 * tag has been clicked.
34599 * @returns {Observable<Tag>}
34602 return this._click$;
34607 Object.defineProperty(OutlineTag.prototype, "editable", {
34609 * Get editable property.
34610 * @returns {boolean} Value indicating if tag is editable.
34613 return this._editable;
34616 * Set editable property.
34619 * @fires Tag#changed
34621 set: function (value) {
34622 this._editable = value;
34623 this._notifyChanged$.next(this);
34628 Object.defineProperty(OutlineTag.prototype, "fillColor", {
34630 * Get fill color property.
34631 * @returns {number}
34634 return this._fillColor;
34637 * Set fill color property.
34640 * @fires Tag#changed
34642 set: function (value) {
34643 this._fillColor = value;
34644 this._notifyChanged$.next(this);
34649 Object.defineProperty(OutlineTag.prototype, "fillOpacity", {
34651 * Get fill opacity property.
34652 * @returns {number}
34655 return this._fillOpacity;
34658 * Set fill opacity property.
34661 * @fires Tag#changed
34663 set: function (value) {
34664 this._fillOpacity = value;
34665 this._notifyChanged$.next(this);
34670 Object.defineProperty(OutlineTag.prototype, "geometry", {
34673 return this._geometry;
34678 Object.defineProperty(OutlineTag.prototype, "icon", {
34680 * Get icon property.
34681 * @returns {string}
34687 * Set icon property.
34690 * @fires Tag#changed
34692 set: function (value) {
34693 this._icon = value;
34694 this._notifyChanged$.next(this);
34699 Object.defineProperty(OutlineTag.prototype, "iconFloat", {
34701 * Get icon float property.
34702 * @returns {Alignment}
34705 return this._iconFloat;
34708 * Set icon float property.
34709 * @param {Alignment}
34711 * @fires Tag#changed
34713 set: function (value) {
34714 this._iconFloat = value;
34715 this._notifyChanged$.next(this);
34720 Object.defineProperty(OutlineTag.prototype, "iconIndex", {
34722 * Get icon index property.
34723 * @returns {number}
34726 return this._iconIndex;
34729 * Set icon index property.
34732 * @fires Tag#changed
34734 set: function (value) {
34735 this._iconIndex = value;
34736 this._notifyChanged$.next(this);
34741 Object.defineProperty(OutlineTag.prototype, "indicateVertices", {
34743 * Get indicate vertices property.
34744 * @returns {boolean} Value indicating if vertices should be indicated
34745 * when tag is editable.
34748 return this._indicateVertices;
34751 * Set indicate vertices property.
34754 * @fires Tag#changed
34756 set: function (value) {
34757 this._indicateVertices = value;
34758 this._notifyChanged$.next(this);
34763 Object.defineProperty(OutlineTag.prototype, "lineColor", {
34765 * Get line color property.
34766 * @returns {number}
34769 return this._lineColor;
34772 * Set line color property.
34775 * @fires Tag#changed
34777 set: function (value) {
34778 this._lineColor = value;
34779 this._notifyChanged$.next(this);
34784 Object.defineProperty(OutlineTag.prototype, "lineOpacity", {
34786 * Get line opacity property.
34787 * @returns {number}
34790 return this._lineOpacity;
34793 * Set line opacity property.
34796 * @fires Tag#changed
34798 set: function (value) {
34799 this._lineOpacity = value;
34800 this._notifyChanged$.next(this);
34805 Object.defineProperty(OutlineTag.prototype, "lineWidth", {
34807 * Get line width property.
34808 * @returns {number}
34811 return this._lineWidth;
34814 * Set line width property.
34817 * @fires Tag#changed
34819 set: function (value) {
34820 this._lineWidth = value;
34821 this._notifyChanged$.next(this);
34826 Object.defineProperty(OutlineTag.prototype, "text", {
34828 * Get text property.
34829 * @returns {string}
34835 * Set text property.
34838 * @fires Tag#changed
34840 set: function (value) {
34841 this._text = value;
34842 this._notifyChanged$.next(this);
34847 Object.defineProperty(OutlineTag.prototype, "textColor", {
34849 * Get text color property.
34850 * @returns {number}
34853 return this._textColor;
34856 * Set text color property.
34859 * @fires Tag#changed
34861 set: function (value) {
34862 this._textColor = value;
34863 this._notifyChanged$.next(this);
34869 * Set options for tag.
34871 * @description Sets all the option properties provided and keeps
34872 * the rest of the values as is.
34874 * @param {IOutlineTagOptions} options - Outline tag options
34876 * @fires {Tag#changed}
34878 OutlineTag.prototype.setOptions = function (options) {
34879 this._editable = options.editable == null ? this._editable : options.editable;
34880 this._icon = options.icon === undefined ? this._icon : options.icon;
34881 this._iconFloat = options.iconFloat == null ? this._iconFloat : options.iconFloat;
34882 this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
34883 this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
34884 this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
34885 this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
34886 this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
34887 this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
34888 this._text = options.text === undefined ? this._text : options.text;
34889 this._textColor = options.textColor == null ? this._textColor : options.textColor;
34890 this._notifyChanged$.next(this);
34893 * Event fired when the icon of the outline tag is clicked.
34895 * @event OutlineTag#click
34896 * @type {OutlineTag} The tag instance that was clicked.
34898 OutlineTag.click = "click";
34900 }(Component_1.Tag));
34901 exports.OutlineTag = OutlineTag;
34902 exports.default = OutlineTag;
34904 },{"../../../Component":290,"../../../Viewer":301,"rxjs/Subject":34}],378:[function(require,module,exports){
34906 /// <reference path="../../../../typings/index.d.ts" />
34907 Object.defineProperty(exports, "__esModule", { value: true });
34908 var Subject_1 = require("rxjs/Subject");
34909 var Geo_1 = require("../../../Geo");
34910 var RenderTag = /** @class */ (function () {
34911 function RenderTag(tag, transform, viewportCoords) {
34913 this._transform = transform;
34914 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
34915 this._glObjectsChanged$ = new Subject_1.Subject();
34916 this._interact$ = new Subject_1.Subject();
34918 Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", {
34920 return this._glObjectsChanged$;
34925 Object.defineProperty(RenderTag.prototype, "interact$", {
34927 return this._interact$;
34932 Object.defineProperty(RenderTag.prototype, "tag", {
34941 exports.RenderTag = RenderTag;
34942 exports.default = RenderTag;
34944 },{"../../../Geo":293,"rxjs/Subject":34}],379:[function(require,module,exports){
34946 /// <reference path="../../../../typings/index.d.ts" />
34947 var __extends = (this && this.__extends) || (function () {
34948 var extendStatics = Object.setPrototypeOf ||
34949 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34950 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34951 return function (d, b) {
34952 extendStatics(d, b);
34953 function __() { this.constructor = d; }
34954 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34957 Object.defineProperty(exports, "__esModule", { value: true });
34958 var vd = require("virtual-dom");
34959 var Component_1 = require("../../../Component");
34960 var Viewer_1 = require("../../../Viewer");
34962 * @class SpotRenderTag
34963 * @classdesc Tag visualizing the properties of a SpotTag.
34965 var SpotRenderTag = /** @class */ (function (_super) {
34966 __extends(SpotRenderTag, _super);
34967 function SpotRenderTag() {
34968 return _super !== null && _super.apply(this, arguments) || this;
34970 SpotRenderTag.prototype.dispose = function () { };
34971 SpotRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
34973 var tag = this._tag;
34975 offsetHeight: size.height, offsetWidth: size.width,
34978 var _a = tag.geometry.getCentroid2d(), centroidBasicX = _a[0], centroidBasicY = _a[1];
34979 var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
34980 if (centroidCanvas != null) {
34981 var interactNone = function (e) {
34982 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: tag });
34984 var canvasX = Math.round(centroidCanvas[0]);
34985 var canvasY = Math.round(centroidCanvas[1]);
34986 if (tag.icon != null) {
34987 if (atlas.loaded) {
34988 var sprite = atlas.getDOMSprite(tag.icon, Viewer_1.Alignment.Bottom);
34989 var iconTransform = "translate(" + canvasX + "px," + (canvasY + 8) + "px)";
34991 onmousedown: interactNone,
34993 pointerEvents: "all",
34994 transform: iconTransform,
34997 vNodes.push(vd.h("div", properties, [sprite]));
35000 else if (tag.text != null) {
35001 var textTransform = "translate(-50%,0%) translate(" + canvasX + "px," + (canvasY + 8) + "px)";
35003 onmousedown: interactNone,
35005 color: this._colorToCss(tag.textColor),
35006 transform: textTransform,
35008 textContent: tag.text,
35010 vNodes.push(vd.h("span.TagSymbol", properties, []));
35012 var interact = this._interact(Component_1.TagOperation.Centroid, tag, "move");
35013 var background = this._colorToCss(tag.color);
35014 var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
35015 if (tag.editable) {
35016 var interactorProperties = {
35017 onmousedown: interact,
35019 background: background,
35020 transform: transform,
35023 vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, []));
35025 var pointProperties = {
35027 background: background,
35028 transform: transform,
35031 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
35035 SpotRenderTag.prototype.getGLObjects = function () { return []; };
35036 SpotRenderTag.prototype.getRetrievableObjects = function () { return []; };
35037 SpotRenderTag.prototype._colorToCss = function (color) {
35038 return "#" + ("000000" + color.toString(16)).substr(-6);
35040 SpotRenderTag.prototype._interact = function (operation, tag, cursor, vertexIndex) {
35042 return function (e) {
35043 var offsetX = e.offsetX - e.target.offsetWidth / 2;
35044 var offsetY = e.offsetY - e.target.offsetHeight / 2;
35045 _this._interact$.next({
35049 operation: operation,
35051 vertexIndex: vertexIndex,
35055 return SpotRenderTag;
35056 }(Component_1.RenderTag));
35057 exports.SpotRenderTag = SpotRenderTag;
35059 },{"../../../Component":290,"../../../Viewer":301,"virtual-dom":246}],380:[function(require,module,exports){
35061 var __extends = (this && this.__extends) || (function () {
35062 var extendStatics = Object.setPrototypeOf ||
35063 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35064 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35065 return function (d, b) {
35066 extendStatics(d, b);
35067 function __() { this.constructor = d; }
35068 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35071 Object.defineProperty(exports, "__esModule", { value: true });
35072 var Component_1 = require("../../../Component");
35076 * @classdesc Tag holding properties for visualizing the centroid of a geometry.
35080 * var geometry = new Mapillary.TagComponent.PointGeometry([0.3, 0.3]);
35081 * var tag = new Mapillary.TagComponent.SpotTag(
35084 * { editable: true, color: 0xff0000 });
35086 * tagComponent.add([tag]);
35089 var SpotTag = /** @class */ (function (_super) {
35090 __extends(SpotTag, _super);
35092 * Create a spot tag.
35096 * @param {string} id
35097 * @param {Geometry} geometry
35098 * @param {IOutlineTagOptions} options - Options defining the visual appearance and
35099 * behavior of the spot tag.
35101 function SpotTag(id, geometry, options) {
35102 var _this = _super.call(this, id, geometry) || this;
35103 options = !!options ? options : {};
35104 _this._color = options.color == null ? 0xFFFFFF : options.color;
35105 _this._editable = options.editable == null ? false : options.editable;
35106 _this._icon = options.icon === undefined ? null : options.icon;
35107 _this._text = options.text === undefined ? null : options.text;
35108 _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
35111 Object.defineProperty(SpotTag.prototype, "color", {
35113 * Get color property.
35114 * @returns {number} The color of the spot as a hexagonal number;
35117 return this._color;
35120 * Set color property.
35123 * @fires Tag#changed
35125 set: function (value) {
35126 this._color = value;
35127 this._notifyChanged$.next(this);
35132 Object.defineProperty(SpotTag.prototype, "editable", {
35134 * Get editable property.
35135 * @returns {boolean} Value indicating if tag is editable.
35138 return this._editable;
35141 * Set editable property.
35144 * @fires Tag#changed
35146 set: function (value) {
35147 this._editable = value;
35148 this._notifyChanged$.next(this);
35153 Object.defineProperty(SpotTag.prototype, "icon", {
35155 * Get icon property.
35156 * @returns {string}
35162 * Set icon property.
35165 * @fires Tag#changed
35167 set: function (value) {
35168 this._icon = value;
35169 this._notifyChanged$.next(this);
35174 Object.defineProperty(SpotTag.prototype, "text", {
35176 * Get text property.
35177 * @returns {string}
35183 * Set text property.
35186 * @fires Tag#changed
35188 set: function (value) {
35189 this._text = value;
35190 this._notifyChanged$.next(this);
35195 Object.defineProperty(SpotTag.prototype, "textColor", {
35197 * Get text color property.
35198 * @returns {number}
35201 return this._textColor;
35204 * Set text color property.
35207 * @fires Tag#changed
35209 set: function (value) {
35210 this._textColor = value;
35211 this._notifyChanged$.next(this);
35217 * Set options for tag.
35219 * @description Sets all the option properties provided and keps
35220 * the rest of the values as is.
35222 * @param {ISpotTagOptions} options - Spot tag options
35224 * @fires {Tag#changed}
35226 SpotTag.prototype.setOptions = function (options) {
35227 this._color = options.color == null ? this._color : options.color;
35228 this._editable = options.editable == null ? this._editable : options.editable;
35229 this._icon = options.icon === undefined ? this._icon : options.icon;
35230 this._text = options.text === undefined ? this._text : options.text;
35231 this._textColor = options.textColor == null ? this._textColor : options.textColor;
35232 this._notifyChanged$.next(this);
35235 }(Component_1.Tag));
35236 exports.SpotTag = SpotTag;
35237 exports.default = SpotTag;
35239 },{"../../../Component":290}],381:[function(require,module,exports){
35241 var __extends = (this && this.__extends) || (function () {
35242 var extendStatics = Object.setPrototypeOf ||
35243 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35244 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35245 return function (d, b) {
35246 extendStatics(d, b);
35247 function __() { this.constructor = d; }
35248 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35251 Object.defineProperty(exports, "__esModule", { value: true });
35252 var Subject_1 = require("rxjs/Subject");
35253 var Utils_1 = require("../../../Utils");
35257 * @classdesc Abstract class representing the basic functionality of for a tag.
35259 var Tag = /** @class */ (function (_super) {
35260 __extends(Tag, _super);
35265 * @param {string} id
35266 * @param {Geometry} geometry
35268 function Tag(id, geometry) {
35269 var _this = _super.call(this) || this;
35271 _this._geometry = geometry;
35272 _this._notifyChanged$ = new Subject_1.Subject();
35273 _this._notifyChanged$
35274 .subscribe(function (t) {
35275 _this.fire(Tag.changed, _this);
35277 _this._geometry.changed$
35278 .subscribe(function (g) {
35279 _this.fire(Tag.geometrychanged, _this);
35283 Object.defineProperty(Tag.prototype, "id", {
35286 * @returns {string}
35294 Object.defineProperty(Tag.prototype, "geometry", {
35296 * Get geometry property.
35297 * @returns {Geometry} The geometry of the tag.
35300 return this._geometry;
35305 Object.defineProperty(Tag.prototype, "changed$", {
35307 * Get changed observable.
35308 * @returns {Observable<Tag>}
35312 return this._notifyChanged$;
35317 Object.defineProperty(Tag.prototype, "geometryChanged$", {
35319 * Get geometry changed observable.
35320 * @returns {Observable<Tag>}
35325 return this._geometry.changed$
35326 .map(function (geometry) {
35335 * Event fired when a property related to the visual appearance of the
35338 * @event Tag#changed
35339 * @type {Tag} The tag instance that has changed.
35341 Tag.changed = "changed";
35343 * Event fired when the geometry of the tag has changed.
35345 * @event Tag#geometrychanged
35346 * @type {Tag} The tag instance whose geometry has changed.
35348 Tag.geometrychanged = "geometrychanged";
35350 }(Utils_1.EventEmitter));
35352 exports.default = Tag;
35354 },{"../../../Utils":300,"rxjs/Subject":34}],382:[function(require,module,exports){
35356 Object.defineProperty(exports, "__esModule", { value: true });
35357 var HandlerBase = /** @class */ (function () {
35358 function HandlerBase(component, container, navigator) {
35359 this._component = component;
35360 this._container = container;
35361 this._navigator = navigator;
35362 this._enabled = false;
35364 Object.defineProperty(HandlerBase.prototype, "isEnabled", {
35366 * Returns a Boolean indicating whether the interaction is enabled.
35368 * @returns {boolean} `true` if the interaction is enabled.
35371 return this._enabled;
35377 * Enables the interaction.
35379 * @example ```<component-name>.<handler-name>.enable();```
35381 HandlerBase.prototype.enable = function () {
35382 if (this._enabled || !this._component.activated) {
35386 this._enabled = true;
35387 this._component.configure(this._getConfiguration(true));
35390 * Disables the interaction.
35392 * @example ```<component-name>.<handler-name>.disable();```
35394 HandlerBase.prototype.disable = function () {
35395 if (!this._enabled) {
35399 this._enabled = false;
35400 if (this._component.activated) {
35401 this._component.configure(this._getConfiguration(false));
35404 return HandlerBase;
35406 exports.HandlerBase = HandlerBase;
35407 exports.default = HandlerBase;
35409 },{}],383:[function(require,module,exports){
35411 /// <reference path="../../../typings/index.d.ts" />
35412 Object.defineProperty(exports, "__esModule", { value: true });
35413 var THREE = require("three");
35414 var Component_1 = require("../../Component");
35415 var MeshFactory = /** @class */ (function () {
35416 function MeshFactory(imagePlaneDepth, imageSphereRadius) {
35417 this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200;
35418 this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200;
35420 MeshFactory.prototype.createMesh = function (node, transform) {
35421 var mesh = node.pano ?
35422 this._createImageSphere(node, transform) :
35423 this._createImagePlane(node, transform);
35426 MeshFactory.prototype.createScaledFlatMesh = function (node, transform, dx, dy) {
35427 var texture = this._createTexture(node.image);
35428 var materialParameters = this._createPlaneMaterialParameters(transform, texture);
35429 var material = new THREE.ShaderMaterial(materialParameters);
35430 var geometry = this._getFlatImagePlaneGeo(transform, dx, dy);
35431 return new THREE.Mesh(geometry, material);
35433 MeshFactory.prototype.createFlatMesh = function (node, transform, basicX0, basicX1, basicY0, basicY1) {
35434 var texture = this._createTexture(node.image);
35435 var materialParameters = this._createPlaneMaterialParameters(transform, texture);
35436 var material = new THREE.ShaderMaterial(materialParameters);
35437 var geometry = this._getFlatImagePlaneGeoFromBasic(transform, basicX0, basicX1, basicY0, basicY1);
35438 return new THREE.Mesh(geometry, material);
35440 MeshFactory.prototype.createCurtainMesh = function (node, transform) {
35441 if (node.pano && !node.fullPano) {
35442 throw new Error("Cropped panoramas cannot have curtain.");
35445 this._createSphereCurtainMesh(node, transform) :
35446 this._createCurtainMesh(node, transform);
35448 MeshFactory.prototype._createCurtainMesh = function (node, transform) {
35449 var texture = this._createTexture(node.image);
35450 var materialParameters = this._createCurtainPlaneMaterialParameters(transform, texture);
35451 var material = new THREE.ShaderMaterial(materialParameters);
35452 var geometry = this._useMesh(transform, node) ?
35453 this._getImagePlaneGeo(transform, node) :
35454 this._getRegularFlatImagePlaneGeo(transform);
35455 return new THREE.Mesh(geometry, material);
35457 MeshFactory.prototype._createSphereCurtainMesh = function (node, transform) {
35458 var texture = this._createTexture(node.image);
35459 var materialParameters = this._createCurtainSphereMaterialParameters(transform, texture);
35460 var material = new THREE.ShaderMaterial(materialParameters);
35461 return this._useMesh(transform, node) ?
35462 new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
35463 new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
35465 MeshFactory.prototype._createImageSphere = function (node, transform) {
35466 var texture = this._createTexture(node.image);
35467 var materialParameters = this._createSphereMaterialParameters(transform, texture);
35468 var material = new THREE.ShaderMaterial(materialParameters);
35469 var mesh = this._useMesh(transform, node) ?
35470 new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
35471 new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
35474 MeshFactory.prototype._createImagePlane = function (node, transform) {
35475 var texture = this._createTexture(node.image);
35476 var materialParameters = this._createPlaneMaterialParameters(transform, texture);
35477 var material = new THREE.ShaderMaterial(materialParameters);
35478 var geometry = this._useMesh(transform, node) ?
35479 this._getImagePlaneGeo(transform, node) :
35480 this._getRegularFlatImagePlaneGeo(transform);
35481 return new THREE.Mesh(geometry, material);
35483 MeshFactory.prototype._createSphereMaterialParameters = function (transform, texture) {
35484 var gpano = transform.gpano;
35485 var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
35486 var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
35487 var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
35488 var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
35489 var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
35490 var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
35491 var materialParameters = {
35493 fragmentShader: Component_1.Shaders.equirectangular.fragment,
35494 side: THREE.DoubleSide,
35511 value: transform.rt,
35519 value: thetaLength,
35526 vertexShader: Component_1.Shaders.equirectangular.vertex,
35528 return materialParameters;
35530 MeshFactory.prototype._createCurtainSphereMaterialParameters = function (transform, texture) {
35531 var gpano = transform.gpano;
35532 var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
35533 var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
35534 var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
35535 var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
35536 var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
35537 var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
35538 var materialParameters = {
35540 fragmentShader: Component_1.Shaders.equirectangularCurtain.fragment,
35541 side: THREE.DoubleSide,
35562 value: transform.rt,
35570 value: thetaLength,
35577 vertexShader: Component_1.Shaders.equirectangularCurtain.vertex,
35579 return materialParameters;
35581 MeshFactory.prototype._createPlaneMaterialParameters = function (transform, texture) {
35582 var materialParameters = {
35584 fragmentShader: Component_1.Shaders.perspective.fragment,
35585 side: THREE.DoubleSide,
35594 value: transform.projectorMatrix(),
35601 vertexShader: Component_1.Shaders.perspective.vertex,
35603 return materialParameters;
35605 MeshFactory.prototype._createCurtainPlaneMaterialParameters = function (transform, texture) {
35606 var materialParameters = {
35608 fragmentShader: Component_1.Shaders.perspectiveCurtain.fragment,
35609 side: THREE.DoubleSide,
35622 value: transform.projectorMatrix(),
35629 vertexShader: Component_1.Shaders.perspective.vertex,
35631 return materialParameters;
35633 MeshFactory.prototype._createTexture = function (image) {
35634 var texture = new THREE.Texture(image);
35635 texture.minFilter = THREE.LinearFilter;
35636 texture.needsUpdate = true;
35639 MeshFactory.prototype._useMesh = function (transform, node) {
35640 return node.mesh.vertices.length && transform.hasValidScale;
35642 MeshFactory.prototype._getImageSphereGeo = function (transform, node) {
35643 var t = new THREE.Matrix4().getInverse(transform.srt);
35644 // push everything at least 5 meters in front of the camera
35645 var minZ = 5.0 * transform.scale;
35646 var maxZ = this._imageSphereRadius * transform.scale;
35647 var vertices = node.mesh.vertices;
35648 var numVertices = vertices.length / 3;
35649 var positions = new Float32Array(vertices.length);
35650 for (var i = 0; i < numVertices; ++i) {
35652 var x = vertices[index + 0];
35653 var y = vertices[index + 1];
35654 var z = vertices[index + 2];
35655 var l = Math.sqrt(x * x + y * y + z * z);
35656 var boundedL = Math.max(minZ, Math.min(l, maxZ));
35657 var factor = boundedL / l;
35658 var p = new THREE.Vector3(x * factor, y * factor, z * factor);
35660 positions[index + 0] = p.x;
35661 positions[index + 1] = p.y;
35662 positions[index + 2] = p.z;
35664 var faces = node.mesh.faces;
35665 var indices = new Uint16Array(faces.length);
35666 for (var i = 0; i < faces.length; ++i) {
35667 indices[i] = faces[i];
35669 var geometry = new THREE.BufferGeometry();
35670 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
35671 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
35674 MeshFactory.prototype._getImagePlaneGeo = function (transform, node) {
35675 var t = new THREE.Matrix4().getInverse(transform.srt);
35676 // push everything at least 5 meters in front of the camera
35677 var minZ = 5.0 * transform.scale;
35678 var maxZ = this._imagePlaneDepth * transform.scale;
35679 var vertices = node.mesh.vertices;
35680 var numVertices = vertices.length / 3;
35681 var positions = new Float32Array(vertices.length);
35682 for (var i = 0; i < numVertices; ++i) {
35684 var x = vertices[index + 0];
35685 var y = vertices[index + 1];
35686 var z = vertices[index + 2];
35687 var boundedZ = Math.max(minZ, Math.min(z, maxZ));
35688 var factor = boundedZ / z;
35689 var p = new THREE.Vector3(x * factor, y * factor, boundedZ);
35691 positions[index + 0] = p.x;
35692 positions[index + 1] = p.y;
35693 positions[index + 2] = p.z;
35695 var faces = node.mesh.faces;
35696 var indices = new Uint16Array(faces.length);
35697 for (var i = 0; i < faces.length; ++i) {
35698 indices[i] = faces[i];
35700 var geometry = new THREE.BufferGeometry();
35701 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
35702 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
35705 MeshFactory.prototype._getFlatImageSphereGeo = function (transform) {
35706 var gpano = transform.gpano;
35707 var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels;
35708 var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
35709 var thetaStart = Math.PI *
35710 (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) /
35711 gpano.FullPanoHeightPixels;
35712 var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
35713 var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength);
35714 geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt));
35717 MeshFactory.prototype._getRegularFlatImagePlaneGeo = function (transform) {
35718 var width = transform.width;
35719 var height = transform.height;
35720 var size = Math.max(width, height);
35721 var dx = width / 2.0 / size;
35722 var dy = height / 2.0 / size;
35723 return this._getFlatImagePlaneGeo(transform, dx, dy);
35725 MeshFactory.prototype._getFlatImagePlaneGeo = function (transform, dx, dy) {
35727 vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
35728 vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
35729 vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
35730 vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
35731 return this._createFlatGeometry(vertices);
35733 MeshFactory.prototype._getFlatImagePlaneGeoFromBasic = function (transform, basicX0, basicX1, basicY0, basicY1) {
35735 vertices.push(transform.unprojectBasic([basicX0, basicY0], this._imagePlaneDepth));
35736 vertices.push(transform.unprojectBasic([basicX1, basicY0], this._imagePlaneDepth));
35737 vertices.push(transform.unprojectBasic([basicX1, basicY1], this._imagePlaneDepth));
35738 vertices.push(transform.unprojectBasic([basicX0, basicY1], this._imagePlaneDepth));
35739 return this._createFlatGeometry(vertices);
35741 MeshFactory.prototype._createFlatGeometry = function (vertices) {
35742 var positions = new Float32Array(12);
35743 for (var i = 0; i < vertices.length; i++) {
35745 positions[index + 0] = vertices[i][0];
35746 positions[index + 1] = vertices[i][1];
35747 positions[index + 2] = vertices[i][2];
35749 var indices = new Uint16Array(6);
35756 var geometry = new THREE.BufferGeometry();
35757 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
35758 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
35761 return MeshFactory;
35763 exports.MeshFactory = MeshFactory;
35764 exports.default = MeshFactory;
35766 },{"../../Component":290,"three":240}],384:[function(require,module,exports){
35768 /// <reference path="../../../typings/index.d.ts" />
35769 Object.defineProperty(exports, "__esModule", { value: true });
35770 var THREE = require("three");
35771 var MeshScene = /** @class */ (function () {
35772 function MeshScene() {
35773 this.scene = new THREE.Scene();
35774 this.sceneOld = new THREE.Scene();
35775 this.imagePlanes = [];
35776 this.imagePlanesOld = [];
35778 MeshScene.prototype.updateImagePlanes = function (planes) {
35779 this._dispose(this.imagePlanesOld, this.sceneOld);
35780 for (var _i = 0, _a = this.imagePlanes; _i < _a.length; _i++) {
35781 var plane = _a[_i];
35782 this.scene.remove(plane);
35783 this.sceneOld.add(plane);
35785 for (var _b = 0, planes_1 = planes; _b < planes_1.length; _b++) {
35786 var plane = planes_1[_b];
35787 this.scene.add(plane);
35789 this.imagePlanesOld = this.imagePlanes;
35790 this.imagePlanes = planes;
35792 MeshScene.prototype.addImagePlanes = function (planes) {
35793 for (var _i = 0, planes_2 = planes; _i < planes_2.length; _i++) {
35794 var plane = planes_2[_i];
35795 this.scene.add(plane);
35796 this.imagePlanes.push(plane);
35799 MeshScene.prototype.addImagePlanesOld = function (planes) {
35800 for (var _i = 0, planes_3 = planes; _i < planes_3.length; _i++) {
35801 var plane = planes_3[_i];
35802 this.sceneOld.add(plane);
35803 this.imagePlanesOld.push(plane);
35806 MeshScene.prototype.setImagePlanes = function (planes) {
35808 this.addImagePlanes(planes);
35810 MeshScene.prototype.setImagePlanesOld = function (planes) {
35812 this.addImagePlanesOld(planes);
35814 MeshScene.prototype.clear = function () {
35818 MeshScene.prototype._clear = function () {
35819 this._dispose(this.imagePlanes, this.scene);
35820 this.imagePlanes.length = 0;
35822 MeshScene.prototype._clearOld = function () {
35823 this._dispose(this.imagePlanesOld, this.sceneOld);
35824 this.imagePlanesOld.length = 0;
35826 MeshScene.prototype._dispose = function (planes, scene) {
35827 for (var _i = 0, planes_4 = planes; _i < planes_4.length; _i++) {
35828 var plane = planes_4[_i];
35829 scene.remove(plane);
35830 plane.geometry.dispose();
35831 plane.material.dispose();
35832 var texture = plane.material.uniforms.projectorTex.value;
35833 if (texture != null) {
35840 exports.MeshScene = MeshScene;
35841 exports.default = MeshScene;
35843 },{"three":240}],385:[function(require,module,exports){
35845 /// <reference path="../../../typings/index.d.ts" />
35846 var __extends = (this && this.__extends) || (function () {
35847 var extendStatics = Object.setPrototypeOf ||
35848 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35849 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35850 return function (d, b) {
35851 extendStatics(d, b);
35852 function __() { this.constructor = d; }
35853 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35856 Object.defineProperty(exports, "__esModule", { value: true });
35857 var vd = require("virtual-dom");
35858 var Observable_1 = require("rxjs/Observable");
35859 var Subject_1 = require("rxjs/Subject");
35860 var Component_1 = require("../../Component");
35861 var Geo_1 = require("../../Geo");
35862 var State_1 = require("../../State");
35863 var ZoomComponent = /** @class */ (function (_super) {
35864 __extends(ZoomComponent, _super);
35865 function ZoomComponent(name, container, navigator) {
35866 var _this = _super.call(this, name, container, navigator) || this;
35867 _this._viewportCoords = new Geo_1.ViewportCoords();
35868 _this._zoomDelta$ = new Subject_1.Subject();
35871 ZoomComponent.prototype._activate = function () {
35873 this._renderSubscription = Observable_1.Observable
35874 .combineLatest(this._navigator.stateService.currentState$, this._navigator.stateService.state$)
35875 .map(function (_a) {
35876 var frame = _a[0], state = _a[1];
35877 return [frame.state.zoom, state];
35879 .map(function (_a) {
35880 var zoom = _a[0], state = _a[1];
35881 var zoomInIcon = vd.h("div.ZoomInIcon", []);
35882 var zoomInButton = zoom >= 3 || state === State_1.State.Waiting ?
35883 vd.h("div.ZoomInButtonDisabled", [zoomInIcon]) :
35884 vd.h("div.ZoomInButton", { onclick: function () { _this._zoomDelta$.next(1); } }, [zoomInIcon]);
35885 var zoomOutIcon = vd.h("div.ZoomOutIcon", []);
35886 var zoomOutButton = zoom <= 0 || state === State_1.State.Waiting ?
35887 vd.h("div.ZoomOutButtonDisabled", [zoomOutIcon]) :
35888 vd.h("div.ZoomOutButton", { onclick: function () { _this._zoomDelta$.next(-1); } }, [zoomOutIcon]);
35891 vnode: vd.h("div.ZoomContainer", { oncontextmenu: function (event) { event.preventDefault(); } }, [zoomInButton, zoomOutButton]),
35894 .subscribe(this._container.domRenderer.render$);
35895 this._zoomSubscription = this._zoomDelta$
35896 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
35897 .subscribe(function (_a) {
35898 var zoomDelta = _a[0], render = _a[1], transform = _a[2];
35899 var unprojected = _this._viewportCoords.unprojectFromViewport(0, 0, render.perspective);
35900 var reference = transform.projectBasic(unprojected.toArray());
35901 _this._navigator.stateService.zoomIn(zoomDelta, reference);
35904 ZoomComponent.prototype._deactivate = function () {
35905 this._renderSubscription.unsubscribe();
35906 this._zoomSubscription.unsubscribe();
35908 ZoomComponent.prototype._getDefaultConfiguration = function () {
35911 ZoomComponent.componentName = "zoom";
35912 return ZoomComponent;
35913 }(Component_1.Component));
35914 exports.ZoomComponent = ZoomComponent;
35915 Component_1.ComponentService.register(ZoomComponent);
35916 exports.default = ZoomComponent;
35918 },{"../../Component":290,"../../Geo":293,"../../State":297,"rxjs/Observable":29,"rxjs/Subject":34,"virtual-dom":246}],386:[function(require,module,exports){
35920 var __extends = (this && this.__extends) || (function () {
35921 var extendStatics = Object.setPrototypeOf ||
35922 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35923 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35924 return function (d, b) {
35925 extendStatics(d, b);
35926 function __() { this.constructor = d; }
35927 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35930 Object.defineProperty(exports, "__esModule", { value: true });
35931 var MapillaryError_1 = require("./MapillaryError");
35933 * @class AbortMapillaryError
35935 * @classdesc Error thrown when a move to request has been
35936 * aborted before completing because of a subsequent request.
35938 var AbortMapillaryError = /** @class */ (function (_super) {
35939 __extends(AbortMapillaryError, _super);
35940 function AbortMapillaryError(message) {
35941 var _this = _super.call(this, message != null ? message : "The request was aborted.") || this;
35942 Object.setPrototypeOf(_this, AbortMapillaryError.prototype);
35943 _this.name = "AbortMapillaryError";
35946 return AbortMapillaryError;
35947 }(MapillaryError_1.MapillaryError));
35948 exports.AbortMapillaryError = AbortMapillaryError;
35949 exports.default = AbortMapillaryError;
35951 },{"./MapillaryError":389}],387:[function(require,module,exports){
35953 var __extends = (this && this.__extends) || (function () {
35954 var extendStatics = Object.setPrototypeOf ||
35955 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35956 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35957 return function (d, b) {
35958 extendStatics(d, b);
35959 function __() { this.constructor = d; }
35960 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35963 Object.defineProperty(exports, "__esModule", { value: true });
35964 var MapillaryError_1 = require("./MapillaryError");
35965 var ArgumentMapillaryError = /** @class */ (function (_super) {
35966 __extends(ArgumentMapillaryError, _super);
35967 function ArgumentMapillaryError(message) {
35968 var _this = _super.call(this, message != null ? message : "The argument is not valid.") || this;
35969 Object.setPrototypeOf(_this, ArgumentMapillaryError.prototype);
35970 _this.name = "ArgumentMapillaryError";
35973 return ArgumentMapillaryError;
35974 }(MapillaryError_1.MapillaryError));
35975 exports.ArgumentMapillaryError = ArgumentMapillaryError;
35976 exports.default = ArgumentMapillaryError;
35978 },{"./MapillaryError":389}],388:[function(require,module,exports){
35980 var __extends = (this && this.__extends) || (function () {
35981 var extendStatics = Object.setPrototypeOf ||
35982 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35983 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35984 return function (d, b) {
35985 extendStatics(d, b);
35986 function __() { this.constructor = d; }
35987 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35990 Object.defineProperty(exports, "__esModule", { value: true });
35991 var MapillaryError_1 = require("./MapillaryError");
35992 var GraphMapillaryError = /** @class */ (function (_super) {
35993 __extends(GraphMapillaryError, _super);
35994 function GraphMapillaryError(message) {
35995 var _this = _super.call(this, message) || this;
35996 Object.setPrototypeOf(_this, GraphMapillaryError.prototype);
35997 _this.name = "GraphMapillaryError";
36000 return GraphMapillaryError;
36001 }(MapillaryError_1.MapillaryError));
36002 exports.GraphMapillaryError = GraphMapillaryError;
36003 exports.default = GraphMapillaryError;
36005 },{"./MapillaryError":389}],389:[function(require,module,exports){
36007 var __extends = (this && this.__extends) || (function () {
36008 var extendStatics = Object.setPrototypeOf ||
36009 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
36010 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
36011 return function (d, b) {
36012 extendStatics(d, b);
36013 function __() { this.constructor = d; }
36014 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
36017 Object.defineProperty(exports, "__esModule", { value: true });
36018 var MapillaryError = /** @class */ (function (_super) {
36019 __extends(MapillaryError, _super);
36020 function MapillaryError(message) {
36021 var _this = _super.call(this, message) || this;
36022 Object.setPrototypeOf(_this, MapillaryError.prototype);
36023 _this.name = "MapillaryError";
36026 return MapillaryError;
36028 exports.MapillaryError = MapillaryError;
36029 exports.default = MapillaryError;
36031 },{}],390:[function(require,module,exports){
36033 /// <reference path="../../typings/index.d.ts" />
36034 Object.defineProperty(exports, "__esModule", { value: true });
36035 var THREE = require("three");
36039 * @classdesc Holds information about a camera.
36041 var Camera = /** @class */ (function () {
36043 * Create a new camera instance.
36044 * @param {Transform} [transform] - Optional transform instance.
36046 function Camera(transform) {
36047 if (transform != null) {
36048 this._position = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0));
36049 this._lookat = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10));
36050 this._up = transform.upVector();
36051 this._focal = this._getFocal(transform);
36054 this._position = new THREE.Vector3(0, 0, 0);
36055 this._lookat = new THREE.Vector3(0, 0, 1);
36056 this._up = new THREE.Vector3(0, -1, 0);
36060 Object.defineProperty(Camera.prototype, "position", {
36063 * @returns {THREE.Vector3} The position vector.
36066 return this._position;
36071 Object.defineProperty(Camera.prototype, "lookat", {
36074 * @returns {THREE.Vector3} The lookat vector.
36077 return this._lookat;
36082 Object.defineProperty(Camera.prototype, "up", {
36085 * @returns {THREE.Vector3} The up vector.
36093 Object.defineProperty(Camera.prototype, "focal", {
36096 * @returns {number} The focal length.
36099 return this._focal;
36104 set: function (value) {
36105 this._focal = value;
36111 * Update this camera to the linearly interpolated value of two other cameras.
36113 * @param {Camera} a - First camera.
36114 * @param {Camera} b - Second camera.
36115 * @param {number} alpha - Interpolation value on the interval [0, 1].
36117 Camera.prototype.lerpCameras = function (a, b, alpha) {
36118 this._position.subVectors(b.position, a.position).multiplyScalar(alpha).add(a.position);
36119 this._lookat.subVectors(b.lookat, a.lookat).multiplyScalar(alpha).add(a.lookat);
36120 this._up.subVectors(b.up, a.up).multiplyScalar(alpha).add(a.up);
36121 this._focal = (1 - alpha) * a.focal + alpha * b.focal;
36124 * Copy the properties of another camera to this camera.
36126 * @param {Camera} other - Another camera.
36128 Camera.prototype.copy = function (other) {
36129 this._position.copy(other.position);
36130 this._lookat.copy(other.lookat);
36131 this._up.copy(other.up);
36132 this._focal = other.focal;
36135 * Clone this camera.
36137 * @returns {Camera} A camera with cloned properties equal to this camera.
36139 Camera.prototype.clone = function () {
36140 var camera = new Camera();
36141 camera.position.copy(this._position);
36142 camera.lookat.copy(this._lookat);
36143 camera.up.copy(this._up);
36144 camera.focal = this._focal;
36148 * Determine the distance between this camera and another camera.
36150 * @param {Camera} other - Another camera.
36151 * @returns {number} The distance between the cameras.
36153 Camera.prototype.diff = function (other) {
36154 var pd = this._position.distanceToSquared(other.position);
36155 var ld = this._lookat.distanceToSquared(other.lookat);
36156 var ud = this._up.distanceToSquared(other.up);
36157 var fd = 100 * Math.abs(this._focal - other.focal);
36158 return Math.max(pd, ld, ud, fd);
36161 * Get the focal length based on the transform.
36163 * @description Returns the focal length of the transform if gpano info is not available.
36164 * Returns a focal length corresponding to a vertical fov clamped to [45, 90] degrees based on
36165 * the gpano information if available.
36167 * @returns {number} Focal length.
36169 Camera.prototype._getFocal = function (transform) {
36170 if (transform.gpano == null) {
36171 return transform.focal;
36173 var vFov = Math.PI * transform.gpano.CroppedAreaImageHeightPixels / transform.gpano.FullPanoHeightPixels;
36174 var focal = 0.5 / Math.tan(vFov / 2);
36175 return Math.min(1 / (2 * (Math.sqrt(2) - 1)), Math.max(0.5, focal));
36179 exports.Camera = Camera;
36181 },{"three":240}],391:[function(require,module,exports){
36183 Object.defineProperty(exports, "__esModule", { value: true });
36187 * @classdesc Converts coordinates between the geodetic (WGS84),
36188 * Earth-Centered, Earth-Fixed (ECEF) and local topocentric
36189 * East, North, Up (ENU) reference frames.
36191 * The WGS84 has latitude (degrees), longitude (degrees) and
36192 * altitude (meters) values.
36194 * The ECEF Z-axis pierces the north pole and the
36195 * XY-axis defines the equatorial plane. The X-axis extends
36196 * from the geocenter to the intersection of the Equator and
36197 * the Greenwich Meridian. All values in meters.
36199 * The WGS84 parameters are:
36203 * f = 1 / 298.257223563
36204 * e = Math.sqrt((a^2 - b^2) / a^2)
36205 * e' = Math.sqrt((a^2 - b^2) / b^2)
36207 * The WGS84 to ECEF conversion is performed using the following:
36209 * X = (N - h) * cos(phi) * cos(lambda)
36210 * Y = (N + h) * cos(phi) * sin(lambda)
36211 * Z = (b^2 * N / a^2 + h) * sin(phi)
36216 * lambda = longitude
36217 * h = height above ellipsoid (altitude)
36218 * N = Radius of curvature (meters)
36219 * = a / Math.sqrt(1 - e^2 * sin(phi)^2)
36221 * The ECEF to WGS84 conversion is performed using the following:
36223 * phi = arctan((Z + e'^2 * b * sin(theta)^3) / (p - e^2 * a * cos(theta)^3))
36224 * lambda = arctan(Y / X)
36225 * h = p / cos(phi) - N
36229 * p = Math.sqrt(X^2 + Y^2)
36230 * theta = arctan(Z * a / p * b)
36232 * In the ENU reference frame the x-axis points to the
36233 * East, the y-axis to the North and the z-axis Up. All values
36236 * The ECEF to ENU conversion is performed using the following:
36238 * | x | | -sin(lambda_r) cos(lambda_r) 0 | | X - X_r |
36239 * | y | = | -sin(phi_r) * cos(lambda_r) -sin(phi_r) * sin(lambda_r) cos(phi_r) | | Y - Y_r |
36240 * | z | | cos(phi_r) * cos(lambda_r) cos(phi_r) * sin(lambda_r) sin(phi_r) | | Z - Z_r |
36244 * phi_r = latitude of reference
36245 * lambda_r = longitude of reference
36246 * X_r, Y_r, Z_r = ECEF coordinates of reference
36248 * The ENU to ECEF conversion is performed by solving the above equation for X, Y, Z.
36250 * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in
36251 * the first step for both conversions.
36253 var GeoCoords = /** @class */ (function () {
36254 function GeoCoords() {
36255 this._wgs84a = 6378137.0;
36256 this._wgs84b = 6356752.31424518;
36259 * Convert coordinates from geodetic (WGS84) reference to local topocentric
36262 * @param {number} lat Latitude in degrees.
36263 * @param {number} lon Longitude in degrees.
36264 * @param {number} alt Altitude in meters.
36265 * @param {number} refLat Reference latitude in degrees.
36266 * @param {number} refLon Reference longitude in degrees.
36267 * @param {number} refAlt Reference altitude in meters.
36268 * @returns {Array<number>} The x, y, z local topocentric ENU coordinates.
36270 GeoCoords.prototype.geodeticToEnu = function (lat, lon, alt, refLat, refLon, refAlt) {
36271 var ecef = this.geodeticToEcef(lat, lon, alt);
36272 return this.ecefToEnu(ecef[0], ecef[1], ecef[2], refLat, refLon, refAlt);
36275 * Convert coordinates from local topocentric (ENU) reference to
36276 * geodetic (WGS84) reference.
36278 * @param {number} x Topocentric ENU coordinate in East direction.
36279 * @param {number} y Topocentric ENU coordinate in North direction.
36280 * @param {number} z Topocentric ENU coordinate in Up direction.
36281 * @param {number} refLat Reference latitude in degrees.
36282 * @param {number} refLon Reference longitude in degrees.
36283 * @param {number} refAlt Reference altitude in meters.
36284 * @returns {Array<number>} The latitude and longitude in degrees
36285 * as well as altitude in meters.
36287 GeoCoords.prototype.enuToGeodetic = function (x, y, z, refLat, refLon, refAlt) {
36288 var ecef = this.enuToEcef(x, y, z, refLat, refLon, refAlt);
36289 return this.ecefToGeodetic(ecef[0], ecef[1], ecef[2]);
36292 * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
36293 * to local topocentric (ENU) reference.
36295 * @param {number} X ECEF X-value.
36296 * @param {number} Y ECEF Y-value.
36297 * @param {number} Z ECEF Z-value.
36298 * @param {number} refLat Reference latitude in degrees.
36299 * @param {number} refLon Reference longitude in degrees.
36300 * @param {number} refAlt Reference altitude in meters.
36301 * @returns {Array<number>} The x, y, z topocentric ENU coordinates in East, North
36302 * and Up directions respectively.
36304 GeoCoords.prototype.ecefToEnu = function (X, Y, Z, refLat, refLon, refAlt) {
36305 var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
36306 var V = [X - refEcef[0], Y - refEcef[1], Z - refEcef[2]];
36307 refLat = refLat * Math.PI / 180.0;
36308 refLon = refLon * Math.PI / 180.0;
36309 var cosLat = Math.cos(refLat);
36310 var sinLat = Math.sin(refLat);
36311 var cosLon = Math.cos(refLon);
36312 var sinLon = Math.sin(refLon);
36313 var x = -sinLon * V[0] + cosLon * V[1];
36314 var y = -sinLat * cosLon * V[0] - sinLat * sinLon * V[1] + cosLat * V[2];
36315 var z = cosLat * cosLon * V[0] + cosLat * sinLon * V[1] + sinLat * V[2];
36319 * Convert coordinates from local topocentric (ENU) reference
36320 * to Earth-Centered, Earth-Fixed (ECEF) reference.
36322 * @param {number} x Topocentric ENU coordinate in East direction.
36323 * @param {number} y Topocentric ENU coordinate in North direction.
36324 * @param {number} z Topocentric ENU coordinate in Up direction.
36325 * @param {number} refLat Reference latitude in degrees.
36326 * @param {number} refLon Reference longitude in degrees.
36327 * @param {number} refAlt Reference altitude in meters.
36328 * @returns {Array<number>} The X, Y, Z ECEF coordinates.
36330 GeoCoords.prototype.enuToEcef = function (x, y, z, refLat, refLon, refAlt) {
36331 var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
36332 refLat = refLat * Math.PI / 180.0;
36333 refLon = refLon * Math.PI / 180.0;
36334 var cosLat = Math.cos(refLat);
36335 var sinLat = Math.sin(refLat);
36336 var cosLon = Math.cos(refLon);
36337 var sinLon = Math.sin(refLon);
36338 var X = -sinLon * x - sinLat * cosLon * y + cosLat * cosLon * z + refEcef[0];
36339 var Y = cosLon * x - sinLat * sinLon * y + cosLat * sinLon * z + refEcef[1];
36340 var Z = cosLat * y + sinLat * z + refEcef[2];
36344 * Convert coordinates from geodetic reference (WGS84) to Earth-Centered,
36345 * Earth-Fixed (ECEF) reference.
36347 * @param {number} lat Latitude in degrees.
36348 * @param {number} lon Longitude in degrees.
36349 * @param {number} alt Altitude in meters.
36350 * @returns {Array<number>} The X, Y, Z ECEF coordinates.
36352 GeoCoords.prototype.geodeticToEcef = function (lat, lon, alt) {
36353 var a = this._wgs84a;
36354 var b = this._wgs84b;
36355 lat = lat * Math.PI / 180.0;
36356 lon = lon * Math.PI / 180.0;
36357 var cosLat = Math.cos(lat);
36358 var sinLat = Math.sin(lat);
36359 var cosLon = Math.cos(lon);
36360 var sinLon = Math.sin(lon);
36363 var L = 1.0 / Math.sqrt(a2 * cosLat * cosLat + b2 * sinLat * sinLat);
36364 var nhcl = (a2 * L + alt) * cosLat;
36365 var X = nhcl * cosLon;
36366 var Y = nhcl * sinLon;
36367 var Z = (b2 * L + alt) * sinLat;
36371 * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
36372 * to geodetic reference (WGS84).
36374 * @param {number} X ECEF X-value.
36375 * @param {number} Y ECEF Y-value.
36376 * @param {number} Z ECEF Z-value.
36377 * @returns {Array<number>} The latitude and longitude in degrees
36378 * as well as altitude in meters.
36380 GeoCoords.prototype.ecefToGeodetic = function (X, Y, Z) {
36381 var a = this._wgs84a;
36382 var b = this._wgs84b;
36385 var a2mb2 = a2 - b2;
36386 var ea = Math.sqrt(a2mb2 / a2);
36387 var eb = Math.sqrt(a2mb2 / b2);
36388 var p = Math.sqrt(X * X + Y * Y);
36389 var theta = Math.atan2(Z * a, p * b);
36390 var sinTheta = Math.sin(theta);
36391 var cosTheta = Math.cos(theta);
36392 var lon = Math.atan2(Y, X);
36393 var lat = Math.atan2(Z + eb * eb * b * sinTheta * sinTheta * sinTheta, p - ea * ea * a * cosTheta * cosTheta * cosTheta);
36394 var sinLat = Math.sin(lat);
36395 var cosLat = Math.cos(lat);
36396 var N = a / Math.sqrt(1 - ea * ea * sinLat * sinLat);
36397 var alt = p / cosLat - N;
36398 return [lat * 180.0 / Math.PI, lon * 180.0 / Math.PI, alt];
36402 exports.GeoCoords = GeoCoords;
36403 exports.default = GeoCoords;
36405 },{}],392:[function(require,module,exports){
36407 /// <reference path="../../typings/index.d.ts" />
36408 Object.defineProperty(exports, "__esModule", { value: true });
36409 var THREE = require("three");
36413 * @classdesc Provides methods for scalar, vector and matrix calculations.
36415 var Spatial = /** @class */ (function () {
36416 function Spatial() {
36417 this._epsilon = 1e-9;
36420 * Converts azimuthal phi rotation (counter-clockwise with origin on X-axis) to
36421 * bearing (clockwise with origin at north or Y-axis).
36423 * @param {number} phi - Azimuthal phi angle in radians.
36424 * @returns {number} Bearing in radians.
36426 Spatial.prototype.azimuthalToBearing = function (phi) {
36427 return -phi + Math.PI / 2;
36430 * Converts degrees to radians.
36432 * @param {number} deg - Degrees.
36433 * @returns {number} Radians.
36435 Spatial.prototype.degToRad = function (deg) {
36436 return Math.PI * deg / 180;
36439 * Converts radians to degrees.
36441 * @param {number} rad - Radians.
36442 * @returns {number} Degrees.
36444 Spatial.prototype.radToDeg = function (rad) {
36445 return 180 * rad / Math.PI;
36448 * Creates a rotation matrix from an angle-axis vector.
36450 * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
36451 * @returns {THREE.Matrix4} Rotation matrix.
36453 Spatial.prototype.rotationMatrix = function (angleAxis) {
36454 var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]);
36455 var angle = axis.length();
36459 return new THREE.Matrix4().makeRotationAxis(axis, angle);
36462 * Rotates a vector according to a angle-axis rotation vector.
36464 * @param {Array<number>} vector - Vector to rotate.
36465 * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
36466 * @returns {THREE.Vector3} Rotated vector.
36468 Spatial.prototype.rotate = function (vector, angleAxis) {
36469 var v = new THREE.Vector3(vector[0], vector[1], vector[2]);
36470 var rotationMatrix = this.rotationMatrix(angleAxis);
36471 v.applyMatrix4(rotationMatrix);
36475 * Calculates the optical center from a rotation vector
36476 * on the angle-axis representation and a translation vector
36477 * according to C = -R^T t.
36479 * @param {Array<number>} rotation - Angle-axis representation of a rotation.
36480 * @param {Array<number>} translation - Translation vector.
36481 * @returns {THREE.Vector3} Optical center.
36483 Spatial.prototype.opticalCenter = function (rotation, translation) {
36484 var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
36485 var vector = [-translation[0], -translation[1], -translation[2]];
36486 return this.rotate(vector, angleAxis);
36489 * Calculates the viewing direction from a rotation vector
36490 * on the angle-axis representation.
36492 * @param {number[]} rotation - Angle-axis representation of a rotation.
36493 * @returns {THREE.Vector3} Viewing direction.
36495 Spatial.prototype.viewingDirection = function (rotation) {
36496 var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
36497 return this.rotate([0, 0, 1], angleAxis);
36500 * Wrap a number on the interval [min, max].
36502 * @param {number} value - Value to wrap.
36503 * @param {number} min - Lower endpoint of interval.
36504 * @param {number} max - Upper endpoint of interval.
36505 * @returns {number} The wrapped number.
36507 Spatial.prototype.wrap = function (value, min, max) {
36509 throw new Error("Invalid arguments: max must be larger than min.");
36511 var interval = (max - min);
36512 while (value > max || value < min) {
36514 value = value - interval;
36516 else if (value < min) {
36517 value = value + interval;
36523 * Wrap an angle on the interval [-Pi, Pi].
36525 * @param {number} angle - Value to wrap.
36526 * @returns {number} Wrapped angle.
36528 Spatial.prototype.wrapAngle = function (angle) {
36529 return this.wrap(angle, -Math.PI, Math.PI);
36532 * Limit the value to the interval [min, max] by changing the value to
36533 * the nearest available one when it is outside the interval.
36535 * @param {number} value - Value to clamp.
36536 * @param {number} min - Minimum of the interval.
36537 * @param {number} max - Maximum of the interval.
36538 * @returns {number} Clamped value.
36540 Spatial.prototype.clamp = function (value, min, max) {
36550 * Calculates the counter-clockwise angle from the first
36551 * vector (x1, y1)^T to the second (x2, y2)^T.
36553 * @param {number} x1 - X coordinate of first vector.
36554 * @param {number} y1 - Y coordinate of first vector.
36555 * @param {number} x2 - X coordinate of second vector.
36556 * @param {number} y2 - Y coordinate of second vector.
36557 * @returns {number} Counter clockwise angle between the vectors.
36559 Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) {
36560 var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1);
36561 return this.wrapAngle(angle);
36564 * Calculates the minimum (absolute) angle change for rotation
36565 * from one angle to another on the [-Pi, Pi] interval.
36567 * @param {number} angle1 - Start angle.
36568 * @param {number} angle2 - Destination angle.
36569 * @returns {number} Absolute angle change between angles.
36571 Spatial.prototype.angleDifference = function (angle1, angle2) {
36572 var angle = angle2 - angle1;
36573 return this.wrapAngle(angle);
36576 * Calculates the relative rotation angle between two
36577 * angle-axis vectors.
36579 * @param {number} rotation1 - First angle-axis vector.
36580 * @param {number} rotation2 - Second angle-axis vector.
36581 * @returns {number} Relative rotation angle.
36583 Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) {
36584 var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]);
36585 var R2 = this.rotationMatrix(rotation2);
36586 var R = R1T.multiply(R2);
36587 var elements = R.elements;
36588 // from Tr(R) = 1 + 2 * cos(theta)
36589 var tr = elements[0] + elements[5] + elements[10];
36590 var theta = Math.acos(Math.max(Math.min((tr - 1) / 2, 1), -1));
36594 * Calculates the angle from a vector to a plane.
36596 * @param {Array<number>} vector - The vector.
36597 * @param {Array<number>} planeNormal - Normal of the plane.
36598 * @returns {number} Angle from between plane and vector.
36600 Spatial.prototype.angleToPlane = function (vector, planeNormal) {
36601 var v = new THREE.Vector3().fromArray(vector);
36602 var norm = v.length();
36603 if (norm < this._epsilon) {
36606 var projection = v.dot(new THREE.Vector3().fromArray(planeNormal));
36607 return Math.asin(projection / norm);
36610 * Calculates the distance between two coordinates
36611 * (latitude longitude pairs) in meters according to
36612 * the haversine formula.
36614 * @param {number} lat1 - Latitude of the first coordinate in degrees.
36615 * @param {number} lon1 - Longitude of the first coordinate in degrees.
36616 * @param {number} lat2 - Latitude of the second coordinate in degrees.
36617 * @param {number} lon2 - Longitude of the second coordinate in degrees.
36618 * @returns {number} Distance between lat lon positions in meters.
36620 Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) {
36622 var dLat = this.degToRad(lat2 - lat1);
36623 var dLon = this.degToRad(lon2 - lon1);
36624 var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
36625 Math.cos(this.degToRad(lat1)) * Math.cos(this.degToRad(lat2)) *
36626 Math.sin(dLon / 2) * Math.sin(dLon / 2);
36627 var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav));
36632 exports.Spatial = Spatial;
36633 exports.default = Spatial;
36635 },{"three":240}],393:[function(require,module,exports){
36637 /// <reference path="../../typings/index.d.ts" />
36638 Object.defineProperty(exports, "__esModule", { value: true });
36639 var THREE = require("three");
36643 * @classdesc Class used for calculating coordinate transformations
36646 var Transform = /** @class */ (function () {
36648 * Create a new transform instance.
36649 * @param {number} orientation - Image orientation.
36650 * @param {number} width - Image height.
36651 * @param {number} height - Image width.
36652 * @param {number} focal - Focal length.
36653 * @param {number} scale - Atomic scale.
36654 * @param {IGPano} gpano - Panorama properties.
36655 * @param {Array<number>} rotation - Rotation vector in three dimensions.
36656 * @param {Array<number>} translation - Translation vector in three dimensions.
36657 * @param {HTMLImageElement} image - Image for fallback size calculations.
36659 function Transform(orientation, width, height, focal, scale, gpano, rotation, translation, image, textureScale) {
36660 this._orientation = this._getValue(orientation, 1);
36661 var imageWidth = image != null ? image.width : 4;
36662 var imageHeight = image != null ? image.height : 3;
36663 var keepOrientation = this._orientation < 5;
36664 this._width = this._getValue(width, keepOrientation ? imageWidth : imageHeight);
36665 this._height = this._getValue(height, keepOrientation ? imageHeight : imageWidth);
36666 this._basicAspect = keepOrientation ?
36667 this._width / this._height :
36668 this._height / this._width;
36669 this._basicWidth = keepOrientation ? width : height;
36670 this._basicHeight = keepOrientation ? height : width;
36671 this._focal = this._getValue(focal, 1);
36672 this._scale = this._getValue(scale, 0);
36673 this._gpano = gpano != null ? gpano : null;
36674 this._rt = this._getRt(rotation, translation);
36675 this._srt = this._getSrt(this._rt, this._scale);
36676 this._textureScale = !!textureScale ? textureScale : [1, 1];
36678 Object.defineProperty(Transform.prototype, "basicAspect", {
36680 * Get basic aspect.
36681 * @returns {number} The orientation adjusted aspect ratio.
36684 return this._basicAspect;
36689 Object.defineProperty(Transform.prototype, "basicHeight", {
36691 * Get basic height.
36693 * @description Does not fall back to node image height but
36694 * uses original value from API so can be faulty.
36696 * @returns {number} The height of the basic version image
36697 * (adjusted for orientation).
36700 return this._basicHeight;
36705 Object.defineProperty(Transform.prototype, "basicWidth", {
36709 * @description Does not fall back to node image width but
36710 * uses original value from API so can be faulty.
36712 * @returns {number} The width of the basic version image
36713 * (adjusted for orientation).
36716 return this._basicWidth;
36721 Object.defineProperty(Transform.prototype, "focal", {
36724 * @returns {number} The node focal length.
36727 return this._focal;
36732 Object.defineProperty(Transform.prototype, "fullPano", {
36736 * @returns {boolean} Value indicating whether the node is a complete
36740 return this._gpano != null &&
36741 this._gpano.CroppedAreaLeftPixels === 0 &&
36742 this._gpano.CroppedAreaTopPixels === 0 &&
36743 this._gpano.CroppedAreaImageWidthPixels === this._gpano.FullPanoWidthPixels &&
36744 this._gpano.CroppedAreaImageHeightPixels === this._gpano.FullPanoHeightPixels;
36749 Object.defineProperty(Transform.prototype, "gpano", {
36752 * @returns {number} The node gpano information.
36755 return this._gpano;
36760 Object.defineProperty(Transform.prototype, "height", {
36764 * @description Falls back to the node image height if
36765 * the API data is faulty.
36767 * @returns {number} The orientation adjusted image height.
36770 return this._height;
36775 Object.defineProperty(Transform.prototype, "orientation", {
36778 * @returns {number} The image orientation.
36781 return this._orientation;
36786 Object.defineProperty(Transform.prototype, "rt", {
36789 * @returns {THREE.Matrix4} The extrinsic camera matrix.
36797 Object.defineProperty(Transform.prototype, "srt", {
36800 * @returns {THREE.Matrix4} The scaled extrinsic camera matrix.
36808 Object.defineProperty(Transform.prototype, "scale", {
36811 * @returns {number} The node atomic reconstruction scale.
36814 return this._scale;
36819 Object.defineProperty(Transform.prototype, "hasValidScale", {
36821 * Get has valid scale.
36822 * @returns {boolean} Value indicating if the scale of the transform is valid.
36825 return this._scale > 1e-2 && this._scale < 50;
36830 Object.defineProperty(Transform.prototype, "width", {
36834 * @description Falls back to the node image width if
36835 * the API data is faulty.
36837 * @returns {number} The orientation adjusted image width.
36840 return this._width;
36846 * Calculate the up vector for the node transform.
36848 * @returns {THREE.Vector3} Normalized and orientation adjusted up vector.
36850 Transform.prototype.upVector = function () {
36851 var rte = this._rt.elements;
36852 switch (this._orientation) {
36854 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
36856 return new THREE.Vector3(rte[1], rte[5], rte[9]);
36858 return new THREE.Vector3(-rte[0], -rte[4], -rte[8]);
36860 return new THREE.Vector3(rte[0], rte[4], rte[8]);
36862 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
36866 * Calculate projector matrix for projecting 3D points to texture map
36867 * coordinates (u and v).
36869 * @returns {THREE.Matrix4} Projection matrix for 3D point to texture
36870 * map coordinate calculations.
36872 Transform.prototype.projectorMatrix = function () {
36873 var projector = this._normalizedToTextureMatrix();
36874 var f = this._focal;
36875 var projection = new THREE.Matrix4().set(f, 0, 0, 0, 0, f, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
36876 projector.multiply(projection);
36877 projector.multiply(this._rt);
36881 * Project 3D world coordinates to basic coordinates.
36883 * @param {Array<number>} point3d - 3D world coordinates.
36884 * @return {Array<number>} 2D basic coordinates.
36886 Transform.prototype.projectBasic = function (point3d) {
36887 var sfm = this.projectSfM(point3d);
36888 return this._sfmToBasic(sfm);
36891 * Unproject basic coordinates to 3D world coordinates.
36893 * @param {Array<number>} basic - 2D basic coordinates.
36894 * @param {Array<number>} distance - Depth to unproject from camera center.
36895 * @returns {Array<number>} Unprojected 3D world coordinates.
36897 Transform.prototype.unprojectBasic = function (basic, distance) {
36898 var sfm = this._basicToSfm(basic);
36899 return this.unprojectSfM(sfm, distance);
36902 * Project 3D world coordinates to SfM coordinates.
36904 * @param {Array<number>} point3d - 3D world coordinates.
36905 * @return {Array<number>} 2D SfM coordinates.
36907 Transform.prototype.projectSfM = function (point3d) {
36908 var v = new THREE.Vector4(point3d[0], point3d[1], point3d[2], 1);
36909 v.applyMatrix4(this._rt);
36910 return this._bearingToSfm([v.x, v.y, v.z]);
36913 * Unproject SfM coordinates to a 3D world coordinates.
36915 * @param {Array<number>} sfm - 2D SfM coordinates.
36916 * @param {Array<number>} distance - Depth to unproject from camera center.
36917 * @returns {Array<number>} Unprojected 3D world coordinates.
36919 Transform.prototype.unprojectSfM = function (sfm, distance) {
36920 var bearing = this._sfmToBearing(sfm);
36921 var v = new THREE.Vector4(distance * bearing[0], distance * bearing[1], distance * bearing[2], 1);
36922 v.applyMatrix4(new THREE.Matrix4().getInverse(this._rt));
36923 return [v.x / v.w, v.y / v.w, v.z / v.w];
36926 * Transform SfM coordinates to bearing vector (3D cartesian
36927 * coordinates on the unit sphere).
36929 * @param {Array<number>} sfm - 2D SfM coordinates.
36930 * @returns {Array<number>} Bearing vector (3D cartesian coordinates
36931 * on the unit sphere).
36933 Transform.prototype._sfmToBearing = function (sfm) {
36934 if (this._fullPano()) {
36935 var lon = sfm[0] * 2 * Math.PI;
36936 var lat = -sfm[1] * 2 * Math.PI;
36937 var x = Math.cos(lat) * Math.sin(lon);
36938 var y = -Math.sin(lat);
36939 var z = Math.cos(lat) * Math.cos(lon);
36942 else if (this._gpano) {
36943 var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
36944 var fullPanoPixel = [
36945 sfm[0] * size + this.gpano.CroppedAreaImageWidthPixels / 2 + this.gpano.CroppedAreaLeftPixels,
36946 sfm[1] * size + this.gpano.CroppedAreaImageHeightPixels / 2 + this.gpano.CroppedAreaTopPixels,
36948 var lon = 2 * Math.PI * (fullPanoPixel[0] / this.gpano.FullPanoWidthPixels - 0.5);
36949 var lat = -Math.PI * (fullPanoPixel[1] / this.gpano.FullPanoHeightPixels - 0.5);
36950 var x = Math.cos(lat) * Math.sin(lon);
36951 var y = -Math.sin(lat);
36952 var z = Math.cos(lat) * Math.cos(lon);
36956 var v = new THREE.Vector3(sfm[0], sfm[1], this._focal);
36958 return [v.x, v.y, v.z];
36962 * Transform bearing vector (3D cartesian coordiantes on the unit sphere) to
36965 * @param {Array<number>} bearing - Bearing vector (3D cartesian coordinates on the
36967 * @returns {Array<number>} 2D SfM coordinates.
36969 Transform.prototype._bearingToSfm = function (bearing) {
36970 if (this._fullPano()) {
36971 var x = bearing[0];
36972 var y = bearing[1];
36973 var z = bearing[2];
36974 var lon = Math.atan2(x, z);
36975 var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
36976 return [lon / (2 * Math.PI), -lat / (2 * Math.PI)];
36978 else if (this._gpano) {
36979 var x = bearing[0];
36980 var y = bearing[1];
36981 var z = bearing[2];
36982 var lon = Math.atan2(x, z);
36983 var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
36984 var fullPanoPixel = [
36985 (lon / (2 * Math.PI) + 0.5) * this.gpano.FullPanoWidthPixels,
36986 (-lat / Math.PI + 0.5) * this.gpano.FullPanoHeightPixels,
36988 var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
36990 (fullPanoPixel[0] - this.gpano.CroppedAreaLeftPixels - this.gpano.CroppedAreaImageWidthPixels / 2) / size,
36991 (fullPanoPixel[1] - this.gpano.CroppedAreaTopPixels - this.gpano.CroppedAreaImageHeightPixels / 2) / size,
36995 if (bearing[2] > 0) {
36997 bearing[0] * this._focal / bearing[2],
36998 bearing[1] * this._focal / bearing[2],
37003 bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
37004 bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
37010 * Convert basic coordinates to SfM coordinates.
37012 * @param {Array<number>} basic - 2D basic coordinates.
37013 * @returns {Array<number>} 2D SfM coordinates.
37015 Transform.prototype._basicToSfm = function (basic) {
37018 switch (this._orientation) {
37020 rotatedX = basic[0];
37021 rotatedY = basic[1];
37024 rotatedX = 1 - basic[0];
37025 rotatedY = 1 - basic[1];
37028 rotatedX = basic[1];
37029 rotatedY = 1 - basic[0];
37032 rotatedX = 1 - basic[1];
37033 rotatedY = basic[0];
37036 rotatedX = basic[0];
37037 rotatedY = basic[1];
37040 var w = this._width;
37041 var h = this._height;
37042 var s = Math.max(w, h);
37043 var sfmX = rotatedX * w / s - w / s / 2;
37044 var sfmY = rotatedY * h / s - h / s / 2;
37045 return [sfmX, sfmY];
37048 * Convert SfM coordinates to basic coordinates.
37050 * @param {Array<number>} sfm - 2D SfM coordinates.
37051 * @returns {Array<number>} 2D basic coordinates.
37053 Transform.prototype._sfmToBasic = function (sfm) {
37054 var w = this._width;
37055 var h = this._height;
37056 var s = Math.max(w, h);
37057 var rotatedX = (sfm[0] + w / s / 2) / w * s;
37058 var rotatedY = (sfm[1] + h / s / 2) / h * s;
37061 switch (this._orientation) {
37067 basicX = 1 - rotatedX;
37068 basicY = 1 - rotatedY;
37071 basicX = 1 - rotatedY;
37076 basicY = 1 - rotatedX;
37083 return [basicX, basicY];
37086 * Determines if the gpano information indicates a full panorama.
37088 * @returns {boolean} Value determining if the gpano information indicates
37091 Transform.prototype._fullPano = function () {
37092 return this.gpano != null &&
37093 this.gpano.CroppedAreaLeftPixels === 0 &&
37094 this.gpano.CroppedAreaTopPixels === 0 &&
37095 this.gpano.CroppedAreaImageWidthPixels === this.gpano.FullPanoWidthPixels &&
37096 this.gpano.CroppedAreaImageHeightPixels === this.gpano.FullPanoHeightPixels;
37099 * Checks a value and returns it if it exists and is larger than 0.
37100 * Fallbacks if it is null.
37102 * @param {number} value - Value to check.
37103 * @param {number} fallback - Value to fall back to.
37104 * @returns {number} The value or its fallback value if it is not defined or negative.
37106 Transform.prototype._getValue = function (value, fallback) {
37107 return value != null && value > 0 ? value : fallback;
37110 * Creates the extrinsic camera matrix [ R | t ].
37112 * @param {Array<number>} rotation - Rotation vector in angle axis representation.
37113 * @param {Array<number>} translation - Translation vector.
37114 * @returns {THREE.Matrix4} Extrisic camera matrix.
37116 Transform.prototype._getRt = function (rotation, translation) {
37117 var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]);
37118 var angle = axis.length();
37122 var rt = new THREE.Matrix4();
37123 rt.makeRotationAxis(axis, angle);
37124 rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2]));
37128 * Calculates the scaled extrinsic camera matrix scale * [ R | t ].
37130 * @param {THREE.Matrix4} rt - Extrisic camera matrix.
37131 * @param {number} scale - Scale factor.
37132 * @returns {THREE.Matrix4} Scaled extrisic camera matrix.
37134 Transform.prototype._getSrt = function (rt, scale) {
37135 var srt = rt.clone();
37136 var elements = srt.elements;
37137 elements[12] = scale * elements[12];
37138 elements[13] = scale * elements[13];
37139 elements[14] = scale * elements[14];
37140 srt.scale(new THREE.Vector3(scale, scale, scale));
37144 * Calculate a transformation matrix from normalized coordinates for
37145 * texture map coordinates.
37147 * @returns {THREE.Matrix4} Normalized coordinates to texture map
37148 * coordinates transformation matrix.
37150 Transform.prototype._normalizedToTextureMatrix = function () {
37151 var size = Math.max(this._width, this._height);
37152 var scaleX = this._orientation < 5 ? this._textureScale[0] : this._textureScale[1];
37153 var scaleY = this._orientation < 5 ? this._textureScale[1] : this._textureScale[0];
37154 var w = size / this._width * scaleX;
37155 var h = size / this._height * scaleY;
37156 switch (this._orientation) {
37158 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
37160 return new THREE.Matrix4().set(-w, 0, 0, 0.5, 0, h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
37162 return new THREE.Matrix4().set(0, -h, 0, 0.5, -w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
37164 return new THREE.Matrix4().set(0, h, 0, 0.5, w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
37166 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
37171 exports.Transform = Transform;
37173 },{"three":240}],394:[function(require,module,exports){
37175 /// <reference path="../../typings/index.d.ts" />
37176 Object.defineProperty(exports, "__esModule", { value: true });
37177 var THREE = require("three");
37179 * @class ViewportCoords
37181 * @classdesc Provides methods for calculating 2D coordinate conversions
37182 * as well as 3D projection and unprojection.
37184 * Basic coordinates are 2D coordinates on the [0, 1] interval and
37185 * have the origin point, (0, 0), at the top left corner and the
37186 * maximum value, (1, 1), at the bottom right corner of the original
37189 * Viewport coordinates are 2D coordinates on the [-1, 1] interval and
37190 * have the origin point in the center. The bottom left corner point is
37191 * (-1, -1) and the top right corner point is (1, 1).
37193 * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and
37194 * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left
37195 * corner and the maximum value is (canvasWidth, canvasHeight) is in the
37196 * bottom right corner.
37198 * 3D coordinates are in the topocentric world reference frame.
37200 var ViewportCoords = /** @class */ (function () {
37201 function ViewportCoords() {
37202 this._unprojectDepth = 200;
37205 * Convert basic coordinates to canvas coordinates.
37207 * @description Transform origin and camera position needs to be the
37208 * equal for reliable return value.
37210 * @param {number} basicX - Basic X coordinate.
37211 * @param {number} basicY - Basic Y coordinate.
37212 * @param {HTMLElement} container - The viewer container.
37213 * @param {Transform} transform - Transform of the node to unproject from.
37214 * @param {THREE.Camera} camera - Camera used in rendering.
37215 * @returns {Array<number>} 2D canvas coordinates.
37217 ViewportCoords.prototype.basicToCanvas = function (basicX, basicY, container, transform, camera) {
37218 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
37219 var canvas = this.projectToCanvas(point3d, container, camera);
37223 * Convert basic coordinates to canvas coordinates safely. If 3D point is
37224 * behind camera null will be returned.
37226 * @description Transform origin and camera position needs to be the
37227 * equal for reliable return value.
37229 * @param {number} basicX - Basic X coordinate.
37230 * @param {number} basicY - Basic Y coordinate.
37231 * @param {HTMLElement} container - The viewer container.
37232 * @param {Transform} transform - Transform of the node to unproject from.
37233 * @param {THREE.Camera} camera - Camera used in rendering.
37234 * @returns {Array<number>} 2D canvas coordinates if the basic point represents a 3D point
37235 * in front of the camera, otherwise null.
37237 ViewportCoords.prototype.basicToCanvasSafe = function (basicX, basicY, container, transform, camera) {
37238 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
37239 var pointCamera = this.worldToCamera(point3d, camera);
37240 if (pointCamera[2] > 0) {
37243 var _a = this.cameraToViewport(pointCamera, camera), viewportX = _a[0], viewportY = _a[1];
37244 var canvas = this.viewportToCanvas(viewportX, viewportY, container);
37248 * Convert basic coordinates to viewport coordinates.
37250 * @description Transform origin and camera position needs to be the
37251 * equal for reliable return value.
37253 * @param {number} basicX - Basic X coordinate.
37254 * @param {number} basicY - Basic Y coordinate.
37255 * @param {Transform} transform - Transform of the node to unproject from.
37256 * @param {THREE.Camera} camera - Camera used in rendering.
37257 * @returns {Array<number>} 2D viewport coordinates.
37259 ViewportCoords.prototype.basicToViewport = function (basicX, basicY, transform, camera) {
37260 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
37261 var viewport = this.projectToViewport(point3d, camera);
37265 * Convert camera 3D coordinates to viewport coordinates.
37267 * @param {number} pointCamera - 3D point in camera coordinate system.
37268 * @param {THREE.Camera} camera - Camera used in rendering.
37269 * @returns {Array<number>} 2D viewport coordinates.
37271 ViewportCoords.prototype.cameraToViewport = function (pointCamera, camera) {
37272 var viewport = new THREE.Vector3().fromArray(pointCamera)
37273 .applyMatrix4(camera.projectionMatrix);
37274 return [viewport.x, viewport.y];
37277 * Get canvas pixel position from event.
37279 * @param {Event} event - Event containing clientX and clientY properties.
37280 * @param {HTMLElement} element - HTML element.
37281 * @returns {Array<number>} 2D canvas coordinates.
37283 ViewportCoords.prototype.canvasPosition = function (event, element) {
37284 var clientRect = element.getBoundingClientRect();
37285 var canvasX = event.clientX - clientRect.left - element.clientLeft;
37286 var canvasY = event.clientY - clientRect.top - element.clientTop;
37287 return [canvasX, canvasY];
37290 * Convert canvas coordinates to basic coordinates.
37292 * @description Transform origin and camera position needs to be the
37293 * equal for reliable return value.
37295 * @param {number} canvasX - Canvas X coordinate.
37296 * @param {number} canvasY - Canvas Y coordinate.
37297 * @param {HTMLElement} container - The viewer container.
37298 * @param {Transform} transform - Transform of the node to unproject from.
37299 * @param {THREE.Camera} camera - Camera used in rendering.
37300 * @returns {Array<number>} 2D basic coordinates.
37302 ViewportCoords.prototype.canvasToBasic = function (canvasX, canvasY, container, transform, camera) {
37303 var point3d = this.unprojectFromCanvas(canvasX, canvasY, container, camera)
37305 var basic = transform.projectBasic(point3d);
37309 * Convert canvas coordinates to viewport coordinates.
37311 * @param {number} canvasX - Canvas X coordinate.
37312 * @param {number} canvasY - Canvas Y coordinate.
37313 * @param {HTMLElement} container - The viewer container.
37314 * @returns {Array<number>} 2D viewport coordinates.
37316 ViewportCoords.prototype.canvasToViewport = function (canvasX, canvasY, container) {
37317 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
37318 var viewportX = 2 * canvasX / canvasWidth - 1;
37319 var viewportY = 1 - 2 * canvasY / canvasHeight;
37320 return [viewportX, viewportY];
37323 * Determines the width and height of the container in canvas coordinates.
37325 * @param {HTMLElement} container - The viewer container.
37326 * @returns {Array<number>} 2D canvas coordinates.
37328 ViewportCoords.prototype.containerToCanvas = function (container) {
37329 return [container.offsetWidth, container.offsetHeight];
37332 * Determine basic distances from image to canvas corners.
37334 * @description Transform origin and camera position needs to be the
37335 * equal for reliable return value.
37337 * Determines the smallest basic distance for every side of the canvas.
37339 * @param {Transform} transform - Transform of the node to unproject from.
37340 * @param {THREE.Camera} camera - Camera used in rendering.
37341 * @returns {Array<number>} Array of basic distances as [top, right, bottom, left].
37343 ViewportCoords.prototype.getBasicDistances = function (transform, camera) {
37344 var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
37345 var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
37346 var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
37347 var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
37348 var topBasicDistance = 0;
37349 var rightBasicDistance = 0;
37350 var bottomBasicDistance = 0;
37351 var leftBasicDistance = 0;
37352 if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
37353 topBasicDistance = topLeftBasic[1] > topRightBasic[1] ?
37357 if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
37358 rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ?
37359 topRightBasic[0] - 1 :
37360 bottomRightBasic[0] - 1;
37362 if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
37363 bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ?
37364 bottomRightBasic[1] - 1 :
37365 bottomLeftBasic[1] - 1;
37367 if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
37368 leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ?
37369 -bottomLeftBasic[0] :
37372 return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance];
37375 * Determine pixel distances from image to canvas corners.
37377 * @description Transform origin and camera position needs to be the
37378 * equal for reliable return value.
37380 * Determines the smallest pixel distance for every side of the canvas.
37382 * @param {HTMLElement} container - The viewer container.
37383 * @param {Transform} transform - Transform of the node to unproject from.
37384 * @param {THREE.Camera} camera - Camera used in rendering.
37385 * @returns {Array<number>} Array of pixel distances as [top, right, bottom, left].
37387 ViewportCoords.prototype.getPixelDistances = function (container, transform, camera) {
37388 var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
37389 var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
37390 var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
37391 var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
37392 var topPixelDistance = 0;
37393 var rightPixelDistance = 0;
37394 var bottomPixelDistance = 0;
37395 var leftPixelDistance = 0;
37396 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
37397 if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
37398 var basicX = topLeftBasic[1] > topRightBasic[1] ?
37401 var canvas = this.basicToCanvas(basicX, 0, container, transform, camera);
37402 topPixelDistance = canvas[1] > 0 ? canvas[1] : 0;
37404 if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
37405 var basicY = topRightBasic[0] < bottomRightBasic[0] ?
37407 bottomRightBasic[1];
37408 var canvas = this.basicToCanvas(1, basicY, container, transform, camera);
37409 rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0;
37411 if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
37412 var basicX = bottomRightBasic[1] < bottomLeftBasic[1] ?
37413 bottomRightBasic[0] :
37414 bottomLeftBasic[0];
37415 var canvas = this.basicToCanvas(basicX, 1, container, transform, camera);
37416 bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0;
37418 if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
37419 var basicY = bottomLeftBasic[0] > topLeftBasic[0] ?
37420 bottomLeftBasic[1] :
37422 var canvas = this.basicToCanvas(0, basicY, container, transform, camera);
37423 leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0;
37425 return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance];
37428 * Determine if an event occured inside an element.
37430 * @param {Event} event - Event containing clientX and clientY properties.
37431 * @param {HTMLElement} element - HTML element.
37432 * @returns {boolean} Value indicating if the event occured inside the element or not.
37434 ViewportCoords.prototype.insideElement = function (event, element) {
37435 var clientRect = element.getBoundingClientRect();
37436 var minX = clientRect.left + element.clientLeft;
37437 var maxX = minX + element.clientWidth;
37438 var minY = clientRect.top + element.clientTop;
37439 var maxY = minY + element.clientHeight;
37440 return event.clientX > minX &&
37441 event.clientX < maxX &&
37442 event.clientY > minY &&
37443 event.clientY < maxY;
37446 * Project 3D world coordinates to canvas coordinates.
37448 * @param {Array<number>} point3D - 3D world coordinates.
37449 * @param {HTMLElement} container - The viewer container.
37450 * @param {THREE.Camera} camera - Camera used in rendering.
37451 * @returns {Array<number>} 2D canvas coordinates.
37453 ViewportCoords.prototype.projectToCanvas = function (point3d, container, camera) {
37454 var viewport = this.projectToViewport(point3d, camera);
37455 var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
37459 * Project 3D world coordinates to viewport coordinates.
37461 * @param {Array<number>} point3D - 3D world coordinates.
37462 * @param {THREE.Camera} camera - Camera used in rendering.
37463 * @returns {Array<number>} 2D viewport coordinates.
37465 ViewportCoords.prototype.projectToViewport = function (point3d, camera) {
37466 var viewport = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
37468 return [viewport.x, viewport.y];
37471 * Uproject canvas coordinates to 3D world coordinates.
37473 * @param {number} canvasX - Canvas X coordinate.
37474 * @param {number} canvasY - Canvas Y coordinate.
37475 * @param {HTMLElement} container - The viewer container.
37476 * @param {THREE.Camera} camera - Camera used in rendering.
37477 * @returns {Array<number>} 3D world coordinates.
37479 ViewportCoords.prototype.unprojectFromCanvas = function (canvasX, canvasY, container, camera) {
37480 var viewport = this.canvasToViewport(canvasX, canvasY, container);
37481 var point3d = this.unprojectFromViewport(viewport[0], viewport[1], camera);
37485 * Unproject viewport coordinates to 3D world coordinates.
37487 * @param {number} viewportX - Viewport X coordinate.
37488 * @param {number} viewportY - Viewport Y coordinate.
37489 * @param {THREE.Camera} camera - Camera used in rendering.
37490 * @returns {Array<number>} 3D world coordinates.
37492 ViewportCoords.prototype.unprojectFromViewport = function (viewportX, viewportY, camera) {
37493 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
37494 .unproject(camera);
37498 * Convert viewport coordinates to basic coordinates.
37500 * @description Transform origin and camera position needs to be the
37501 * equal for reliable return value.
37503 * @param {number} viewportX - Viewport X coordinate.
37504 * @param {number} viewportY - Viewport Y coordinate.
37505 * @param {Transform} transform - Transform of the node to unproject from.
37506 * @param {THREE.Camera} camera - Camera used in rendering.
37507 * @returns {Array<number>} 2D basic coordinates.
37509 ViewportCoords.prototype.viewportToBasic = function (viewportX, viewportY, transform, camera) {
37510 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
37513 var basic = transform.projectBasic(point3d);
37517 * Convert viewport coordinates to canvas coordinates.
37519 * @param {number} viewportX - Viewport X coordinate.
37520 * @param {number} viewportY - Viewport Y coordinate.
37521 * @param {HTMLElement} container - The viewer container.
37522 * @returns {Array<number>} 2D canvas coordinates.
37524 ViewportCoords.prototype.viewportToCanvas = function (viewportX, viewportY, container) {
37525 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
37526 var canvasX = canvasWidth * (viewportX + 1) / 2;
37527 var canvasY = -canvasHeight * (viewportY - 1) / 2;
37528 return [canvasX, canvasY];
37531 * Convert 3D world coordinates to 3D camera coordinates.
37533 * @param {number} point3D - 3D point in world coordinate system.
37534 * @param {THREE.Camera} camera - Camera used in rendering.
37535 * @returns {Array<number>} 3D camera coordinates.
37537 ViewportCoords.prototype.worldToCamera = function (point3d, camera) {
37538 var pointCamera = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
37539 .applyMatrix4(camera.matrixWorldInverse);
37540 return pointCamera.toArray();
37542 return ViewportCoords;
37544 exports.ViewportCoords = ViewportCoords;
37545 exports.default = ViewportCoords;
37547 },{"three":240}],395:[function(require,module,exports){
37549 Object.defineProperty(exports, "__esModule", { value: true });
37553 * @classdesc Represents a class for creating node filters. Implementation and
37554 * definitions based on https://github.com/mapbox/feature-filter.
37556 var FilterCreator = /** @class */ (function () {
37557 function FilterCreator() {
37560 * Create a filter from a filter expression.
37562 * @description The following filters are supported:
37579 * @param {FilterExpression} filter - Comparison, set membership or combinding filter
37581 * @returns {FilterFunction} Function taking a node and returning a boolean that
37582 * indicates whether the node passed the test or not.
37584 FilterCreator.prototype.createFilter = function (filter) {
37585 return new Function("node", "return " + this._compile(filter) + ";");
37587 FilterCreator.prototype._compile = function (filter) {
37588 if (filter == null || filter.length <= 1) {
37591 var operator = filter[0];
37592 var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) :
37593 operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) :
37594 operator === ">" ||
37595 operator === ">=" ||
37596 operator === "<" ||
37597 operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) :
37598 operator === "in" ?
37599 this._compileInOp(filter[1], filter.slice(2)) :
37600 operator === "!in" ?
37601 this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) :
37602 operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") :
37604 return "(" + operation + ")";
37606 FilterCreator.prototype._compare = function (a, b) {
37607 return a < b ? -1 : a > b ? 1 : 0;
37609 FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) {
37610 var left = this._compilePropertyReference(property);
37611 var right = JSON.stringify(value);
37612 return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right;
37614 FilterCreator.prototype._compileInOp = function (property, values) {
37615 var compare = this._compare;
37616 var left = JSON.stringify(values.sort(compare));
37617 var right = this._compilePropertyReference(property);
37618 return left + ".indexOf(" + right + ")!==-1";
37620 FilterCreator.prototype._compileLogicalOp = function (filters, operator) {
37621 var compile = this._compile.bind(this);
37622 return filters.map(compile).join(operator);
37624 FilterCreator.prototype._compileNegation = function (expression) {
37625 return "!(" + expression + ")";
37627 FilterCreator.prototype._compilePropertyReference = function (property) {
37628 return "node[" + JSON.stringify(property) + "]";
37630 return FilterCreator;
37632 exports.FilterCreator = FilterCreator;
37633 exports.default = FilterCreator;
37635 },{}],396:[function(require,module,exports){
37637 /// <reference path="../../typings/index.d.ts" />
37638 Object.defineProperty(exports, "__esModule", { value: true });
37639 var rbush = require("rbush");
37640 var Observable_1 = require("rxjs/Observable");
37641 var Subject_1 = require("rxjs/Subject");
37642 var Edge_1 = require("../Edge");
37643 var Error_1 = require("../Error");
37644 var Graph_1 = require("../Graph");
37648 * @classdesc Represents a graph of nodes with edges.
37650 var Graph = /** @class */ (function () {
37652 * Create a new graph instance.
37654 * @param {APIv3} [apiV3] - API instance for retrieving data.
37655 * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival.
37656 * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations.
37657 * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations.
37658 * @param {FilterCreator} [filterCreator] - Instance for filter creation.
37659 * @param {IGraphConfiguration} [configuration] - Configuration struct.
37661 function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator, configuration) {
37662 this._apiV3 = apiV3;
37663 this._cachedNodes = {};
37664 this._cachedNodeTiles = {};
37665 this._cachedSequenceNodes = {};
37666 this._cachedSpatialEdges = {};
37667 this._cachedTiles = {};
37668 this._cachingFill$ = {};
37669 this._cachingFull$ = {};
37670 this._cachingSequenceNodes$ = {};
37671 this._cachingSequences$ = {};
37672 this._cachingSpatialArea$ = {};
37673 this._cachingTiles$ = {};
37674 this._changed$ = new Subject_1.Subject();
37675 this._defaultAlt = 2;
37676 this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator();
37677 this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator();
37678 this._filter = this._filterCreator.createFilter(undefined);
37679 this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator();
37680 this._configuration = configuration != null ?
37684 maxUnusedNodes: 100,
37685 maxUnusedPreStoredNodes: 30,
37686 maxUnusedTiles: 20,
37689 this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lat", ".lon", ".lat", ".lon"]);
37690 this._nodeIndexTiles = {};
37691 this._nodeToTile = {};
37692 this._preStored = {};
37693 this._requiredNodeTiles = {};
37694 this._requiredSpatialArea = {};
37695 this._sequences = {};
37696 this._tilePrecision = 7;
37697 this._tileThreshold = 20;
37699 Object.defineProperty(Graph.prototype, "changed$", {
37703 * @returns {Observable<Graph>} Observable emitting
37704 * the graph every time it has changed.
37707 return this._changed$;
37713 * Caches the full node data for all images within a bounding
37716 * @description The node assets are not cached.
37718 * @param {ILatLon} sw - South west corner of bounding box.
37719 * @param {ILatLon} ne - North east corner of bounding box.
37720 * @returns {Observable<Graph>} Observable emitting the full
37721 * nodes in the bounding box.
37723 Graph.prototype.cacheBoundingBox$ = function (sw, ne) {
37725 var cacheTiles$ = this._graphCalculator.encodeHsFromBoundingBox(sw, ne)
37726 .filter(function (h) {
37727 return !(h in _this._cachedTiles);
37729 .map(function (h) {
37730 return h in _this._cachingTiles$ ?
37731 _this._cachingTiles$[h] :
37732 _this._cacheTile$(h);
37734 if (cacheTiles$.length === 0) {
37735 cacheTiles$.push(Observable_1.Observable.of(this));
37737 return Observable_1.Observable
37741 .mergeMap(function (graph) {
37742 var nodes = _this._nodeIndex
37749 .map(function (item) {
37752 var fullNodes = [];
37753 var coreNodes = [];
37754 for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
37755 var node = nodes_1[_i];
37757 fullNodes.push(node);
37760 coreNodes.push(node.key);
37763 var coreNodeBatches = [];
37764 var batchSize = 200;
37765 while (coreNodes.length > 0) {
37766 coreNodeBatches.push(coreNodes.splice(0, batchSize));
37768 var fullNodes$ = Observable_1.Observable.of(fullNodes);
37769 var fillNodes$ = coreNodeBatches
37770 .map(function (batch) {
37771 return _this._apiV3.imageByKeyFill$(batch)
37772 .map(function (imageByKeyFill) {
37773 var filledNodes = [];
37774 for (var fillKey in imageByKeyFill) {
37775 if (!imageByKeyFill.hasOwnProperty(fillKey)) {
37778 if (_this.hasNode(fillKey)) {
37779 var node = _this.getNode(fillKey);
37781 _this._makeFull(node, imageByKeyFill[fillKey]);
37783 filledNodes.push(node);
37786 return filledNodes;
37789 return Observable_1.Observable
37790 .merge(fullNodes$, Observable_1.Observable
37794 .reduce(function (acc, value) {
37795 return acc.concat(value);
37799 * Retrieve and cache node fill properties.
37801 * @param {string} key - Key of node to fill.
37802 * @returns {Observable<Graph>} Observable emitting the graph
37803 * when the node has been updated.
37804 * @throws {GraphMapillaryError} When the operation is not valid on the
37807 Graph.prototype.cacheFill$ = function (key) {
37809 if (key in this._cachingFull$) {
37810 throw new Error_1.GraphMapillaryError("Cannot fill node while caching full (" + key + ").");
37812 if (!this.hasNode(key)) {
37813 throw new Error_1.GraphMapillaryError("Cannot fill node that does not exist in graph (" + key + ").");
37815 if (key in this._cachingFill$) {
37816 return this._cachingFill$[key];
37818 var node = this.getNode(key);
37820 throw new Error_1.GraphMapillaryError("Cannot fill node that is already full (" + key + ").");
37822 this._cachingFill$[key] = this._apiV3.imageByKeyFill$([key])
37823 .do(function (imageByKeyFill) {
37825 _this._makeFull(node, imageByKeyFill[key]);
37827 delete _this._cachingFill$[key];
37829 .map(function (imageByKeyFill) {
37832 .finally(function () {
37833 if (key in _this._cachingFill$) {
37834 delete _this._cachingFill$[key];
37836 _this._changed$.next(_this);
37840 return this._cachingFill$[key];
37843 * Retrieve and cache full node properties.
37845 * @param {string} key - Key of node to fill.
37846 * @returns {Observable<Graph>} Observable emitting the graph
37847 * when the node has been updated.
37848 * @throws {GraphMapillaryError} When the operation is not valid on the
37851 Graph.prototype.cacheFull$ = function (key) {
37853 if (key in this._cachingFull$) {
37854 return this._cachingFull$[key];
37856 if (this.hasNode(key)) {
37857 throw new Error_1.GraphMapillaryError("Cannot cache full node that already exist in graph (" + key + ").");
37859 this._cachingFull$[key] = this._apiV3.imageByKeyFull$([key])
37860 .do(function (imageByKeyFull) {
37861 var fn = imageByKeyFull[key];
37862 if (_this.hasNode(key)) {
37863 var node = _this.getNode(key);
37865 _this._makeFull(node, fn);
37869 if (fn.sequence_key == null) {
37870 throw new Error_1.GraphMapillaryError("Node has no sequence key (" + key + ").");
37872 var node = new Graph_1.Node(fn);
37873 _this._makeFull(node, fn);
37874 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
37875 _this._preStore(h, node);
37876 _this._setNode(node);
37877 delete _this._cachingFull$[key];
37880 .map(function (imageByKeyFull) {
37883 .finally(function () {
37884 if (key in _this._cachingFull$) {
37885 delete _this._cachingFull$[key];
37887 _this._changed$.next(_this);
37891 return this._cachingFull$[key];
37894 * Retrieve and cache a node sequence.
37896 * @param {string} key - Key of node for which to retrieve sequence.
37897 * @returns {Observable<Graph>} Observable emitting the graph
37898 * when the sequence has been retrieved.
37899 * @throws {GraphMapillaryError} When the operation is not valid on the
37902 Graph.prototype.cacheNodeSequence$ = function (key) {
37903 if (!this.hasNode(key)) {
37904 throw new Error_1.GraphMapillaryError("Cannot cache sequence edges of node that does not exist in graph (" + key + ").");
37906 var node = this.getNode(key);
37907 if (node.sequenceKey in this._sequences) {
37908 throw new Error_1.GraphMapillaryError("Sequence already cached (" + key + "), (" + node.sequenceKey + ").");
37910 return this._cacheSequence$(node.sequenceKey);
37913 * Retrieve and cache a sequence.
37915 * @param {string} sequenceKey - Key of sequence to cache.
37916 * @returns {Observable<Graph>} Observable emitting the graph
37917 * when the sequence has been retrieved.
37918 * @throws {GraphMapillaryError} When the operation is not valid on the
37921 Graph.prototype.cacheSequence$ = function (sequenceKey) {
37922 if (sequenceKey in this._sequences) {
37923 throw new Error_1.GraphMapillaryError("Sequence already cached (" + sequenceKey + ")");
37925 return this._cacheSequence$(sequenceKey);
37928 * Cache sequence edges for a node.
37930 * @param {string} key - Key of node.
37931 * @throws {GraphMapillaryError} When the operation is not valid on the
37934 Graph.prototype.cacheSequenceEdges = function (key) {
37935 var node = this.getNode(key);
37936 if (!(node.sequenceKey in this._sequences)) {
37937 throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")");
37939 var sequence = this._sequences[node.sequenceKey].sequence;
37940 var edges = this._edgeCalculator.computeSequenceEdges(node, sequence);
37941 node.cacheSequenceEdges(edges);
37944 * Retrieve and cache full nodes for all keys in a sequence.
37946 * @param {string} sequenceKey - Key of sequence.
37947 * @param {string} referenceNodeKey - Key of node to use as reference
37948 * for optimized caching.
37949 * @returns {Observable<Graph>} Observable emitting the graph
37950 * when the nodes of the sequence has been cached.
37952 Graph.prototype.cacheSequenceNodes$ = function (sequenceKey, referenceNodeKey) {
37954 if (!this.hasSequence(sequenceKey)) {
37955 throw new Error_1.GraphMapillaryError("Cannot cache sequence nodes of sequence that does not exist in graph (" + sequenceKey + ").");
37957 if (this.hasSequenceNodes(sequenceKey)) {
37958 throw new Error_1.GraphMapillaryError("Sequence nodes already cached (" + sequenceKey + ").");
37960 var sequence = this.getSequence(sequenceKey);
37961 if (sequence.key in this._cachingSequenceNodes$) {
37962 return this._cachingSequenceNodes$[sequence.key];
37965 var keys = sequence.keys.slice();
37966 var referenceBatchSize = 50;
37967 if (!!referenceNodeKey && keys.length > referenceBatchSize) {
37968 var referenceIndex = keys.indexOf(referenceNodeKey);
37969 var startIndex = Math.max(0, Math.min(referenceIndex - referenceBatchSize / 2, keys.length - referenceBatchSize));
37970 batches.push(keys.splice(startIndex, referenceBatchSize));
37972 var batchSize = 200;
37973 while (keys.length > 0) {
37974 batches.push(keys.splice(0, batchSize));
37976 var batchesToCache = batches.length;
37977 var sequenceNodes$ = Observable_1.Observable
37979 .mergeMap(function (batch) {
37980 return _this._apiV3.imageByKeyFull$(batch)
37981 .do(function (imageByKeyFull) {
37982 for (var fullKey in imageByKeyFull) {
37983 if (!imageByKeyFull.hasOwnProperty(fullKey)) {
37986 var fn = imageByKeyFull[fullKey];
37987 if (_this.hasNode(fullKey)) {
37988 var node = _this.getNode(fn.key);
37990 _this._makeFull(node, fn);
37994 if (fn.sequence_key == null) {
37995 console.warn("Sequence missing, discarding node (" + fn.key + ")");
37997 var node = new Graph_1.Node(fn);
37998 _this._makeFull(node, fn);
37999 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
38000 _this._preStore(h, node);
38001 _this._setNode(node);
38006 .map(function (imageByKeyFull) {
38011 .finally(function () {
38012 delete _this._cachingSequenceNodes$[sequence.key];
38013 if (batchesToCache === 0) {
38014 _this._cachedSequenceNodes[sequence.key] = true;
38019 this._cachingSequenceNodes$[sequence.key] = sequenceNodes$;
38020 return sequenceNodes$;
38023 * Retrieve and cache full nodes for a node spatial area.
38025 * @param {string} key - Key of node for which to retrieve sequence.
38026 * @returns {Observable<Graph>} Observable emitting the graph
38027 * when the nodes in the spatial area has been made full.
38028 * @throws {GraphMapillaryError} When the operation is not valid on the
38031 Graph.prototype.cacheSpatialArea$ = function (key) {
38033 if (!this.hasNode(key)) {
38034 throw new Error_1.GraphMapillaryError("Cannot cache spatial area of node that does not exist in graph (" + key + ").");
38036 if (key in this._cachedSpatialEdges) {
38037 throw new Error_1.GraphMapillaryError("Node already spatially cached (" + key + ").");
38039 if (!(key in this._requiredSpatialArea)) {
38040 throw new Error_1.GraphMapillaryError("Spatial area not determined (" + key + ").");
38042 var spatialArea = this._requiredSpatialArea[key];
38043 if (Object.keys(spatialArea.cacheNodes).length === 0) {
38044 throw new Error_1.GraphMapillaryError("Spatial nodes already cached (" + key + ").");
38046 if (key in this._cachingSpatialArea$) {
38047 return this._cachingSpatialArea$[key];
38050 while (spatialArea.cacheKeys.length > 0) {
38051 batches.push(spatialArea.cacheKeys.splice(0, 200));
38053 var batchesToCache = batches.length;
38054 var spatialNodes$ = [];
38055 var _loop_1 = function (batch) {
38056 var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch)
38057 .do(function (imageByKeyFill) {
38058 for (var fillKey in imageByKeyFill) {
38059 if (!imageByKeyFill.hasOwnProperty(fillKey)) {
38062 var spatialNode = spatialArea.cacheNodes[fillKey];
38063 if (spatialNode.full) {
38064 delete spatialArea.cacheNodes[fillKey];
38067 var fillNode = imageByKeyFill[fillKey];
38068 _this._makeFull(spatialNode, fillNode);
38069 delete spatialArea.cacheNodes[fillKey];
38071 if (--batchesToCache === 0) {
38072 delete _this._cachingSpatialArea$[key];
38075 .map(function (imageByKeyFill) {
38078 .catch(function (error) {
38079 for (var _i = 0, batch_1 = batch; _i < batch_1.length; _i++) {
38080 var batchKey = batch_1[_i];
38081 if (batchKey in spatialArea.all) {
38082 delete spatialArea.all[batchKey];
38084 if (batchKey in spatialArea.cacheNodes) {
38085 delete spatialArea.cacheNodes[batchKey];
38088 if (--batchesToCache === 0) {
38089 delete _this._cachingSpatialArea$[key];
38093 .finally(function () {
38094 if (Object.keys(spatialArea.cacheNodes).length === 0) {
38095 _this._changed$.next(_this);
38100 spatialNodes$.push(spatialNodeBatch$);
38103 for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {
38104 var batch = batches_1[_i];
38107 this._cachingSpatialArea$[key] = spatialNodes$;
38108 return spatialNodes$;
38111 * Cache spatial edges for a node.
38113 * @param {string} key - Key of node.
38114 * @throws {GraphMapillaryError} When the operation is not valid on the
38117 Graph.prototype.cacheSpatialEdges = function (key) {
38118 if (key in this._cachedSpatialEdges) {
38119 throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ").");
38121 var node = this.getNode(key);
38122 var sequence = this._sequences[node.sequenceKey].sequence;
38123 var fallbackKeys = [];
38124 var prevKey = sequence.findPrevKey(node.key);
38125 if (prevKey != null) {
38126 fallbackKeys.push(prevKey);
38128 var nextKey = sequence.findNextKey(node.key);
38129 if (nextKey != null) {
38130 fallbackKeys.push(nextKey);
38132 var allSpatialNodes = this._requiredSpatialArea[key].all;
38133 var potentialNodes = [];
38134 var filter = this._filter;
38135 for (var spatialNodeKey in allSpatialNodes) {
38136 if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) {
38139 var spatialNode = allSpatialNodes[spatialNodeKey];
38140 if (filter(spatialNode)) {
38141 potentialNodes.push(spatialNode);
38144 var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys);
38145 var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey);
38146 edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges));
38147 edges = edges.concat(this._edgeCalculator.computePanoEdges(node, potentialEdges));
38148 edges = edges.concat(this._edgeCalculator.computePerspectiveToPanoEdges(node, potentialEdges));
38149 edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges));
38150 node.cacheSpatialEdges(edges);
38151 this._cachedSpatialEdges[key] = node;
38152 delete this._requiredSpatialArea[key];
38153 delete this._cachedNodeTiles[key];
38156 * Retrieve and cache geohash tiles for a node.
38158 * @param {string} key - Key of node for which to retrieve tiles.
38159 * @returns {Array<Observable<Graph>>} Array of observables emitting
38160 * the graph for each tile required for the node has been cached.
38161 * @throws {GraphMapillaryError} When the operation is not valid on the
38164 Graph.prototype.cacheTiles$ = function (key) {
38166 if (key in this._cachedNodeTiles) {
38167 throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
38169 if (key in this._cachedSpatialEdges) {
38170 throw new Error_1.GraphMapillaryError("Spatial edges already cached so tiles considered cached (" + key + ").");
38172 if (!(key in this._requiredNodeTiles)) {
38173 throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ").");
38175 var nodeTiles = this._requiredNodeTiles[key];
38176 if (nodeTiles.cache.length === 0 &&
38177 nodeTiles.caching.length === 0) {
38178 throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
38180 if (!this.hasNode(key)) {
38181 throw new Error_1.GraphMapillaryError("Cannot cache tiles of node that does not exist in graph (" + key + ").");
38183 var hs = nodeTiles.cache.slice();
38184 nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs);
38185 nodeTiles.cache = [];
38186 var cacheTiles$ = [];
38187 var _loop_2 = function (h) {
38188 var cacheTile$ = h in this_2._cachingTiles$ ?
38189 this_2._cachingTiles$[h] :
38190 this_2._cacheTile$(h);
38191 cacheTiles$.push(cacheTile$
38192 .do(function (graph) {
38193 var index = nodeTiles.caching.indexOf(h);
38195 nodeTiles.caching.splice(index, 1);
38197 if (nodeTiles.caching.length === 0 &&
38198 nodeTiles.cache.length === 0) {
38199 delete _this._requiredNodeTiles[key];
38200 _this._cachedNodeTiles[key] = true;
38203 .catch(function (error) {
38204 var index = nodeTiles.caching.indexOf(h);
38206 nodeTiles.caching.splice(index, 1);
38208 if (nodeTiles.caching.length === 0 &&
38209 nodeTiles.cache.length === 0) {
38210 delete _this._requiredNodeTiles[key];
38211 _this._cachedNodeTiles[key] = true;
38215 .finally(function () {
38216 _this._changed$.next(_this);
38222 for (var _i = 0, _a = nodeTiles.caching; _i < _a.length; _i++) {
38226 return cacheTiles$;
38229 * Initialize the cache for a node.
38231 * @param {string} key - Key of node.
38232 * @throws {GraphMapillaryError} When the operation is not valid on the
38235 Graph.prototype.initializeCache = function (key) {
38236 if (key in this._cachedNodes) {
38237 throw new Error_1.GraphMapillaryError("Node already in cache (" + key + ").");
38239 var node = this.getNode(key);
38240 node.initializeCache(new Graph_1.NodeCache());
38241 var accessed = new Date().getTime();
38242 this._cachedNodes[key] = { accessed: accessed, node: node };
38243 this._updateCachedTileAccess(key, accessed);
38246 * Get a value indicating if the graph is fill caching a node.
38248 * @param {string} key - Key of node.
38249 * @returns {boolean} Value indicating if the node is being fill cached.
38251 Graph.prototype.isCachingFill = function (key) {
38252 return key in this._cachingFill$;
38255 * Get a value indicating if the graph is fully caching a node.
38257 * @param {string} key - Key of node.
38258 * @returns {boolean} Value indicating if the node is being fully cached.
38260 Graph.prototype.isCachingFull = function (key) {
38261 return key in this._cachingFull$;
38264 * Get a value indicating if the graph is caching a sequence of a node.
38266 * @param {string} key - Key of node.
38267 * @returns {boolean} Value indicating if the sequence of a node is
38270 Graph.prototype.isCachingNodeSequence = function (key) {
38271 var node = this.getNode(key);
38272 return node.sequenceKey in this._cachingSequences$;
38275 * Get a value indicating if the graph is caching a sequence.
38277 * @param {string} sequenceKey - Key of sequence.
38278 * @returns {boolean} Value indicating if the sequence is
38281 Graph.prototype.isCachingSequence = function (sequenceKey) {
38282 return sequenceKey in this._cachingSequences$;
38285 * Get a value indicating if the graph is caching sequence nodes.
38287 * @param {string} sequenceKey - Key of sequence.
38288 * @returns {boolean} Value indicating if the sequence nodes are
38291 Graph.prototype.isCachingSequenceNodes = function (sequenceKey) {
38292 return sequenceKey in this._cachingSequenceNodes$;
38295 * Get a value indicating if the graph is caching the tiles
38296 * required for calculating spatial edges of a node.
38298 * @param {string} key - Key of node.
38299 * @returns {boolean} Value indicating if the tiles of
38300 * a node are being cached.
38302 Graph.prototype.isCachingTiles = function (key) {
38303 return key in this._requiredNodeTiles &&
38304 this._requiredNodeTiles[key].cache.length === 0 &&
38305 this._requiredNodeTiles[key].caching.length > 0;
38308 * Get a value indicating if the cache has been initialized
38311 * @param {string} key - Key of node.
38312 * @returns {boolean} Value indicating if the cache has been
38313 * initialized for a node.
38315 Graph.prototype.hasInitializedCache = function (key) {
38316 return key in this._cachedNodes;
38319 * Get a value indicating if a node exist in the graph.
38321 * @param {string} key - Key of node.
38322 * @returns {boolean} Value indicating if a node exist in the graph.
38324 Graph.prototype.hasNode = function (key) {
38325 var accessed = new Date().getTime();
38326 this._updateCachedNodeAccess(key, accessed);
38327 this._updateCachedTileAccess(key, accessed);
38328 return key in this._nodes;
38331 * Get a value indicating if a node sequence exist in the graph.
38333 * @param {string} key - Key of node.
38334 * @returns {boolean} Value indicating if a node sequence exist
38337 Graph.prototype.hasNodeSequence = function (key) {
38338 var node = this.getNode(key);
38339 var sequenceKey = node.sequenceKey;
38340 var hasNodeSequence = sequenceKey in this._sequences;
38341 if (hasNodeSequence) {
38342 this._sequences[sequenceKey].accessed = new Date().getTime();
38344 return hasNodeSequence;
38347 * Get a value indicating if a sequence exist in the graph.
38349 * @param {string} sequenceKey - Key of sequence.
38350 * @returns {boolean} Value indicating if a sequence exist
38353 Graph.prototype.hasSequence = function (sequenceKey) {
38354 var hasSequence = sequenceKey in this._sequences;
38356 this._sequences[sequenceKey].accessed = new Date().getTime();
38358 return hasSequence;
38361 * Get a value indicating if sequence nodes has been cached in the graph.
38363 * @param {string} sequenceKey - Key of sequence.
38364 * @returns {boolean} Value indicating if a sequence nodes has been
38365 * cached in the graph.
38367 Graph.prototype.hasSequenceNodes = function (sequenceKey) {
38368 return sequenceKey in this._cachedSequenceNodes;
38371 * Get a value indicating if the graph has fully cached
38372 * all nodes in the spatial area of a node.
38374 * @param {string} key - Key of node.
38375 * @returns {boolean} Value indicating if the spatial area
38376 * of a node has been cached.
38378 Graph.prototype.hasSpatialArea = function (key) {
38379 if (!this.hasNode(key)) {
38380 throw new Error_1.GraphMapillaryError("Spatial area nodes cannot be determined if node not in graph (" + key + ").");
38382 if (key in this._cachedSpatialEdges) {
38385 if (key in this._requiredSpatialArea) {
38386 return Object.keys(this._requiredSpatialArea[key].cacheNodes).length === 0;
38388 var node = this.getNode(key);
38389 var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold);
38390 var spatialItems = this._nodeIndex.search({
38396 var spatialNodes = {
38401 for (var _i = 0, spatialItems_1 = spatialItems; _i < spatialItems_1.length; _i++) {
38402 var spatialItem = spatialItems_1[_i];
38403 spatialNodes.all[spatialItem.node.key] = spatialItem.node;
38404 if (!spatialItem.node.full) {
38405 spatialNodes.cacheKeys.push(spatialItem.node.key);
38406 spatialNodes.cacheNodes[spatialItem.node.key] = spatialItem.node;
38409 this._requiredSpatialArea[key] = spatialNodes;
38410 return spatialNodes.cacheKeys.length === 0;
38413 * Get a value indicating if the graph has a tiles required
38416 * @param {string} key - Key of node.
38417 * @returns {boolean} Value indicating if the the tiles required
38418 * by a node has been cached.
38420 Graph.prototype.hasTiles = function (key) {
38422 if (key in this._cachedNodeTiles) {
38425 if (key in this._cachedSpatialEdges) {
38428 if (!this.hasNode(key)) {
38429 throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ").");
38431 var nodeTiles = { cache: [], caching: [] };
38432 if (!(key in this._requiredNodeTiles)) {
38433 var node = this.getNode(key);
38434 nodeTiles.cache = this._graphCalculator
38435 .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold)
38436 .filter(function (h) {
38437 return !(h in _this._cachedTiles);
38439 if (nodeTiles.cache.length > 0) {
38440 this._requiredNodeTiles[key] = nodeTiles;
38444 nodeTiles = this._requiredNodeTiles[key];
38446 return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0;
38451 * @param {string} key - Key of node.
38452 * @returns {Node} Retrieved node.
38454 Graph.prototype.getNode = function (key) {
38455 var accessed = new Date().getTime();
38456 this._updateCachedNodeAccess(key, accessed);
38457 this._updateCachedTileAccess(key, accessed);
38458 return this._nodes[key];
38463 * @param {string} sequenceKey - Key of sequence.
38464 * @returns {Node} Retrieved sequence.
38466 Graph.prototype.getSequence = function (sequenceKey) {
38467 var sequenceAccess = this._sequences[sequenceKey];
38468 sequenceAccess.accessed = new Date().getTime();
38469 return sequenceAccess.sequence;
38472 * Reset all spatial edges of the graph nodes.
38474 Graph.prototype.resetSpatialEdges = function () {
38475 var cachedKeys = Object.keys(this._cachedSpatialEdges);
38476 for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) {
38477 var cachedKey = cachedKeys_1[_i];
38478 var node = this._cachedSpatialEdges[cachedKey];
38479 node.resetSpatialEdges();
38480 delete this._cachedSpatialEdges[cachedKey];
38484 * Reset the complete graph but keep the nodes corresponding
38485 * to the supplied keys. All other nodes will be disposed.
38487 * @param {Array<string>} keepKeys - Keys for nodes to keep
38488 * in graph after reset.
38490 Graph.prototype.reset = function (keepKeys) {
38492 for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) {
38493 var key = keepKeys_1[_i];
38494 if (!this.hasNode(key)) {
38495 throw new Error("Node does not exist " + key);
38497 var node = this.getNode(key);
38498 node.resetSequenceEdges();
38499 node.resetSpatialEdges();
38502 for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) {
38503 var cachedKey = _b[_a];
38504 if (keepKeys.indexOf(cachedKey) !== -1) {
38507 this._cachedNodes[cachedKey].node.dispose();
38508 delete this._cachedNodes[cachedKey];
38510 this._cachedNodeTiles = {};
38511 this._cachedSpatialEdges = {};
38512 this._cachedTiles = {};
38513 this._cachingFill$ = {};
38514 this._cachingFull$ = {};
38515 this._cachingSequences$ = {};
38516 this._cachingSpatialArea$ = {};
38517 this._cachingTiles$ = {};
38519 this._nodeToTile = {};
38520 this._preStored = {};
38521 for (var _c = 0, nodes_2 = nodes; _c < nodes_2.length; _c++) {
38522 var node = nodes_2[_c];
38523 this._nodes[node.key] = node;
38524 var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision);
38525 this._preStore(h, node);
38527 this._requiredNodeTiles = {};
38528 this._requiredSpatialArea = {};
38529 this._sequences = {};
38530 this._nodeIndexTiles = {};
38531 this._nodeIndex.clear();
38534 * Set the spatial node filter.
38536 * @param {FilterExpression} filter - Filter expression to be applied
38537 * when calculating spatial edges.
38539 Graph.prototype.setFilter = function (filter) {
38540 this._filter = this._filterCreator.createFilter(filter);
38543 * Uncache the graph according to the graph configuration.
38545 * @description Uncaches unused tiles, unused nodes and
38546 * sequences according to the numbers specified in the
38547 * graph configuration. Sequences does not have a direct
38548 * reference to either tiles or nodes and may be uncached
38549 * even if they are related to the nodes that should be kept.
38551 * @param {Array<string>} keepKeys - Keys of nodes to keep in
38552 * graph unrelated to last access. Tiles related to those keys
38553 * will also be kept in graph.
38554 * @param {string} keepSequenceKey - Optional key of sequence
38555 * for which the belonging nodes should not be disposed or
38556 * removed from the graph. These nodes may still be uncached if
38557 * not specified in keep keys param.
38559 Graph.prototype.uncache = function (keepKeys, keepSequenceKey) {
38560 var keysInUse = {};
38561 this._addNewKeys(keysInUse, this._cachingFull$);
38562 this._addNewKeys(keysInUse, this._cachingFill$);
38563 this._addNewKeys(keysInUse, this._cachingSpatialArea$);
38564 this._addNewKeys(keysInUse, this._requiredNodeTiles);
38565 this._addNewKeys(keysInUse, this._requiredSpatialArea);
38566 for (var _i = 0, keepKeys_2 = keepKeys; _i < keepKeys_2.length; _i++) {
38567 var key = keepKeys_2[_i];
38568 if (key in keysInUse) {
38571 keysInUse[key] = true;
38574 for (var key in keysInUse) {
38575 if (!keysInUse.hasOwnProperty(key)) {
38578 var node = this._nodes[key];
38579 var nodeHs = this._graphCalculator.encodeHs(node.latLon);
38580 for (var _a = 0, nodeHs_1 = nodeHs; _a < nodeHs_1.length; _a++) {
38581 var nodeH = nodeHs_1[_a];
38582 if (!(nodeH in keepHs)) {
38583 keepHs[nodeH] = true;
38587 var potentialHs = [];
38588 for (var h in this._cachedTiles) {
38589 if (!this._cachedTiles.hasOwnProperty(h) || h in keepHs) {
38592 potentialHs.push([h, this._cachedTiles[h]]);
38594 var uncacheHs = potentialHs
38595 .sort(function (h1, h2) {
38596 return h2[1].accessed - h1[1].accessed;
38598 .slice(this._configuration.maxUnusedTiles)
38599 .map(function (h) {
38602 for (var _b = 0, uncacheHs_1 = uncacheHs; _b < uncacheHs_1.length; _b++) {
38603 var uncacheH = uncacheHs_1[_b];
38604 this._uncacheTile(uncacheH, keepSequenceKey);
38606 var potentialPreStored = [];
38607 var nonCachedPreStored = [];
38608 for (var h in this._preStored) {
38609 if (!this._preStored.hasOwnProperty(h) || h in this._cachingTiles$) {
38612 var prestoredNodes = this._preStored[h];
38613 for (var key in prestoredNodes) {
38614 if (!prestoredNodes.hasOwnProperty(key) || key in keysInUse) {
38617 if (prestoredNodes[key].sequenceKey === keepSequenceKey) {
38620 if (key in this._cachedNodes) {
38621 potentialPreStored.push([this._cachedNodes[key], h]);
38624 nonCachedPreStored.push([key, h]);
38628 var uncachePreStored = potentialPreStored
38629 .sort(function (_a, _b) {
38630 var na1 = _a[0], h1 = _a[1];
38631 var na2 = _b[0], h2 = _b[1];
38632 return na2.accessed - na1.accessed;
38634 .slice(this._configuration.maxUnusedPreStoredNodes)
38635 .map(function (_a) {
38636 var na = _a[0], h = _a[1];
38637 return [na.node.key, h];
38639 this._uncachePreStored(nonCachedPreStored);
38640 this._uncachePreStored(uncachePreStored);
38641 var potentialNodes = [];
38642 for (var key in this._cachedNodes) {
38643 if (!this._cachedNodes.hasOwnProperty(key) || key in keysInUse) {
38646 potentialNodes.push(this._cachedNodes[key]);
38648 var uncacheNodes = potentialNodes
38649 .sort(function (n1, n2) {
38650 return n2.accessed - n1.accessed;
38652 .slice(this._configuration.maxUnusedNodes);
38653 for (var _c = 0, uncacheNodes_1 = uncacheNodes; _c < uncacheNodes_1.length; _c++) {
38654 var nodeAccess = uncacheNodes_1[_c];
38655 nodeAccess.node.uncache();
38656 var key = nodeAccess.node.key;
38657 delete this._cachedNodes[key];
38658 if (key in this._cachedNodeTiles) {
38659 delete this._cachedNodeTiles[key];
38661 if (key in this._cachedSpatialEdges) {
38662 delete this._cachedSpatialEdges[key];
38665 var potentialSequences = [];
38666 for (var sequenceKey in this._sequences) {
38667 if (!this._sequences.hasOwnProperty(sequenceKey) ||
38668 sequenceKey in this._cachingSequences$ ||
38669 sequenceKey === keepSequenceKey) {
38672 potentialSequences.push(this._sequences[sequenceKey]);
38674 var uncacheSequences = potentialSequences
38675 .sort(function (s1, s2) {
38676 return s2.accessed - s1.accessed;
38678 .slice(this._configuration.maxSequences);
38679 for (var _d = 0, uncacheSequences_1 = uncacheSequences; _d < uncacheSequences_1.length; _d++) {
38680 var sequenceAccess = uncacheSequences_1[_d];
38681 var sequenceKey = sequenceAccess.sequence.key;
38682 delete this._sequences[sequenceKey];
38683 if (sequenceKey in this._cachedSequenceNodes) {
38684 delete this._cachedSequenceNodes[sequenceKey];
38686 sequenceAccess.sequence.dispose();
38689 Graph.prototype._addNewKeys = function (keys, dict) {
38690 for (var key in dict) {
38691 if (!dict.hasOwnProperty(key) || !this.hasNode(key)) {
38694 if (!(key in keys)) {
38699 Graph.prototype._cacheSequence$ = function (sequenceKey) {
38701 if (sequenceKey in this._cachingSequences$) {
38702 return this._cachingSequences$[sequenceKey];
38704 this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey])
38705 .do(function (sequenceByKey) {
38706 if (!(sequenceKey in _this._sequences)) {
38707 _this._sequences[sequenceKey] = {
38708 accessed: new Date().getTime(),
38709 sequence: new Graph_1.Sequence(sequenceByKey[sequenceKey]),
38712 delete _this._cachingSequences$[sequenceKey];
38714 .map(function (sequenceByKey) {
38717 .finally(function () {
38718 if (sequenceKey in _this._cachingSequences$) {
38719 delete _this._cachingSequences$[sequenceKey];
38721 _this._changed$.next(_this);
38725 return this._cachingSequences$[sequenceKey];
38727 Graph.prototype._cacheTile$ = function (h) {
38729 this._cachingTiles$[h] = this._apiV3.imagesByH$([h])
38730 .do(function (imagesByH) {
38731 var coreNodes = imagesByH[h];
38732 if (h in _this._cachedTiles) {
38735 _this._nodeIndexTiles[h] = [];
38736 _this._cachedTiles[h] = { accessed: new Date().getTime(), nodes: [] };
38737 var hCache = _this._cachedTiles[h].nodes;
38738 var preStored = _this._removeFromPreStore(h);
38739 for (var index in coreNodes) {
38740 if (!coreNodes.hasOwnProperty(index)) {
38743 var coreNode = coreNodes[index];
38744 if (coreNode == null) {
38747 if (coreNode.sequence_key == null) {
38748 console.warn("Sequence missing, discarding node (" + coreNode.key + ")");
38751 if (preStored != null && coreNode.key in preStored) {
38752 var preStoredNode = preStored[coreNode.key];
38753 delete preStored[coreNode.key];
38754 hCache.push(preStoredNode);
38755 var preStoredNodeIndexItem = {
38756 lat: preStoredNode.latLon.lat,
38757 lon: preStoredNode.latLon.lon,
38758 node: preStoredNode,
38760 _this._nodeIndex.insert(preStoredNodeIndexItem);
38761 _this._nodeIndexTiles[h].push(preStoredNodeIndexItem);
38762 _this._nodeToTile[preStoredNode.key] = h;
38765 var node = new Graph_1.Node(coreNode);
38767 var nodeIndexItem = {
38768 lat: node.latLon.lat,
38769 lon: node.latLon.lon,
38772 _this._nodeIndex.insert(nodeIndexItem);
38773 _this._nodeIndexTiles[h].push(nodeIndexItem);
38774 _this._nodeToTile[node.key] = h;
38775 _this._setNode(node);
38777 delete _this._cachingTiles$[h];
38779 .map(function (imagesByH) {
38782 .catch(function (error) {
38783 delete _this._cachingTiles$[h];
38788 return this._cachingTiles$[h];
38790 Graph.prototype._makeFull = function (node, fillNode) {
38791 if (fillNode.calt == null) {
38792 fillNode.calt = this._defaultAlt;
38794 if (fillNode.c_rotation == null) {
38795 fillNode.c_rotation = this._graphCalculator.rotationFromCompass(fillNode.ca, fillNode.orientation);
38797 node.makeFull(fillNode);
38799 Graph.prototype._preStore = function (h, node) {
38800 if (!(h in this._preStored)) {
38801 this._preStored[h] = {};
38803 this._preStored[h][node.key] = node;
38805 Graph.prototype._removeFromPreStore = function (h) {
38806 var preStored = null;
38807 if (h in this._preStored) {
38808 preStored = this._preStored[h];
38809 delete this._preStored[h];
38813 Graph.prototype._setNode = function (node) {
38814 var key = node.key;
38815 if (this.hasNode(key)) {
38816 throw new Error_1.GraphMapillaryError("Node already exist (" + key + ").");
38818 this._nodes[key] = node;
38820 Graph.prototype._uncacheTile = function (h, keepSequenceKey) {
38821 for (var _i = 0, _a = this._cachedTiles[h].nodes; _i < _a.length; _i++) {
38823 var key = node.key;
38824 delete this._nodeToTile[key];
38825 if (key in this._cachedNodes) {
38826 delete this._cachedNodes[key];
38828 if (key in this._cachedNodeTiles) {
38829 delete this._cachedNodeTiles[key];
38831 if (key in this._cachedSpatialEdges) {
38832 delete this._cachedSpatialEdges[key];
38834 if (node.sequenceKey === keepSequenceKey) {
38835 this._preStore(h, node);
38839 delete this._nodes[key];
38840 if (node.sequenceKey in this._cachedSequenceNodes) {
38841 delete this._cachedSequenceNodes[node.sequenceKey];
38846 for (var _b = 0, _c = this._nodeIndexTiles[h]; _b < _c.length; _b++) {
38847 var nodeIndexItem = _c[_b];
38848 this._nodeIndex.remove(nodeIndexItem);
38850 delete this._nodeIndexTiles[h];
38851 delete this._cachedTiles[h];
38853 Graph.prototype._uncachePreStored = function (preStored) {
38855 for (var _i = 0, preStored_1 = preStored; _i < preStored_1.length; _i++) {
38856 var _a = preStored_1[_i], key = _a[0], h = _a[1];
38857 if (key in this._nodes) {
38858 delete this._nodes[key];
38860 if (key in this._cachedNodes) {
38861 delete this._cachedNodes[key];
38863 var node = this._preStored[h][key];
38864 if (node.sequenceKey in this._cachedSequenceNodes) {
38865 delete this._cachedSequenceNodes[node.sequenceKey];
38867 delete this._preStored[h][key];
38871 for (var h in hs) {
38872 if (!hs.hasOwnProperty(h)) {
38875 if (Object.keys(this._preStored[h]).length === 0) {
38876 delete this._preStored[h];
38880 Graph.prototype._updateCachedTileAccess = function (key, accessed) {
38881 if (key in this._nodeToTile) {
38882 this._cachedTiles[this._nodeToTile[key]].accessed = accessed;
38885 Graph.prototype._updateCachedNodeAccess = function (key, accessed) {
38886 if (key in this._cachedNodes) {
38887 this._cachedNodes[key].accessed = accessed;
38892 exports.Graph = Graph;
38893 exports.default = Graph;
38895 },{"../Edge":291,"../Error":292,"../Graph":294,"rbush":25,"rxjs/Observable":29,"rxjs/Subject":34}],397:[function(require,module,exports){
38897 /// <reference path="../../typings/index.d.ts" />
38898 Object.defineProperty(exports, "__esModule", { value: true });
38899 var geohash = require("latlon-geohash");
38900 var THREE = require("three");
38901 var Error_1 = require("../Error");
38902 var Geo_1 = require("../Geo");
38903 var GeoHashDirections = /** @class */ (function () {
38904 function GeoHashDirections() {
38906 GeoHashDirections.n = "n";
38907 GeoHashDirections.nw = "nw";
38908 GeoHashDirections.w = "w";
38909 GeoHashDirections.sw = "sw";
38910 GeoHashDirections.s = "s";
38911 GeoHashDirections.se = "se";
38912 GeoHashDirections.e = "e";
38913 GeoHashDirections.ne = "ne";
38914 return GeoHashDirections;
38917 * @class GraphCalculator
38919 * @classdesc Represents a calculator for graph entities.
38921 var GraphCalculator = /** @class */ (function () {
38923 * Create a new graph calculator instance.
38925 * @param {GeoCoords} geoCoords - Geo coords instance.
38927 function GraphCalculator(geoCoords) {
38928 this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords();
38931 * Encode the geohash tile for geodetic coordinates.
38933 * @param {ILatLon} latlon - Latitude and longitude to encode.
38934 * @param {number} precision - Precision of the encoding.
38936 * @returns {string} The geohash tile for the lat, lon and precision.
38938 GraphCalculator.prototype.encodeH = function (latLon, precision) {
38939 if (precision === void 0) { precision = 7; }
38940 return geohash.encode(latLon.lat, latLon.lon, precision);
38943 * Encode the geohash tiles within a threshold from a position
38944 * using Manhattan distance.
38946 * @param {ILatLon} latlon - Latitude and longitude to encode.
38947 * @param {number} precision - Precision of the encoding.
38948 * @param {number} threshold - Threshold of the encoding in meters.
38950 * @returns {string} The geohash tiles reachable within the threshold.
38952 GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) {
38953 if (precision === void 0) { precision = 7; }
38954 if (threshold === void 0) { threshold = 20; }
38955 var h = geohash.encode(latLon.lat, latLon.lon, precision);
38956 var bounds = geohash.bounds(h);
38957 var ne = bounds.ne;
38958 var sw = bounds.sw;
38959 var neighbours = geohash.neighbours(h);
38960 var bl = [0, 0, 0];
38961 var tr = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, sw.lat, sw.lon, 0);
38962 var position = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, sw.lat, sw.lon, 0);
38963 var left = position[0] - bl[0];
38964 var right = tr[0] - position[0];
38965 var bottom = position[1] - bl[1];
38966 var top = tr[1] - position[1];
38967 var l = left < threshold;
38968 var r = right < threshold;
38969 var b = bottom < threshold;
38970 var t = top < threshold;
38973 hs.push(neighbours[GeoHashDirections.n]);
38976 hs.push(neighbours[GeoHashDirections.nw]);
38979 hs.push(neighbours[GeoHashDirections.w]);
38982 hs.push(neighbours[GeoHashDirections.sw]);
38985 hs.push(neighbours[GeoHashDirections.s]);
38988 hs.push(neighbours[GeoHashDirections.se]);
38991 hs.push(neighbours[GeoHashDirections.e]);
38994 hs.push(neighbours[GeoHashDirections.ne]);
38999 * Encode the minimum set of geohash tiles containing a bounding box.
39001 * @description The current algorithm does expect the bounding box
39002 * to be sufficiently small to be contained in an area with the size
39003 * of maximally four tiles. Up to nine adjacent tiles may be returned.
39004 * The method currently uses the largest side as the threshold leading to
39005 * more tiles being returned than needed in edge cases.
39007 * @param {ILatLon} sw - South west corner of bounding box.
39008 * @param {ILatLon} ne - North east corner of bounding box.
39009 * @param {number} precision - Precision of the encoding.
39011 * @returns {string} The geohash tiles containing the bounding box.
39013 GraphCalculator.prototype.encodeHsFromBoundingBox = function (sw, ne, precision) {
39014 if (precision === void 0) { precision = 7; }
39015 if (ne.lat <= sw.lat || ne.lon <= sw.lon) {
39016 throw new Error_1.GraphMapillaryError("North east needs to be top right of south west");
39018 var centerLat = (sw.lat + ne.lat) / 2;
39019 var centerLon = (sw.lon + ne.lon) / 2;
39020 var enu = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, centerLat, centerLon, 0);
39021 var threshold = Math.max(enu[0], enu[1]);
39022 return this.encodeHs({ lat: centerLat, lon: centerLon }, precision, threshold);
39025 * Get the bounding box corners for a circle with radius of a threshold
39026 * with center in a geodetic position.
39028 * @param {ILatLon} latlon - Latitude and longitude to encode.
39029 * @param {number} threshold - Threshold distance from the position in meters.
39031 * @returns {Array<ILatLon>} The south west and north east corners of the
39034 GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) {
39035 var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0);
39036 var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0);
39038 { lat: bl[0], lon: bl[1] },
39039 { lat: tr[0], lon: tr[1] },
39043 * Convert a compass angle to an angle axis rotation vector.
39045 * @param {number} compassAngle - The compass angle in degrees.
39046 * @param {number} orientation - The orientation of the original image.
39048 * @returns {Array<number>} Angle axis rotation vector.
39050 GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) {
39054 switch (orientation) {
39073 var rz = new THREE.Matrix4().makeRotationZ(z);
39074 var euler = new THREE.Euler(x, y, compassAngle * Math.PI / 180, "XYZ");
39075 var re = new THREE.Matrix4().makeRotationFromEuler(euler);
39076 var rotation = new THREE.Vector4().setAxisAngleFromRotationMatrix(re.multiply(rz));
39077 return rotation.multiplyScalar(rotation.w).toArray().slice(0, 3);
39079 return GraphCalculator;
39081 exports.GraphCalculator = GraphCalculator;
39082 exports.default = GraphCalculator;
39084 },{"../Error":292,"../Geo":293,"latlon-geohash":21,"three":240}],398:[function(require,module,exports){
39086 Object.defineProperty(exports, "__esModule", { value: true });
39088 * Enumeration for graph modes.
39091 * @description Modes for the retrieval and caching performed
39092 * by the graph service on the graph.
39095 (function (GraphMode) {
39097 * Caching is performed on sequences only and sequence edges are
39098 * calculated. Spatial tiles
39099 * are not retrieved and spatial edges are not calculated when
39100 * caching nodes. Complete sequences are being cached for requested
39101 * nodes within the graph.
39103 GraphMode[GraphMode["Sequence"] = 0] = "Sequence";
39105 * Caching is performed with emphasis on spatial data. Sequence edges
39106 * as well as spatial edges are cached. Sequence data
39107 * is still requested but complete sequences are not being cached
39108 * for requested nodes.
39110 * This is the initial mode of the graph service.
39112 GraphMode[GraphMode["Spatial"] = 1] = "Spatial";
39113 })(GraphMode = exports.GraphMode || (exports.GraphMode = {}));
39114 exports.default = GraphMode;
39116 },{}],399:[function(require,module,exports){
39118 Object.defineProperty(exports, "__esModule", { value: true });
39119 var Observable_1 = require("rxjs/Observable");
39120 var Subject_1 = require("rxjs/Subject");
39121 var Graph_1 = require("../Graph");
39123 * @class GraphService
39125 * @classdesc Represents a service for graph operations.
39127 var GraphService = /** @class */ (function () {
39129 * Create a new graph service instance.
39131 * @param {Graph} graph - Graph instance to be operated on.
39133 function GraphService(graph, imageLoadingService) {
39134 this._graph$ = Observable_1.Observable
39136 .concat(graph.changed$)
39139 this._graph$.subscribe(function () { });
39140 this._graphMode = Graph_1.GraphMode.Spatial;
39141 this._graphModeSubject$ = new Subject_1.Subject();
39142 this._graphMode$ = this._graphModeSubject$
39143 .startWith(this._graphMode)
39146 this._graphMode$.subscribe(function () { });
39147 this._imageLoadingService = imageLoadingService;
39148 this._firstGraphSubjects$ = [];
39149 this._initializeCacheSubscriptions = [];
39150 this._sequenceSubscriptions = [];
39151 this._spatialSubscriptions = [];
39153 Object.defineProperty(GraphService.prototype, "graphMode$", {
39155 * Get graph mode observable.
39157 * @description Emits the current graph mode.
39159 * @returns {Observable<GraphMode>} Observable
39160 * emitting the current graph mode when it changes.
39163 return this._graphMode$;
39169 * Cache full nodes in a bounding box.
39171 * @description When called, the full properties of
39172 * the node are retrieved. The node cache is not initialized
39173 * for any new nodes retrieved and the node assets are not
39174 * retrieved, {@link cacheNode$} needs to be called for caching
39177 * @param {ILatLon} sw - South west corner of bounding box.
39178 * @param {ILatLon} ne - North east corner of bounding box.
39179 * @return {Observable<Array<Node>>} Observable emitting a single item,
39180 * the nodes of the bounding box, when they have all been retrieved.
39181 * @throws {Error} Propagates any IO node caching errors to the caller.
39183 GraphService.prototype.cacheBoundingBox$ = function (sw, ne) {
39184 return this._graph$
39186 .mergeMap(function (graph) {
39187 return graph.cacheBoundingBox$(sw, ne);
39191 * Cache a node in the graph and retrieve it.
39193 * @description When called, the full properties of
39194 * the node are retrieved and the node cache is initialized.
39195 * After that the node assets are cached and the node
39196 * is emitted to the observable when.
39197 * In parallel to caching the node assets, the sequence and
39198 * spatial edges of the node are cached. For this, the sequence
39199 * of the node and the required tiles and spatial nodes are
39200 * retrieved. The sequence and spatial edges may be set before
39201 * or after the node is returned.
39203 * @param {string} key - Key of the node to cache.
39204 * @return {Observable<Node>} Observable emitting a single item,
39205 * the node, when it has been retrieved and its assets are cached.
39206 * @throws {Error} Propagates any IO node caching errors to the caller.
39208 GraphService.prototype.cacheNode$ = function (key) {
39210 var firstGraphSubject$ = new Subject_1.Subject();
39211 this._firstGraphSubjects$.push(firstGraphSubject$);
39212 var firstGraph$ = firstGraphSubject$
39215 var node$ = firstGraph$
39216 .map(function (graph) {
39217 return graph.getNode(key);
39219 .mergeMap(function (node) {
39220 return node.assetsCached ?
39221 Observable_1.Observable.of(node) :
39222 node.cacheAssets$();
39226 node$.subscribe(function (node) {
39227 _this._imageLoadingService.loadnode$.next(node);
39228 }, function (error) {
39229 console.error("Failed to cache node (" + key + ")", error);
39231 var initializeCacheSubscription = this._graph$
39233 .mergeMap(function (graph) {
39234 if (graph.isCachingFull(key) || !graph.hasNode(key)) {
39235 return graph.cacheFull$(key);
39237 if (graph.isCachingFill(key) || !graph.getNode(key).full) {
39238 return graph.cacheFill$(key);
39240 return Observable_1.Observable.of(graph);
39242 .do(function (graph) {
39243 if (!graph.hasInitializedCache(key)) {
39244 graph.initializeCache(key);
39247 .finally(function () {
39248 if (initializeCacheSubscription == null) {
39251 _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions);
39252 _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$);
39254 .subscribe(function (graph) {
39255 firstGraphSubject$.next(graph);
39256 firstGraphSubject$.complete();
39257 }, function (error) {
39258 firstGraphSubject$.error(error);
39260 if (!initializeCacheSubscription.closed) {
39261 this._initializeCacheSubscriptions.push(initializeCacheSubscription);
39263 var graphSequence$ = firstGraph$
39264 .mergeMap(function (graph) {
39265 if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) {
39266 return graph.cacheNodeSequence$(key);
39268 return Observable_1.Observable.of(graph);
39272 var sequenceSubscription = graphSequence$
39273 .do(function (graph) {
39274 if (!graph.getNode(key).sequenceEdges.cached) {
39275 graph.cacheSequenceEdges(key);
39278 .finally(function () {
39279 if (sequenceSubscription == null) {
39282 _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions);
39284 .subscribe(function (graph) { return; }, function (error) {
39285 console.error("Failed to cache sequence edges (" + key + ").", error);
39287 if (!sequenceSubscription.closed) {
39288 this._sequenceSubscriptions.push(sequenceSubscription);
39290 if (this._graphMode === Graph_1.GraphMode.Spatial) {
39291 var spatialSubscription_1 = firstGraph$
39292 .expand(function (graph) {
39293 if (graph.hasTiles(key)) {
39294 return Observable_1.Observable.empty();
39296 return Observable_1.Observable
39297 .from(graph.cacheTiles$(key))
39298 .mergeMap(function (graph$) {
39300 .mergeMap(function (g) {
39301 if (g.isCachingTiles(key)) {
39302 return Observable_1.Observable.empty();
39304 return Observable_1.Observable.of(g);
39306 .catch(function (error, caught$) {
39307 console.error("Failed to cache tile data (" + key + ").", error);
39308 return Observable_1.Observable.empty();
39313 .mergeMap(function (graph) {
39314 if (graph.hasSpatialArea(key)) {
39315 return Observable_1.Observable.of(graph);
39317 return Observable_1.Observable
39318 .from(graph.cacheSpatialArea$(key))
39319 .mergeMap(function (graph$) {
39321 .catch(function (error, caught$) {
39322 console.error("Failed to cache spatial nodes (" + key + ").", error);
39323 return Observable_1.Observable.empty();
39328 .mergeMap(function (graph) {
39329 return graph.hasNodeSequence(key) ?
39330 Observable_1.Observable.of(graph) :
39331 graph.cacheNodeSequence$(key);
39333 .do(function (graph) {
39334 if (!graph.getNode(key).spatialEdges.cached) {
39335 graph.cacheSpatialEdges(key);
39338 .finally(function () {
39339 if (spatialSubscription_1 == null) {
39342 _this._removeFromArray(spatialSubscription_1, _this._spatialSubscriptions);
39344 .subscribe(function (graph) { return; }, function (error) {
39345 console.error("Failed to cache spatial edges (" + key + ").", error);
39347 if (!spatialSubscription_1.closed) {
39348 this._spatialSubscriptions.push(spatialSubscription_1);
39352 .first(function (node) {
39353 return node.assetsCached;
39357 * Cache a sequence in the graph and retrieve it.
39359 * @param {string} sequenceKey - Sequence key.
39360 * @returns {Observable<Sequence>} Observable emitting a single item,
39361 * the sequence, when it has been retrieved and its assets are cached.
39362 * @throws {Error} Propagates any IO node caching errors to the caller.
39364 GraphService.prototype.cacheSequence$ = function (sequenceKey) {
39365 return this._graph$
39367 .mergeMap(function (graph) {
39368 if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
39369 return graph.cacheSequence$(sequenceKey);
39371 return Observable_1.Observable.of(graph);
39373 .map(function (graph) {
39374 return graph.getSequence(sequenceKey);
39378 * Cache a sequence and its nodes in the graph and retrieve the sequence.
39380 * @description Caches a sequence and its assets are cached and
39381 * retrieves all nodes belonging to the sequence. The node assets
39382 * or edges will not be cached.
39384 * @param {string} sequenceKey - Sequence key.
39385 * @param {string} referenceNodeKey - Key of node to use as reference
39386 * for optimized caching.
39387 * @returns {Observable<Sequence>} Observable emitting a single item,
39388 * the sequence, when it has been retrieved, its assets are cached and
39389 * all nodes belonging to the sequence has been retrieved.
39390 * @throws {Error} Propagates any IO node caching errors to the caller.
39392 GraphService.prototype.cacheSequenceNodes$ = function (sequenceKey, referenceNodeKey) {
39393 return this._graph$
39395 .mergeMap(function (graph) {
39396 if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
39397 return graph.cacheSequence$(sequenceKey);
39399 return Observable_1.Observable.of(graph);
39401 .mergeMap(function (graph) {
39402 if (graph.isCachingSequenceNodes(sequenceKey) || !graph.hasSequenceNodes(sequenceKey)) {
39403 return graph.cacheSequenceNodes$(sequenceKey, referenceNodeKey);
39405 return Observable_1.Observable.of(graph);
39407 .map(function (graph) {
39408 return graph.getSequence(sequenceKey);
39412 * Set a spatial edge filter on the graph.
39414 * @description Resets the spatial edges of all cached nodes.
39416 * @param {FilterExpression} filter - Filter expression to be applied.
39417 * @return {Observable<Graph>} Observable emitting a single item,
39418 * the graph, when the spatial edges have been reset.
39420 GraphService.prototype.setFilter$ = function (filter) {
39421 this._resetSubscriptions(this._spatialSubscriptions);
39422 return this._graph$
39424 .do(function (graph) {
39425 graph.resetSpatialEdges();
39426 graph.setFilter(filter);
39428 .map(function (graph) {
39433 * Set the graph mode.
39435 * @description If graph mode is set to spatial, caching
39436 * is performed with emphasis on spatial edges. If graph
39437 * mode is set to sequence no tile data is requested and
39438 * no spatial edges are computed.
39440 * When setting graph mode to sequence all spatial
39441 * subscriptions are aborted.
39443 * @param {GraphMode} mode - Graph mode to set.
39445 GraphService.prototype.setGraphMode = function (mode) {
39446 if (this._graphMode === mode) {
39449 if (mode === Graph_1.GraphMode.Sequence) {
39450 this._resetSubscriptions(this._spatialSubscriptions);
39452 this._graphMode = mode;
39453 this._graphModeSubject$.next(this._graphMode);
39458 * @description Resets the graph but keeps the nodes of the
39461 * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
39462 * @return {Observable<Node>} Observable emitting a single item,
39463 * the graph, when it has been reset.
39465 GraphService.prototype.reset$ = function (keepKeys) {
39466 this._abortSubjects(this._firstGraphSubjects$);
39467 this._resetSubscriptions(this._initializeCacheSubscriptions);
39468 this._resetSubscriptions(this._sequenceSubscriptions);
39469 this._resetSubscriptions(this._spatialSubscriptions);
39470 return this._graph$
39472 .do(function (graph) {
39473 graph.reset(keepKeys);
39475 .map(function (graph) {
39480 * Uncache the graph.
39482 * @description Uncaches the graph by removing tiles, nodes and
39483 * sequences. Keeps the nodes of the supplied keys and the tiles
39484 * related to those nodes.
39486 * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
39487 * @param {string} keepSequenceKey - Optional key of sequence
39488 * for which the belonging nodes should not be disposed or
39489 * removed from the graph. These nodes may still be uncached if
39490 * not specified in keep keys param.
39491 * @return {Observable<Graph>} Observable emitting a single item,
39492 * the graph, when the graph has been uncached.
39494 GraphService.prototype.uncache$ = function (keepKeys, keepSequenceKey) {
39495 return this._graph$
39497 .do(function (graph) {
39498 graph.uncache(keepKeys, keepSequenceKey);
39500 .map(function (graph) {
39504 GraphService.prototype._abortSubjects = function (subjects) {
39505 for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) {
39506 var subject = _a[_i];
39507 this._removeFromArray(subject, subjects);
39508 subject.error(new Error("Cache node request was aborted."));
39511 GraphService.prototype._removeFromArray = function (object, objects) {
39512 var index = objects.indexOf(object);
39513 if (index !== -1) {
39514 objects.splice(index, 1);
39517 GraphService.prototype._resetSubscriptions = function (subscriptions) {
39518 for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) {
39519 var subscription = _a[_i];
39520 this._removeFromArray(subscription, subscriptions);
39521 if (!subscription.closed) {
39522 subscription.unsubscribe();
39526 return GraphService;
39528 exports.GraphService = GraphService;
39529 exports.default = GraphService;
39531 },{"../Graph":294,"rxjs/Observable":29,"rxjs/Subject":34}],400:[function(require,module,exports){
39533 /// <reference path="../../typings/index.d.ts" />
39534 Object.defineProperty(exports, "__esModule", { value: true });
39535 var Subject_1 = require("rxjs/Subject");
39536 var ImageLoadingService = /** @class */ (function () {
39537 function ImageLoadingService() {
39538 this._loadnode$ = new Subject_1.Subject();
39539 this._loadstatus$ = this._loadnode$
39540 .scan(function (_a, node) {
39542 var changed = false;
39543 if (node.loadStatus.total === 0 || node.loadStatus.loaded === node.loadStatus.total) {
39544 if (node.key in nodes) {
39545 delete nodes[node.key];
39550 nodes[node.key] = node.loadStatus;
39553 return [nodes, changed];
39555 .filter(function (_a) {
39556 var nodes = _a[0], changed = _a[1];
39559 .map(function (_a) {
39565 this._loadstatus$.subscribe(function () { });
39567 Object.defineProperty(ImageLoadingService.prototype, "loadnode$", {
39569 return this._loadnode$;
39574 Object.defineProperty(ImageLoadingService.prototype, "loadstatus$", {
39576 return this._loadstatus$;
39581 return ImageLoadingService;
39583 exports.ImageLoadingService = ImageLoadingService;
39585 },{"rxjs/Subject":34}],401:[function(require,module,exports){
39587 /// <reference path="../../typings/index.d.ts" />
39588 Object.defineProperty(exports, "__esModule", { value: true });
39589 var Pbf = require("pbf");
39590 var MeshReader = /** @class */ (function () {
39591 function MeshReader() {
39593 MeshReader.read = function (buffer) {
39594 var pbf = new Pbf(buffer);
39595 return pbf.readFields(MeshReader._readMeshField, { faces: [], vertices: [] });
39597 MeshReader._readMeshField = function (tag, mesh, pbf) {
39599 mesh.vertices.push(pbf.readFloat());
39601 else if (tag === 2) {
39602 mesh.faces.push(pbf.readVarint());
39607 exports.MeshReader = MeshReader;
39609 },{"pbf":23}],402:[function(require,module,exports){
39611 Object.defineProperty(exports, "__esModule", { value: true });
39615 * @classdesc Represents a node in the navigation graph.
39617 * Explanation of position and bearing properties:
39619 * When images are uploaded they will have GPS information in the EXIF, this is what
39620 * is called `originalLatLon` {@link Node.originalLatLon}.
39622 * When Structure from Motions has been run for a node a `computedLatLon` that
39623 * differs from the `originalLatLon` will be created. It is different because
39624 * GPS positions are not very exact and SfM aligns the camera positions according
39625 * to the 3D reconstruction {@link Node.computedLatLon}.
39627 * At last there exist a `latLon` property which evaluates to
39628 * the `computedLatLon` from SfM if it exists but falls back
39629 * to the `originalLatLon` from the EXIF GPS otherwise {@link Node.latlon}.
39631 * Everything that is done in in the Viewer is based on the SfM positions,
39632 * i.e. `computedLatLon`. That is why the smooth transitions go in the right
39633 * direction (nd not in strange directions because of bad GPS).
39635 * E.g. when placing a marker in the Viewer it is relative to the SfM
39636 * position i.e. the `computedLatLon`.
39638 * The same concept as above also applies to the compass angle (or bearing) properties
39639 * `originalCa`, `computedCa` and `ca`.
39641 var Node = /** @class */ (function () {
39643 * Create a new node instance.
39645 * @description Nodes are always created internally by the library.
39646 * Nodes can not be added to the library through any API method.
39648 * @param {ICoreNode} coreNode - Raw core node data.
39650 function Node(core) {
39651 this._cache = null;
39655 Object.defineProperty(Node.prototype, "assetsCached", {
39657 * Get assets cached.
39659 * @description The assets that need to be cached for this property
39660 * to report true are the following: fill properties, image and mesh.
39661 * The library ensures that the current node will always have the
39664 * @returns {boolean} Value indicating whether all assets have been
39668 return this._core != null &&
39669 this._fill != null &&
39670 this._cache != null &&
39671 this._cache.image != null &&
39672 this._cache.mesh != null;
39677 Object.defineProperty(Node.prototype, "alt", {
39681 * @description If SfM has not been run the computed altitude is
39682 * set to a default value of two meters.
39684 * @returns {number} Altitude, in meters.
39687 return this._fill.calt;
39692 Object.defineProperty(Node.prototype, "ca", {
39696 * @description If the SfM computed compass angle exists it will
39697 * be returned, otherwise the original EXIF compass angle.
39699 * @returns {number} Compass angle, measured in degrees.
39702 return this._fill.cca != null ? this._fill.cca : this._fill.ca;
39707 Object.defineProperty(Node.prototype, "capturedAt", {
39711 * @returns {number} Timestamp when the image was captured.
39714 return this._fill.captured_at;
39719 Object.defineProperty(Node.prototype, "cameraUuid", {
39723 * @description Will be undefined if the camera uuid was not
39724 * recorded in the image exif information.
39726 * @returns {string} Universally unique id for camera used
39727 * when capturing image.
39730 return this._fill.captured_with_camera_uuid;
39735 Object.defineProperty(Node.prototype, "computedCA", {
39739 * @description Will not be set if SfM has not been run.
39741 * @returns {number} SfM computed compass angle, measured in degrees.
39744 return this._fill.cca;
39749 Object.defineProperty(Node.prototype, "computedLatLon", {
39751 * Get computedLatLon.
39753 * @description Will not be set if SfM has not been run.
39755 * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum,
39756 * measured in degrees.
39759 return this._core.cl;
39764 Object.defineProperty(Node.prototype, "focal", {
39768 * @description Will not be set if SfM has not been run.
39770 * @returns {number} SfM computed focal length.
39773 return this._fill.cfocal;
39778 Object.defineProperty(Node.prototype, "full", {
39782 * @description The library ensures that the current node will
39785 * @returns {boolean} Value indicating whether the node has all
39786 * properties filled.
39789 return this._fill != null;
39794 Object.defineProperty(Node.prototype, "fullPano", {
39798 * @returns {boolean} Value indicating whether the node is a complete
39802 return this._fill.gpano != null &&
39803 this._fill.gpano.CroppedAreaLeftPixels === 0 &&
39804 this._fill.gpano.CroppedAreaTopPixels === 0 &&
39805 this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels &&
39806 this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels;
39811 Object.defineProperty(Node.prototype, "gpano", {
39815 * @description Will not be set for non panoramic images.
39817 * @returns {IGPano} Panorama information for panorama images.
39820 return this._fill.gpano;
39825 Object.defineProperty(Node.prototype, "height", {
39829 * @returns {number} Height of original image, not adjusted
39833 return this._fill.height;
39838 Object.defineProperty(Node.prototype, "image", {
39842 * @description The image will always be set on the current node.
39844 * @returns {HTMLImageElement} Cached image element of the node.
39847 return this._cache.image;
39852 Object.defineProperty(Node.prototype, "image$", {
39856 * @returns {Observable<HTMLImageElement>} Observable emitting
39857 * the cached image when it is updated.
39860 return this._cache.image$;
39865 Object.defineProperty(Node.prototype, "key", {
39869 * @returns {string} Unique key of the node.
39872 return this._core.key;
39877 Object.defineProperty(Node.prototype, "latLon", {
39881 * @description If the SfM computed latitude longitude exist
39882 * it will be returned, otherwise the original EXIF latitude
39885 * @returns {ILatLon} Latitude longitude in WGS84 datum,
39886 * measured in degrees.
39889 return this._core.cl != null ? this._core.cl : this._core.l;
39894 Object.defineProperty(Node.prototype, "loadStatus", {
39898 * @returns {ILoadStatus} Value indicating the load status
39899 * of the mesh and image.
39902 return this._cache.loadStatus;
39907 Object.defineProperty(Node.prototype, "merged", {
39911 * @returns {boolean} Value indicating whether SfM has been
39912 * run on the node and the node has been merged into a
39913 * connected component.
39916 return this._fill != null &&
39917 this._fill.merge_version != null &&
39918 this._fill.merge_version > 0;
39923 Object.defineProperty(Node.prototype, "mergeCC", {
39927 * @description Will not be set if SfM has not yet been run on
39930 * @returns {number} SfM connected component key to which
39934 return this._fill.merge_cc;
39939 Object.defineProperty(Node.prototype, "mergeVersion", {
39941 * Get mergeVersion.
39943 * @returns {number} Version for which SfM was run and image was merged.
39946 return this._fill.merge_version;
39951 Object.defineProperty(Node.prototype, "mesh", {
39955 * @description The mesh will always be set on the current node.
39957 * @returns {IMesh} SfM triangulated mesh of reconstructed
39958 * atomic 3D points.
39961 return this._cache.mesh;
39966 Object.defineProperty(Node.prototype, "organizationKey", {
39968 * Get organizationKey.
39970 * @returns {string} Unique key of the organization to which
39971 * the node belongs. If the node does not belong to an
39972 * organization the organization key will be undefined.
39975 return this._fill.organization_key;
39980 Object.defineProperty(Node.prototype, "orientation", {
39984 * @returns {number} EXIF orientation of original image.
39987 return this._fill.orientation;
39992 Object.defineProperty(Node.prototype, "originalCA", {
39996 * @returns {number} Original EXIF compass angle, measured in
40000 return this._fill.ca;
40005 Object.defineProperty(Node.prototype, "originalLatLon", {
40007 * Get originalLatLon.
40009 * @returns {ILatLon} Original EXIF latitude longitude in
40010 * WGS84 datum, measured in degrees.
40013 return this._core.l;
40018 Object.defineProperty(Node.prototype, "pano", {
40022 * @returns {boolean} Value indicating whether the node is a panorama.
40023 * It could be a cropped or full panorama.
40026 return this._fill.gpano != null &&
40027 this._fill.gpano.FullPanoWidthPixels != null;
40032 Object.defineProperty(Node.prototype, "private", {
40036 * @returns {boolean} Value specifying if image is accessible to
40037 * organization members only or to everyone.
40040 return this._fill.private;
40045 Object.defineProperty(Node.prototype, "projectKey", {
40049 * @returns {string} Unique key of the project to which
40050 * the node belongs. If the node does not belong to a
40051 * project the project key will be undefined.
40053 * @deprecated This property will be deprecated in favor
40054 * of the organization key and private properties.
40057 return this._fill.project != null ?
40058 this._fill.project.key :
40064 Object.defineProperty(Node.prototype, "rotation", {
40068 * @description Will not be set if SfM has not been run.
40070 * @returns {Array<number>} Rotation vector in angle axis representation.
40073 return this._fill.c_rotation;
40078 Object.defineProperty(Node.prototype, "scale", {
40082 * @description Will not be set if SfM has not been run.
40084 * @returns {number} Scale of atomic reconstruction.
40087 return this._fill.atomic_scale;
40092 Object.defineProperty(Node.prototype, "sequenceKey", {
40096 * @returns {string} Unique key of the sequence to which
40097 * the node belongs.
40100 return this._core.sequence_key;
40105 Object.defineProperty(Node.prototype, "sequenceEdges", {
40107 * Get sequenceEdges.
40109 * @returns {IEdgeStatus} Value describing the status of the
40113 return this._cache.sequenceEdges;
40118 Object.defineProperty(Node.prototype, "sequenceEdges$", {
40120 * Get sequenceEdges$.
40122 * @returns {Observable<IEdgeStatus>} Observable emitting
40123 * values describing the status of the sequence edges.
40126 return this._cache.sequenceEdges$;
40131 Object.defineProperty(Node.prototype, "spatialEdges", {
40133 * Get spatialEdges.
40135 * @returns {IEdgeStatus} Value describing the status of the
40139 return this._cache.spatialEdges;
40144 Object.defineProperty(Node.prototype, "spatialEdges$", {
40146 * Get spatialEdges$.
40148 * @returns {Observable<IEdgeStatus>} Observable emitting
40149 * values describing the status of the spatial edges.
40152 return this._cache.spatialEdges$;
40157 Object.defineProperty(Node.prototype, "userKey", {
40161 * @returns {string} Unique key of the user who uploaded
40165 return this._fill.user.key;
40170 Object.defineProperty(Node.prototype, "username", {
40174 * @returns {string} Username of the user who uploaded
40178 return this._fill.user.username;
40183 Object.defineProperty(Node.prototype, "width", {
40187 * @returns {number} Width of original image, not
40188 * adjusted for orientation.
40191 return this._fill.width;
40197 * Cache the image and mesh assets.
40199 * @description The assets are always cached internally by the
40200 * library prior to setting a node as the current node.
40202 * @returns {Observable<Node>} Observable emitting this node whenever the
40203 * load status has changed and when the mesh or image has been fully loaded.
40205 Node.prototype.cacheAssets$ = function () {
40207 return this._cache.cacheAssets$(this.key, this.pano, this.merged)
40208 .map(function (cache) {
40212 Node.prototype.cacheImage$ = function (imageSize) {
40214 return this._cache.cacheImage$(this.key, imageSize)
40215 .map(function (cache) {
40220 * Cache the sequence edges.
40222 * @description The sequence edges are cached asynchronously
40223 * internally by the library.
40225 * @param {Array<IEdge>} edges - Sequence edges to cache.
40227 Node.prototype.cacheSequenceEdges = function (edges) {
40228 this._cache.cacheSequenceEdges(edges);
40231 * Cache the spatial edges.
40233 * @description The spatial edges are cached asynchronously
40234 * internally by the library.
40236 * @param {Array<IEdge>} edges - Spatial edges to cache.
40238 Node.prototype.cacheSpatialEdges = function (edges) {
40239 this._cache.cacheSpatialEdges(edges);
40242 * Dispose the node.
40244 * @description Disposes all cached assets.
40246 Node.prototype.dispose = function () {
40247 if (this._cache != null) {
40248 this._cache.dispose();
40249 this._cache = null;
40255 * Initialize the node cache.
40257 * @description The node cache is initialized internally by
40260 * @param {NodeCache} cache - The node cache to set as cache.
40262 Node.prototype.initializeCache = function (cache) {
40263 if (this._cache != null) {
40264 throw new Error("Node cache already initialized (" + this.key + ").");
40266 this._cache = cache;
40269 * Fill the node with all properties.
40271 * @description The node is filled internally by
40274 * @param {IFillNode} fill - The fill node struct.
40276 Node.prototype.makeFull = function (fill) {
40277 if (fill == null) {
40278 throw new Error("Fill can not be null.");
40283 * Reset the sequence edges.
40285 Node.prototype.resetSequenceEdges = function () {
40286 this._cache.resetSequenceEdges();
40289 * Reset the spatial edges.
40291 Node.prototype.resetSpatialEdges = function () {
40292 this._cache.resetSpatialEdges();
40295 * Clears the image and mesh assets, aborts
40296 * any outstanding requests and resets edges.
40298 Node.prototype.uncache = function () {
40299 if (this._cache == null) {
40302 this._cache.dispose();
40303 this._cache = null;
40307 exports.Node = Node;
40308 exports.default = Node;
40310 },{}],403:[function(require,module,exports){
40311 (function (Buffer){
40313 Object.defineProperty(exports, "__esModule", { value: true });
40314 var Subject_1 = require("rxjs/Subject");
40315 var Observable_1 = require("rxjs/Observable");
40316 var Graph_1 = require("../Graph");
40317 var Utils_1 = require("../Utils");
40321 * @classdesc Represents the cached properties of a node.
40323 var NodeCache = /** @class */ (function () {
40325 * Create a new node cache instance.
40327 function NodeCache() {
40328 this._disposed = false;
40329 this._image = null;
40330 this._loadStatus = { loaded: 0, total: 0 };
40332 this._sequenceEdges = { cached: false, edges: [] };
40333 this._spatialEdges = { cached: false, edges: [] };
40334 this._imageChanged$ = new Subject_1.Subject();
40335 this._image$ = this._imageChanged$
40339 this._iamgeSubscription = this._image$.subscribe();
40340 this._sequenceEdgesChanged$ = new Subject_1.Subject();
40341 this._sequenceEdges$ = this._sequenceEdgesChanged$
40342 .startWith(this._sequenceEdges)
40345 this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(function () { });
40346 this._spatialEdgesChanged$ = new Subject_1.Subject();
40347 this._spatialEdges$ = this._spatialEdgesChanged$
40348 .startWith(this._spatialEdges)
40351 this._spatialEdgesSubscription = this._spatialEdges$.subscribe(function () { });
40352 this._cachingAssets$ = null;
40354 Object.defineProperty(NodeCache.prototype, "image", {
40358 * @description Will not be set when assets have not been cached
40359 * or when the object has been disposed.
40361 * @returns {HTMLImageElement} Cached image element of the node.
40364 return this._image;
40369 Object.defineProperty(NodeCache.prototype, "image$", {
40373 * @returns {Observable<HTMLImageElement>} Observable emitting
40374 * the cached image when it is updated.
40377 return this._image$;
40382 Object.defineProperty(NodeCache.prototype, "loadStatus", {
40386 * @returns {ILoadStatus} Value indicating the load status
40387 * of the mesh and image.
40390 return this._loadStatus;
40395 Object.defineProperty(NodeCache.prototype, "mesh", {
40399 * @description Will not be set when assets have not been cached
40400 * or when the object has been disposed.
40402 * @returns {IMesh} SfM triangulated mesh of reconstructed
40403 * atomic 3D points.
40411 Object.defineProperty(NodeCache.prototype, "sequenceEdges", {
40413 * Get sequenceEdges.
40415 * @returns {IEdgeStatus} Value describing the status of the
40419 return this._sequenceEdges;
40424 Object.defineProperty(NodeCache.prototype, "sequenceEdges$", {
40426 * Get sequenceEdges$.
40428 * @returns {Observable<IEdgeStatus>} Observable emitting
40429 * values describing the status of the sequence edges.
40432 return this._sequenceEdges$;
40437 Object.defineProperty(NodeCache.prototype, "spatialEdges", {
40439 * Get spatialEdges.
40441 * @returns {IEdgeStatus} Value describing the status of the
40445 return this._spatialEdges;
40450 Object.defineProperty(NodeCache.prototype, "spatialEdges$", {
40452 * Get spatialEdges$.
40454 * @returns {Observable<IEdgeStatus>} Observable emitting
40455 * values describing the status of the spatial edges.
40458 return this._spatialEdges$;
40464 * Cache the image and mesh assets.
40466 * @param {string} key - Key of the node to cache.
40467 * @param {boolean} pano - Value indicating whether node is a panorama.
40468 * @param {boolean} merged - Value indicating whether node is merged.
40469 * @returns {Observable<NodeCache>} Observable emitting this node
40470 * cache whenever the load status has changed and when the mesh or image
40471 * has been fully loaded.
40473 NodeCache.prototype.cacheAssets$ = function (key, pano, merged) {
40475 if (this._cachingAssets$ != null) {
40476 return this._cachingAssets$;
40478 var imageSize = pano ?
40479 Utils_1.Settings.basePanoramaSize :
40480 Utils_1.Settings.baseImageSize;
40481 this._cachingAssets$ = Observable_1.Observable
40482 .combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged), function (imageStatus, meshStatus) {
40483 _this._loadStatus.loaded = 0;
40484 _this._loadStatus.total = 0;
40486 _this._mesh = meshStatus.object;
40487 _this._loadStatus.loaded += meshStatus.loaded.loaded;
40488 _this._loadStatus.total += meshStatus.loaded.total;
40491 _this._image = imageStatus.object;
40492 _this._loadStatus.loaded += imageStatus.loaded.loaded;
40493 _this._loadStatus.total += imageStatus.loaded.total;
40497 .finally(function () {
40498 _this._cachingAssets$ = null;
40502 this._cachingAssets$
40503 .first(function (nodeCache) {
40504 return !!nodeCache._image;
40506 .subscribe(function (nodeCache) {
40507 _this._imageChanged$.next(_this._image);
40508 }, function (error) { });
40509 return this._cachingAssets$;
40512 * Cache an image with a higher resolution than the current one.
40514 * @param {string} key - Key of the node to cache.
40515 * @param {ImageSize} imageSize - The size to cache.
40516 * @returns {Observable<NodeCache>} Observable emitting a single item,
40517 * the node cache, when the image has been cached. If supplied image
40518 * size is not larger than the current image size the node cache is
40519 * returned immediately.
40521 NodeCache.prototype.cacheImage$ = function (key, imageSize) {
40523 if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) {
40524 return Observable_1.Observable.of(this);
40526 var cacheImage$ = this._cacheImage$(key, imageSize)
40527 .first(function (status) {
40528 return status.object != null;
40530 .do(function (status) {
40531 _this._disposeImage();
40532 _this._image = status.object;
40534 .map(function (imageStatus) {
40540 .subscribe(function (nodeCache) {
40541 _this._imageChanged$.next(_this._image);
40542 }, function (error) { });
40543 return cacheImage$;
40546 * Cache the sequence edges.
40548 * @param {Array<IEdge>} edges - Sequence edges to cache.
40550 NodeCache.prototype.cacheSequenceEdges = function (edges) {
40551 this._sequenceEdges = { cached: true, edges: edges };
40552 this._sequenceEdgesChanged$.next(this._sequenceEdges);
40555 * Cache the spatial edges.
40557 * @param {Array<IEdge>} edges - Spatial edges to cache.
40559 NodeCache.prototype.cacheSpatialEdges = function (edges) {
40560 this._spatialEdges = { cached: true, edges: edges };
40561 this._spatialEdgesChanged$.next(this._spatialEdges);
40564 * Dispose the node cache.
40566 * @description Disposes all cached assets and unsubscribes to
40569 NodeCache.prototype.dispose = function () {
40570 this._iamgeSubscription.unsubscribe();
40571 this._sequenceEdgesSubscription.unsubscribe();
40572 this._spatialEdgesSubscription.unsubscribe();
40573 this._disposeImage();
40575 this._loadStatus.loaded = 0;
40576 this._loadStatus.total = 0;
40577 this._sequenceEdges = { cached: false, edges: [] };
40578 this._spatialEdges = { cached: false, edges: [] };
40579 this._imageChanged$.next(null);
40580 this._sequenceEdgesChanged$.next(this._sequenceEdges);
40581 this._spatialEdgesChanged$.next(this._spatialEdges);
40582 this._disposed = true;
40583 if (this._imageRequest != null) {
40584 this._imageRequest.abort();
40586 if (this._meshRequest != null) {
40587 this._meshRequest.abort();
40591 * Reset the sequence edges.
40593 NodeCache.prototype.resetSequenceEdges = function () {
40594 this._sequenceEdges = { cached: false, edges: [] };
40595 this._sequenceEdgesChanged$.next(this._sequenceEdges);
40598 * Reset the spatial edges.
40600 NodeCache.prototype.resetSpatialEdges = function () {
40601 this._spatialEdges = { cached: false, edges: [] };
40602 this._spatialEdgesChanged$.next(this._spatialEdges);
40607 * @param {string} key - Key of the node to cache.
40608 * @param {boolean} pano - Value indicating whether node is a panorama.
40609 * @returns {Observable<ILoadStatusObject<HTMLImageElement>>} Observable
40610 * emitting a load status object every time the load status changes
40611 * and completes when the image is fully loaded.
40613 NodeCache.prototype._cacheImage$ = function (key, imageSize) {
40615 return Observable_1.Observable.create(function (subscriber) {
40616 var xmlHTTP = new XMLHttpRequest();
40617 xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize, Utils_1.Urls.origin), true);
40618 xmlHTTP.responseType = "arraybuffer";
40619 xmlHTTP.timeout = 15000;
40620 xmlHTTP.onload = function (pe) {
40621 if (xmlHTTP.status !== 200) {
40622 _this._imageRequest = null;
40623 subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
40626 var image = new Image();
40627 image.crossOrigin = "Anonymous";
40628 image.onload = function (e) {
40629 _this._imageRequest = null;
40630 if (_this._disposed) {
40631 window.URL.revokeObjectURL(image.src);
40632 subscriber.error(new Error("Image load was aborted (" + key + ")"));
40635 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
40636 subscriber.complete();
40638 image.onerror = function (error) {
40639 _this._imageRequest = null;
40640 subscriber.error(new Error("Failed to load image (" + key + ")"));
40642 var blob = new Blob([xmlHTTP.response]);
40643 image.src = window.URL.createObjectURL(blob);
40645 xmlHTTP.onprogress = function (pe) {
40646 if (_this._disposed) {
40649 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
40651 xmlHTTP.onerror = function (error) {
40652 _this._imageRequest = null;
40653 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
40655 xmlHTTP.ontimeout = function (e) {
40656 _this._imageRequest = null;
40657 subscriber.error(new Error("Image request timed out (" + key + ")"));
40659 xmlHTTP.onabort = function (event) {
40660 _this._imageRequest = null;
40661 subscriber.error(new Error("Image request was aborted (" + key + ")"));
40663 _this._imageRequest = xmlHTTP;
40664 xmlHTTP.send(null);
40670 * @param {string} key - Key of the node to cache.
40671 * @param {boolean} merged - Value indicating whether node is merged.
40672 * @returns {Observable<ILoadStatusObject<IMesh>>} Observable emitting
40673 * a load status object every time the load status changes and completes
40674 * when the mesh is fully loaded.
40676 NodeCache.prototype._cacheMesh$ = function (key, merged) {
40678 return Observable_1.Observable.create(function (subscriber) {
40680 subscriber.next(_this._createEmptyMeshLoadStatus());
40681 subscriber.complete();
40684 var xmlHTTP = new XMLHttpRequest();
40685 xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true);
40686 xmlHTTP.responseType = "arraybuffer";
40687 xmlHTTP.timeout = 15000;
40688 xmlHTTP.onload = function (pe) {
40689 _this._meshRequest = null;
40690 if (_this._disposed) {
40693 var mesh = xmlHTTP.status === 200 ?
40694 Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) :
40695 { faces: [], vertices: [] };
40696 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: mesh });
40697 subscriber.complete();
40699 xmlHTTP.onprogress = function (pe) {
40700 if (_this._disposed) {
40703 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
40705 xmlHTTP.onerror = function (e) {
40706 _this._meshRequest = null;
40707 console.error("Failed to cache mesh (" + key + ")");
40708 subscriber.next(_this._createEmptyMeshLoadStatus());
40709 subscriber.complete();
40711 xmlHTTP.ontimeout = function (e) {
40712 _this._meshRequest = null;
40713 console.error("Mesh request timed out (" + key + ")");
40714 subscriber.next(_this._createEmptyMeshLoadStatus());
40715 subscriber.complete();
40717 xmlHTTP.onabort = function (e) {
40718 _this._meshRequest = null;
40719 subscriber.error(new Error("Mesh request was aborted (" + key + ")"));
40721 _this._meshRequest = xmlHTTP;
40722 xmlHTTP.send(null);
40726 * Create a load status object with an empty mesh.
40728 * @returns {ILoadStatusObject<IMesh>} Load status object
40731 NodeCache.prototype._createEmptyMeshLoadStatus = function () {
40733 loaded: { loaded: 0, total: 0 },
40734 object: { faces: [], vertices: [] },
40737 NodeCache.prototype._disposeImage = function () {
40738 if (this._image != null) {
40739 window.URL.revokeObjectURL(this._image.src);
40741 this._image = null;
40745 exports.NodeCache = NodeCache;
40746 exports.default = NodeCache;
40748 }).call(this,require("buffer").Buffer)
40750 },{"../Graph":294,"../Utils":300,"buffer":7,"rxjs/Observable":29,"rxjs/Subject":34}],404:[function(require,module,exports){
40752 /// <reference path="../../typings/index.d.ts" />
40753 Object.defineProperty(exports, "__esModule", { value: true });
40754 var _ = require("underscore");
40758 * @classdesc Represents a sequence of ordered nodes.
40760 var Sequence = /** @class */ (function () {
40762 * Create a new sequene instance.
40764 * @param {ISequence} sequence - Raw sequence data.
40766 function Sequence(sequence) {
40767 this._key = sequence.key;
40768 this._keys = sequence.keys;
40770 Object.defineProperty(Sequence.prototype, "key", {
40774 * @returns {string} Unique sequence key.
40782 Object.defineProperty(Sequence.prototype, "keys", {
40786 * @returns {Array<string>} Array of ordered node keys in the sequence.
40795 * Dispose the sequence.
40797 * @description Disposes all cached assets.
40799 Sequence.prototype.dispose = function () {
40804 * Find the next node key in the sequence with respect to
40805 * the provided node key.
40807 * @param {string} key - Reference node key.
40808 * @returns {string} Next key in sequence if it exists, null otherwise.
40810 Sequence.prototype.findNextKey = function (key) {
40811 var i = _.indexOf(this._keys, key);
40812 if ((i + 1) >= this._keys.length || i === -1) {
40816 return this._keys[i + 1];
40820 * Find the previous node key in the sequence with respect to
40821 * the provided node key.
40823 * @param {string} key - Reference node key.
40824 * @returns {string} Previous key in sequence if it exists, null otherwise.
40826 Sequence.prototype.findPrevKey = function (key) {
40827 var i = _.indexOf(this._keys, key);
40828 if (i === 0 || i === -1) {
40832 return this._keys[i - 1];
40837 exports.Sequence = Sequence;
40838 exports.default = Sequence;
40840 },{"underscore":242}],405:[function(require,module,exports){
40842 /// <reference path="../../../typings/index.d.ts" />
40843 Object.defineProperty(exports, "__esModule", { value: true });
40844 var THREE = require("three");
40845 var Edge_1 = require("../../Edge");
40846 var Error_1 = require("../../Error");
40847 var Geo_1 = require("../../Geo");
40849 * @class EdgeCalculator
40851 * @classdesc Represents a class for calculating node edges.
40853 var EdgeCalculator = /** @class */ (function () {
40855 * Create a new edge calculator instance.
40857 * @param {EdgeCalculatorSettings} settings - Settings struct.
40858 * @param {EdgeCalculatorDirections} directions - Directions struct.
40859 * @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
40861 function EdgeCalculator(settings, directions, coefficients) {
40862 this._spatial = new Geo_1.Spatial();
40863 this._geoCoords = new Geo_1.GeoCoords();
40864 this._settings = settings != null ? settings : new Edge_1.EdgeCalculatorSettings();
40865 this._directions = directions != null ? directions : new Edge_1.EdgeCalculatorDirections();
40866 this._coefficients = coefficients != null ? coefficients : new Edge_1.EdgeCalculatorCoefficients();
40869 * Returns the potential edges to destination nodes for a set
40870 * of nodes with respect to a source node.
40872 * @param {Node} node - Source node.
40873 * @param {Array<Node>} nodes - Potential destination nodes.
40874 * @param {Array<string>} fallbackKeys - Keys for destination nodes that should
40875 * be returned even if they do not meet the criteria for a potential edge.
40876 * @throws {ArgumentMapillaryError} If node is not full.
40878 EdgeCalculator.prototype.getPotentialEdges = function (node, potentialNodes, fallbackKeys) {
40880 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40882 if (!node.merged) {
40885 var currentDirection = this._spatial.viewingDirection(node.rotation);
40886 var currentVerticalDirection = this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
40887 var potentialEdges = [];
40888 for (var _i = 0, potentialNodes_1 = potentialNodes; _i < potentialNodes_1.length; _i++) {
40889 var potential = potentialNodes_1[_i];
40890 if (!potential.merged ||
40891 potential.key === node.key) {
40894 var enu = this._geoCoords.geodeticToEnu(potential.latLon.lat, potential.latLon.lon, potential.alt, node.latLon.lat, node.latLon.lon, node.alt);
40895 var motion = new THREE.Vector3(enu[0], enu[1], enu[2]);
40896 var distance = motion.length();
40897 if (distance > this._settings.maxDistance &&
40898 fallbackKeys.indexOf(potential.key) < 0) {
40901 var motionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, motion.x, motion.y);
40902 var verticalMotion = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
40903 var direction = this._spatial.viewingDirection(potential.rotation);
40904 var directionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
40905 var verticalDirection = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
40906 var verticalDirectionChange = verticalDirection - currentVerticalDirection;
40907 var rotation = this._spatial.relativeRotationAngle(node.rotation, potential.rotation);
40908 var worldMotionAzimuth = this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
40909 var sameSequence = potential.sequenceKey != null &&
40910 node.sequenceKey != null &&
40911 potential.sequenceKey === node.sequenceKey;
40912 var sameMergeCC = (potential.mergeCC == null && node.mergeCC == null) ||
40913 potential.mergeCC === node.mergeCC;
40914 var sameUser = potential.userKey === node.userKey;
40915 var potentialEdge = {
40916 capturedAt: potential.capturedAt,
40917 croppedPano: potential.pano && !potential.fullPano,
40918 directionChange: directionChange,
40919 distance: distance,
40920 fullPano: potential.fullPano,
40921 key: potential.key,
40922 motionChange: motionChange,
40923 rotation: rotation,
40924 sameMergeCC: sameMergeCC,
40925 sameSequence: sameSequence,
40926 sameUser: sameUser,
40927 sequenceKey: potential.sequenceKey,
40928 verticalDirectionChange: verticalDirectionChange,
40929 verticalMotion: verticalMotion,
40930 worldMotionAzimuth: worldMotionAzimuth,
40932 potentialEdges.push(potentialEdge);
40934 return potentialEdges;
40937 * Computes the sequence edges for a node.
40939 * @param {Node} node - Source node.
40940 * @throws {ArgumentMapillaryError} If node is not full.
40942 EdgeCalculator.prototype.computeSequenceEdges = function (node, sequence) {
40944 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40946 if (node.sequenceKey !== sequence.key) {
40947 throw new Error_1.ArgumentMapillaryError("Node and sequence does not correspond.");
40950 var nextKey = sequence.findNextKey(node.key);
40951 if (nextKey != null) {
40954 direction: Edge_1.EdgeDirection.Next,
40955 worldMotionAzimuth: Number.NaN,
40961 var prevKey = sequence.findPrevKey(node.key);
40962 if (prevKey != null) {
40965 direction: Edge_1.EdgeDirection.Prev,
40966 worldMotionAzimuth: Number.NaN,
40975 * Computes the similar edges for a node.
40977 * @description Similar edges for perspective images and cropped panoramas
40978 * look roughly in the same direction and are positioned closed to the node.
40979 * Similar edges for full panoramas only target other full panoramas.
40981 * @param {Node} node - Source node.
40982 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
40983 * @throws {ArgumentMapillaryError} If node is not full.
40985 EdgeCalculator.prototype.computeSimilarEdges = function (node, potentialEdges) {
40988 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40990 var nodeFullPano = node.fullPano;
40991 var sequenceGroups = {};
40992 for (var _i = 0, potentialEdges_1 = potentialEdges; _i < potentialEdges_1.length; _i++) {
40993 var potentialEdge = potentialEdges_1[_i];
40994 if (potentialEdge.sequenceKey == null) {
40997 if (potentialEdge.sameSequence) {
41000 if (nodeFullPano) {
41001 if (!potentialEdge.fullPano) {
41006 if (!potentialEdge.fullPano &&
41007 Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
41011 if (potentialEdge.distance > this._settings.similarMaxDistance) {
41014 if (potentialEdge.sameUser &&
41015 Math.abs(potentialEdge.capturedAt - node.capturedAt) <
41016 this._settings.similarMinTimeDifference) {
41019 if (sequenceGroups[potentialEdge.sequenceKey] == null) {
41020 sequenceGroups[potentialEdge.sequenceKey] = [];
41022 sequenceGroups[potentialEdge.sequenceKey].push(potentialEdge);
41024 var similarEdges = [];
41025 var calculateScore = node.fullPano ?
41026 function (potentialEdge) {
41027 return potentialEdge.distance;
41029 function (potentialEdge) {
41030 return _this._coefficients.similarDistance * potentialEdge.distance +
41031 _this._coefficients.similarRotation * potentialEdge.rotation;
41033 for (var sequenceKey in sequenceGroups) {
41034 if (!sequenceGroups.hasOwnProperty(sequenceKey)) {
41037 var lowestScore = Number.MAX_VALUE;
41038 var similarEdge = null;
41039 for (var _a = 0, _b = sequenceGroups[sequenceKey]; _a < _b.length; _a++) {
41040 var potentialEdge = _b[_a];
41041 var score = calculateScore(potentialEdge);
41042 if (score < lowestScore) {
41043 lowestScore = score;
41044 similarEdge = potentialEdge;
41047 if (similarEdge == null) {
41050 similarEdges.push(similarEdge);
41052 return similarEdges
41053 .map(function (potentialEdge) {
41056 direction: Edge_1.EdgeDirection.Similar,
41057 worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
41060 to: potentialEdge.key,
41065 * Computes the step edges for a perspective node.
41067 * @description Step edge targets can only be other perspective nodes.
41068 * Returns an empty array for cropped and full panoramas.
41070 * @param {Node} node - Source node.
41071 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
41072 * @param {string} prevKey - Key of previous node in sequence.
41073 * @param {string} prevKey - Key of next node in sequence.
41074 * @throws {ArgumentMapillaryError} If node is not full.
41076 EdgeCalculator.prototype.computeStepEdges = function (node, potentialEdges, prevKey, nextKey) {
41078 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
41084 for (var k in this._directions.steps) {
41085 if (!this._directions.steps.hasOwnProperty(k)) {
41088 var step = this._directions.steps[k];
41089 var lowestScore = Number.MAX_VALUE;
41091 var fallback = null;
41092 for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) {
41093 var potential = potentialEdges_2[_i];
41094 if (potential.croppedPano || potential.fullPano) {
41097 if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
41100 var motionDifference = this._spatial.angleDifference(step.motionChange, potential.motionChange);
41101 var directionMotionDifference = this._spatial.angleDifference(potential.directionChange, motionDifference);
41102 var drift = Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
41103 if (Math.abs(drift) > this._settings.stepMaxDrift) {
41106 var potentialKey = potential.key;
41107 if (step.useFallback && (potentialKey === prevKey || potentialKey === nextKey)) {
41108 fallback = potential;
41110 if (potential.distance > this._settings.stepMaxDistance) {
41113 motionDifference = Math.sqrt(motionDifference * motionDifference +
41114 potential.verticalMotion * potential.verticalMotion);
41115 var score = this._coefficients.stepPreferredDistance *
41116 Math.abs(potential.distance - this._settings.stepPreferredDistance) /
41117 this._settings.stepMaxDistance +
41118 this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
41119 this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
41120 this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
41121 this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
41122 if (score < lowestScore) {
41123 lowestScore = score;
41127 edge = edge == null ? fallback : edge;
41128 if (edge != null) {
41131 direction: step.direction,
41132 worldMotionAzimuth: edge.worldMotionAzimuth,
41142 * Computes the turn edges for a perspective node.
41144 * @description Turn edge targets can only be other perspective images.
41145 * Returns an empty array for cropped and full panoramas.
41147 * @param {Node} node - Source node.
41148 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
41149 * @throws {ArgumentMapillaryError} If node is not full.
41151 EdgeCalculator.prototype.computeTurnEdges = function (node, potentialEdges) {
41153 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
41159 for (var k in this._directions.turns) {
41160 if (!this._directions.turns.hasOwnProperty(k)) {
41163 var turn = this._directions.turns[k];
41164 var lowestScore = Number.MAX_VALUE;
41166 for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) {
41167 var potential = potentialEdges_3[_i];
41168 if (potential.croppedPano || potential.fullPano) {
41171 if (potential.distance > this._settings.turnMaxDistance) {
41174 var rig = turn.direction !== Edge_1.EdgeDirection.TurnU &&
41175 potential.distance < this._settings.turnMaxRigDistance &&
41176 Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
41177 var directionDifference = this._spatial.angleDifference(turn.directionChange, potential.directionChange);
41178 var score = void 0;
41180 potential.directionChange * turn.directionChange > 0 &&
41181 Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
41182 score = -Math.PI / 2 + Math.abs(potential.directionChange);
41185 if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
41188 var motionDifference = turn.motionChange ?
41189 this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
41190 motionDifference = Math.sqrt(motionDifference * motionDifference +
41191 potential.verticalMotion * potential.verticalMotion);
41193 this._coefficients.turnDistance * potential.distance /
41194 this._settings.turnMaxDistance +
41195 this._coefficients.turnMotion * motionDifference / Math.PI +
41196 this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
41197 this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
41199 if (score < lowestScore) {
41200 lowestScore = score;
41204 if (edge != null) {
41207 direction: turn.direction,
41208 worldMotionAzimuth: edge.worldMotionAzimuth,
41218 * Computes the pano edges for a perspective node.
41220 * @description Perspective to pano edge targets can only be
41221 * full pano nodes. Returns an empty array for cropped and full panoramas.
41223 * @param {Node} node - Source node.
41224 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
41225 * @throws {ArgumentMapillaryError} If node is not full.
41227 EdgeCalculator.prototype.computePerspectiveToPanoEdges = function (node, potentialEdges) {
41229 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
41234 var lowestScore = Number.MAX_VALUE;
41236 for (var _i = 0, potentialEdges_4 = potentialEdges; _i < potentialEdges_4.length; _i++) {
41237 var potential = potentialEdges_4[_i];
41238 if (!potential.fullPano) {
41241 var score = this._coefficients.panoPreferredDistance *
41242 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
41243 this._settings.panoMaxDistance +
41244 this._coefficients.panoMotion * Math.abs(potential.motionChange) / Math.PI +
41245 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
41246 if (score < lowestScore) {
41247 lowestScore = score;
41251 if (edge == null) {
41257 direction: Edge_1.EdgeDirection.Pano,
41258 worldMotionAzimuth: edge.worldMotionAzimuth,
41266 * Computes the full pano and step edges for a full pano node.
41268 * @description Pano to pano edge targets can only be
41269 * full pano nodes. Pano to step edge targets can only be perspective
41271 * Returns an empty array for cropped panoramas and perspective nodes.
41273 * @param {Node} node - Source node.
41274 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
41275 * @throws {ArgumentMapillaryError} If node is not full.
41277 EdgeCalculator.prototype.computePanoEdges = function (node, potentialEdges) {
41279 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
41281 if (!node.fullPano) {
41284 var panoEdges = [];
41285 var potentialPanos = [];
41286 var potentialSteps = [];
41287 for (var _i = 0, potentialEdges_5 = potentialEdges; _i < potentialEdges_5.length; _i++) {
41288 var potential = potentialEdges_5[_i];
41289 if (potential.distance > this._settings.panoMaxDistance) {
41292 if (potential.fullPano) {
41293 if (potential.distance < this._settings.panoMinDistance) {
41296 potentialPanos.push(potential);
41299 if (potential.croppedPano) {
41302 for (var k in this._directions.panos) {
41303 if (!this._directions.panos.hasOwnProperty(k)) {
41306 var pano = this._directions.panos[k];
41307 var turn = this._spatial.angleDifference(potential.directionChange, potential.motionChange);
41308 var turnChange = this._spatial.angleDifference(pano.directionChange, turn);
41309 if (Math.abs(turnChange) > this._settings.panoMaxStepTurnChange) {
41312 potentialSteps.push([pano.direction, potential]);
41313 // break if step direction found
41318 var maxRotationDifference = Math.PI / this._settings.panoMaxItems;
41319 var occupiedAngles = [];
41320 var stepAngles = [];
41321 for (var index = 0; index < this._settings.panoMaxItems; index++) {
41322 var rotation = index / this._settings.panoMaxItems * 2 * Math.PI;
41323 var lowestScore = Number.MAX_VALUE;
41325 for (var _a = 0, potentialPanos_1 = potentialPanos; _a < potentialPanos_1.length; _a++) {
41326 var potential = potentialPanos_1[_a];
41327 var motionDifference = this._spatial.angleDifference(rotation, potential.motionChange);
41328 if (Math.abs(motionDifference) > maxRotationDifference) {
41331 var occupiedDifference = Number.MAX_VALUE;
41332 for (var _b = 0, occupiedAngles_1 = occupiedAngles; _b < occupiedAngles_1.length; _b++) {
41333 var occupiedAngle = occupiedAngles_1[_b];
41334 var difference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
41335 if (difference < occupiedDifference) {
41336 occupiedDifference = difference;
41339 if (occupiedDifference <= maxRotationDifference) {
41342 var score = this._coefficients.panoPreferredDistance *
41343 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
41344 this._settings.panoMaxDistance +
41345 this._coefficients.panoMotion * Math.abs(motionDifference) / maxRotationDifference +
41346 this._coefficients.panoSequencePenalty * (potential.sameSequence ? 0 : 1) +
41347 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
41348 if (score < lowestScore) {
41349 lowestScore = score;
41353 if (edge != null) {
41354 occupiedAngles.push(edge.motionChange);
41357 direction: Edge_1.EdgeDirection.Pano,
41358 worldMotionAzimuth: edge.worldMotionAzimuth,
41365 stepAngles.push(rotation);
41368 var occupiedStepAngles = {};
41369 occupiedStepAngles[Edge_1.EdgeDirection.Pano] = occupiedAngles;
41370 occupiedStepAngles[Edge_1.EdgeDirection.StepForward] = [];
41371 occupiedStepAngles[Edge_1.EdgeDirection.StepLeft] = [];
41372 occupiedStepAngles[Edge_1.EdgeDirection.StepBackward] = [];
41373 occupiedStepAngles[Edge_1.EdgeDirection.StepRight] = [];
41374 for (var _c = 0, stepAngles_1 = stepAngles; _c < stepAngles_1.length; _c++) {
41375 var stepAngle = stepAngles_1[_c];
41376 var occupations = [];
41377 for (var k in this._directions.panos) {
41378 if (!this._directions.panos.hasOwnProperty(k)) {
41381 var pano = this._directions.panos[k];
41382 var allOccupiedAngles = occupiedStepAngles[Edge_1.EdgeDirection.Pano]
41383 .concat(occupiedStepAngles[pano.direction])
41384 .concat(occupiedStepAngles[pano.prev])
41385 .concat(occupiedStepAngles[pano.next]);
41386 var lowestScore = Number.MAX_VALUE;
41388 for (var _d = 0, potentialSteps_1 = potentialSteps; _d < potentialSteps_1.length; _d++) {
41389 var potential = potentialSteps_1[_d];
41390 if (potential[0] !== pano.direction) {
41393 var motionChange = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
41394 if (Math.abs(motionChange) > maxRotationDifference) {
41397 var minOccupiedDifference = Number.MAX_VALUE;
41398 for (var _e = 0, allOccupiedAngles_1 = allOccupiedAngles; _e < allOccupiedAngles_1.length; _e++) {
41399 var occupiedAngle = allOccupiedAngles_1[_e];
41400 var occupiedDifference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
41401 if (occupiedDifference < minOccupiedDifference) {
41402 minOccupiedDifference = occupiedDifference;
41405 if (minOccupiedDifference <= maxRotationDifference) {
41408 var score = this._coefficients.panoPreferredDistance *
41409 Math.abs(potential[1].distance - this._settings.panoPreferredDistance) /
41410 this._settings.panoMaxDistance +
41411 this._coefficients.panoMotion * Math.abs(motionChange) / maxRotationDifference +
41412 this._coefficients.panoMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
41413 if (score < lowestScore) {
41414 lowestScore = score;
41418 if (edge != null) {
41419 occupations.push(edge);
41422 direction: edge[0],
41423 worldMotionAzimuth: edge[1].worldMotionAzimuth,
41430 for (var _f = 0, occupations_1 = occupations; _f < occupations_1.length; _f++) {
41431 var occupation = occupations_1[_f];
41432 occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
41437 return EdgeCalculator;
41439 exports.EdgeCalculator = EdgeCalculator;
41440 exports.default = EdgeCalculator;
41442 },{"../../Edge":291,"../../Error":292,"../../Geo":293,"three":240}],406:[function(require,module,exports){
41444 Object.defineProperty(exports, "__esModule", { value: true });
41445 var EdgeCalculatorCoefficients = /** @class */ (function () {
41446 function EdgeCalculatorCoefficients() {
41447 this.panoPreferredDistance = 2;
41448 this.panoMotion = 2;
41449 this.panoSequencePenalty = 1;
41450 this.panoMergeCCPenalty = 4;
41451 this.stepPreferredDistance = 4;
41452 this.stepMotion = 3;
41453 this.stepRotation = 4;
41454 this.stepSequencePenalty = 2;
41455 this.stepMergeCCPenalty = 6;
41456 this.similarDistance = 2;
41457 this.similarRotation = 3;
41458 this.turnDistance = 4;
41459 this.turnMotion = 2;
41460 this.turnSequencePenalty = 1;
41461 this.turnMergeCCPenalty = 4;
41463 return EdgeCalculatorCoefficients;
41465 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients;
41466 exports.default = EdgeCalculatorCoefficients;
41468 },{}],407:[function(require,module,exports){
41470 Object.defineProperty(exports, "__esModule", { value: true });
41471 var Edge_1 = require("../../Edge");
41472 var EdgeCalculatorDirections = /** @class */ (function () {
41473 function EdgeCalculatorDirections() {
41477 this.steps[Edge_1.EdgeDirection.StepForward] = {
41478 direction: Edge_1.EdgeDirection.StepForward,
41482 this.steps[Edge_1.EdgeDirection.StepBackward] = {
41483 direction: Edge_1.EdgeDirection.StepBackward,
41484 motionChange: Math.PI,
41487 this.steps[Edge_1.EdgeDirection.StepLeft] = {
41488 direction: Edge_1.EdgeDirection.StepLeft,
41489 motionChange: Math.PI / 2,
41490 useFallback: false,
41492 this.steps[Edge_1.EdgeDirection.StepRight] = {
41493 direction: Edge_1.EdgeDirection.StepRight,
41494 motionChange: -Math.PI / 2,
41495 useFallback: false,
41497 this.turns[Edge_1.EdgeDirection.TurnLeft] = {
41498 direction: Edge_1.EdgeDirection.TurnLeft,
41499 directionChange: Math.PI / 2,
41500 motionChange: Math.PI / 4,
41502 this.turns[Edge_1.EdgeDirection.TurnRight] = {
41503 direction: Edge_1.EdgeDirection.TurnRight,
41504 directionChange: -Math.PI / 2,
41505 motionChange: -Math.PI / 4,
41507 this.turns[Edge_1.EdgeDirection.TurnU] = {
41508 direction: Edge_1.EdgeDirection.TurnU,
41509 directionChange: Math.PI,
41510 motionChange: null,
41512 this.panos[Edge_1.EdgeDirection.StepForward] = {
41513 direction: Edge_1.EdgeDirection.StepForward,
41514 directionChange: 0,
41515 next: Edge_1.EdgeDirection.StepLeft,
41516 prev: Edge_1.EdgeDirection.StepRight,
41518 this.panos[Edge_1.EdgeDirection.StepBackward] = {
41519 direction: Edge_1.EdgeDirection.StepBackward,
41520 directionChange: Math.PI,
41521 next: Edge_1.EdgeDirection.StepRight,
41522 prev: Edge_1.EdgeDirection.StepLeft,
41524 this.panos[Edge_1.EdgeDirection.StepLeft] = {
41525 direction: Edge_1.EdgeDirection.StepLeft,
41526 directionChange: Math.PI / 2,
41527 next: Edge_1.EdgeDirection.StepBackward,
41528 prev: Edge_1.EdgeDirection.StepForward,
41530 this.panos[Edge_1.EdgeDirection.StepRight] = {
41531 direction: Edge_1.EdgeDirection.StepRight,
41532 directionChange: -Math.PI / 2,
41533 next: Edge_1.EdgeDirection.StepForward,
41534 prev: Edge_1.EdgeDirection.StepBackward,
41537 return EdgeCalculatorDirections;
41539 exports.EdgeCalculatorDirections = EdgeCalculatorDirections;
41541 },{"../../Edge":291}],408:[function(require,module,exports){
41543 Object.defineProperty(exports, "__esModule", { value: true });
41544 var EdgeCalculatorSettings = /** @class */ (function () {
41545 function EdgeCalculatorSettings() {
41546 this.panoMinDistance = 0.1;
41547 this.panoMaxDistance = 20;
41548 this.panoPreferredDistance = 5;
41549 this.panoMaxItems = 4;
41550 this.panoMaxStepTurnChange = Math.PI / 8;
41551 this.rotationMaxDistance = this.turnMaxRigDistance;
41552 this.rotationMaxDirectionChange = Math.PI / 6;
41553 this.rotationMaxVerticalDirectionChange = Math.PI / 8;
41554 this.similarMaxDirectionChange = Math.PI / 8;
41555 this.similarMaxDistance = 12;
41556 this.similarMinTimeDifference = 12 * 3600 * 1000;
41557 this.stepMaxDistance = 20;
41558 this.stepMaxDirectionChange = Math.PI / 6;
41559 this.stepMaxDrift = Math.PI / 6;
41560 this.stepPreferredDistance = 4;
41561 this.turnMaxDistance = 15;
41562 this.turnMaxDirectionChange = 2 * Math.PI / 9;
41563 this.turnMaxRigDistance = 0.65;
41564 this.turnMinRigDirectionChange = Math.PI / 6;
41566 Object.defineProperty(EdgeCalculatorSettings.prototype, "maxDistance", {
41568 return Math.max(this.panoMaxDistance, this.similarMaxDistance, this.stepMaxDistance, this.turnMaxDistance);
41573 return EdgeCalculatorSettings;
41575 exports.EdgeCalculatorSettings = EdgeCalculatorSettings;
41576 exports.default = EdgeCalculatorSettings;
41578 },{}],409:[function(require,module,exports){
41580 Object.defineProperty(exports, "__esModule", { value: true });
41582 * Enumeration for edge directions
41585 * @description Directions for edges in node graph describing
41586 * sequence, spatial and node type relations between nodes.
41589 (function (EdgeDirection) {
41591 * Next node in the sequence.
41593 EdgeDirection[EdgeDirection["Next"] = 0] = "Next";
41595 * Previous node in the sequence.
41597 EdgeDirection[EdgeDirection["Prev"] = 1] = "Prev";
41599 * Step to the left keeping viewing direction.
41601 EdgeDirection[EdgeDirection["StepLeft"] = 2] = "StepLeft";
41603 * Step to the right keeping viewing direction.
41605 EdgeDirection[EdgeDirection["StepRight"] = 3] = "StepRight";
41607 * Step forward keeping viewing direction.
41609 EdgeDirection[EdgeDirection["StepForward"] = 4] = "StepForward";
41611 * Step backward keeping viewing direction.
41613 EdgeDirection[EdgeDirection["StepBackward"] = 5] = "StepBackward";
41615 * Turn 90 degrees counter clockwise.
41617 EdgeDirection[EdgeDirection["TurnLeft"] = 6] = "TurnLeft";
41619 * Turn 90 degrees clockwise.
41621 EdgeDirection[EdgeDirection["TurnRight"] = 7] = "TurnRight";
41623 * Turn 180 degrees.
41625 EdgeDirection[EdgeDirection["TurnU"] = 8] = "TurnU";
41627 * Panorama in general direction.
41629 EdgeDirection[EdgeDirection["Pano"] = 9] = "Pano";
41631 * Looking in roughly the same direction at rougly the same position.
41633 EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar";
41634 })(EdgeDirection = exports.EdgeDirection || (exports.EdgeDirection = {}));
41636 },{}],410:[function(require,module,exports){
41638 /// <reference path="../../typings/index.d.ts" />
41639 Object.defineProperty(exports, "__esModule", { value: true });
41640 var _ = require("underscore");
41641 var vd = require("virtual-dom");
41642 var Subject_1 = require("rxjs/Subject");
41643 var Render_1 = require("../Render");
41644 var DOMRenderer = /** @class */ (function () {
41645 function DOMRenderer(element, renderService, currentFrame$) {
41646 this._adaptiveOperation$ = new Subject_1.Subject();
41647 this._render$ = new Subject_1.Subject();
41648 this._renderAdaptive$ = new Subject_1.Subject();
41649 this._renderService = renderService;
41650 this._currentFrame$ = currentFrame$;
41651 var rootNode = vd.create(vd.h("div.domRenderer", []));
41652 element.appendChild(rootNode);
41653 this._offset$ = this._adaptiveOperation$
41654 .scan(function (adaptive, operation) {
41655 return operation(adaptive);
41657 elementHeight: element.offsetHeight,
41658 elementWidth: element.offsetWidth,
41660 renderMode: Render_1.RenderMode.Fill,
41662 .filter(function (adaptive) {
41663 return adaptive.imageAspect > 0 && adaptive.elementWidth > 0 && adaptive.elementHeight > 0;
41665 .map(function (adaptive) {
41666 var elementAspect = adaptive.elementWidth / adaptive.elementHeight;
41667 var ratio = adaptive.imageAspect / elementAspect;
41668 var verticalOffset = 0;
41669 var horizontalOffset = 0;
41670 if (adaptive.renderMode === Render_1.RenderMode.Letterbox) {
41671 if (adaptive.imageAspect > elementAspect) {
41672 verticalOffset = adaptive.elementHeight * (1 - 1 / ratio) / 2;
41675 horizontalOffset = adaptive.elementWidth * (1 - ratio) / 2;
41679 if (adaptive.imageAspect > elementAspect) {
41680 horizontalOffset = -adaptive.elementWidth * (ratio - 1) / 2;
41683 verticalOffset = -adaptive.elementHeight * (1 / ratio - 1) / 2;
41687 bottom: verticalOffset,
41688 left: horizontalOffset,
41689 right: horizontalOffset,
41690 top: verticalOffset,
41693 this._currentFrame$
41694 .filter(function (frame) {
41695 return frame.state.currentNode != null;
41697 .distinctUntilChanged(function (k1, k2) {
41699 }, function (frame) {
41700 return frame.state.currentNode.key;
41702 .map(function (frame) {
41703 return frame.state.currentTransform.basicAspect;
41705 .map(function (aspect) {
41706 return function (adaptive) {
41707 adaptive.imageAspect = aspect;
41711 .subscribe(this._adaptiveOperation$);
41712 this._renderAdaptive$
41713 .scan(function (vNodeHashes, vNodeHash) {
41714 if (vNodeHash.vnode == null) {
41715 delete vNodeHashes[vNodeHash.name];
41718 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
41720 return vNodeHashes;
41722 .combineLatest(this._offset$)
41723 .map(function (vo) {
41724 var vNodes = _.values(vo[0]);
41725 var offset = vo[1];
41728 bottom: offset.bottom + "px",
41729 left: offset.left + "px",
41730 "pointer-events": "none",
41731 position: "absolute",
41732 right: offset.right + "px",
41733 top: offset.top + "px",
41737 name: "adaptiveDomRenderer",
41738 vnode: vd.h("div.adaptiveDomRenderer", properties, vNodes),
41741 .subscribe(this._render$);
41742 this._vNode$ = this._render$
41743 .scan(function (vNodeHashes, vNodeHash) {
41744 if (vNodeHash.vnode == null) {
41745 delete vNodeHashes[vNodeHash.name];
41748 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
41750 return vNodeHashes;
41752 .map(function (vNodeHashes) {
41753 var vNodes = _.values(vNodeHashes);
41754 return vd.h("div.domRenderer", vNodes);
41756 this._vPatch$ = this._vNode$
41757 .scan(function (nodePatch, vNode) {
41758 nodePatch.vpatch = vd.diff(nodePatch.vnode, vNode);
41759 nodePatch.vnode = vNode;
41761 }, { vnode: vd.h("div.domRenderer", []), vpatch: null })
41763 this._element$ = this._vPatch$
41764 .scan(function (oldElement, vPatch) {
41765 return vd.patch(oldElement, vPatch);
41769 this._element$.subscribe(function () { });
41770 this._renderService.size$
41771 .map(function (size) {
41772 return function (adaptive) {
41773 adaptive.elementWidth = size.width;
41774 adaptive.elementHeight = size.height;
41778 .subscribe(this._adaptiveOperation$);
41779 this._renderService.renderMode$
41780 .map(function (renderMode) {
41781 return function (adaptive) {
41782 adaptive.renderMode = renderMode;
41786 .subscribe(this._adaptiveOperation$);
41788 Object.defineProperty(DOMRenderer.prototype, "element$", {
41790 return this._element$;
41795 Object.defineProperty(DOMRenderer.prototype, "render$", {
41797 return this._render$;
41802 Object.defineProperty(DOMRenderer.prototype, "renderAdaptive$", {
41804 return this._renderAdaptive$;
41809 DOMRenderer.prototype.clear = function (name) {
41810 this._renderAdaptive$.next({ name: name, vnode: null });
41811 this._render$.next({ name: name, vnode: null });
41813 return DOMRenderer;
41815 exports.DOMRenderer = DOMRenderer;
41816 exports.default = DOMRenderer;
41818 },{"../Render":296,"rxjs/Subject":34,"underscore":242,"virtual-dom":246}],411:[function(require,module,exports){
41820 Object.defineProperty(exports, "__esModule", { value: true });
41822 (function (GLRenderStage) {
41823 GLRenderStage[GLRenderStage["Background"] = 0] = "Background";
41824 GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground";
41825 })(GLRenderStage = exports.GLRenderStage || (exports.GLRenderStage = {}));
41826 exports.default = GLRenderStage;
41828 },{}],412:[function(require,module,exports){
41830 /// <reference path="../../typings/index.d.ts" />
41831 Object.defineProperty(exports, "__esModule", { value: true });
41832 var THREE = require("three");
41833 var Observable_1 = require("rxjs/Observable");
41834 var Subject_1 = require("rxjs/Subject");
41835 var Render_1 = require("../Render");
41836 var Utils_1 = require("../Utils");
41837 var GLRenderer = /** @class */ (function () {
41838 function GLRenderer(canvasContainer, renderService, dom) {
41840 this._renderFrame$ = new Subject_1.Subject();
41841 this._renderCameraOperation$ = new Subject_1.Subject();
41842 this._render$ = new Subject_1.Subject();
41843 this._clear$ = new Subject_1.Subject();
41844 this._renderOperation$ = new Subject_1.Subject();
41845 this._rendererOperation$ = new Subject_1.Subject();
41846 this._eraserOperation$ = new Subject_1.Subject();
41847 this._renderService = renderService;
41848 this._dom = !!dom ? dom : new Utils_1.DOM();
41849 this._renderer$ = this._rendererOperation$
41850 .scan(function (renderer, operation) {
41851 return operation(renderer);
41852 }, { needsRender: false, renderer: null })
41853 .filter(function (renderer) {
41854 return !!renderer.renderer;
41856 this._renderCollection$ = this._renderOperation$
41857 .scan(function (hashes, operation) {
41858 return operation(hashes);
41861 this._renderCamera$ = this._renderCameraOperation$
41862 .scan(function (rc, operation) {
41863 return operation(rc);
41864 }, { frameId: -1, needsRender: false, perspective: null });
41865 this._eraser$ = this._eraserOperation$
41866 .startWith(function (eraser) {
41869 .scan(function (eraser, operation) {
41870 return operation(eraser);
41871 }, { needsRender: false });
41872 Observable_1.Observable
41873 .combineLatest([this._renderer$, this._renderCollection$, this._renderCamera$, this._eraser$], function (renderer, hashes, rc, eraser) {
41874 var renders = Object.keys(hashes)
41875 .map(function (key) {
41876 return hashes[key];
41878 return { camera: rc, eraser: eraser, renderer: renderer, renders: renders };
41880 .filter(function (co) {
41881 var needsRender = co.renderer.needsRender ||
41882 co.camera.needsRender ||
41883 co.eraser.needsRender;
41884 var frameId = co.camera.frameId;
41885 for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
41886 var render = _a[_i];
41887 if (render.frameId !== frameId) {
41890 needsRender = needsRender || render.needsRender;
41892 return needsRender;
41894 .distinctUntilChanged(function (n1, n2) {
41897 return co.eraser.needsRender ? -1 : co.camera.frameId;
41899 .subscribe(function (co) {
41900 co.renderer.needsRender = false;
41901 co.camera.needsRender = false;
41902 co.eraser.needsRender = false;
41903 var perspectiveCamera = co.camera.perspective;
41904 var backgroundRenders = [];
41905 var foregroundRenders = [];
41906 for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
41907 var render = _a[_i];
41908 if (render.stage === Render_1.GLRenderStage.Background) {
41909 backgroundRenders.push(render.render);
41911 else if (render.stage === Render_1.GLRenderStage.Foreground) {
41912 foregroundRenders.push(render.render);
41915 var renderer = co.renderer.renderer;
41917 for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) {
41918 var render = backgroundRenders_1[_b];
41919 render(perspectiveCamera, renderer);
41921 renderer.clearDepth();
41922 for (var _c = 0, foregroundRenders_1 = foregroundRenders; _c < foregroundRenders_1.length; _c++) {
41923 var render = foregroundRenders_1[_c];
41924 render(perspectiveCamera, renderer);
41928 .map(function (rc) {
41929 return function (irc) {
41930 irc.frameId = rc.frameId;
41931 irc.perspective = rc.perspective;
41932 if (rc.changed === true) {
41933 irc.needsRender = true;
41938 .subscribe(this._renderCameraOperation$);
41939 this._renderFrameSubscribe();
41940 var renderHash$ = this._render$
41941 .map(function (hash) {
41942 return function (hashes) {
41943 hashes[hash.name] = hash.render;
41947 var clearHash$ = this._clear$
41948 .map(function (name) {
41949 return function (hashes) {
41950 delete hashes[name];
41954 Observable_1.Observable
41955 .merge(renderHash$, clearHash$)
41956 .subscribe(this._renderOperation$);
41957 this._webGLRenderer$ = this._render$
41959 .map(function (hash) {
41960 var canvas = _this._dom.createElement("canvas", "mapillary-js-canvas");
41961 canvas.style.position = "absolute";
41962 canvas.setAttribute("tabindex", "0");
41963 canvasContainer.appendChild(canvas);
41964 var element = renderService.element;
41965 var webGLRenderer = new THREE.WebGLRenderer({ canvas: canvas });
41966 webGLRenderer.setPixelRatio(window.devicePixelRatio);
41967 webGLRenderer.setSize(element.offsetWidth, element.offsetHeight);
41968 webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0);
41969 webGLRenderer.autoClear = false;
41970 return webGLRenderer;
41974 this._webGLRenderer$.subscribe(function () { });
41975 var createRenderer$ = this._webGLRenderer$
41977 .map(function (webGLRenderer) {
41978 return function (renderer) {
41979 renderer.needsRender = true;
41980 renderer.renderer = webGLRenderer;
41984 var resizeRenderer$ = this._renderService.size$
41985 .map(function (size) {
41986 return function (renderer) {
41987 if (renderer.renderer == null) {
41990 renderer.renderer.setSize(size.width, size.height);
41991 renderer.needsRender = true;
41995 var clearRenderer$ = this._clear$
41996 .map(function (name) {
41997 return function (renderer) {
41998 if (renderer.renderer == null) {
42001 renderer.needsRender = true;
42005 Observable_1.Observable
42006 .merge(createRenderer$, resizeRenderer$, clearRenderer$)
42007 .subscribe(this._rendererOperation$);
42008 var renderCollectionEmpty$ = this._renderCollection$
42009 .filter(function (hashes) {
42010 return Object.keys(hashes).length === 0;
42013 renderCollectionEmpty$
42014 .subscribe(function (hashes) {
42015 if (_this._renderFrameSubscription == null) {
42018 _this._renderFrameSubscription.unsubscribe();
42019 _this._renderFrameSubscription = null;
42020 _this._renderFrameSubscribe();
42022 renderCollectionEmpty$
42023 .map(function (hashes) {
42024 return function (eraser) {
42025 eraser.needsRender = true;
42029 .subscribe(this._eraserOperation$);
42031 Object.defineProperty(GLRenderer.prototype, "render$", {
42033 return this._render$;
42038 Object.defineProperty(GLRenderer.prototype, "webGLRenderer$", {
42040 return this._webGLRenderer$;
42045 GLRenderer.prototype.clear = function (name) {
42046 this._clear$.next(name);
42048 GLRenderer.prototype._renderFrameSubscribe = function () {
42052 .map(function (renderHash) {
42053 return function (irc) {
42054 irc.needsRender = true;
42058 .subscribe(function (operation) {
42059 _this._renderCameraOperation$.next(operation);
42061 this._renderFrameSubscription = this._render$
42063 .mergeMap(function (hash) {
42064 return _this._renderService.renderCameraFrame$;
42066 .subscribe(this._renderFrame$);
42070 exports.GLRenderer = GLRenderer;
42071 exports.default = GLRenderer;
42073 },{"../Render":296,"../Utils":300,"rxjs/Observable":29,"rxjs/Subject":34,"three":240}],413:[function(require,module,exports){
42075 /// <reference path="../../typings/index.d.ts" />
42076 Object.defineProperty(exports, "__esModule", { value: true });
42077 var THREE = require("three");
42078 var Geo_1 = require("../Geo");
42079 var Render_1 = require("../Render");
42080 var RenderCamera = /** @class */ (function () {
42081 function RenderCamera(elementWidth, elementHeight, renderMode) {
42084 this._frameId = -1;
42085 this._changed = false;
42086 this._changedForFrame = -1;
42087 this.currentAspect = 1;
42088 this.currentPano = false;
42089 this.previousAspect = 1;
42090 this.previousPano = false;
42091 this.renderMode = renderMode;
42092 this._spatial = new Geo_1.Spatial();
42093 this._camera = new Geo_1.Camera();
42094 var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
42095 this._perspective = new THREE.PerspectiveCamera(50, perspectiveCameraAspect, 0.4, 10000);
42096 this._perspective.matrixAutoUpdate = false;
42097 this._rotation = { phi: 0, theta: 0 };
42099 Object.defineProperty(RenderCamera.prototype, "camera", {
42101 return this._camera;
42106 Object.defineProperty(RenderCamera.prototype, "changed", {
42108 return this.frameId === this._changedForFrame;
42113 Object.defineProperty(RenderCamera.prototype, "frameId", {
42115 return this._frameId;
42117 set: function (value) {
42118 this._frameId = value;
42119 if (this._changed) {
42120 this._changed = false;
42121 this._changedForFrame = value;
42127 Object.defineProperty(RenderCamera.prototype, "perspective", {
42129 return this._perspective;
42134 Object.defineProperty(RenderCamera.prototype, "rotation", {
42136 return this._rotation;
42141 RenderCamera.prototype.updateAspect = function (elementWidth, elementHeight) {
42142 var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
42143 this._perspective.aspect = perspectiveCameraAspect;
42144 this._changed = true;
42146 RenderCamera.prototype.updateProjection = function () {
42147 var currentAspect = this._getAspect(this.currentAspect, this.currentPano, this.perspective.aspect);
42148 var previousAspect = this._getAspect(this.previousAspect, this.previousPano, this.perspective.aspect);
42149 var aspect = (1 - this.alpha) * previousAspect + this.alpha * currentAspect;
42150 var verticalFov = this._getVerticalFov(aspect, this._camera.focal, this.zoom);
42151 this._perspective.fov = verticalFov;
42152 this._perspective.updateProjectionMatrix();
42153 this._changed = true;
42155 RenderCamera.prototype.updatePerspective = function (camera) {
42156 this._perspective.up.copy(camera.up);
42157 this._perspective.position.copy(camera.position);
42158 this._perspective.lookAt(camera.lookat);
42159 this._perspective.updateMatrix();
42160 this._perspective.updateMatrixWorld(false);
42161 this._changed = true;
42163 RenderCamera.prototype.updateRotation = function (camera) {
42164 this._rotation = this._getRotation(camera);
42166 RenderCamera.prototype._getVerticalFov = function (aspect, focal, zoom) {
42167 return 2 * Math.atan(0.5 / (Math.pow(2, zoom) * aspect * focal)) * 180 / Math.PI;
42169 RenderCamera.prototype._getAspect = function (nodeAspect, pano, perspectiveCameraAspect) {
42173 var coeff = Math.max(1, 1 / nodeAspect);
42174 var usePerspective = this.renderMode === Render_1.RenderMode.Letterbox ?
42175 nodeAspect > perspectiveCameraAspect :
42176 nodeAspect < perspectiveCameraAspect;
42177 var aspect = usePerspective ?
42178 coeff * perspectiveCameraAspect :
42179 coeff * nodeAspect;
42182 RenderCamera.prototype._getPerspectiveCameraAspect = function (elementWidth, elementHeight) {
42183 return elementWidth === 0 ? 0 : elementWidth / elementHeight;
42185 RenderCamera.prototype._getRotation = function (camera) {
42186 var direction = camera.lookat.clone().sub(camera.position);
42187 var up = camera.up.clone();
42188 var upProjection = direction.clone().dot(up);
42189 var planeProjection = direction.clone().sub(up.clone().multiplyScalar(upProjection));
42190 var phi = Math.atan2(planeProjection.y, planeProjection.x);
42191 var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
42192 return { phi: phi, theta: theta };
42194 return RenderCamera;
42196 exports.RenderCamera = RenderCamera;
42197 exports.default = RenderCamera;
42199 },{"../Geo":293,"../Render":296,"three":240}],414:[function(require,module,exports){
42201 Object.defineProperty(exports, "__esModule", { value: true });
42203 * Enumeration for render mode
42206 * @description Modes for specifying how rendering is done
42207 * in the viewer. All modes preserves the original aspect
42208 * ratio of the images.
42211 (function (RenderMode) {
42213 * Displays all content within the viewer.
42215 * @description Black bars shown on both
42216 * sides of the content. Bars are shown
42217 * either below and above or to the left
42218 * and right of the content depending on
42219 * the aspect ratio relation between the
42220 * image and the viewer.
42222 RenderMode[RenderMode["Letterbox"] = 0] = "Letterbox";
42224 * Fills the viewer by cropping content.
42226 * @description Cropping is done either
42227 * in horizontal or vertical direction
42228 * depending on the aspect ratio relation
42229 * between the image and the viewer.
42231 RenderMode[RenderMode["Fill"] = 1] = "Fill";
42232 })(RenderMode = exports.RenderMode || (exports.RenderMode = {}));
42233 exports.default = RenderMode;
42235 },{}],415:[function(require,module,exports){
42237 /// <reference path="../../typings/index.d.ts" />
42238 Object.defineProperty(exports, "__esModule", { value: true });
42239 var Subject_1 = require("rxjs/Subject");
42240 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
42241 var Geo_1 = require("../Geo");
42242 var Render_1 = require("../Render");
42243 var RenderService = /** @class */ (function () {
42244 function RenderService(element, currentFrame$, renderMode) {
42246 this._element = element;
42247 this._currentFrame$ = currentFrame$;
42248 this._spatial = new Geo_1.Spatial();
42249 renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill;
42250 this._resize$ = new Subject_1.Subject();
42251 this._renderCameraOperation$ = new Subject_1.Subject();
42253 new BehaviorSubject_1.BehaviorSubject({
42254 height: this._element.offsetHeight,
42255 width: this._element.offsetWidth,
42259 return { height: _this._element.offsetHeight, width: _this._element.offsetWidth };
42261 .subscribe(this._size$);
42262 this._renderMode$ = new BehaviorSubject_1.BehaviorSubject(renderMode);
42263 this._renderCameraHolder$ = this._renderCameraOperation$
42264 .startWith(function (rc) {
42267 .scan(function (rc, operation) {
42268 return operation(rc);
42269 }, new Render_1.RenderCamera(this._element.offsetWidth, this._element.offsetHeight, renderMode))
42272 this._renderCameraFrame$ = this._currentFrame$
42273 .withLatestFrom(this._renderCameraHolder$, function (frame, renderCamera) {
42274 return [frame, renderCamera];
42276 .do(function (args) {
42277 var frame = args[0];
42279 var camera = frame.state.camera;
42280 if (rc.alpha !== frame.state.alpha ||
42281 rc.zoom !== frame.state.zoom ||
42282 rc.camera.diff(camera) > 1e-9) {
42283 var currentTransform = frame.state.currentTransform;
42284 var previousTransform = frame.state.previousTransform != null ?
42285 frame.state.previousTransform :
42286 frame.state.currentTransform;
42287 var previousNode = frame.state.previousNode != null ?
42288 frame.state.previousNode :
42289 frame.state.currentNode;
42290 rc.currentAspect = currentTransform.basicAspect;
42291 rc.currentPano = frame.state.currentNode.pano;
42292 rc.previousAspect = previousTransform.basicAspect;
42293 rc.previousPano = previousNode.pano;
42294 rc.alpha = frame.state.alpha;
42295 rc.zoom = frame.state.zoom;
42296 rc.camera.copy(camera);
42297 rc.updatePerspective(camera);
42298 rc.updateRotation(camera);
42299 rc.updateProjection();
42301 rc.frameId = frame.id;
42303 .map(function (args) {
42308 this._renderCamera$ = this._renderCameraFrame$
42309 .filter(function (rc) {
42314 this._bearing$ = this._renderCamera$
42315 .map(function (renderCamera) {
42316 var bearing = _this._spatial.radToDeg(_this._spatial.azimuthalToBearing(renderCamera.rotation.phi));
42317 return _this._spatial.wrap(bearing, 0, 360);
42323 .map(function (size) {
42324 return function (rc) {
42325 rc.updateAspect(size.width, size.height);
42326 rc.updateProjection();
42330 .subscribe(this._renderCameraOperation$);
42333 .map(function (rm) {
42334 return function (rc) {
42335 rc.renderMode = rm;
42336 rc.updateProjection();
42340 .subscribe(this._renderCameraOperation$);
42341 this._bearing$.subscribe(function () { });
42342 this._renderCameraHolder$.subscribe(function () { });
42343 this._size$.subscribe(function () { });
42344 this._renderMode$.subscribe(function () { });
42345 this._renderCamera$.subscribe(function () { });
42346 this._renderCameraFrame$.subscribe(function () { });
42348 Object.defineProperty(RenderService.prototype, "bearing$", {
42350 return this._bearing$;
42355 Object.defineProperty(RenderService.prototype, "element", {
42357 return this._element;
42362 Object.defineProperty(RenderService.prototype, "resize$", {
42364 return this._resize$;
42369 Object.defineProperty(RenderService.prototype, "size$", {
42371 return this._size$;
42376 Object.defineProperty(RenderService.prototype, "renderMode$", {
42378 return this._renderMode$;
42383 Object.defineProperty(RenderService.prototype, "renderCameraFrame$", {
42385 return this._renderCameraFrame$;
42390 Object.defineProperty(RenderService.prototype, "renderCamera$", {
42392 return this._renderCamera$;
42397 return RenderService;
42399 exports.RenderService = RenderService;
42400 exports.default = RenderService;
42402 },{"../Geo":293,"../Render":296,"rxjs/BehaviorSubject":26,"rxjs/Subject":34}],416:[function(require,module,exports){
42404 Object.defineProperty(exports, "__esModule", { value: true });
42405 var RotationDelta = /** @class */ (function () {
42406 function RotationDelta(phi, theta) {
42408 this._theta = theta;
42410 Object.defineProperty(RotationDelta.prototype, "phi", {
42414 set: function (value) {
42420 Object.defineProperty(RotationDelta.prototype, "theta", {
42422 return this._theta;
42424 set: function (value) {
42425 this._theta = value;
42430 Object.defineProperty(RotationDelta.prototype, "isZero", {
42432 return this._phi === 0 && this._theta === 0;
42437 RotationDelta.prototype.copy = function (delta) {
42438 this._phi = delta.phi;
42439 this._theta = delta.theta;
42441 RotationDelta.prototype.lerp = function (other, alpha) {
42442 this._phi = (1 - alpha) * this._phi + alpha * other.phi;
42443 this._theta = (1 - alpha) * this._theta + alpha * other.theta;
42445 RotationDelta.prototype.multiply = function (value) {
42446 this._phi *= value;
42447 this._theta *= value;
42449 RotationDelta.prototype.threshold = function (value) {
42450 this._phi = Math.abs(this._phi) > value ? this._phi : 0;
42451 this._theta = Math.abs(this._theta) > value ? this._theta : 0;
42453 RotationDelta.prototype.lengthSquared = function () {
42454 return this._phi * this._phi + this._theta * this._theta;
42456 RotationDelta.prototype.reset = function () {
42460 return RotationDelta;
42462 exports.RotationDelta = RotationDelta;
42463 exports.default = RotationDelta;
42465 },{}],417:[function(require,module,exports){
42467 Object.defineProperty(exports, "__esModule", { value: true });
42469 (function (State) {
42470 State[State["Traversing"] = 0] = "Traversing";
42471 State[State["Waiting"] = 1] = "Waiting";
42472 State[State["WaitingInteractively"] = 2] = "WaitingInteractively";
42473 })(State = exports.State || (exports.State = {}));
42474 exports.default = State;
42476 },{}],418:[function(require,module,exports){
42478 Object.defineProperty(exports, "__esModule", { value: true });
42479 var State_1 = require("../State");
42480 var Geo_1 = require("../Geo");
42481 var StateContext = /** @class */ (function () {
42482 function StateContext(transitionMode) {
42483 this._state = new State_1.TraversingState({
42485 camera: new Geo_1.Camera(),
42487 reference: { alt: 0, lat: 0, lon: 0 },
42489 transitionMode: transitionMode == null ? State_1.TransitionMode.Default : transitionMode,
42493 StateContext.prototype.traverse = function () {
42494 this._state = this._state.traverse();
42496 StateContext.prototype.wait = function () {
42497 this._state = this._state.wait();
42499 StateContext.prototype.waitInteractively = function () {
42500 this._state = this._state.waitInteractively();
42502 Object.defineProperty(StateContext.prototype, "state", {
42504 if (this._state instanceof State_1.TraversingState) {
42505 return State_1.State.Traversing;
42507 else if (this._state instanceof State_1.WaitingState) {
42508 return State_1.State.Waiting;
42510 else if (this._state instanceof State_1.InteractiveWaitingState) {
42511 return State_1.State.WaitingInteractively;
42513 throw new Error("Invalid state");
42518 Object.defineProperty(StateContext.prototype, "reference", {
42520 return this._state.reference;
42525 Object.defineProperty(StateContext.prototype, "alpha", {
42527 return this._state.alpha;
42532 Object.defineProperty(StateContext.prototype, "camera", {
42534 return this._state.camera;
42539 Object.defineProperty(StateContext.prototype, "zoom", {
42541 return this._state.zoom;
42546 Object.defineProperty(StateContext.prototype, "currentNode", {
42548 return this._state.currentNode;
42553 Object.defineProperty(StateContext.prototype, "previousNode", {
42555 return this._state.previousNode;
42560 Object.defineProperty(StateContext.prototype, "currentCamera", {
42562 return this._state.currentCamera;
42567 Object.defineProperty(StateContext.prototype, "currentTransform", {
42569 return this._state.currentTransform;
42574 Object.defineProperty(StateContext.prototype, "previousTransform", {
42576 return this._state.previousTransform;
42581 Object.defineProperty(StateContext.prototype, "trajectory", {
42583 return this._state.trajectory;
42588 Object.defineProperty(StateContext.prototype, "currentIndex", {
42590 return this._state.currentIndex;
42595 Object.defineProperty(StateContext.prototype, "lastNode", {
42597 return this._state.trajectory[this._state.trajectory.length - 1];
42602 Object.defineProperty(StateContext.prototype, "nodesAhead", {
42604 return this._state.trajectory.length - 1 - this._state.currentIndex;
42609 Object.defineProperty(StateContext.prototype, "motionless", {
42611 return this._state.motionless;
42616 StateContext.prototype.getCenter = function () {
42617 return this._state.getCenter();
42619 StateContext.prototype.setCenter = function (center) {
42620 this._state.setCenter(center);
42622 StateContext.prototype.setZoom = function (zoom) {
42623 this._state.setZoom(zoom);
42625 StateContext.prototype.update = function (fps) {
42626 this._state.update(fps);
42628 StateContext.prototype.append = function (nodes) {
42629 this._state.append(nodes);
42631 StateContext.prototype.prepend = function (nodes) {
42632 this._state.prepend(nodes);
42634 StateContext.prototype.remove = function (n) {
42635 this._state.remove(n);
42637 StateContext.prototype.clear = function () {
42638 this._state.clear();
42640 StateContext.prototype.clearPrior = function () {
42641 this._state.clearPrior();
42643 StateContext.prototype.cut = function () {
42646 StateContext.prototype.set = function (nodes) {
42647 this._state.set(nodes);
42649 StateContext.prototype.rotate = function (delta) {
42650 this._state.rotate(delta);
42652 StateContext.prototype.rotateBasic = function (basicRotation) {
42653 this._state.rotateBasic(basicRotation);
42655 StateContext.prototype.rotateBasicUnbounded = function (basicRotation) {
42656 this._state.rotateBasicUnbounded(basicRotation);
42658 StateContext.prototype.rotateBasicWithoutInertia = function (basicRotation) {
42659 this._state.rotateBasicWithoutInertia(basicRotation);
42661 StateContext.prototype.rotateToBasic = function (basic) {
42662 this._state.rotateToBasic(basic);
42664 StateContext.prototype.move = function (delta) {
42665 this._state.move(delta);
42667 StateContext.prototype.moveTo = function (delta) {
42668 this._state.moveTo(delta);
42670 StateContext.prototype.zoomIn = function (delta, reference) {
42671 this._state.zoomIn(delta, reference);
42673 StateContext.prototype.setSpeed = function (speed) {
42674 this._state.setSpeed(speed);
42676 StateContext.prototype.setTransitionMode = function (mode) {
42677 this._state.setTransitionMode(mode);
42679 return StateContext;
42681 exports.StateContext = StateContext;
42683 },{"../Geo":293,"../State":297}],419:[function(require,module,exports){
42685 Object.defineProperty(exports, "__esModule", { value: true });
42686 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
42687 var Subject_1 = require("rxjs/Subject");
42688 var AnimationFrame_1 = require("rxjs/util/AnimationFrame");
42689 var State_1 = require("../State");
42690 var StateService = /** @class */ (function () {
42691 function StateService(transitionMode) {
42693 this._appendNode$ = new Subject_1.Subject();
42694 this._start$ = new Subject_1.Subject();
42695 this._frame$ = new Subject_1.Subject();
42696 this._fpsSampleRate = 30;
42697 this._contextOperation$ = new BehaviorSubject_1.BehaviorSubject(function (context) {
42700 this._context$ = this._contextOperation$
42701 .scan(function (context, operation) {
42702 return operation(context);
42703 }, new State_1.StateContext(transitionMode))
42706 this._state$ = this._context$
42707 .map(function (context) {
42708 return context.state;
42710 .distinctUntilChanged()
42713 this._fps$ = this._start$
42714 .switchMap(function () {
42715 return _this._frame$
42716 .bufferCount(1, _this._fpsSampleRate)
42717 .map(function (frameIds) {
42718 return new Date().getTime();
42721 .map(function (times) {
42722 return Math.max(20, 1000 * _this._fpsSampleRate / (times[1] - times[0]));
42727 this._currentState$ = this._frame$
42728 .withLatestFrom(this._fps$, this._context$, function (frameId, fps, context) {
42729 return [frameId, fps, context];
42731 .filter(function (fc) {
42732 return fc[2].currentNode != null;
42734 .do(function (fc) {
42735 fc[2].update(fc[1]);
42737 .map(function (fc) {
42738 return { fps: fc[1], id: fc[0], state: fc[2] };
42741 this._lastState$ = this._currentState$
42744 var nodeChanged$ = this._currentState$
42745 .distinctUntilChanged(undefined, function (f) {
42746 return f.state.currentNode.key;
42750 var nodeChangedSubject$ = new Subject_1.Subject();
42752 .subscribe(nodeChangedSubject$);
42753 this._currentKey$ = new BehaviorSubject_1.BehaviorSubject(null);
42754 nodeChangedSubject$
42755 .map(function (f) {
42756 return f.state.currentNode.key;
42758 .subscribe(this._currentKey$);
42759 this._currentNode$ = nodeChangedSubject$
42760 .map(function (f) {
42761 return f.state.currentNode;
42765 this._currentCamera$ = nodeChangedSubject$
42766 .map(function (f) {
42767 return f.state.currentCamera;
42771 this._currentTransform$ = nodeChangedSubject$
42772 .map(function (f) {
42773 return f.state.currentTransform;
42777 this._reference$ = nodeChangedSubject$
42778 .map(function (f) {
42779 return f.state.reference;
42781 .distinctUntilChanged(function (r1, r2) {
42782 return r1.lat === r2.lat && r1.lon === r2.lon;
42783 }, function (reference) {
42784 return { lat: reference.lat, lon: reference.lon };
42788 this._currentNodeExternal$ = nodeChanged$
42789 .map(function (f) {
42790 return f.state.currentNode;
42795 .map(function (node) {
42796 return function (context) {
42797 context.append([node]);
42801 .subscribe(this._contextOperation$);
42802 this._inMotionOperation$ = new Subject_1.Subject();
42804 .map(function (frame) {
42807 .subscribe(this._inMotionOperation$);
42808 this._inMotionOperation$
42809 .distinctUntilChanged()
42810 .filter(function (moving) {
42813 .switchMap(function (moving) {
42814 return _this._currentState$
42815 .filter(function (frame) {
42816 return frame.state.nodesAhead === 0;
42818 .map(function (frame) {
42819 return [frame.state.camera.clone(), frame.state.zoom];
42822 .map(function (pair) {
42823 var c1 = pair[0][0];
42824 var c2 = pair[1][0];
42825 var z1 = pair[0][1];
42826 var z2 = pair[1][1];
42827 return c1.diff(c2) > 1e-5 || Math.abs(z1 - z2) > 1e-5;
42829 .first(function (changed) {
42833 .subscribe(this._inMotionOperation$);
42834 this._inMotion$ = this._inMotionOperation$
42835 .distinctUntilChanged()
42838 this._inTranslationOperation$ = new Subject_1.Subject();
42840 .map(function (frame) {
42843 .subscribe(this._inTranslationOperation$);
42844 this._inTranslationOperation$
42845 .distinctUntilChanged()
42846 .filter(function (inTranslation) {
42847 return inTranslation;
42849 .switchMap(function (inTranslation) {
42850 return _this._currentState$
42851 .filter(function (frame) {
42852 return frame.state.nodesAhead === 0;
42854 .map(function (frame) {
42855 return frame.state.camera.position.clone();
42858 .map(function (pair) {
42859 return pair[0].distanceToSquared(pair[1]) !== 0;
42861 .first(function (changed) {
42865 .subscribe(this._inTranslationOperation$);
42866 this._inTranslation$ = this._inTranslationOperation$
42867 .distinctUntilChanged()
42870 this._state$.subscribe(function () { });
42871 this._currentNode$.subscribe(function () { });
42872 this._currentCamera$.subscribe(function () { });
42873 this._currentTransform$.subscribe(function () { });
42874 this._reference$.subscribe(function () { });
42875 this._currentNodeExternal$.subscribe(function () { });
42876 this._lastState$.subscribe(function () { });
42877 this._inMotion$.subscribe(function () { });
42878 this._inTranslation$.subscribe(function () { });
42879 this._frameId = null;
42880 this._frameGenerator = new AnimationFrame_1.RequestAnimationFrameDefinition(window);
42882 Object.defineProperty(StateService.prototype, "currentState$", {
42884 return this._currentState$;
42889 Object.defineProperty(StateService.prototype, "currentNode$", {
42891 return this._currentNode$;
42896 Object.defineProperty(StateService.prototype, "currentKey$", {
42898 return this._currentKey$;
42903 Object.defineProperty(StateService.prototype, "currentNodeExternal$", {
42905 return this._currentNodeExternal$;
42910 Object.defineProperty(StateService.prototype, "currentCamera$", {
42912 return this._currentCamera$;
42917 Object.defineProperty(StateService.prototype, "currentTransform$", {
42919 return this._currentTransform$;
42924 Object.defineProperty(StateService.prototype, "state$", {
42926 return this._state$;
42931 Object.defineProperty(StateService.prototype, "reference$", {
42933 return this._reference$;
42938 Object.defineProperty(StateService.prototype, "inMotion$", {
42940 return this._inMotion$;
42945 Object.defineProperty(StateService.prototype, "inTranslation$", {
42947 return this._inTranslation$;
42952 Object.defineProperty(StateService.prototype, "appendNode$", {
42954 return this._appendNode$;
42959 StateService.prototype.traverse = function () {
42960 this._inMotionOperation$.next(true);
42961 this._invokeContextOperation(function (context) { context.traverse(); });
42963 StateService.prototype.wait = function () {
42964 this._invokeContextOperation(function (context) { context.wait(); });
42966 StateService.prototype.waitInteractively = function () {
42967 this._invokeContextOperation(function (context) { context.waitInteractively(); });
42969 StateService.prototype.appendNodes = function (nodes) {
42970 this._invokeContextOperation(function (context) { context.append(nodes); });
42972 StateService.prototype.prependNodes = function (nodes) {
42973 this._invokeContextOperation(function (context) { context.prepend(nodes); });
42975 StateService.prototype.removeNodes = function (n) {
42976 this._invokeContextOperation(function (context) { context.remove(n); });
42978 StateService.prototype.clearNodes = function () {
42979 this._invokeContextOperation(function (context) { context.clear(); });
42981 StateService.prototype.clearPriorNodes = function () {
42982 this._invokeContextOperation(function (context) { context.clearPrior(); });
42984 StateService.prototype.cutNodes = function () {
42985 this._invokeContextOperation(function (context) { context.cut(); });
42987 StateService.prototype.setNodes = function (nodes) {
42988 this._invokeContextOperation(function (context) { context.set(nodes); });
42990 StateService.prototype.rotate = function (delta) {
42991 this._inMotionOperation$.next(true);
42992 this._invokeContextOperation(function (context) { context.rotate(delta); });
42994 StateService.prototype.rotateBasic = function (basicRotation) {
42995 this._inMotionOperation$.next(true);
42996 this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); });
42998 StateService.prototype.rotateBasicUnbounded = function (basicRotation) {
42999 this._inMotionOperation$.next(true);
43000 this._invokeContextOperation(function (context) { context.rotateBasicUnbounded(basicRotation); });
43002 StateService.prototype.rotateBasicWithoutInertia = function (basicRotation) {
43003 this._inMotionOperation$.next(true);
43004 this._invokeContextOperation(function (context) { context.rotateBasicWithoutInertia(basicRotation); });
43006 StateService.prototype.rotateToBasic = function (basic) {
43007 this._inMotionOperation$.next(true);
43008 this._invokeContextOperation(function (context) { context.rotateToBasic(basic); });
43010 StateService.prototype.move = function (delta) {
43011 this._inMotionOperation$.next(true);
43012 this._invokeContextOperation(function (context) { context.move(delta); });
43014 StateService.prototype.moveTo = function (position) {
43015 this._inMotionOperation$.next(true);
43016 this._invokeContextOperation(function (context) { context.moveTo(position); });
43019 * Change zoom level while keeping the reference point position approximately static.
43021 * @parameter {number} delta - Change in zoom level.
43022 * @parameter {Array<number>} reference - Reference point in basic coordinates.
43024 StateService.prototype.zoomIn = function (delta, reference) {
43025 this._inMotionOperation$.next(true);
43026 this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); });
43028 StateService.prototype.getCenter = function () {
43029 return this._lastState$
43031 .map(function (frame) {
43032 return frame.state.getCenter();
43035 StateService.prototype.getZoom = function () {
43036 return this._lastState$
43038 .map(function (frame) {
43039 return frame.state.zoom;
43042 StateService.prototype.setCenter = function (center) {
43043 this._inMotionOperation$.next(true);
43044 this._invokeContextOperation(function (context) { context.setCenter(center); });
43046 StateService.prototype.setSpeed = function (speed) {
43047 this._invokeContextOperation(function (context) { context.setSpeed(speed); });
43049 StateService.prototype.setTransitionMode = function (mode) {
43050 this._invokeContextOperation(function (context) { context.setTransitionMode(mode); });
43052 StateService.prototype.setZoom = function (zoom) {
43053 this._inMotionOperation$.next(true);
43054 this._invokeContextOperation(function (context) { context.setZoom(zoom); });
43056 StateService.prototype.start = function () {
43057 if (this._frameId == null) {
43058 this._start$.next(null);
43059 this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
43060 this._frame$.next(this._frameId);
43063 StateService.prototype.stop = function () {
43064 if (this._frameId != null) {
43065 this._frameGenerator.cancelAnimationFrame(this._frameId);
43066 this._frameId = null;
43069 StateService.prototype._invokeContextOperation = function (action) {
43070 this._contextOperation$
43071 .next(function (context) {
43076 StateService.prototype._frame = function (time) {
43077 this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
43078 this._frame$.next(this._frameId);
43080 return StateService;
43082 exports.StateService = StateService;
43084 },{"../State":297,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/util/AnimationFrame":217}],420:[function(require,module,exports){
43086 Object.defineProperty(exports, "__esModule", { value: true });
43088 * Enumeration for transition mode
43091 * @description Modes for specifying how transitions
43092 * between nodes are performed.
43094 var TransitionMode;
43095 (function (TransitionMode) {
43097 * Default transitions.
43099 * @description The viewer dynamically determines
43100 * whether transitions should be performed with or
43101 * without motion and blending for each transition
43102 * based on the underlying data.
43104 TransitionMode[TransitionMode["Default"] = 0] = "Default";
43106 * Instantaneous transitions.
43108 * @description All transitions are performed
43109 * without motion or blending.
43111 TransitionMode[TransitionMode["Instantaneous"] = 1] = "Instantaneous";
43112 })(TransitionMode = exports.TransitionMode || (exports.TransitionMode = {}));
43113 exports.default = TransitionMode;
43115 },{}],421:[function(require,module,exports){
43117 var __extends = (this && this.__extends) || (function () {
43118 var extendStatics = Object.setPrototypeOf ||
43119 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
43120 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
43121 return function (d, b) {
43122 extendStatics(d, b);
43123 function __() { this.constructor = d; }
43124 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
43127 Object.defineProperty(exports, "__esModule", { value: true });
43128 var THREE = require("three");
43129 var State_1 = require("../../State");
43130 var InteractiveStateBase = /** @class */ (function (_super) {
43131 __extends(InteractiveStateBase, _super);
43132 function InteractiveStateBase(state) {
43133 var _this = _super.call(this, state) || this;
43134 _this._animationSpeed = 1 / 40;
43135 _this._rotationDelta = new State_1.RotationDelta(0, 0);
43136 _this._requestedRotationDelta = null;
43137 _this._basicRotation = [0, 0];
43138 _this._requestedBasicRotation = null;
43139 _this._requestedBasicRotationUnbounded = null;
43140 _this._rotationAcceleration = 0.86;
43141 _this._rotationIncreaseAlpha = 0.97;
43142 _this._rotationDecreaseAlpha = 0.9;
43143 _this._rotationThreshold = 1e-3;
43144 _this._unboundedRotationAlpha = 0.8;
43145 _this._desiredZoom = state.zoom;
43146 _this._minZoom = 0;
43147 _this._maxZoom = 3;
43148 _this._lookatDepth = 10;
43149 _this._desiredLookat = null;
43150 _this._desiredCenter = null;
43153 InteractiveStateBase.prototype.rotate = function (rotationDelta) {
43154 if (this._currentNode == null) {
43157 this._desiredZoom = this._zoom;
43158 this._desiredLookat = null;
43159 this._requestedBasicRotation = null;
43160 if (this._requestedRotationDelta != null) {
43161 this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi;
43162 this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta;
43165 this._requestedRotationDelta = new State_1.RotationDelta(rotationDelta.phi, rotationDelta.theta);
43168 InteractiveStateBase.prototype.rotateBasic = function (basicRotation) {
43169 if (this._currentNode == null) {
43172 this._desiredZoom = this._zoom;
43173 this._desiredLookat = null;
43174 this._requestedRotationDelta = null;
43175 if (this._requestedBasicRotation != null) {
43176 this._requestedBasicRotation[0] += basicRotation[0];
43177 this._requestedBasicRotation[1] += basicRotation[1];
43178 var threshold = 0.05 / Math.pow(2, this._zoom);
43179 this._requestedBasicRotation[0] =
43180 this._spatial.clamp(this._requestedBasicRotation[0], -threshold, threshold);
43181 this._requestedBasicRotation[1] =
43182 this._spatial.clamp(this._requestedBasicRotation[1], -threshold, threshold);
43185 this._requestedBasicRotation = basicRotation.slice();
43188 InteractiveStateBase.prototype.rotateBasicUnbounded = function (basicRotation) {
43189 if (this._currentNode == null) {
43192 if (this._requestedBasicRotationUnbounded != null) {
43193 this._requestedBasicRotationUnbounded[0] += basicRotation[0];
43194 this._requestedBasicRotationUnbounded[1] += basicRotation[1];
43197 this._requestedBasicRotationUnbounded = basicRotation.slice();
43200 InteractiveStateBase.prototype.rotateBasicWithoutInertia = function (basic) {
43201 if (this._currentNode == null) {
43204 this._desiredZoom = this._zoom;
43205 this._desiredLookat = null;
43206 this._requestedRotationDelta = null;
43207 this._requestedBasicRotation = null;
43208 var threshold = 0.05 / Math.pow(2, this._zoom);
43209 var basicRotation = basic.slice();
43210 basicRotation[0] = this._spatial.clamp(basicRotation[0], -threshold, threshold);
43211 basicRotation[1] = this._spatial.clamp(basicRotation[1], -threshold, threshold);
43212 this._applyRotationBasic(basicRotation);
43214 InteractiveStateBase.prototype.rotateToBasic = function (basic) {
43215 if (this._currentNode == null) {
43218 this._desiredZoom = this._zoom;
43219 this._desiredLookat = null;
43220 basic[0] = this._spatial.clamp(basic[0], 0, 1);
43221 basic[1] = this._spatial.clamp(basic[1], 0, 1);
43222 var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth);
43223 this._currentCamera.lookat.fromArray(lookat);
43225 InteractiveStateBase.prototype.zoomIn = function (delta, reference) {
43226 if (this._currentNode == null) {
43229 this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta));
43230 var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray());
43231 var currentCenterX = currentCenter[0];
43232 var currentCenterY = currentCenter[1];
43233 var zoom0 = Math.pow(2, this._zoom);
43234 var zoom1 = Math.pow(2, this._desiredZoom);
43235 var refX = reference[0];
43236 var refY = reference[1];
43237 if (this.currentTransform.gpano != null &&
43238 this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
43239 if (refX - currentCenterX > 0.5) {
43242 else if (currentCenterX - refX > 0.5) {
43246 var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX);
43247 var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY);
43248 var gpano = this.currentTransform.gpano;
43249 if (this._currentNode.fullPano) {
43250 newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
43251 newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95);
43253 else if (gpano != null &&
43254 this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
43255 newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
43256 newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1);
43259 newCenterX = this._spatial.clamp(newCenterX, 0, 1);
43260 newCenterY = this._spatial.clamp(newCenterY, 0, 1);
43262 this._desiredLookat = new THREE.Vector3()
43263 .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth));
43265 InteractiveStateBase.prototype.setCenter = function (center) {
43266 this._desiredLookat = null;
43267 this._requestedRotationDelta = null;
43268 this._requestedBasicRotation = null;
43269 this._desiredZoom = this._zoom;
43271 this._spatial.clamp(center[0], 0, 1),
43272 this._spatial.clamp(center[1], 0, 1),
43274 if (this._currentNode == null) {
43275 this._desiredCenter = clamped;
43278 this._desiredCenter = null;
43279 var currentLookat = new THREE.Vector3()
43280 .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth));
43281 var previousTransform = this.previousTransform != null ?
43282 this.previousTransform :
43283 this.currentTransform;
43284 var previousLookat = new THREE.Vector3()
43285 .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth));
43286 this._currentCamera.lookat.copy(currentLookat);
43287 this._previousCamera.lookat.copy(previousLookat);
43289 InteractiveStateBase.prototype.setZoom = function (zoom) {
43290 this._desiredLookat = null;
43291 this._requestedRotationDelta = null;
43292 this._requestedBasicRotation = null;
43293 this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom);
43294 this._desiredZoom = this._zoom;
43296 InteractiveStateBase.prototype._applyRotation = function (camera) {
43297 if (camera == null) {
43300 var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
43301 var qInverse = q.clone().inverse();
43302 var offset = new THREE.Vector3();
43303 offset.copy(camera.lookat).sub(camera.position);
43304 offset.applyQuaternion(q);
43305 var length = offset.length();
43306 var phi = Math.atan2(offset.y, offset.x);
43307 phi += this._rotationDelta.phi;
43308 var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
43309 theta += this._rotationDelta.theta;
43310 theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
43311 offset.x = Math.sin(theta) * Math.cos(phi);
43312 offset.y = Math.sin(theta) * Math.sin(phi);
43313 offset.z = Math.cos(theta);
43314 offset.applyQuaternion(qInverse);
43315 camera.lookat.copy(camera.position).add(offset.multiplyScalar(length));
43317 InteractiveStateBase.prototype._applyRotationBasic = function (basicRotation) {
43318 var currentNode = this._currentNode;
43319 var previousNode = this._previousNode != null ?
43320 this.previousNode :
43322 var currentCamera = this._currentCamera;
43323 var previousCamera = this._previousCamera;
43324 var currentTransform = this.currentTransform;
43325 var previousTransform = this.previousTransform != null ?
43326 this.previousTransform :
43327 this.currentTransform;
43328 var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray());
43329 var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray());
43330 var currentGPano = currentTransform.gpano;
43331 var previousGPano = previousTransform.gpano;
43332 if (currentNode.fullPano) {
43333 currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1);
43334 currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0.05, 0.95);
43336 else if (currentGPano != null &&
43337 currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) {
43338 currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1);
43339 currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
43342 currentBasic[0] = this._spatial.clamp(currentBasic[0] + basicRotation[0], 0, 1);
43343 currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
43345 if (previousNode.fullPano) {
43346 previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1);
43347 previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0.05, 0.95);
43349 else if (previousGPano != null &&
43350 previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) {
43351 previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1);
43352 previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0, 1);
43355 previousBasic[0] = this._spatial.clamp(previousBasic[0] + basicRotation[0], 0, 1);
43356 previousBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
43358 var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth);
43359 currentCamera.lookat.fromArray(currentLookat);
43360 var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth);
43361 previousCamera.lookat.fromArray(previousLookat);
43363 InteractiveStateBase.prototype._updateZoom = function (animationSpeed) {
43364 var diff = this._desiredZoom - this._zoom;
43365 var sign = diff > 0 ? 1 : diff < 0 ? -1 : 0;
43369 else if (Math.abs(diff) < 2e-3) {
43370 this._zoom = this._desiredZoom;
43371 if (this._desiredLookat != null) {
43372 this._desiredLookat = null;
43376 this._zoom += sign * Math.max(Math.abs(5 * animationSpeed * diff), 2e-3);
43379 InteractiveStateBase.prototype._updateLookat = function (animationSpeed) {
43380 if (this._desiredLookat === null) {
43383 var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat);
43384 if (Math.abs(diff) < 1e-6) {
43385 this._currentCamera.lookat.copy(this._desiredLookat);
43386 this._desiredLookat = null;
43389 this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed);
43392 InteractiveStateBase.prototype._updateRotation = function () {
43393 if (this._requestedRotationDelta != null) {
43394 var length_1 = this._rotationDelta.lengthSquared();
43395 var requestedLength = this._requestedRotationDelta.lengthSquared();
43396 if (requestedLength > length_1) {
43397 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha);
43400 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha);
43402 this._requestedRotationDelta = null;
43405 if (this._rotationDelta.isZero) {
43408 this._rotationDelta.multiply(this._rotationAcceleration);
43409 this._rotationDelta.threshold(this._rotationThreshold);
43411 InteractiveStateBase.prototype._updateRotationBasic = function () {
43412 if (this._requestedBasicRotation != null) {
43413 var x = this._basicRotation[0];
43414 var y = this._basicRotation[1];
43415 var reqX = this._requestedBasicRotation[0];
43416 var reqY = this._requestedBasicRotation[1];
43417 if (Math.abs(reqX) > Math.abs(x)) {
43418 this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX;
43421 this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX;
43423 if (Math.abs(reqY) > Math.abs(y)) {
43424 this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY;
43427 this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY;
43429 this._requestedBasicRotation = null;
43432 if (this._requestedBasicRotationUnbounded != null) {
43433 var reqX = this._requestedBasicRotationUnbounded[0];
43434 var reqY = this._requestedBasicRotationUnbounded[1];
43435 if (Math.abs(reqX) > 0) {
43436 this._basicRotation[0] = (1 - this._unboundedRotationAlpha) * this._basicRotation[0] + this._unboundedRotationAlpha * reqX;
43438 if (Math.abs(reqY) > 0) {
43439 this._basicRotation[1] = (1 - this._unboundedRotationAlpha) * this._basicRotation[1] + this._unboundedRotationAlpha * reqY;
43441 if (this._desiredLookat != null) {
43442 var desiredBasicLookat = this.currentTransform.projectBasic(this._desiredLookat.toArray());
43443 desiredBasicLookat[0] += reqX;
43444 desiredBasicLookat[1] += reqY;
43445 this._desiredLookat = new THREE.Vector3()
43446 .fromArray(this.currentTransform.unprojectBasic(desiredBasicLookat, this._lookatDepth));
43448 this._requestedBasicRotationUnbounded = null;
43450 if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) {
43453 this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0];
43454 this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1];
43455 if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) &&
43456 Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) {
43457 this._basicRotation = [0, 0];
43460 InteractiveStateBase.prototype._clearRotation = function () {
43461 if (this._currentNode.fullPano) {
43464 if (this._requestedRotationDelta != null) {
43465 this._requestedRotationDelta = null;
43467 if (!this._rotationDelta.isZero) {
43468 this._rotationDelta.reset();
43470 if (this._requestedBasicRotation != null) {
43471 this._requestedBasicRotation = null;
43473 if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) {
43474 this._basicRotation = [0, 0];
43477 InteractiveStateBase.prototype._setDesiredCenter = function () {
43478 if (this._desiredCenter == null) {
43481 var lookatDirection = new THREE.Vector3()
43482 .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth))
43483 .sub(this._currentCamera.position);
43484 this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection));
43485 this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection));
43486 this._desiredCenter = null;
43488 InteractiveStateBase.prototype._setDesiredZoom = function () {
43489 this._desiredZoom =
43490 this._currentNode.fullPano || this._previousNode == null ?
43493 return InteractiveStateBase;
43494 }(State_1.StateBase));
43495 exports.InteractiveStateBase = InteractiveStateBase;
43496 exports.default = InteractiveStateBase;
43498 },{"../../State":297,"three":240}],422:[function(require,module,exports){
43500 var __extends = (this && this.__extends) || (function () {
43501 var extendStatics = Object.setPrototypeOf ||
43502 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
43503 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
43504 return function (d, b) {
43505 extendStatics(d, b);
43506 function __() { this.constructor = d; }
43507 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
43510 Object.defineProperty(exports, "__esModule", { value: true });
43511 var State_1 = require("../../State");
43512 var InteractiveWaitingState = /** @class */ (function (_super) {
43513 __extends(InteractiveWaitingState, _super);
43514 function InteractiveWaitingState(state) {
43515 var _this = _super.call(this, state) || this;
43516 _this._adjustCameras();
43517 _this._motionless = _this._motionlessTransition();
43520 InteractiveWaitingState.prototype.traverse = function () {
43521 return new State_1.TraversingState(this);
43523 InteractiveWaitingState.prototype.wait = function () {
43524 return new State_1.WaitingState(this);
43526 InteractiveWaitingState.prototype.waitInteractively = function () {
43527 throw new Error("Not implemented");
43529 InteractiveWaitingState.prototype.prepend = function (nodes) {
43530 _super.prototype.prepend.call(this, nodes);
43531 this._motionless = this._motionlessTransition();
43533 InteractiveWaitingState.prototype.set = function (nodes) {
43534 _super.prototype.set.call(this, nodes);
43535 this._motionless = this._motionlessTransition();
43537 InteractiveWaitingState.prototype.setSpeed = function (speed) { return; };
43538 InteractiveWaitingState.prototype.move = function (delta) {
43539 this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
43541 InteractiveWaitingState.prototype.moveTo = function (position) {
43542 this._alpha = Math.max(0, Math.min(1, position));
43544 InteractiveWaitingState.prototype.update = function (fps) {
43545 this._updateRotation();
43546 if (!this._rotationDelta.isZero) {
43547 this._applyRotation(this._previousCamera);
43548 this._applyRotation(this._currentCamera);
43550 this._updateRotationBasic();
43551 if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
43552 this._applyRotationBasic(this._basicRotation);
43554 var animationSpeed = this._animationSpeed * (60 / fps);
43555 this._updateZoom(animationSpeed);
43556 this._updateLookat(animationSpeed);
43557 this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
43559 InteractiveWaitingState.prototype._getAlpha = function () {
43560 return this._motionless ? Math.round(this._alpha) : this._alpha;
43562 InteractiveWaitingState.prototype._setCurrentCamera = function () {
43563 _super.prototype._setCurrentCamera.call(this);
43564 this._adjustCameras();
43566 InteractiveWaitingState.prototype._adjustCameras = function () {
43567 if (this._previousNode == null) {
43570 if (this._currentNode.fullPano) {
43571 var lookat = this._camera.lookat.clone().sub(this._camera.position);
43572 this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
43574 if (this._previousNode.fullPano) {
43575 var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
43576 this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
43579 return InteractiveWaitingState;
43580 }(State_1.InteractiveStateBase));
43581 exports.InteractiveWaitingState = InteractiveWaitingState;
43582 exports.default = InteractiveWaitingState;
43584 },{"../../State":297}],423:[function(require,module,exports){
43586 /// <reference path="../../../typings/index.d.ts" />
43587 Object.defineProperty(exports, "__esModule", { value: true });
43588 var Error_1 = require("../../Error");
43589 var Geo_1 = require("../../Geo");
43590 var State_1 = require("../../State");
43591 var StateBase = /** @class */ (function () {
43592 function StateBase(state) {
43593 this._spatial = new Geo_1.Spatial();
43594 this._geoCoords = new Geo_1.GeoCoords();
43595 this._referenceThreshold = 0.01;
43596 this._transitionMode = state.transitionMode;
43597 this._reference = state.reference;
43598 this._alpha = state.alpha;
43599 this._camera = state.camera.clone();
43600 this._zoom = state.zoom;
43601 this._currentIndex = state.currentIndex;
43602 this._trajectory = state.trajectory.slice();
43603 this._trajectoryTransforms = [];
43604 this._trajectoryCameras = [];
43605 for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) {
43607 var translation = this._nodeToTranslation(node);
43608 var transform = new Geo_1.Transform(node.orientation, node.width, node.height, node.focal, node.scale, node.gpano, node.rotation, translation, node.image);
43609 this._trajectoryTransforms.push(transform);
43610 this._trajectoryCameras.push(new Geo_1.Camera(transform));
43612 this._currentNode = this._trajectory.length > 0 ?
43613 this._trajectory[this._currentIndex] :
43615 this._previousNode = this._trajectory.length > 1 && this.currentIndex > 0 ?
43616 this._trajectory[this._currentIndex - 1] :
43618 this._currentCamera = this._trajectoryCameras.length > 0 ?
43619 this._trajectoryCameras[this._currentIndex].clone() :
43620 new Geo_1.Camera();
43621 this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
43622 this._trajectoryCameras[this._currentIndex - 1].clone() :
43623 this._currentCamera.clone();
43625 Object.defineProperty(StateBase.prototype, "reference", {
43627 return this._reference;
43632 Object.defineProperty(StateBase.prototype, "alpha", {
43634 return this._getAlpha();
43639 Object.defineProperty(StateBase.prototype, "camera", {
43641 return this._camera;
43646 Object.defineProperty(StateBase.prototype, "zoom", {
43653 Object.defineProperty(StateBase.prototype, "trajectory", {
43655 return this._trajectory;
43660 Object.defineProperty(StateBase.prototype, "currentIndex", {
43662 return this._currentIndex;
43667 Object.defineProperty(StateBase.prototype, "currentNode", {
43669 return this._currentNode;
43674 Object.defineProperty(StateBase.prototype, "previousNode", {
43676 return this._previousNode;
43681 Object.defineProperty(StateBase.prototype, "currentCamera", {
43683 return this._currentCamera;
43688 Object.defineProperty(StateBase.prototype, "currentTransform", {
43690 return this._trajectoryTransforms.length > 0 ?
43691 this._trajectoryTransforms[this.currentIndex] : null;
43696 Object.defineProperty(StateBase.prototype, "previousTransform", {
43698 return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
43699 this._trajectoryTransforms[this.currentIndex - 1] : null;
43704 Object.defineProperty(StateBase.prototype, "motionless", {
43706 return this._motionless;
43711 Object.defineProperty(StateBase.prototype, "transitionMode", {
43713 return this._transitionMode;
43718 StateBase.prototype.append = function (nodes) {
43719 if (nodes.length < 1) {
43720 throw Error("Trajectory can not be empty");
43722 if (this._currentIndex < 0) {
43726 this._trajectory = this._trajectory.concat(nodes);
43727 this._appendToTrajectories(nodes);
43730 StateBase.prototype.prepend = function (nodes) {
43731 if (nodes.length < 1) {
43732 throw Error("Trajectory can not be empty");
43734 this._trajectory = nodes.slice().concat(this._trajectory);
43735 this._currentIndex += nodes.length;
43736 this._setCurrentNode();
43737 var referenceReset = this._setReference(this._currentNode);
43738 if (referenceReset) {
43739 this._setTrajectories();
43742 this._prependToTrajectories(nodes);
43744 this._setCurrentCamera();
43746 StateBase.prototype.remove = function (n) {
43748 throw Error("n must be a positive integer");
43750 if (this._currentIndex - 1 < n) {
43751 throw Error("Current and previous nodes can not be removed");
43753 for (var i = 0; i < n; i++) {
43754 this._trajectory.shift();
43755 this._trajectoryTransforms.shift();
43756 this._trajectoryCameras.shift();
43757 this._currentIndex--;
43759 this._setCurrentNode();
43761 StateBase.prototype.clearPrior = function () {
43762 if (this._currentIndex > 0) {
43763 this.remove(this._currentIndex - 1);
43766 StateBase.prototype.clear = function () {
43768 if (this._currentIndex > 0) {
43769 this.remove(this._currentIndex - 1);
43772 StateBase.prototype.cut = function () {
43773 while (this._trajectory.length - 1 > this._currentIndex) {
43774 this._trajectory.pop();
43775 this._trajectoryTransforms.pop();
43776 this._trajectoryCameras.pop();
43779 StateBase.prototype.set = function (nodes) {
43780 this._setTrajectory(nodes);
43781 this._setCurrentNode();
43782 this._setReference(this._currentNode);
43783 this._setTrajectories();
43784 this._setCurrentCamera();
43786 StateBase.prototype.getCenter = function () {
43787 return this._currentNode != null ?
43788 this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
43791 StateBase.prototype.setTransitionMode = function (mode) {
43792 this._transitionMode = mode;
43794 StateBase.prototype._setCurrent = function () {
43795 this._setCurrentNode();
43796 var referenceReset = this._setReference(this._currentNode);
43797 if (referenceReset) {
43798 this._setTrajectories();
43800 this._setCurrentCamera();
43802 StateBase.prototype._setCurrentCamera = function () {
43803 this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
43804 this._previousCamera = this._currentIndex > 0 ?
43805 this._trajectoryCameras[this._currentIndex - 1].clone() :
43806 this._currentCamera.clone();
43808 StateBase.prototype._motionlessTransition = function () {
43809 var nodesSet = this._currentNode != null && this._previousNode != null;
43810 return nodesSet && (this._transitionMode === State_1.TransitionMode.Instantaneous || !(this._currentNode.merged &&
43811 this._previousNode.merged &&
43812 this._withinOriginalDistance() &&
43813 this._sameConnectedComponent()));
43815 StateBase.prototype._setReference = function (node) {
43816 // do not reset reference if node is within threshold distance
43817 if (Math.abs(node.latLon.lat - this.reference.lat) < this._referenceThreshold &&
43818 Math.abs(node.latLon.lon - this.reference.lon) < this._referenceThreshold) {
43821 // do not reset reference if previous node exist and transition is with motion
43822 if (this._previousNode != null && !this._motionlessTransition()) {
43825 this._reference.lat = node.latLon.lat;
43826 this._reference.lon = node.latLon.lon;
43827 this._reference.alt = node.alt;
43830 StateBase.prototype._setCurrentNode = function () {
43831 this._currentNode = this._trajectory.length > 0 ?
43832 this._trajectory[this._currentIndex] :
43834 this._previousNode = this._currentIndex > 0 ?
43835 this._trajectory[this._currentIndex - 1] :
43838 StateBase.prototype._setTrajectory = function (nodes) {
43839 if (nodes.length < 1) {
43840 throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty");
43842 if (this._currentNode != null) {
43843 this._trajectory = [this._currentNode].concat(nodes);
43844 this._currentIndex = 1;
43847 this._trajectory = nodes.slice();
43848 this._currentIndex = 0;
43851 StateBase.prototype._setTrajectories = function () {
43852 this._trajectoryTransforms.length = 0;
43853 this._trajectoryCameras.length = 0;
43854 this._appendToTrajectories(this._trajectory);
43856 StateBase.prototype._appendToTrajectories = function (nodes) {
43857 for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
43858 var node = nodes_1[_i];
43859 if (!node.assetsCached) {
43860 throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory");
43862 var translation = this._nodeToTranslation(node);
43863 var transform = new Geo_1.Transform(node.orientation, node.width, node.height, node.focal, node.scale, node.gpano, node.rotation, translation, node.image);
43864 this._trajectoryTransforms.push(transform);
43865 this._trajectoryCameras.push(new Geo_1.Camera(transform));
43868 StateBase.prototype._prependToTrajectories = function (nodes) {
43869 for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) {
43871 if (!node.assetsCached) {
43872 throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory");
43874 var translation = this._nodeToTranslation(node);
43875 var transform = new Geo_1.Transform(node.orientation, node.width, node.height, node.focal, node.scale, node.gpano, node.rotation, translation, node.image);
43876 this._trajectoryTransforms.unshift(transform);
43877 this._trajectoryCameras.unshift(new Geo_1.Camera(transform));
43880 StateBase.prototype._nodeToTranslation = function (node) {
43881 var C = this._geoCoords.geodeticToEnu(node.latLon.lat, node.latLon.lon, node.alt, this._reference.lat, this._reference.lon, this._reference.alt);
43882 var RC = this._spatial.rotate(C, node.rotation);
43883 return [-RC.x, -RC.y, -RC.z];
43885 StateBase.prototype._sameConnectedComponent = function () {
43886 var current = this._currentNode;
43887 var previous = this._previousNode;
43888 return !!current && !!previous &&
43889 current.mergeCC === previous.mergeCC;
43891 StateBase.prototype._withinOriginalDistance = function () {
43892 var current = this._currentNode;
43893 var previous = this._previousNode;
43894 if (!current || !previous) {
43897 // 50 km/h moves 28m in 2s
43898 var distance = this._spatial.distanceFromLatLon(current.originalLatLon.lat, current.originalLatLon.lon, previous.originalLatLon.lat, previous.originalLatLon.lon);
43899 return distance < 25;
43903 exports.StateBase = StateBase;
43905 },{"../../Error":292,"../../Geo":293,"../../State":297}],424:[function(require,module,exports){
43907 /// <reference path="../../../typings/index.d.ts" />
43908 var __extends = (this && this.__extends) || (function () {
43909 var extendStatics = Object.setPrototypeOf ||
43910 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
43911 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
43912 return function (d, b) {
43913 extendStatics(d, b);
43914 function __() { this.constructor = d; }
43915 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
43918 Object.defineProperty(exports, "__esModule", { value: true });
43919 var UnitBezier = require("@mapbox/unitbezier");
43920 var State_1 = require("../../State");
43921 var TraversingState = /** @class */ (function (_super) {
43922 __extends(TraversingState, _super);
43923 function TraversingState(state) {
43924 var _this = _super.call(this, state) || this;
43925 _this._adjustCameras();
43926 _this._motionless = _this._motionlessTransition();
43927 _this._baseAlpha = _this._alpha;
43928 _this._speedCoefficient = 1;
43929 _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
43930 _this._useBezier = false;
43933 TraversingState.prototype.traverse = function () {
43934 throw new Error("Not implemented");
43936 TraversingState.prototype.wait = function () {
43937 return new State_1.WaitingState(this);
43939 TraversingState.prototype.waitInteractively = function () {
43940 return new State_1.InteractiveWaitingState(this);
43942 TraversingState.prototype.append = function (nodes) {
43943 var emptyTrajectory = this._trajectory.length === 0;
43944 if (emptyTrajectory) {
43945 this._resetTransition();
43947 _super.prototype.append.call(this, nodes);
43948 if (emptyTrajectory) {
43949 this._setDesiredCenter();
43950 this._setDesiredZoom();
43953 TraversingState.prototype.prepend = function (nodes) {
43954 var emptyTrajectory = this._trajectory.length === 0;
43955 if (emptyTrajectory) {
43956 this._resetTransition();
43958 _super.prototype.prepend.call(this, nodes);
43959 if (emptyTrajectory) {
43960 this._setDesiredCenter();
43961 this._setDesiredZoom();
43964 TraversingState.prototype.set = function (nodes) {
43965 _super.prototype.set.call(this, nodes);
43966 this._desiredLookat = null;
43967 this._resetTransition();
43968 this._clearRotation();
43969 this._setDesiredCenter();
43970 this._setDesiredZoom();
43971 if (this._trajectory.length < 3) {
43972 this._useBezier = true;
43975 TraversingState.prototype.move = function (delta) {
43976 throw new Error("Not implemented");
43978 TraversingState.prototype.moveTo = function (delta) {
43979 throw new Error("Not implemented");
43981 TraversingState.prototype.setSpeed = function (speed) {
43982 this._speedCoefficient = this._spatial.clamp(speed, 0, 10);
43984 TraversingState.prototype.update = function (fps) {
43985 if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) {
43986 this._currentIndex += 1;
43987 this._useBezier = this._trajectory.length < 3 &&
43988 this._currentIndex + 1 === this._trajectory.length;
43989 this._setCurrent();
43990 this._resetTransition();
43991 this._clearRotation();
43992 this._desiredZoom = this._currentNode.fullPano ? this._zoom : 0;
43993 this._desiredLookat = null;
43995 var animationSpeed = this._animationSpeed * (60 / fps);
43996 this._baseAlpha = Math.min(1, this._baseAlpha + this._speedCoefficient * animationSpeed);
43997 if (this._useBezier) {
43998 this._alpha = this._unitBezier.solve(this._baseAlpha);
44001 this._alpha = this._baseAlpha;
44003 this._updateRotation();
44004 if (!this._rotationDelta.isZero) {
44005 this._applyRotation(this._previousCamera);
44006 this._applyRotation(this._currentCamera);
44008 this._updateRotationBasic();
44009 if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
44010 this._applyRotationBasic(this._basicRotation);
44012 this._updateZoom(animationSpeed);
44013 this._updateLookat(animationSpeed);
44014 this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
44016 TraversingState.prototype._getAlpha = function () {
44017 return this._motionless ? Math.ceil(this._alpha) : this._alpha;
44019 TraversingState.prototype._setCurrentCamera = function () {
44020 _super.prototype._setCurrentCamera.call(this);
44021 this._adjustCameras();
44023 TraversingState.prototype._adjustCameras = function () {
44024 if (this._previousNode == null) {
44027 var lookat = this._camera.lookat.clone().sub(this._camera.position);
44028 this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
44029 if (this._currentNode.fullPano) {
44030 this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
44033 TraversingState.prototype._resetTransition = function () {
44035 this._baseAlpha = 0;
44036 this._motionless = this._motionlessTransition();
44038 return TraversingState;
44039 }(State_1.InteractiveStateBase));
44040 exports.TraversingState = TraversingState;
44041 exports.default = TraversingState;
44043 },{"../../State":297,"@mapbox/unitbezier":2}],425:[function(require,module,exports){
44045 var __extends = (this && this.__extends) || (function () {
44046 var extendStatics = Object.setPrototypeOf ||
44047 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
44048 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
44049 return function (d, b) {
44050 extendStatics(d, b);
44051 function __() { this.constructor = d; }
44052 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
44055 Object.defineProperty(exports, "__esModule", { value: true });
44056 var State_1 = require("../../State");
44057 var WaitingState = /** @class */ (function (_super) {
44058 __extends(WaitingState, _super);
44059 function WaitingState(state) {
44060 var _this = _super.call(this, state) || this;
44062 _this._adjustCameras();
44063 _this._motionless = _this._motionlessTransition();
44066 WaitingState.prototype.traverse = function () {
44067 return new State_1.TraversingState(this);
44069 WaitingState.prototype.wait = function () {
44070 throw new Error("Not implemented");
44072 WaitingState.prototype.waitInteractively = function () {
44073 return new State_1.InteractiveWaitingState(this);
44075 WaitingState.prototype.prepend = function (nodes) {
44076 _super.prototype.prepend.call(this, nodes);
44077 this._motionless = this._motionlessTransition();
44079 WaitingState.prototype.set = function (nodes) {
44080 _super.prototype.set.call(this, nodes);
44081 this._motionless = this._motionlessTransition();
44083 WaitingState.prototype.rotate = function (delta) { return; };
44084 WaitingState.prototype.rotateBasic = function (basicRotation) { return; };
44085 WaitingState.prototype.rotateBasicUnbounded = function (basicRotation) { return; };
44086 WaitingState.prototype.rotateBasicWithoutInertia = function (basicRotation) { return; };
44087 WaitingState.prototype.rotateToBasic = function (basic) { return; };
44088 WaitingState.prototype.setSpeed = function (speed) { return; };
44089 WaitingState.prototype.zoomIn = function (delta, reference) { return; };
44090 WaitingState.prototype.move = function (delta) {
44091 this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
44093 WaitingState.prototype.moveTo = function (position) {
44094 this._alpha = Math.max(0, Math.min(1, position));
44096 WaitingState.prototype.update = function (fps) {
44097 this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
44099 WaitingState.prototype.setCenter = function (center) { return; };
44100 WaitingState.prototype.setZoom = function (zoom) { return; };
44101 WaitingState.prototype._getAlpha = function () {
44102 return this._motionless ? Math.round(this._alpha) : this._alpha;
44104 WaitingState.prototype._setCurrentCamera = function () {
44105 _super.prototype._setCurrentCamera.call(this);
44106 this._adjustCameras();
44108 WaitingState.prototype._adjustCameras = function () {
44109 if (this._previousNode == null) {
44112 if (this._currentNode.fullPano) {
44113 var lookat = this._camera.lookat.clone().sub(this._camera.position);
44114 this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
44116 if (this._previousNode.fullPano) {
44117 var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
44118 this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
44121 return WaitingState;
44122 }(State_1.StateBase));
44123 exports.WaitingState = WaitingState;
44124 exports.default = WaitingState;
44126 },{"../../State":297}],426:[function(require,module,exports){
44128 Object.defineProperty(exports, "__esModule", { value: true });
44129 var Observable_1 = require("rxjs/Observable");
44131 * @class ImageTileLoader
44133 * @classdesc Represents a loader of image tiles.
44135 var ImageTileLoader = /** @class */ (function () {
44137 * Create a new node image tile loader instance.
44139 * @param {string} scheme - The URI scheme.
44140 * @param {string} host - The URI host.
44141 * @param {string} [origin] - The origin query param.
44143 function ImageTileLoader(scheme, host, origin) {
44144 this._scheme = scheme;
44146 this._origin = origin != null ? "?origin=" + origin : "";
44149 * Retrieve an image tile.
44151 * @description Retrieve an image tile by specifying the area
44152 * as well as the scaled size.
44154 * @param {string} identifier - The identifier of the image.
44155 * @param {number} x - The top left x pixel coordinate for the tile
44156 * in the original image.
44157 * @param {number} y - The top left y pixel coordinate for the tile
44158 * in the original image.
44159 * @param {number} w - The pixel width of the tile in the original image.
44160 * @param {number} h - The pixel height of the tile in the original image.
44161 * @param {number} scaledW - The scaled width of the returned tile.
44162 * @param {number} scaledH - The scaled height of the returned tile.
44164 ImageTileLoader.prototype.getTile = function (identifier, x, y, w, h, scaledW, scaledH) {
44165 var characteristics = "/" + identifier + "/" + x + "," + y + "," + w + "," + h + "/" + scaledW + "," + scaledH + "/0/default.jpg";
44166 var url = this._scheme +
44171 var xmlHTTP = null;
44172 return [Observable_1.Observable.create(function (subscriber) {
44173 xmlHTTP = new XMLHttpRequest();
44174 xmlHTTP.open("GET", url, true);
44175 xmlHTTP.responseType = "arraybuffer";
44176 xmlHTTP.timeout = 15000;
44177 xmlHTTP.onload = function (event) {
44178 if (xmlHTTP.status !== 200) {
44179 subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + "). " +
44180 ("Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)));
44183 var image = new Image();
44184 image.crossOrigin = "Anonymous";
44185 image.onload = function (e) {
44186 subscriber.next(image);
44187 subscriber.complete();
44189 image.onerror = function (error) {
44190 subscriber.error(new Error("Failed to load tile image (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
44192 var blob = new Blob([xmlHTTP.response]);
44193 image.src = window.URL.createObjectURL(blob);
44195 xmlHTTP.onerror = function (error) {
44196 subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
44198 xmlHTTP.ontimeout = function (error) {
44199 subscriber.error(new Error("Tile request timed out (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
44201 xmlHTTP.onabort = function (event) {
44202 subscriber.error(new Error("Tile request was aborted (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
44204 xmlHTTP.send(null);
44207 if (xmlHTTP != null) {
44213 return ImageTileLoader;
44215 exports.ImageTileLoader = ImageTileLoader;
44216 exports.default = ImageTileLoader;
44218 },{"rxjs/Observable":29}],427:[function(require,module,exports){
44220 Object.defineProperty(exports, "__esModule", { value: true });
44222 * @class ImageTileStore
44224 * @classdesc Represents a store for image tiles.
44226 var ImageTileStore = /** @class */ (function () {
44228 * Create a new node image tile store instance.
44230 function ImageTileStore() {
44234 * Add an image tile to the store.
44236 * @param {HTMLImageElement} image - The image tile.
44237 * @param {string} key - The identifier for the tile.
44238 * @param {number} level - The level of the tile.
44240 ImageTileStore.prototype.addImage = function (image, key, level) {
44241 if (!(level in this._images)) {
44242 this._images[level] = {};
44244 this._images[level][key] = image;
44247 * Dispose the store.
44249 * @description Disposes all cached assets.
44251 ImageTileStore.prototype.dispose = function () {
44252 for (var _i = 0, _a = Object.keys(this._images); _i < _a.length; _i++) {
44253 var level = _a[_i];
44254 var levelImages = this._images[level];
44255 for (var _b = 0, _c = Object.keys(levelImages); _b < _c.length; _b++) {
44257 window.URL.revokeObjectURL(levelImages[key].src);
44258 delete levelImages[key];
44260 delete this._images[level];
44264 * Get an image tile from the store.
44266 * @param {string} key - The identifier for the tile.
44267 * @param {number} level - The level of the tile.
44269 ImageTileStore.prototype.getImage = function (key, level) {
44270 return this._images[level][key];
44273 * Check if an image tile exist in the store.
44275 * @param {string} key - The identifier for the tile.
44276 * @param {number} level - The level of the tile.
44278 ImageTileStore.prototype.hasImage = function (key, level) {
44279 return level in this._images && key in this._images[level];
44281 return ImageTileStore;
44283 exports.ImageTileStore = ImageTileStore;
44284 exports.default = ImageTileStore;
44286 },{}],428:[function(require,module,exports){
44288 /// <reference path="../../typings/index.d.ts" />
44289 Object.defineProperty(exports, "__esModule", { value: true });
44290 var Geo_1 = require("../Geo");
44292 * @class RegionOfInterestCalculator
44294 * @classdesc Represents a calculator for regions of interest.
44296 var RegionOfInterestCalculator = /** @class */ (function () {
44297 function RegionOfInterestCalculator() {
44298 this._viewportCoords = new Geo_1.ViewportCoords();
44301 * Compute a region of interest based on the current render camera
44302 * and the viewport size.
44304 * @param {RenderCamera} renderCamera - Render camera used for unprojections.
44305 * @param {ISize} size - Viewport size in pixels.
44306 * @param {Transform} transform - Transform used for projections.
44308 * @returns {IRegionOfInterest} A region of interest.
44310 RegionOfInterestCalculator.prototype.computeRegionOfInterest = function (renderCamera, size, transform) {
44311 var viewportBoundaryPoints = this._viewportBoundaryPoints(4);
44312 var bbox = this._viewportPointsBoundingBox(viewportBoundaryPoints, renderCamera, transform);
44313 this._clipBoundingBox(bbox);
44314 var viewportPixelWidth = 2 / size.width;
44315 var viewportPixelHeight = 2 / size.height;
44316 var centralViewportPixel = [
44317 [-0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
44318 [0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
44319 [0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
44320 [-0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
44322 var cpbox = this._viewportPointsBoundingBox(centralViewportPixel, renderCamera, transform);
44325 pixelHeight: cpbox.maxY - cpbox.minY,
44326 pixelWidth: cpbox.maxX - cpbox.minX + (cpbox.minX < cpbox.maxX ? 0 : 1),
44329 RegionOfInterestCalculator.prototype._viewportBoundaryPoints = function (pointsPerSide) {
44331 var os = [[-1, 1], [1, 1], [1, -1], [-1, -1]];
44332 var ds = [[2, 0], [0, -2], [-2, 0], [0, 2]];
44333 for (var side = 0; side < 4; ++side) {
44336 for (var i = 0; i < pointsPerSide; ++i) {
44337 points.push([o[0] + d[0] * i / pointsPerSide,
44338 o[1] + d[1] * i / pointsPerSide]);
44343 RegionOfInterestCalculator.prototype._viewportPointsBoundingBox = function (viewportPoints, renderCamera, transform) {
44345 var basicPoints = viewportPoints
44346 .map(function (point) {
44347 return _this._viewportCoords
44348 .viewportToBasic(point[0], point[1], transform, renderCamera.perspective);
44350 if (transform.gpano != null) {
44351 return this._boundingBoxPano(basicPoints);
44354 return this._boundingBox(basicPoints);
44357 RegionOfInterestCalculator.prototype._boundingBox = function (points) {
44359 maxX: Number.NEGATIVE_INFINITY,
44360 maxY: Number.NEGATIVE_INFINITY,
44361 minX: Number.POSITIVE_INFINITY,
44362 minY: Number.POSITIVE_INFINITY,
44364 for (var i = 0; i < points.length; ++i) {
44365 bbox.minX = Math.min(bbox.minX, points[i][0]);
44366 bbox.maxX = Math.max(bbox.maxX, points[i][0]);
44367 bbox.minY = Math.min(bbox.minY, points[i][1]);
44368 bbox.maxY = Math.max(bbox.maxY, points[i][1]);
44372 RegionOfInterestCalculator.prototype._boundingBoxPano = function (points) {
44376 for (var i = 0; i < points.length; ++i) {
44377 xs.push(points[i][0]);
44378 ys.push(points[i][1]);
44380 xs.sort(function (a, b) { return _this._sign(a - b); });
44381 ys.sort(function (a, b) { return _this._sign(a - b); });
44382 var intervalX = this._intervalPano(xs);
44384 maxX: intervalX[1],
44385 maxY: ys[ys.length - 1],
44386 minX: intervalX[0],
44391 * Find the max interval between consecutive numbers.
44392 * Assumes numbers are between 0 and 1, sorted and that
44393 * x is equivalent to x + 1.
44395 RegionOfInterestCalculator.prototype._intervalPano = function (xs) {
44398 for (var i = 0; i < xs.length - 1; ++i) {
44399 var dx = xs[i + 1] - xs[i];
44405 var loopdx = xs[0] + 1 - xs[xs.length - 1];
44406 if (loopdx > maxdx) {
44407 return [xs[0], xs[xs.length - 1]];
44410 return [xs[maxi + 1], xs[maxi]];
44413 RegionOfInterestCalculator.prototype._clipBoundingBox = function (bbox) {
44414 bbox.minX = Math.max(0, Math.min(1, bbox.minX));
44415 bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
44416 bbox.minY = Math.max(0, Math.min(1, bbox.minY));
44417 bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
44419 RegionOfInterestCalculator.prototype._sign = function (n) {
44420 return n > 0 ? 1 : n < 0 ? -1 : 0;
44422 return RegionOfInterestCalculator;
44424 exports.RegionOfInterestCalculator = RegionOfInterestCalculator;
44425 exports.default = RegionOfInterestCalculator;
44427 },{"../Geo":293}],429:[function(require,module,exports){
44429 /// <reference path="../../typings/index.d.ts" />
44430 Object.defineProperty(exports, "__esModule", { value: true });
44431 var THREE = require("three");
44432 var Subject_1 = require("rxjs/Subject");
44434 * @class TextureProvider
44436 * @classdesc Represents a provider of textures.
44438 var TextureProvider = /** @class */ (function () {
44440 * Create a new node texture provider instance.
44442 * @param {string} key - The identifier of the image for which to request tiles.
44443 * @param {number} width - The full width of the original image.
44444 * @param {number} height - The full height of the original image.
44445 * @param {number} tileSize - The size used when requesting tiles.
44446 * @param {HTMLImageElement} background - Image to use as background.
44447 * @param {ImageTileLoader} imageTileLoader - Loader for retrieving tiles.
44448 * @param {ImageTileStore} imageTileStore - Store for saving tiles.
44449 * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture.
44451 function TextureProvider(key, width, height, tileSize, background, imageTileLoader, imageTileStore, renderer) {
44452 this._disposed = false;
44454 if (width <= 0 || height <= 0) {
44455 console.warn("Original image size (" + width + ", " + height + ") is invalid (" + key + "). Tiles will not be loaded.");
44457 this._width = width;
44458 this._height = height;
44459 this._maxLevel = Math.ceil(Math.log(Math.max(height, width)) / Math.log(2));
44460 this._currentLevel = -1;
44461 this._tileSize = tileSize;
44462 this._updated$ = new Subject_1.Subject();
44463 this._createdSubject$ = new Subject_1.Subject();
44464 this._created$ = this._createdSubject$
44467 this._createdSubscription = this._created$.subscribe(function () { });
44468 this._hasSubject$ = new Subject_1.Subject();
44469 this._has$ = this._hasSubject$
44473 this._hasSubscription = this._has$.subscribe(function () { });
44474 this._abortFunctions = [];
44475 this._tileSubscriptions = {};
44476 this._renderedCurrentLevelTiles = {};
44477 this._renderedTiles = {};
44478 this._background = background;
44479 this._camera = null;
44480 this._imageTileLoader = imageTileLoader;
44481 this._imageTileStore = imageTileStore;
44482 this._renderer = renderer;
44483 this._renderTarget = null;
44486 Object.defineProperty(TextureProvider.prototype, "disposed", {
44490 * @returns {boolean} Value indicating whether provider has
44494 return this._disposed;
44499 Object.defineProperty(TextureProvider.prototype, "hasTexture$", {
44503 * @returns {Observable<boolean>} Observable emitting
44504 * values indicating when the existance of a texture
44513 Object.defineProperty(TextureProvider.prototype, "key", {
44517 * @returns {boolean} The identifier of the image for
44518 * which to render textures.
44526 Object.defineProperty(TextureProvider.prototype, "textureUpdated$", {
44528 * Get textureUpdated$.
44530 * @returns {Observable<boolean>} Observable emitting
44531 * values when an existing texture has been updated.
44534 return this._updated$;
44539 Object.defineProperty(TextureProvider.prototype, "textureCreated$", {
44541 * Get textureCreated$.
44543 * @returns {Observable<boolean>} Observable emitting
44544 * values when a new texture has been created.
44547 return this._created$;
44553 * Abort all outstanding image tile requests.
44555 TextureProvider.prototype.abort = function () {
44556 for (var key in this._tileSubscriptions) {
44557 if (!this._tileSubscriptions.hasOwnProperty(key)) {
44560 this._tileSubscriptions[key].unsubscribe();
44562 this._tileSubscriptions = {};
44563 for (var _i = 0, _a = this._abortFunctions; _i < _a.length; _i++) {
44564 var abort = _a[_i];
44567 this._abortFunctions = [];
44570 * Dispose the provider.
44572 * @description Disposes all cached assets and
44573 * aborts all outstanding image tile requests.
44575 TextureProvider.prototype.dispose = function () {
44576 if (this._disposed) {
44577 console.warn("Texture already disposed (" + this._key + ")");
44581 if (this._renderTarget != null) {
44582 this._renderTarget.dispose();
44583 this._renderTarget = null;
44585 this._imageTileStore.dispose();
44586 this._imageTileStore = null;
44587 this._background = null;
44588 this._camera = null;
44589 this._imageTileLoader = null;
44590 this._renderer = null;
44592 this._createdSubscription.unsubscribe();
44593 this._hasSubscription.unsubscribe();
44594 this._disposed = true;
44597 * Set the region of interest.
44599 * @description When the region of interest is set the
44600 * the tile level is determined and tiles for the region
44601 * are fetched from the store or the loader and renderedLevel
44604 * @param {IRegionOfInterest} roi - Spatial edges to cache.
44606 TextureProvider.prototype.setRegionOfInterest = function (roi) {
44607 if (this._width <= 0 || this._height <= 0) {
44611 var width = 1 / this._roi.pixelWidth;
44612 var height = 1 / this._roi.pixelHeight;
44613 var size = Math.max(height, width);
44614 var currentLevel = Math.max(0, Math.min(this._maxLevel, Math.ceil(Math.log(size) / Math.log(2))));
44615 if (currentLevel !== this._currentLevel) {
44617 this._currentLevel = currentLevel;
44618 if (!(this._currentLevel in this._renderedTiles)) {
44619 this._renderedTiles[this._currentLevel] = [];
44621 this._renderedCurrentLevelTiles = {};
44622 for (var _i = 0, _a = this._renderedTiles[this._currentLevel]; _i < _a.length; _i++) {
44624 this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true;
44627 var topLeft = this._getTileCoords([this._roi.bbox.minX, this._roi.bbox.minY]);
44628 var bottomRight = this._getTileCoords([this._roi.bbox.maxX, this._roi.bbox.maxY]);
44629 var tiles = this._getTiles(topLeft, bottomRight);
44630 if (this._camera == null) {
44631 this._camera = new THREE.OrthographicCamera(-this._width / 2, this._width / 2, this._height / 2, -this._height / 2, -1, 1);
44632 this._camera.position.z = 1;
44633 var gl = this._renderer.getContext();
44634 var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
44635 var backgroundSize = Math.max(this._width, this._height);
44636 var scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize;
44637 var targetWidth = Math.floor(scale * this._width);
44638 var targetHeight = Math.floor(scale * this._height);
44639 this._renderTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, {
44640 depthBuffer: false,
44641 format: THREE.RGBFormat,
44642 magFilter: THREE.LinearFilter,
44643 minFilter: THREE.LinearFilter,
44644 stencilBuffer: false,
44646 this._renderToTarget(0, 0, this._width, this._height, this._background);
44647 this._createdSubject$.next(this._renderTarget.texture);
44648 this._hasSubject$.next(true);
44650 this._fetchTiles(tiles);
44652 TextureProvider.prototype.setTileSize = function (tileSize) {
44653 this._tileSize = tileSize;
44656 * Update the image used as background for the texture.
44658 * @param {HTMLImageElement} background - The background image.
44660 TextureProvider.prototype.updateBackground = function (background) {
44661 this._background = background;
44664 * Retrieve an image tile.
44666 * @description Retrieve an image tile and render it to the
44667 * texture. Add the tile to the store and emit to the updated
44670 * @param {Array<number>} tile - The tile coordinates.
44671 * @param {number} level - The tile level.
44672 * @param {number} x - The top left x pixel coordinate of the tile.
44673 * @param {number} y - The top left y pixel coordinate of the tile.
44674 * @param {number} w - The pixel width of the tile.
44675 * @param {number} h - The pixel height of the tile.
44676 * @param {number} scaledW - The scaled width of the returned tile.
44677 * @param {number} scaledH - The scaled height of the returned tile.
44679 TextureProvider.prototype._fetchTile = function (tile, level, x, y, w, h, scaledX, scaledY) {
44681 var getTile = this._imageTileLoader.getTile(this._key, x, y, w, h, scaledX, scaledY);
44682 var tile$ = getTile[0];
44683 var abort = getTile[1];
44684 this._abortFunctions.push(abort);
44685 var tileKey = this._tileKey(this._tileSize, tile);
44686 var subscription = tile$
44687 .subscribe(function (image) {
44688 _this._renderToTarget(x, y, w, h, image);
44689 _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
44690 _this._removeFromArray(abort, _this._abortFunctions);
44691 _this._setTileRendered(tile, _this._currentLevel);
44692 _this._imageTileStore.addImage(image, tileKey, level);
44693 _this._updated$.next(true);
44694 }, function (error) {
44695 _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
44696 _this._removeFromArray(abort, _this._abortFunctions);
44697 console.error(error);
44699 if (!subscription.closed) {
44700 this._tileSubscriptions[tileKey] = subscription;
44704 * Retrieve image tiles.
44706 * @description Retrieve a image tiles and render them to the
44707 * texture. Retrieve from store if it exists, otherwise Retrieve
44710 * @param {Array<Array<number>>} tiles - Array of tile coordinates to
44713 TextureProvider.prototype._fetchTiles = function (tiles) {
44714 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
44715 for (var _i = 0, tiles_1 = tiles; _i < tiles_1.length; _i++) {
44716 var tile = tiles_1[_i];
44717 var tileKey = this._tileKey(this._tileSize, tile);
44718 if (tileKey in this._renderedCurrentLevelTiles ||
44719 tileKey in this._tileSubscriptions) {
44722 var tileX = tileSize * tile[0];
44723 var tileY = tileSize * tile[1];
44724 var tileWidth = tileX + tileSize > this._width ? this._width - tileX : tileSize;
44725 var tileHeight = tileY + tileSize > this._height ? this._height - tileY : tileSize;
44726 if (this._imageTileStore.hasImage(tileKey, this._currentLevel)) {
44727 this._renderToTarget(tileX, tileY, tileWidth, tileHeight, this._imageTileStore.getImage(tileKey, this._currentLevel));
44728 this._setTileRendered(tile, this._currentLevel);
44729 this._updated$.next(true);
44732 var scaledX = Math.floor(tileWidth / tileSize * this._tileSize);
44733 var scaledY = Math.floor(tileHeight / tileSize * this._tileSize);
44734 this._fetchTile(tile, this._currentLevel, tileX, tileY, tileWidth, tileHeight, scaledX, scaledY);
44738 * Get tile coordinates for a point using the current level.
44740 * @param {Array<number>} point - Point in basic coordinates.
44742 * @returns {Array<number>} x and y tile coodinates.
44744 TextureProvider.prototype._getTileCoords = function (point) {
44745 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
44746 var maxX = Math.ceil(this._width / tileSize) - 1;
44747 var maxY = Math.ceil(this._height / tileSize) - 1;
44749 Math.min(Math.floor(this._width * point[0] / tileSize), maxX),
44750 Math.min(Math.floor(this._height * point[1] / tileSize), maxY),
44754 * Get tile coordinates for all tiles contained in a bounding
44757 * @param {Array<number>} topLeft - Top left tile coordinate of bounding box.
44758 * @param {Array<number>} bottomRight - Bottom right tile coordinate of bounding box.
44760 * @returns {Array<Array<number>>} Array of x, y tile coodinates.
44762 TextureProvider.prototype._getTiles = function (topLeft, bottomRight) {
44764 if (topLeft[0] > bottomRight[0]) {
44765 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
44766 var maxX = Math.ceil(this._width / tileSize) - 1;
44767 for (var x = topLeft[0]; x <= maxX; x++) {
44770 for (var x = 0; x <= bottomRight[0]; x++) {
44775 for (var x = topLeft[0]; x <= bottomRight[0]; x++) {
44780 for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
44782 for (var y = topLeft[1]; y <= bottomRight[1]; y++) {
44783 tiles.push([x, y]);
44789 * Remove an item from an array if it exists in array.
44791 * @param {T} item - Item to remove.
44792 * @param {Array<T>} array - Array from which item should be removed.
44794 TextureProvider.prototype._removeFromArray = function (item, array) {
44795 var index = array.indexOf(item);
44796 if (index !== -1) {
44797 array.splice(index, 1);
44801 * Remove an item from a dictionary.
44803 * @param {string} key - Key of the item to remove.
44804 * @param {Object} dict - Dictionary from which item should be removed.
44806 TextureProvider.prototype._removeFromDictionary = function (key, dict) {
44812 * Render an image tile to the target texture.
44814 * @param {number} x - The top left x pixel coordinate of the tile.
44815 * @param {number} y - The top left y pixel coordinate of the tile.
44816 * @param {number} w - The pixel width of the tile.
44817 * @param {number} h - The pixel height of the tile.
44818 * @param {HTMLImageElement} background - The image tile to render.
44820 TextureProvider.prototype._renderToTarget = function (x, y, w, h, image) {
44821 var texture = new THREE.Texture(image);
44822 texture.minFilter = THREE.LinearFilter;
44823 texture.needsUpdate = true;
44824 var geometry = new THREE.PlaneGeometry(w, h);
44825 var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide });
44826 var mesh = new THREE.Mesh(geometry, material);
44827 mesh.position.x = -this._width / 2 + x + w / 2;
44828 mesh.position.y = this._height / 2 - y - h / 2;
44829 var scene = new THREE.Scene();
44831 this._renderer.render(scene, this._camera, this._renderTarget);
44832 this._renderer.setRenderTarget(undefined);
44833 scene.remove(mesh);
44834 geometry.dispose();
44835 material.dispose();
44839 * Mark a tile as rendered.
44841 * @description Clears tiles marked as rendered in other
44842 * levels of the tile pyramid if they were rendered on
44843 * top of or below the tile.
44845 * @param {Arrary<number>} tile - The tile coordinates.
44846 * @param {number} level - Tile level of the tile coordinates.
44848 TextureProvider.prototype._setTileRendered = function (tile, level) {
44849 var otherLevels = Object.keys(this._renderedTiles)
44850 .map(function (key) {
44851 return parseInt(key, 10);
44853 .filter(function (renderedLevel) {
44854 return renderedLevel !== level;
44856 for (var _i = 0, otherLevels_1 = otherLevels; _i < otherLevels_1.length; _i++) {
44857 var otherLevel = otherLevels_1[_i];
44858 var scale = Math.pow(2, otherLevel - level);
44859 if (otherLevel < level) {
44860 var x = Math.floor(scale * tile[0]);
44861 var y = Math.floor(scale * tile[1]);
44862 for (var _a = 0, _b = this._renderedTiles[otherLevel].slice(); _a < _b.length; _a++) {
44863 var otherTile = _b[_a];
44864 if (otherTile[0] === x && otherTile[1] === y) {
44865 var index = this._renderedTiles[otherLevel].indexOf(otherTile);
44866 this._renderedTiles[otherLevel].splice(index, 1);
44871 var startX = scale * tile[0];
44872 var endX = startX + scale - 1;
44873 var startY = scale * tile[1];
44874 var endY = startY + scale - 1;
44875 for (var _c = 0, _d = this._renderedTiles[otherLevel].slice(); _c < _d.length; _c++) {
44876 var otherTile = _d[_c];
44877 if (otherTile[0] >= startX && otherTile[0] <= endX &&
44878 otherTile[1] >= startY && otherTile[1] <= endY) {
44879 var index = this._renderedTiles[otherLevel].indexOf(otherTile);
44880 this._renderedTiles[otherLevel].splice(index, 1);
44884 if (this._renderedTiles[otherLevel].length === 0) {
44885 delete this._renderedTiles[otherLevel];
44888 this._renderedTiles[level].push(tile);
44889 this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true;
44892 * Create a tile key from a tile coordinates.
44894 * @description Tile keys are used as a hash for
44895 * storing the tile in a dictionary.
44897 * @param {number} tileSize - The tile size.
44898 * @param {Arrary<number>} tile - The tile coordinates.
44900 TextureProvider.prototype._tileKey = function (tileSize, tile) {
44901 return tileSize + "-" + tile[0] + "-" + tile[1];
44903 return TextureProvider;
44905 exports.TextureProvider = TextureProvider;
44906 exports.default = TextureProvider;
44908 },{"rxjs/Subject":34,"three":240}],430:[function(require,module,exports){
44910 Object.defineProperty(exports, "__esModule", { value: true });
44911 var DOM = /** @class */ (function () {
44912 function DOM(doc) {
44913 this._document = !!doc ? doc : document;
44915 Object.defineProperty(DOM.prototype, "document", {
44917 return this._document;
44922 DOM.prototype.createElement = function (tagName, className, container) {
44923 var element = this._document.createElement(tagName);
44925 element.className = className;
44928 container.appendChild(element);
44935 exports.default = DOM;
44937 },{}],431:[function(require,module,exports){
44939 Object.defineProperty(exports, "__esModule", { value: true });
44940 var EventEmitter = /** @class */ (function () {
44941 function EventEmitter() {
44945 * Subscribe to an event by its name.
44946 * @param {string }eventType - The name of the event to subscribe to.
44947 * @param {any} fn - The handler called when the event occurs.
44949 EventEmitter.prototype.on = function (eventType, fn) {
44950 this._events[eventType] = this._events[eventType] || [];
44951 this._events[eventType].push(fn);
44955 * Unsubscribe from an event by its name.
44956 * @param {string} eventType - The name of the event to subscribe to.
44957 * @param {any} fn - The handler to remove.
44959 EventEmitter.prototype.off = function (eventType, fn) {
44964 if (!this._listens(eventType)) {
44965 var idx = this._events[eventType].indexOf(fn);
44967 this._events[eventType].splice(idx, 1);
44969 if (this._events[eventType].length) {
44970 delete this._events[eventType];
44974 delete this._events[eventType];
44978 EventEmitter.prototype.fire = function (eventType, data) {
44979 if (!this._listens(eventType)) {
44982 for (var _i = 0, _a = this._events[eventType]; _i < _a.length; _i++) {
44984 fn.call(this, data);
44988 EventEmitter.prototype._listens = function (eventType) {
44989 return !!(this._events && this._events[eventType]);
44991 return EventEmitter;
44993 exports.EventEmitter = EventEmitter;
44994 exports.default = EventEmitter;
44996 },{}],432:[function(require,module,exports){
44998 Object.defineProperty(exports, "__esModule", { value: true });
44999 var Viewer_1 = require("../Viewer");
45000 var Settings = /** @class */ (function () {
45001 function Settings() {
45003 Settings.setOptions = function (options) {
45004 Settings._baseImageSize = options.baseImageSize != null ?
45005 options.baseImageSize :
45006 Viewer_1.ImageSize.Size640;
45007 Settings._basePanoramaSize = options.basePanoramaSize != null ?
45008 options.basePanoramaSize :
45009 Viewer_1.ImageSize.Size2048;
45010 Settings._maxImageSize = options.maxImageSize != null ?
45011 options.maxImageSize :
45012 Viewer_1.ImageSize.Size2048;
45014 Object.defineProperty(Settings, "baseImageSize", {
45016 return Settings._baseImageSize;
45021 Object.defineProperty(Settings, "basePanoramaSize", {
45023 return Settings._basePanoramaSize;
45028 Object.defineProperty(Settings, "maxImageSize", {
45030 return Settings._maxImageSize;
45037 exports.Settings = Settings;
45038 exports.default = Settings;
45040 },{"../Viewer":301}],433:[function(require,module,exports){
45042 Object.defineProperty(exports, "__esModule", { value: true });
45043 function isBrowser() {
45044 return typeof window !== "undefined" && typeof document !== "undefined";
45046 exports.isBrowser = isBrowser;
45047 function isArraySupported() {
45048 return !!(Array.prototype &&
45049 Array.prototype.filter &&
45050 Array.prototype.indexOf &&
45051 Array.prototype.map &&
45052 Array.prototype.reverse);
45054 exports.isArraySupported = isArraySupported;
45055 function isFunctionSupported() {
45056 return !!(Function.prototype && Function.prototype.bind);
45058 exports.isFunctionSupported = isFunctionSupported;
45059 function isJSONSupported() {
45060 return "JSON" in window && "parse" in JSON && "stringify" in JSON;
45062 exports.isJSONSupported = isJSONSupported;
45063 function isObjectSupported() {
45064 return !!(Object.keys &&
45067 exports.isObjectSupported = isObjectSupported;
45068 function isBlobSupported() {
45069 return "Blob" in window && "URL" in window;
45071 exports.isBlobSupported = isBlobSupported;
45072 var isWebGLSupportedCache = undefined;
45073 function isWebGLSupportedCached() {
45074 if (isWebGLSupportedCache === undefined) {
45075 isWebGLSupportedCache = isWebGLSupported();
45077 return isWebGLSupportedCache;
45079 exports.isWebGLSupportedCached = isWebGLSupportedCached;
45080 function isWebGLSupported() {
45081 var webGLContextAttributes = {
45085 failIfMajorPerformanceCaveat: false,
45086 premultipliedAlpha: true,
45087 preserveDrawingBuffer: false,
45090 var canvas = document.createElement("canvas");
45091 var context = canvas.getContext("webgl", webGLContextAttributes) ||
45092 canvas.getContext("experimental-webgl", webGLContextAttributes);
45096 var requiredExtensions = [
45097 "OES_standard_derivatives",
45099 var supportedExtensions = context.getSupportedExtensions();
45100 for (var _i = 0, requiredExtensions_1 = requiredExtensions; _i < requiredExtensions_1.length; _i++) {
45101 var requiredExtension = requiredExtensions_1[_i];
45102 if (supportedExtensions.indexOf(requiredExtension) === -1) {
45108 exports.isWebGLSupported = isWebGLSupported;
45110 },{}],434:[function(require,module,exports){
45112 Object.defineProperty(exports, "__esModule", { value: true });
45113 var Urls = /** @class */ (function () {
45116 Object.defineProperty(Urls, "explore", {
45118 return Urls._scheme + "://" + Urls._exploreHost;
45123 Object.defineProperty(Urls, "origin", {
45125 return Urls._origin;
45130 Object.defineProperty(Urls, "tileScheme", {
45132 return Urls._scheme;
45137 Object.defineProperty(Urls, "tileDomain", {
45139 return Urls._imageTileHost;
45144 Urls.exporeImage = function (key) {
45145 return Urls._scheme + "://" + Urls._exploreHost + "/app/?pKey=" + key + "&focus=photo";
45147 Urls.exporeUser = function (username) {
45148 return Urls._scheme + "://" + Urls._exploreHost + "/app/user/" + username;
45150 Urls.falcorModel = function (clientId) {
45151 return Urls._scheme + "://" + Urls._apiHost + "/v3/model.json?client_id=" + clientId;
45153 Urls.protoMesh = function (key) {
45154 return Urls._scheme + "://" + Urls._meshHost + "/v2/mesh/" + key;
45156 Urls.thumbnail = function (key, size, origin) {
45157 var query = !!origin ? "?origin=" + origin : "";
45158 return Urls._scheme + "://" + Urls._imageHost + "/" + key + "/thumb-" + size + ".jpg" + query;
45160 Urls.setOptions = function (options) {
45164 if (!!options.apiHost) {
45165 Urls._apiHost = options.apiHost;
45167 if (!!options.exploreHost) {
45168 Urls._exploreHost = options.exploreHost;
45170 if (!!options.imageHost) {
45171 Urls._imageHost = options.imageHost;
45173 if (!!options.imageTileHost) {
45174 Urls._imageTileHost = options.imageTileHost;
45176 if (!!options.meshHost) {
45177 Urls._meshHost = options.meshHost;
45179 if (!!options.scheme) {
45180 Urls._scheme = options.scheme;
45183 Urls._apiHost = "a.mapillary.com";
45184 Urls._exploreHost = "www.mapillary.com";
45185 Urls._imageHost = "d1cuyjsrcm0gby.cloudfront.net";
45186 Urls._imageTileHost = "d2qb1440i7l50o.cloudfront.net";
45187 Urls._meshHost = "d1brzeo354iq2l.cloudfront.net";
45188 Urls._origin = "mapillary.webgl";
45189 Urls._scheme = "https";
45192 exports.Urls = Urls;
45193 exports.default = Urls;
45195 },{}],435:[function(require,module,exports){
45197 Object.defineProperty(exports, "__esModule", { value: true });
45199 * Enumeration for alignments
45204 (function (Alignment) {
45208 Alignment[Alignment["Bottom"] = 0] = "Bottom";
45210 * Align to bottom left
45212 Alignment[Alignment["BottomLeft"] = 1] = "BottomLeft";
45214 * Align to bottom right
45216 Alignment[Alignment["BottomRight"] = 2] = "BottomRight";
45220 Alignment[Alignment["Center"] = 3] = "Center";
45224 Alignment[Alignment["Left"] = 4] = "Left";
45228 Alignment[Alignment["Right"] = 5] = "Right";
45232 Alignment[Alignment["Top"] = 6] = "Top";
45234 * Align to top left
45236 Alignment[Alignment["TopLeft"] = 7] = "TopLeft";
45238 * Align to top right
45240 Alignment[Alignment["TopRight"] = 8] = "TopRight";
45241 })(Alignment = exports.Alignment || (exports.Alignment = {}));
45242 exports.default = Alignment;
45244 },{}],436:[function(require,module,exports){
45246 Object.defineProperty(exports, "__esModule", { value: true });
45247 var Observable_1 = require("rxjs/Observable");
45248 var Graph_1 = require("../Graph");
45249 var CacheService = /** @class */ (function () {
45250 function CacheService(graphService, stateService) {
45251 this._graphService = graphService;
45252 this._stateService = stateService;
45253 this._started = false;
45255 Object.defineProperty(CacheService.prototype, "started", {
45257 return this._started;
45262 CacheService.prototype.start = function () {
45264 if (this._started) {
45267 this._uncacheSubscription = this._stateService.currentState$
45268 .distinctUntilChanged(undefined, function (frame) {
45269 return frame.state.currentNode.key;
45271 .map(function (frame) {
45272 var trajectory = frame.state.trajectory;
45273 var trajectoryKeys = trajectory
45274 .map(function (n) {
45277 var sequenceKey = trajectory[trajectory.length - 1].sequenceKey;
45278 return [trajectoryKeys, sequenceKey];
45281 .withLatestFrom(this._graphService.graphMode$)
45282 .switchMap(function (_a) {
45283 var keepBuffer = _a[0], graphMode = _a[1];
45284 var keepKeys = keepBuffer[0][0];
45285 var keepSequenceKey = graphMode === Graph_1.GraphMode.Sequence ?
45286 keepBuffer[0][1] : undefined;
45287 return _this._graphService.uncache$(keepKeys, keepSequenceKey);
45289 .subscribe(function () { });
45290 this._cacheNodeSubscription = this._graphService.graphMode$
45292 .withLatestFrom(this._stateService.currentState$)
45293 .switchMap(function (_a) {
45294 var mode = _a[0], frame = _a[1];
45295 return mode === Graph_1.GraphMode.Sequence ?
45296 _this._keyToEdges(frame.state.currentNode.key, function (node) {
45297 return node.sequenceEdges$;
45299 Observable_1.Observable
45300 .from(frame.state.trajectory
45301 .map(function (node) {
45304 .slice(frame.state.currentIndex))
45305 .mergeMap(function (key) {
45306 return _this._keyToEdges(key, function (node) {
45307 return node.spatialEdges$;
45311 .subscribe(function () { });
45312 this._started = true;
45314 CacheService.prototype.stop = function () {
45315 if (!this._started) {
45318 this._uncacheSubscription.unsubscribe();
45319 this._uncacheSubscription = null;
45320 this._cacheNodeSubscription.unsubscribe();
45321 this._cacheNodeSubscription = null;
45322 this._started = false;
45324 CacheService.prototype._keyToEdges = function (key, nodeToEdgeMap) {
45325 return this._graphService.cacheNode$(key)
45326 .switchMap(nodeToEdgeMap)
45327 .first(function (status) {
45328 return status.cached;
45331 .catch(function (error) {
45332 console.error("Failed to cache edges (" + key + ").", error);
45333 return Observable_1.Observable.empty();
45336 return CacheService;
45338 exports.CacheService = CacheService;
45339 exports.default = CacheService;
45341 },{"../Graph":294,"rxjs/Observable":29}],437:[function(require,module,exports){
45343 Object.defineProperty(exports, "__esModule", { value: true });
45344 var Component_1 = require("../Component");
45345 var ComponentController = /** @class */ (function () {
45346 function ComponentController(container, navigator, observer, key, options, componentService) {
45348 this._container = container;
45349 this._observer = observer;
45350 this._navigator = navigator;
45351 this._options = options != null ? options : {};
45353 this._navigable = key == null;
45354 this._componentService = !!componentService ?
45356 new Component_1.ComponentService(this._container, this._navigator);
45357 this._coverComponent = this._componentService.getCover();
45358 this._initializeComponents();
45360 this._initilizeCoverComponent();
45361 this._subscribeCoverComponent();
45364 this._navigator.movedToKey$
45365 .first(function (k) {
45368 .subscribe(function (k) {
45370 _this._componentService.deactivateCover();
45371 _this._coverComponent.configure({ key: _this._key, state: Component_1.CoverState.Hidden });
45372 _this._subscribeCoverComponent();
45373 _this._navigator.stateService.start();
45374 _this._navigator.cacheService.start();
45375 _this._observer.startEmit();
45379 Object.defineProperty(ComponentController.prototype, "navigable", {
45381 return this._navigable;
45386 ComponentController.prototype.get = function (name) {
45387 return this._componentService.get(name);
45389 ComponentController.prototype.activate = function (name) {
45390 this._componentService.activate(name);
45392 ComponentController.prototype.activateCover = function () {
45393 this._coverComponent.configure({ state: Component_1.CoverState.Visible });
45395 ComponentController.prototype.deactivate = function (name) {
45396 this._componentService.deactivate(name);
45398 ComponentController.prototype.deactivateCover = function () {
45399 this._coverComponent.configure({ state: Component_1.CoverState.Loading });
45401 ComponentController.prototype.resize = function () {
45402 this._componentService.resize();
45404 ComponentController.prototype._initializeComponents = function () {
45405 var options = this._options;
45406 this._uFalse(options.background, "background");
45407 this._uFalse(options.debug, "debug");
45408 this._uFalse(options.image, "image");
45409 this._uFalse(options.marker, "marker");
45410 this._uFalse(options.navigation, "navigation");
45411 this._uFalse(options.popup, "popup");
45412 this._uFalse(options.route, "route");
45413 this._uFalse(options.slider, "slider");
45414 this._uFalse(options.tag, "tag");
45415 this._uTrue(options.attribution, "attribution");
45416 this._uTrue(options.bearing, "bearing");
45417 this._uTrue(options.cache, "cache");
45418 this._uTrue(options.direction, "direction");
45419 this._uTrue(options.imagePlane, "imagePlane");
45420 this._uTrue(options.keyboard, "keyboard");
45421 this._uTrue(options.loading, "loading");
45422 this._uTrue(options.mouse, "mouse");
45423 this._uTrue(options.sequence, "sequence");
45424 this._uTrue(options.stats, "stats");
45425 this._uTrue(options.zoom, "zoom");
45427 ComponentController.prototype._initilizeCoverComponent = function () {
45428 var options = this._options;
45429 this._coverComponent.configure({ key: this._key });
45430 if (options.cover === undefined || options.cover) {
45431 this.activateCover();
45434 this.deactivateCover();
45437 ComponentController.prototype._setNavigable = function (navigable) {
45438 if (this._navigable === navigable) {
45441 this._navigable = navigable;
45442 this._observer.navigable$.next(navigable);
45444 ComponentController.prototype._subscribeCoverComponent = function () {
45446 this._coverComponent.configuration$.subscribe(function (conf) {
45447 if (conf.state === Component_1.CoverState.Loading) {
45448 _this._navigator.stateService.currentKey$
45450 .switchMap(function (key) {
45451 var keyChanged = key == null || key !== conf.key;
45453 _this._setNavigable(false);
45455 return keyChanged ?
45456 _this._navigator.moveToKey$(conf.key) :
45457 _this._navigator.stateService.currentNode$
45460 .subscribe(function (node) {
45461 _this._navigator.stateService.start();
45462 _this._navigator.cacheService.start();
45463 _this._observer.startEmit();
45464 _this._coverComponent.configure({ state: Component_1.CoverState.Hidden });
45465 _this._componentService.deactivateCover();
45466 _this._setNavigable(true);
45467 }, function (error) {
45468 console.error("Failed to deactivate cover.", error);
45469 _this._coverComponent.configure({ state: Component_1.CoverState.Visible });
45472 else if (conf.state === Component_1.CoverState.Visible) {
45473 _this._observer.stopEmit();
45474 _this._navigator.stateService.stop();
45475 _this._navigator.cacheService.stop();
45476 _this._navigator.playService.stop();
45477 _this._componentService.activateCover();
45478 _this._setNavigable(conf.key == null);
45482 ComponentController.prototype._uFalse = function (option, name) {
45483 if (option === undefined) {
45484 this._componentService.deactivate(name);
45487 if (typeof option === "boolean") {
45489 this._componentService.activate(name);
45492 this._componentService.deactivate(name);
45496 this._componentService.configure(name, option);
45497 this._componentService.activate(name);
45499 ComponentController.prototype._uTrue = function (option, name) {
45500 if (option === undefined) {
45501 this._componentService.activate(name);
45504 if (typeof option === "boolean") {
45506 this._componentService.activate(name);
45509 this._componentService.deactivate(name);
45513 this._componentService.configure(name, option);
45514 this._componentService.activate(name);
45516 return ComponentController;
45518 exports.ComponentController = ComponentController;
45520 },{"../Component":290}],438:[function(require,module,exports){
45522 Object.defineProperty(exports, "__esModule", { value: true });
45523 var Render_1 = require("../Render");
45524 var Utils_1 = require("../Utils");
45525 var Viewer_1 = require("../Viewer");
45526 var Container = /** @class */ (function () {
45527 function Container(id, stateService, options, dom) {
45529 this._dom = !!dom ? dom : new Utils_1.DOM();
45530 this._container = this._dom.document.getElementById(id);
45531 if (!this._container) {
45532 throw new Error("Container '" + id + "' not found.");
45534 this._container.classList.add("mapillary-js");
45535 this._canvasContainer = this._dom.createElement("div", "mapillary-js-interactive", this._container);
45536 this._domContainer = this._dom.createElement("div", "mapillary-js-dom", this._container);
45537 this.renderService = new Render_1.RenderService(this._container, stateService.currentState$, options.renderMode);
45538 this.glRenderer = new Render_1.GLRenderer(this._canvasContainer, this.renderService, this._dom);
45539 this.domRenderer = new Render_1.DOMRenderer(this._domContainer, this.renderService, stateService.currentState$);
45540 this.keyboardService = new Viewer_1.KeyboardService(this._canvasContainer);
45541 this.mouseService = new Viewer_1.MouseService(this._container, this._canvasContainer, this._domContainer, document);
45542 this.touchService = new Viewer_1.TouchService(this._canvasContainer, this._domContainer);
45543 this.spriteService = new Viewer_1.SpriteService(options.sprite);
45545 Object.defineProperty(Container.prototype, "element", {
45547 return this._container;
45552 Object.defineProperty(Container.prototype, "canvasContainer", {
45554 return this._canvasContainer;
45559 Object.defineProperty(Container.prototype, "domContainer", {
45561 return this._domContainer;
45568 exports.Container = Container;
45569 exports.default = Container;
45571 },{"../Render":296,"../Utils":300,"../Viewer":301}],439:[function(require,module,exports){
45573 Object.defineProperty(exports, "__esModule", { value: true });
45575 * Enumeration for image sizes
45578 * @description Image sizes in pixels for the long side of the image.
45581 (function (ImageSize) {
45583 * 320 pixels image size
45585 ImageSize[ImageSize["Size320"] = 320] = "Size320";
45587 * 640 pixels image size
45589 ImageSize[ImageSize["Size640"] = 640] = "Size640";
45591 * 1024 pixels image size
45593 ImageSize[ImageSize["Size1024"] = 1024] = "Size1024";
45595 * 2048 pixels image size
45597 ImageSize[ImageSize["Size2048"] = 2048] = "Size2048";
45598 })(ImageSize = exports.ImageSize || (exports.ImageSize = {}));
45600 },{}],440:[function(require,module,exports){
45602 Object.defineProperty(exports, "__esModule", { value: true });
45603 var Observable_1 = require("rxjs/Observable");
45604 var KeyboardService = /** @class */ (function () {
45605 function KeyboardService(canvasContainer) {
45606 this._keyDown$ = Observable_1.Observable.fromEvent(canvasContainer, "keydown");
45608 Object.defineProperty(KeyboardService.prototype, "keyDown$", {
45610 return this._keyDown$;
45615 return KeyboardService;
45617 exports.KeyboardService = KeyboardService;
45618 exports.default = KeyboardService;
45620 },{"rxjs/Observable":29}],441:[function(require,module,exports){
45622 /// <reference path="../../typings/index.d.ts" />
45623 Object.defineProperty(exports, "__esModule", { value: true });
45624 var _ = require("underscore");
45625 var Subject_1 = require("rxjs/Subject");
45626 var LoadingService = /** @class */ (function () {
45627 function LoadingService() {
45628 this._loadersSubject$ = new Subject_1.Subject();
45629 this._loaders$ = this._loadersSubject$
45630 .scan(function (loaders, loader) {
45631 if (loader.task !== undefined) {
45632 loaders[loader.task] = loader.loading;
45640 Object.defineProperty(LoadingService.prototype, "loading$", {
45642 return this._loaders$
45643 .map(function (loaders) {
45644 return _.reduce(loaders, function (loader, acc) {
45645 return (loader || acc);
45649 .distinctUntilChanged();
45654 LoadingService.prototype.taskLoading$ = function (task) {
45655 return this._loaders$
45656 .map(function (loaders) {
45657 return !!loaders[task];
45660 .distinctUntilChanged();
45662 LoadingService.prototype.startLoading = function (task) {
45663 this._loadersSubject$.next({ loading: true, task: task });
45665 LoadingService.prototype.stopLoading = function (task) {
45666 this._loadersSubject$.next({ loading: false, task: task });
45668 return LoadingService;
45670 exports.LoadingService = LoadingService;
45671 exports.default = LoadingService;
45673 },{"rxjs/Subject":34,"underscore":242}],442:[function(require,module,exports){
45675 Object.defineProperty(exports, "__esModule", { value: true });
45676 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
45677 var Observable_1 = require("rxjs/Observable");
45678 var Subject_1 = require("rxjs/Subject");
45679 var Geo_1 = require("../Geo");
45680 var MouseService = /** @class */ (function () {
45681 function MouseService(container, canvasContainer, domContainer, doc, viewportCoords) {
45683 viewportCoords = viewportCoords != null ? viewportCoords : new Geo_1.ViewportCoords();
45684 this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
45685 this._active$ = this._activeSubject$
45686 .distinctUntilChanged()
45689 this._claimMouse$ = new Subject_1.Subject();
45690 this._claimWheel$ = new Subject_1.Subject();
45691 this._deferPixelClaims$ = new Subject_1.Subject();
45692 this._deferPixels$ = this._deferPixelClaims$
45693 .scan(function (claims, claim) {
45694 if (claim.deferPixels == null) {
45695 delete claims[claim.name];
45698 claims[claim.name] = claim.deferPixels;
45702 .map(function (claims) {
45703 var deferPixelMax = -1;
45704 for (var key in claims) {
45705 if (!claims.hasOwnProperty(key)) {
45708 var deferPixels = claims[key];
45709 if (deferPixels > deferPixelMax) {
45710 deferPixelMax = deferPixels;
45713 return deferPixelMax;
45718 this._deferPixels$.subscribe(function () { });
45719 this._documentMouseMove$ = Observable_1.Observable.fromEvent(doc, "mousemove");
45720 this._documentMouseUp$ = Observable_1.Observable.fromEvent(doc, "mouseup");
45721 this._mouseDown$ = Observable_1.Observable.fromEvent(canvasContainer, "mousedown");
45722 this._mouseLeave$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseleave");
45723 this._mouseMove$ = Observable_1.Observable.fromEvent(canvasContainer, "mousemove");
45724 this._mouseUp$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseup");
45725 this._mouseOut$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseout");
45726 this._mouseOver$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseover");
45727 this._domMouseDown$ = Observable_1.Observable.fromEvent(domContainer, "mousedown");
45728 this._domMouseMove$ = Observable_1.Observable.fromEvent(domContainer, "mousemove");
45729 this._click$ = Observable_1.Observable.fromEvent(canvasContainer, "click");
45730 this._contextMenu$ = Observable_1.Observable.fromEvent(canvasContainer, "contextmenu");
45731 this._dblClick$ = Observable_1.Observable
45732 .merge(Observable_1.Observable.fromEvent(container, "click"), Observable_1.Observable.fromEvent(canvasContainer, "dblclick"))
45734 .filter(function (events) {
45735 var event1 = events[0];
45736 var event2 = events[1];
45737 var event3 = events[2];
45738 return event1.type === "click" &&
45739 event2.type === "click" &&
45740 event3.type === "dblclick" &&
45741 event1.target.parentNode === canvasContainer &&
45742 event2.target.parentNode === canvasContainer;
45744 .map(function (events) {
45748 Observable_1.Observable
45749 .merge(this._domMouseDown$, this._domMouseMove$, this._dblClick$, this._contextMenu$)
45750 .subscribe(function (event) {
45751 event.preventDefault();
45753 this._mouseWheel$ = Observable_1.Observable
45754 .merge(Observable_1.Observable.fromEvent(canvasContainer, "wheel"), Observable_1.Observable.fromEvent(domContainer, "wheel"))
45756 this._consistentContextMenu$ = Observable_1.Observable
45757 .merge(this._mouseDown$, this._mouseMove$, this._mouseOut$, this._mouseUp$, this._contextMenu$)
45759 .filter(function (events) {
45760 // fire context menu on mouse up both on mac and windows
45761 return events[0].type === "mousedown" &&
45762 events[1].type === "contextmenu" &&
45763 events[2].type === "mouseup";
45765 .map(function (events) {
45769 var dragStop$ = Observable_1.Observable
45770 .merge(Observable_1.Observable.fromEvent(window, "blur"), this._documentMouseUp$
45771 .filter(function (e) {
45772 return e.button === 0;
45775 var mouseDragInitiate$ = this._createMouseDragInitiate$(this._mouseDown$, dragStop$, true).share();
45776 this._mouseDragStart$ = this._createMouseDragStart$(mouseDragInitiate$).share();
45777 this._mouseDrag$ = this._createMouseDrag$(mouseDragInitiate$, dragStop$).share();
45778 this._mouseDragEnd$ = this._createMouseDragEnd$(this._mouseDragStart$, dragStop$).share();
45779 var domMouseDragInitiate$ = this._createMouseDragInitiate$(this._domMouseDown$, dragStop$, false).share();
45780 this._domMouseDragStart$ = this._createMouseDragStart$(domMouseDragInitiate$).share();
45781 this._domMouseDrag$ = this._createMouseDrag$(domMouseDragInitiate$, dragStop$).share();
45782 this._domMouseDragEnd$ = this._createMouseDragEnd$(this._domMouseDragStart$, dragStop$).share();
45783 this._proximateClick$ = this._mouseDown$
45784 .switchMap(function (mouseDown) {
45785 return _this._click$
45786 .takeUntil(_this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$))
45790 this._staticClick$ = this._mouseDown$
45791 .switchMap(function (e) {
45792 return _this._click$
45793 .takeUntil(_this._documentMouseMove$)
45797 this._mouseDragStart$.subscribe();
45798 this._mouseDrag$.subscribe();
45799 this._mouseDragEnd$.subscribe();
45800 this._domMouseDragStart$.subscribe();
45801 this._domMouseDrag$.subscribe();
45802 this._domMouseDragEnd$.subscribe();
45803 this._staticClick$.subscribe();
45804 this._mouseOwner$ = this._createOwner$(this._claimMouse$)
45807 this._wheelOwner$ = this._createOwner$(this._claimWheel$)
45810 this._mouseOwner$.subscribe(function () { });
45811 this._wheelOwner$.subscribe(function () { });
45813 Object.defineProperty(MouseService.prototype, "active$", {
45815 return this._active$;
45820 Object.defineProperty(MouseService.prototype, "activate$", {
45822 return this._activeSubject$;
45827 Object.defineProperty(MouseService.prototype, "documentMouseMove$", {
45829 return this._documentMouseMove$;
45834 Object.defineProperty(MouseService.prototype, "documentMouseUp$", {
45836 return this._documentMouseUp$;
45841 Object.defineProperty(MouseService.prototype, "domMouseDragStart$", {
45843 return this._domMouseDragStart$;
45848 Object.defineProperty(MouseService.prototype, "domMouseDrag$", {
45850 return this._domMouseDrag$;
45855 Object.defineProperty(MouseService.prototype, "domMouseDragEnd$", {
45857 return this._domMouseDragEnd$;
45862 Object.defineProperty(MouseService.prototype, "domMouseDown$", {
45864 return this._domMouseDown$;
45869 Object.defineProperty(MouseService.prototype, "domMouseMove$", {
45871 return this._domMouseMove$;
45876 Object.defineProperty(MouseService.prototype, "mouseOwner$", {
45878 return this._mouseOwner$;
45883 Object.defineProperty(MouseService.prototype, "mouseDown$", {
45885 return this._mouseDown$;
45890 Object.defineProperty(MouseService.prototype, "mouseMove$", {
45892 return this._mouseMove$;
45897 Object.defineProperty(MouseService.prototype, "mouseLeave$", {
45899 return this._mouseLeave$;
45904 Object.defineProperty(MouseService.prototype, "mouseOut$", {
45906 return this._mouseOut$;
45911 Object.defineProperty(MouseService.prototype, "mouseOver$", {
45913 return this._mouseOver$;
45918 Object.defineProperty(MouseService.prototype, "mouseUp$", {
45920 return this._mouseUp$;
45925 Object.defineProperty(MouseService.prototype, "click$", {
45927 return this._click$;
45932 Object.defineProperty(MouseService.prototype, "dblClick$", {
45934 return this._dblClick$;
45939 Object.defineProperty(MouseService.prototype, "contextMenu$", {
45941 return this._consistentContextMenu$;
45946 Object.defineProperty(MouseService.prototype, "mouseWheel$", {
45948 return this._mouseWheel$;
45953 Object.defineProperty(MouseService.prototype, "mouseDragStart$", {
45955 return this._mouseDragStart$;
45960 Object.defineProperty(MouseService.prototype, "mouseDrag$", {
45962 return this._mouseDrag$;
45967 Object.defineProperty(MouseService.prototype, "mouseDragEnd$", {
45969 return this._mouseDragEnd$;
45974 Object.defineProperty(MouseService.prototype, "proximateClick$", {
45976 return this._proximateClick$;
45981 Object.defineProperty(MouseService.prototype, "staticClick$", {
45983 return this._staticClick$;
45988 MouseService.prototype.claimMouse = function (name, zindex) {
45989 this._claimMouse$.next({ name: name, zindex: zindex });
45991 MouseService.prototype.unclaimMouse = function (name) {
45992 this._claimMouse$.next({ name: name, zindex: null });
45994 MouseService.prototype.deferPixels = function (name, deferPixels) {
45995 this._deferPixelClaims$.next({ name: name, deferPixels: deferPixels });
45997 MouseService.prototype.undeferPixels = function (name) {
45998 this._deferPixelClaims$.next({ name: name, deferPixels: null });
46000 MouseService.prototype.claimWheel = function (name, zindex) {
46001 this._claimWheel$.next({ name: name, zindex: zindex });
46003 MouseService.prototype.unclaimWheel = function (name) {
46004 this._claimWheel$.next({ name: name, zindex: null });
46006 MouseService.prototype.filtered$ = function (name, observable$) {
46007 return this._filtered(name, observable$, this._mouseOwner$);
46009 MouseService.prototype.filteredWheel$ = function (name, observable$) {
46010 return this._filtered(name, observable$, this._wheelOwner$);
46012 MouseService.prototype._createDeferredMouseMove$ = function (origin, mouseMove$) {
46014 .map(function (mouseMove) {
46015 var deltaX = mouseMove.clientX - origin.clientX;
46016 var deltaY = mouseMove.clientY - origin.clientY;
46017 return [mouseMove, Math.sqrt(deltaX * deltaX + deltaY * deltaY)];
46019 .withLatestFrom(this._deferPixels$)
46020 .filter(function (_a) {
46021 var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1];
46022 return delta > deferPixels;
46024 .map(function (_a) {
46025 var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1];
46029 MouseService.prototype._createMouseDrag$ = function (mouseDragStartInitiate$, stop$) {
46031 return mouseDragStartInitiate$
46032 .map(function (_a) {
46033 var mouseDown = _a[0], mouseMove = _a[1];
46036 .switchMap(function (mouseMove) {
46037 return Observable_1.Observable
46039 .concat(_this._documentMouseMove$)
46043 MouseService.prototype._createMouseDragEnd$ = function (mouseDragStart$, stop$) {
46044 return mouseDragStart$
46045 .switchMap(function (event) {
46046 return stop$.first();
46049 MouseService.prototype._createMouseDragStart$ = function (mouseDragStartInitiate$) {
46050 return mouseDragStartInitiate$
46051 .map(function (_a) {
46052 var mouseDown = _a[0], mouseMove = _a[1];
46056 MouseService.prototype._createMouseDragInitiate$ = function (mouseDown$, stop$, defer) {
46059 .filter(function (mouseDown) {
46060 return mouseDown.button === 0;
46062 .switchMap(function (mouseDown) {
46063 return Observable_1.Observable
46064 .combineLatest(Observable_1.Observable.of(mouseDown), defer ?
46065 _this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$) :
46066 _this._documentMouseMove$)
46071 MouseService.prototype._createOwner$ = function (claim$) {
46073 .scan(function (claims, claim) {
46074 if (claim.zindex == null) {
46075 delete claims[claim.name];
46078 claims[claim.name] = claim.zindex;
46082 .map(function (claims) {
46084 var zIndexMax = -1;
46085 for (var name_1 in claims) {
46086 if (!claims.hasOwnProperty(name_1)) {
46089 if (claims[name_1] > zIndexMax) {
46090 zIndexMax = claims[name_1];
46098 MouseService.prototype._filtered = function (name, observable$, owner$) {
46100 .withLatestFrom(owner$)
46101 .filter(function (_a) {
46102 var item = _a[0], owner = _a[1];
46103 return owner === name;
46105 .map(function (_a) {
46106 var item = _a[0], owner = _a[1];
46110 return MouseService;
46112 exports.MouseService = MouseService;
46113 exports.default = MouseService;
46115 },{"../Geo":293,"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/Subject":34}],443:[function(require,module,exports){
46117 /// <reference path="../../typings/index.d.ts" />
46118 Object.defineProperty(exports, "__esModule", { value: true });
46119 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
46120 var Observable_1 = require("rxjs/Observable");
46121 var ReplaySubject_1 = require("rxjs/ReplaySubject");
46122 var API_1 = require("../API");
46123 var Graph_1 = require("../Graph");
46124 var Edge_1 = require("../Edge");
46125 var Error_1 = require("../Error");
46126 var State_1 = require("../State");
46127 var Viewer_1 = require("../Viewer");
46128 var Navigator = /** @class */ (function () {
46129 function Navigator(clientId, options, token, apiV3, graphService, imageLoadingService, loadingService, stateService, cacheService, playService) {
46130 this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token);
46131 this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService();
46132 this._graphService = graphService != null ?
46134 new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService);
46135 this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService();
46136 this._loadingName = "navigator";
46137 this._stateService = stateService != null ? stateService : new State_1.StateService(options.transitionMode);
46138 this._cacheService = cacheService != null ?
46140 new Viewer_1.CacheService(this._graphService, this._stateService);
46141 this._playService = playService != null ?
46143 new Viewer_1.PlayService(this._graphService, this._stateService);
46144 this._keyRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
46145 this._movedToKey$ = new BehaviorSubject_1.BehaviorSubject(null);
46146 this._request$ = null;
46147 this._requestSubscription = null;
46148 this._nodeRequestSubscription = null;
46150 Object.defineProperty(Navigator.prototype, "apiV3", {
46152 return this._apiV3;
46157 Object.defineProperty(Navigator.prototype, "cacheService", {
46159 return this._cacheService;
46164 Object.defineProperty(Navigator.prototype, "graphService", {
46166 return this._graphService;
46171 Object.defineProperty(Navigator.prototype, "imageLoadingService", {
46173 return this._imageLoadingService;
46178 Object.defineProperty(Navigator.prototype, "loadingService", {
46180 return this._loadingService;
46185 Object.defineProperty(Navigator.prototype, "movedToKey$", {
46187 return this._movedToKey$;
46192 Object.defineProperty(Navigator.prototype, "playService", {
46194 return this._playService;
46199 Object.defineProperty(Navigator.prototype, "stateService", {
46201 return this._stateService;
46206 Navigator.prototype.moveToKey$ = function (key) {
46207 this._abortRequest("to key " + key);
46208 this._loadingService.startLoading(this._loadingName);
46209 var node$ = this._moveToKey$(key);
46210 return this._makeRequest$(node$);
46212 Navigator.prototype.moveDir$ = function (direction) {
46214 this._abortRequest("in dir " + Edge_1.EdgeDirection[direction]);
46215 this._loadingService.startLoading(this._loadingName);
46216 var node$ = this.stateService.currentNode$
46218 .mergeMap(function (node) {
46219 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
46220 node.sequenceEdges$ :
46221 node.spatialEdges$)
46223 .map(function (status) {
46224 for (var _i = 0, _a = status.edges; _i < _a.length; _i++) {
46226 if (edge.data.direction === direction) {
46233 .mergeMap(function (directionKey) {
46234 if (directionKey == null) {
46235 _this._loadingService.stopLoading(_this._loadingName);
46236 return Observable_1.Observable
46237 .throw(new Error("Direction (" + direction + ") does not exist for current node."));
46239 return _this._moveToKey$(directionKey);
46241 return this._makeRequest$(node$);
46243 Navigator.prototype.moveCloseTo$ = function (lat, lon) {
46245 this._abortRequest("to lat " + lat + ", lon " + lon);
46246 this._loadingService.startLoading(this._loadingName);
46247 var node$ = this.apiV3.imageCloseTo$(lat, lon)
46248 .mergeMap(function (fullNode) {
46249 if (fullNode == null) {
46250 _this._loadingService.stopLoading(_this._loadingName);
46251 return Observable_1.Observable
46252 .throw(new Error("No image found close to lat " + lat + ", lon " + lon + "."));
46254 return _this._moveToKey$(fullNode.key);
46256 return this._makeRequest$(node$);
46258 Navigator.prototype.setFilter$ = function (filter) {
46260 this._stateService.clearNodes();
46261 return this._movedToKey$
46263 .mergeMap(function (key) {
46265 return _this._trajectoryKeys$()
46266 .mergeMap(function (keys) {
46267 return _this._graphService.setFilter$(filter)
46268 .mergeMap(function () {
46269 return _this._cacheKeys$(keys);
46274 return _this._keyRequested$
46276 .mergeMap(function (requestedKey) {
46277 if (requestedKey != null) {
46278 return _this._graphService.setFilter$(filter)
46279 .mergeMap(function () {
46280 return _this._graphService.cacheNode$(requestedKey);
46283 return _this._graphService.setFilter$(filter)
46289 .map(function (node) {
46293 Navigator.prototype.setToken$ = function (token) {
46295 this._abortRequest("to set token");
46296 this._stateService.clearNodes();
46297 return this._movedToKey$
46299 .do(function (key) {
46300 _this._apiV3.setToken(token);
46302 .mergeMap(function (key) {
46303 return key == null ?
46304 _this._graphService.reset$([]) :
46305 _this._trajectoryKeys$()
46306 .mergeMap(function (keys) {
46307 return _this._graphService.reset$(keys)
46308 .mergeMap(function () {
46309 return _this._cacheKeys$(keys);
46313 .map(function (node) {
46318 Navigator.prototype._cacheKeys$ = function (keys) {
46320 var cacheNodes$ = keys
46321 .map(function (key) {
46322 return _this._graphService.cacheNode$(key);
46324 return Observable_1.Observable
46328 Navigator.prototype._abortRequest = function (reason) {
46329 if (this._requestSubscription != null) {
46330 this._requestSubscription.unsubscribe();
46331 this._requestSubscription = null;
46333 if (this._nodeRequestSubscription != null) {
46334 this._nodeRequestSubscription.unsubscribe();
46335 this._nodeRequestSubscription = null;
46337 if (this._request$ != null) {
46338 if (!(this._request$.isStopped || this._request$.hasError)) {
46339 this._request$.error(new Error_1.AbortMapillaryError("Request aborted by a subsequent request " + reason + "."));
46341 this._request$ = null;
46344 Navigator.prototype._makeRequest$ = function (node$) {
46346 var request$ = new ReplaySubject_1.ReplaySubject(1);
46347 this._requestSubscription = request$
46348 .subscribe(undefined, function (e) { });
46349 this._request$ = request$;
46350 this._nodeRequestSubscription = node$
46351 .subscribe(function (node) {
46352 request$.next(node);
46353 request$.complete();
46354 _this._request$ = null;
46355 }, function (error) {
46356 request$.error(error);
46357 _this._request$ = null;
46361 Navigator.prototype._moveToKey$ = function (key) {
46363 this._keyRequested$.next(key);
46364 return this._graphService.cacheNode$(key)
46365 .do(function (node) {
46366 _this._stateService.setNodes([node]);
46367 _this._movedToKey$.next(node.key);
46369 .finally(function () {
46370 _this._loadingService.stopLoading(_this._loadingName);
46373 Navigator.prototype._trajectoryKeys$ = function () {
46374 return this._stateService.currentState$
46376 .map(function (frame) {
46377 return frame.state.trajectory
46378 .map(function (node) {
46385 exports.Navigator = Navigator;
46386 exports.default = Navigator;
46388 },{"../API":289,"../Edge":291,"../Error":292,"../Graph":294,"../State":297,"../Viewer":301,"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/ReplaySubject":32}],444:[function(require,module,exports){
46390 Object.defineProperty(exports, "__esModule", { value: true });
46391 var Observable_1 = require("rxjs/Observable");
46392 var Subject_1 = require("rxjs/Subject");
46393 var Viewer_1 = require("../Viewer");
46394 var Observer = /** @class */ (function () {
46395 function Observer(eventEmitter, navigator, container) {
46397 this._container = container;
46398 this._eventEmitter = eventEmitter;
46399 this._navigator = navigator;
46400 this._projection = new Viewer_1.Projection();
46401 this._started = false;
46402 this._navigable$ = new Subject_1.Subject();
46403 // navigable and loading should always emit, also when cover is activated.
46405 .subscribe(function (navigable) {
46406 _this._eventEmitter.fire(Viewer_1.Viewer.navigablechanged, navigable);
46408 this._navigator.loadingService.loading$
46409 .subscribe(function (loading) {
46410 _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading);
46413 Object.defineProperty(Observer.prototype, "started", {
46415 return this._started;
46420 Object.defineProperty(Observer.prototype, "navigable$", {
46422 return this._navigable$;
46427 Observer.prototype.projectBasic$ = function (basicPoint) {
46429 return Observable_1.Observable
46430 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
46432 .map(function (_a) {
46433 var render = _a[0], transform = _a[1];
46434 var canvasPoint = _this._projection.basicToCanvas(basicPoint, _this._container.element, render, transform);
46435 return [Math.round(canvasPoint[0]), Math.round(canvasPoint[1])];
46438 Observer.prototype.startEmit = function () {
46440 if (this._started) {
46443 this._started = true;
46444 this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$
46445 .subscribe(function (node) {
46446 _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node);
46448 this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$
46449 .switchMap(function (node) {
46450 return node.sequenceEdges$;
46452 .subscribe(function (status) {
46453 _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status);
46455 this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$
46456 .switchMap(function (node) {
46457 return node.spatialEdges$;
46459 .subscribe(function (status) {
46460 _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status);
46462 this._moveSubscription = Observable_1.Observable
46463 .combineLatest(this._navigator.stateService.inMotion$, this._container.mouseService.active$, this._container.touchService.active$)
46464 .map(function (values) {
46465 return values[0] || values[1] || values[2];
46467 .distinctUntilChanged()
46468 .subscribe(function (started) {
46470 _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null);
46473 _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null);
46476 this._bearingSubscription = this._container.renderService.bearing$
46478 .distinctUntilChanged(function (b1, b2) {
46479 return Math.abs(b2 - b1) < 1;
46481 .subscribe(function (bearing) {
46482 _this._eventEmitter.fire(Viewer_1.Viewer.bearingchanged, bearing);
46484 var mouseMove$ = this._container.mouseService.active$
46485 .switchMap(function (active) {
46487 Observable_1.Observable.empty() :
46488 _this._container.mouseService.mouseMove$;
46490 this._viewerMouseEventSubscription = Observable_1.Observable
46491 .merge(this._mapMouseEvent$(Viewer_1.Viewer.click, this._container.mouseService.staticClick$), this._mapMouseEvent$(Viewer_1.Viewer.contextmenu, this._container.mouseService.contextMenu$), this._mapMouseEvent$(Viewer_1.Viewer.dblclick, this._container.mouseService.dblClick$), this._mapMouseEvent$(Viewer_1.Viewer.mousedown, this._container.mouseService.mouseDown$), this._mapMouseEvent$(Viewer_1.Viewer.mousemove, mouseMove$), this._mapMouseEvent$(Viewer_1.Viewer.mouseout, this._container.mouseService.mouseOut$), this._mapMouseEvent$(Viewer_1.Viewer.mouseover, this._container.mouseService.mouseOver$), this._mapMouseEvent$(Viewer_1.Viewer.mouseup, this._container.mouseService.mouseUp$))
46492 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
46493 .map(function (_a) {
46494 var _b = _a[0], type = _b[0], event = _b[1], render = _a[1], reference = _a[2], transform = _a[3];
46495 var unprojection = _this._projection.eventToUnprojection(event, _this._container.element, render, reference, transform);
46497 basicPoint: unprojection.basicPoint,
46498 latLon: unprojection.latLon,
46499 originalEvent: event,
46500 pixelPoint: unprojection.pixelPoint,
46501 target: _this._eventEmitter,
46505 .subscribe(function (event) {
46506 _this._eventEmitter.fire(event.type, event);
46509 Observer.prototype.stopEmit = function () {
46510 if (!this.started) {
46513 this._started = false;
46514 this._bearingSubscription.unsubscribe();
46515 this._currentNodeSubscription.unsubscribe();
46516 this._moveSubscription.unsubscribe();
46517 this._sequenceEdgesSubscription.unsubscribe();
46518 this._spatialEdgesSubscription.unsubscribe();
46519 this._viewerMouseEventSubscription.unsubscribe();
46520 this._bearingSubscription = null;
46521 this._currentNodeSubscription = null;
46522 this._moveSubscription = null;
46523 this._sequenceEdgesSubscription = null;
46524 this._spatialEdgesSubscription = null;
46525 this._viewerMouseEventSubscription = null;
46527 Observer.prototype.unproject$ = function (canvasPoint) {
46529 return Observable_1.Observable
46530 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
46532 .map(function (_a) {
46533 var render = _a[0], reference = _a[1], transform = _a[2];
46534 var unprojection = _this._projection.canvasToUnprojection(canvasPoint, _this._container.element, render, reference, transform);
46535 return unprojection.latLon;
46538 Observer.prototype.unprojectBasic$ = function (canvasPoint) {
46540 return Observable_1.Observable
46541 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
46543 .map(function (_a) {
46544 var render = _a[0], transform = _a[1];
46545 return _this._projection.canvasToBasic(canvasPoint, _this._container.element, render, transform);
46548 Observer.prototype._mapMouseEvent$ = function (type, mouseEvent$) {
46549 return mouseEvent$.map(function (event) {
46550 return [type, event];
46555 exports.Observer = Observer;
46556 exports.default = Observer;
46558 },{"../Viewer":301,"rxjs/Observable":29,"rxjs/Subject":34}],445:[function(require,module,exports){
46560 Object.defineProperty(exports, "__esModule", { value: true });
46561 var Observable_1 = require("rxjs/Observable");
46562 var Subject_1 = require("rxjs/Subject");
46563 var Edge_1 = require("../Edge");
46564 var Graph_1 = require("../Graph");
46565 var PlayService = /** @class */ (function () {
46566 function PlayService(graphService, stateService, graphCalculator) {
46567 this._graphService = graphService;
46568 this._stateService = stateService;
46569 this._graphCalculator = !!graphCalculator ? graphCalculator : new Graph_1.GraphCalculator();
46570 this._directionSubject$ = new Subject_1.Subject();
46571 this._direction$ = this._directionSubject$
46572 .startWith(Edge_1.EdgeDirection.Next)
46575 this._direction$.subscribe();
46576 this._playing = false;
46577 this._playingSubject$ = new Subject_1.Subject();
46578 this._playing$ = this._playingSubject$
46579 .startWith(this._playing)
46582 this._playing$.subscribe();
46584 this._speedSubject$ = new Subject_1.Subject();
46585 this._speed$ = this._speedSubject$
46586 .startWith(this._speed)
46589 this._speed$.subscribe();
46590 this._nodesAhead = this._mapNodesAhead(this._mapSpeed(this._speed));
46591 this._bridging$ = null;
46593 Object.defineProperty(PlayService.prototype, "playing", {
46595 return this._playing;
46600 Object.defineProperty(PlayService.prototype, "direction$", {
46602 return this._direction$;
46607 Object.defineProperty(PlayService.prototype, "playing$", {
46609 return this._playing$;
46614 Object.defineProperty(PlayService.prototype, "speed$", {
46616 return this._speed$;
46621 PlayService.prototype.play = function () {
46623 if (this._playing) {
46626 this._stateService.cutNodes();
46627 var stateSpeed = this._setSpeed(this._speed);
46628 this._stateService.setSpeed(stateSpeed);
46629 this._graphModeSubscription = this._speed$
46630 .map(function (speed) {
46631 return speed > 0.54 ? Graph_1.GraphMode.Sequence : Graph_1.GraphMode.Spatial;
46633 .distinctUntilChanged()
46634 .subscribe(function (mode) {
46635 _this._graphService.setGraphMode(mode);
46637 this._cacheSubscription = this._stateService.currentNode$
46638 .map(function (node) {
46639 return [node.sequenceKey, node.key];
46641 .distinctUntilChanged(undefined, function (_a) {
46642 var sequenceKey = _a[0], nodeKey = _a[1];
46643 return sequenceKey;
46645 .combineLatest(this._graphService.graphMode$, this._direction$)
46646 .switchMap(function (_a) {
46647 var _b = _a[0], sequenceKey = _b[0], nodeKey = _b[1], mode = _a[1], direction = _a[2];
46648 if (direction !== Edge_1.EdgeDirection.Next && direction !== Edge_1.EdgeDirection.Prev) {
46649 return Observable_1.Observable.of([undefined, direction]);
46651 var sequence$ = (mode === Graph_1.GraphMode.Sequence ?
46652 _this._graphService.cacheSequenceNodes$(sequenceKey, nodeKey) :
46653 _this._graphService.cacheSequence$(sequenceKey))
46655 .catch(function (error) {
46656 console.error(error);
46657 return Observable_1.Observable.of(undefined);
46659 return Observable_1.Observable
46660 .combineLatest(sequence$, Observable_1.Observable.of(direction));
46662 .switchMap(function (_a) {
46663 var sequence = _a[0], direction = _a[1];
46664 if (sequence === undefined) {
46665 return Observable_1.Observable.empty();
46667 var sequenceKeys = sequence.keys.slice();
46668 if (direction === Edge_1.EdgeDirection.Prev) {
46669 sequenceKeys.reverse();
46671 return _this._stateService.currentState$
46672 .map(function (frame) {
46673 return [frame.state.trajectory[frame.state.trajectory.length - 1].key, frame.state.nodesAhead];
46675 .scan(function (_a, _b) {
46676 var lastRequestKey = _a[0], previousRequestKeys = _a[1];
46677 var lastTrajectoryKey = _b[0], nodesAhead = _b[1];
46678 if (lastRequestKey === undefined) {
46679 lastRequestKey = lastTrajectoryKey;
46681 var lastIndex = sequenceKeys.length - 1;
46682 if (nodesAhead >= _this._nodesAhead || sequenceKeys[lastIndex] === lastRequestKey) {
46683 return [lastRequestKey, []];
46685 var current = sequenceKeys.indexOf(lastTrajectoryKey);
46686 var start = sequenceKeys.indexOf(lastRequestKey) + 1;
46687 var end = Math.min(lastIndex, current + _this._nodesAhead - nodesAhead) + 1;
46688 if (end <= start) {
46689 return [lastRequestKey, []];
46691 return [sequenceKeys[end - 1], sequenceKeys.slice(start, end)];
46692 }, [undefined, []])
46693 .mergeMap(function (_a) {
46694 var lastRequestKey = _a[0], newRequestKeys = _a[1];
46695 return Observable_1.Observable.from(newRequestKeys);
46698 .mergeMap(function (key) {
46699 return _this._graphService.cacheNode$(key)
46700 .catch(function () {
46701 return Observable_1.Observable.empty();
46705 this._playingSubscription = this._stateService.currentState$
46706 .filter(function (frame) {
46707 return frame.state.nodesAhead < _this._nodesAhead;
46709 .distinctUntilChanged(undefined, function (frame) {
46710 return frame.state.lastNode.key;
46712 .map(function (frame) {
46713 var lastNode = frame.state.lastNode;
46714 var trajectory = frame.state.trajectory;
46715 var increasingTime = undefined;
46716 for (var i = trajectory.length - 2; i >= 0; i--) {
46717 var node = trajectory[i];
46718 if (node.sequenceKey !== lastNode.sequenceKey) {
46721 if (node.capturedAt !== lastNode.capturedAt) {
46722 increasingTime = node.capturedAt < lastNode.capturedAt;
46726 return [frame.state.lastNode, increasingTime];
46728 .withLatestFrom(this._direction$)
46729 .switchMap(function (_a) {
46730 var _b = _a[0], node = _b[0], increasingTime = _b[1], direction = _a[1];
46731 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
46732 node.sequenceEdges$ :
46733 node.spatialEdges$)
46734 .first(function (status) {
46735 return status.cached;
46738 .zip(Observable_1.Observable.of(direction))
46739 .map(function (_a) {
46740 var s = _a[0], d = _a[1];
46741 for (var _i = 0, _b = s.edges; _i < _b.length; _i++) {
46743 if (edge.data.direction === d) {
46749 .switchMap(function (key) {
46750 return key != null ?
46751 _this._graphService.cacheNode$(key) :
46752 _this._bridge$(node, increasingTime)
46753 .filter(function (n) {
46758 .subscribe(function (node) {
46759 _this._stateService.appendNodes([node]);
46760 }, function (error) {
46761 console.error(error);
46764 this._clearSubscription = this._stateService.currentNode$
46765 .bufferCount(1, 10)
46766 .subscribe(function (nodes) {
46767 _this._stateService.clearPriorNodes();
46769 this._setPlaying(true);
46770 var currentLastNodes$ = this._stateService.currentState$
46771 .map(function (frame) {
46772 return frame.state;
46774 .distinctUntilChanged(function (_a, _b) {
46775 var kc1 = _a[0], kl1 = _a[1];
46776 var kc2 = _b[0], kl2 = _b[1];
46777 return kc1 === kc2 && kl1 === kl2;
46778 }, function (state) {
46779 return [state.currentNode.key, state.lastNode.key];
46781 .filter(function (state) {
46782 return state.currentNode.key === state.lastNode.key &&
46783 state.currentIndex === state.trajectory.length - 1;
46785 .map(function (state) {
46786 return state.currentNode;
46788 this._stopSubscription = Observable_1.Observable
46789 .combineLatest(currentLastNodes$, this._direction$)
46790 .switchMap(function (_a) {
46791 var node = _a[0], direction = _a[1];
46792 var edgeStatus$ = ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
46793 node.sequenceEdges$ :
46794 node.spatialEdges$)
46795 .first(function (status) {
46796 return status.cached;
46799 .catch(function (error) {
46800 console.error(error);
46801 return Observable_1.Observable.of({ cached: false, edges: [] });
46803 return Observable_1.Observable
46804 .combineLatest(Observable_1.Observable.of(direction), edgeStatus$)
46805 .map(function (_a) {
46806 var d = _a[0], es = _a[1];
46807 for (var _i = 0, _b = es.edges; _i < _b.length; _i++) {
46809 if (edge.data.direction === d) {
46816 .mergeMap(function (hasEdge) {
46817 if (hasEdge || !_this._bridging$) {
46818 return Observable_1.Observable.of(hasEdge);
46820 return _this._bridging$
46821 .map(function (node) {
46822 return node != null;
46824 .catch(function (error) {
46825 console.error(error);
46826 return Observable_1.Observable.of(false);
46829 .first(function (hasEdge) {
46832 .subscribe(undefined, undefined, function () { _this.stop(); });
46833 if (this._stopSubscription.closed) {
46834 this._stopSubscription = null;
46837 PlayService.prototype.setDirection = function (direction) {
46838 this._directionSubject$.next(direction);
46840 PlayService.prototype.setSpeed = function (speed) {
46841 speed = Math.max(0, Math.min(1, speed));
46842 if (speed === this._speed) {
46845 var stateSpeed = this._setSpeed(speed);
46846 if (this._playing) {
46847 this._stateService.setSpeed(stateSpeed);
46849 this._speedSubject$.next(this._speed);
46851 PlayService.prototype.stop = function () {
46852 if (!this._playing) {
46855 if (!!this._stopSubscription) {
46856 if (!this._stopSubscription.closed) {
46857 this._stopSubscription.unsubscribe();
46859 this._stopSubscription = null;
46861 this._graphModeSubscription.unsubscribe();
46862 this._graphModeSubscription = null;
46863 this._cacheSubscription.unsubscribe();
46864 this._cacheSubscription = null;
46865 this._playingSubscription.unsubscribe();
46866 this._playingSubscription = null;
46867 this._clearSubscription.unsubscribe();
46868 this._clearSubscription = null;
46869 this._stateService.setSpeed(1);
46870 this._stateService.cutNodes();
46871 this._graphService.setGraphMode(Graph_1.GraphMode.Spatial);
46872 this._setPlaying(false);
46874 PlayService.prototype._bridge$ = function (node, increasingTime) {
46876 if (increasingTime === undefined) {
46877 return Observable_1.Observable.of(null);
46879 var boundingBox = this._graphCalculator.boundingBoxCorners(node.latLon, 25);
46880 this._bridging$ = this._graphService.cacheBoundingBox$(boundingBox[0], boundingBox[1])
46881 .mergeMap(function (nodes) {
46882 var nextNode = null;
46883 for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
46884 var n = nodes_1[_i];
46885 if (n.sequenceKey === node.sequenceKey ||
46887 n.cameraUuid !== node.cameraUuid ||
46888 n.capturedAt === node.capturedAt ||
46889 n.capturedAt > node.capturedAt !== increasingTime) {
46892 var delta = Math.abs(n.capturedAt - node.capturedAt);
46893 if (delta > 15000) {
46896 if (!nextNode || delta < Math.abs(nextNode.capturedAt - node.capturedAt)) {
46900 return !!nextNode ?
46901 _this._graphService.cacheNode$(nextNode.key) :
46902 Observable_1.Observable.of(null);
46904 .finally(function () {
46905 _this._bridging$ = null;
46909 return this._bridging$;
46911 PlayService.prototype._mapSpeed = function (speed) {
46912 var x = 2 * speed - 1;
46913 return Math.pow(10, x) - 0.2 * x;
46915 PlayService.prototype._mapNodesAhead = function (stateSpeed) {
46916 return Math.round(Math.max(10, Math.min(50, 8 + 6 * stateSpeed)));
46918 PlayService.prototype._setPlaying = function (playing) {
46919 this._playing = playing;
46920 this._playingSubject$.next(playing);
46922 PlayService.prototype._setSpeed = function (speed) {
46923 this._speed = speed;
46924 var stateSpeed = this._mapSpeed(this._speed);
46925 this._nodesAhead = this._mapNodesAhead(stateSpeed);
46928 return PlayService;
46930 exports.PlayService = PlayService;
46931 exports.default = PlayService;
46933 },{"../Edge":291,"../Graph":294,"rxjs/Observable":29,"rxjs/Subject":34}],446:[function(require,module,exports){
46935 /// <reference path="../../typings/index.d.ts" />
46936 Object.defineProperty(exports, "__esModule", { value: true });
46937 var THREE = require("three");
46938 var Geo_1 = require("../Geo");
46939 var Projection = /** @class */ (function () {
46940 function Projection(geoCoords, viewportCoords) {
46941 this._geoCoords = !!geoCoords ? geoCoords : new Geo_1.GeoCoords();
46942 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
46944 Projection.prototype.basicToCanvas = function (basicPoint, container, render, transform) {
46945 return this._viewportCoords
46946 .basicToCanvas(basicPoint[0], basicPoint[1], container, transform, render.perspective);
46948 Projection.prototype.canvasToBasic = function (canvasPoint, container, render, transform) {
46949 var basicPoint = this._viewportCoords
46950 .canvasToBasic(canvasPoint[0], canvasPoint[1], container, transform, render.perspective);
46951 if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
46956 Projection.prototype.eventToUnprojection = function (event, container, render, reference, transform) {
46957 var pixelPoint = this._viewportCoords.canvasPosition(event, container);
46958 return this.canvasToUnprojection(pixelPoint, container, render, reference, transform);
46960 Projection.prototype.canvasToUnprojection = function (canvasPoint, container, render, reference, transform) {
46961 var canvasX = canvasPoint[0];
46962 var canvasY = canvasPoint[1];
46963 var _a = this._viewportCoords.canvasToViewport(canvasX, canvasY, container), viewportX = _a[0], viewportY = _a[1];
46964 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
46965 .unproject(render.perspective);
46966 var basicPoint = transform.projectBasic(point3d.toArray());
46967 if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
46970 var direction3d = point3d.clone().sub(render.camera.position).normalize();
46971 var dist = -2 / direction3d.z;
46973 if (dist > 0 && dist < 100 && !!basicPoint) {
46974 var point = direction3d.clone().multiplyScalar(dist).add(render.camera.position);
46975 var latLonArray = this._geoCoords
46976 .enuToGeodetic(point.x, point.y, point.z, reference.lat, reference.lon, reference.alt)
46978 latLon = { lat: latLonArray[0], lon: latLonArray[1] };
46980 var unprojection = {
46981 basicPoint: basicPoint,
46983 pixelPoint: [canvasX, canvasY],
46985 return unprojection;
46989 exports.Projection = Projection;
46990 exports.default = Projection;
46992 },{"../Geo":293,"three":240}],447:[function(require,module,exports){
46994 /// <reference path="../../typings/index.d.ts" />
46995 Object.defineProperty(exports, "__esModule", { value: true });
46996 var THREE = require("three");
46997 var vd = require("virtual-dom");
46998 var Subject_1 = require("rxjs/Subject");
46999 var Viewer_1 = require("../Viewer");
47000 var SpriteAtlas = /** @class */ (function () {
47001 function SpriteAtlas() {
47003 Object.defineProperty(SpriteAtlas.prototype, "json", {
47004 set: function (value) {
47005 this._json = value;
47010 Object.defineProperty(SpriteAtlas.prototype, "image", {
47011 set: function (value) {
47012 this._image = value;
47013 this._texture = new THREE.Texture(this._image);
47014 this._texture.minFilter = THREE.NearestFilter;
47019 Object.defineProperty(SpriteAtlas.prototype, "loaded", {
47021 return !!(this._image && this._json);
47026 SpriteAtlas.prototype.getGLSprite = function (name) {
47027 if (!this.loaded) {
47028 throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
47030 var definition = this._json[name];
47032 console.warn("Sprite with key" + name + "does not exist in sprite definition.");
47033 return new THREE.Object3D();
47035 var texture = this._texture.clone();
47036 texture.needsUpdate = true;
47037 var width = this._image.width;
47038 var height = this._image.height;
47039 texture.offset.x = definition.x / width;
47040 texture.offset.y = (height - definition.y - definition.height) / height;
47041 texture.repeat.x = definition.width / width;
47042 texture.repeat.y = definition.height / height;
47043 var material = new THREE.SpriteMaterial({ map: texture });
47044 return new THREE.Sprite(material);
47046 SpriteAtlas.prototype.getDOMSprite = function (name, float) {
47047 if (!this.loaded) {
47048 throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
47050 if (float == null) {
47051 float = Viewer_1.Alignment.Center;
47053 var definition = this._json[name];
47055 console.warn("Sprite with key" + name + "does not exist in sprite definition.");
47056 return vd.h("div", {}, []);
47058 var clipTop = definition.y;
47059 var clipRigth = definition.x + definition.width;
47060 var clipBottom = definition.y + definition.height;
47061 var clipLeft = definition.x;
47062 var left = -definition.x;
47063 var top = -definition.y;
47064 var height = this._image.height;
47065 var width = this._image.width;
47067 case Viewer_1.Alignment.Bottom:
47068 case Viewer_1.Alignment.Center:
47069 case Viewer_1.Alignment.Top:
47070 left -= definition.width / 2;
47072 case Viewer_1.Alignment.BottomLeft:
47073 case Viewer_1.Alignment.Left:
47074 case Viewer_1.Alignment.TopLeft:
47075 left -= definition.width;
47077 case Viewer_1.Alignment.BottomRight:
47078 case Viewer_1.Alignment.Right:
47079 case Viewer_1.Alignment.TopRight:
47084 case Viewer_1.Alignment.Center:
47085 case Viewer_1.Alignment.Left:
47086 case Viewer_1.Alignment.Right:
47087 top -= definition.height / 2;
47089 case Viewer_1.Alignment.Top:
47090 case Viewer_1.Alignment.TopLeft:
47091 case Viewer_1.Alignment.TopRight:
47092 top -= definition.height;
47094 case Viewer_1.Alignment.Bottom:
47095 case Viewer_1.Alignment.BottomLeft:
47096 case Viewer_1.Alignment.BottomRight:
47100 var pixelRatioInverse = 1 / definition.pixelRatio;
47101 clipTop *= pixelRatioInverse;
47102 clipRigth *= pixelRatioInverse;
47103 clipBottom *= pixelRatioInverse;
47104 clipLeft *= pixelRatioInverse;
47105 left *= pixelRatioInverse;
47106 top *= pixelRatioInverse;
47107 height *= pixelRatioInverse;
47108 width *= pixelRatioInverse;
47110 src: this._image.src,
47112 clip: "rect(" + clipTop + "px, " + clipRigth + "px, " + clipBottom + "px, " + clipLeft + "px)",
47113 height: height + "px",
47115 position: "absolute",
47117 width: width + "px",
47120 return vd.h("img", properties, []);
47122 return SpriteAtlas;
47124 var SpriteService = /** @class */ (function () {
47125 function SpriteService(sprite) {
47127 this._retina = window.devicePixelRatio > 1;
47128 this._spriteAtlasOperation$ = new Subject_1.Subject();
47129 this._spriteAtlas$ = this._spriteAtlasOperation$
47130 .startWith(function (atlas) {
47133 .scan(function (atlas, operation) {
47134 return operation(atlas);
47135 }, new SpriteAtlas())
47138 this._spriteAtlas$.subscribe(function () { });
47139 if (sprite == null) {
47142 var format = this._retina ? "@2x" : "";
47143 var imageXmlHTTP = new XMLHttpRequest();
47144 imageXmlHTTP.open("GET", sprite + format + ".png", true);
47145 imageXmlHTTP.responseType = "arraybuffer";
47146 imageXmlHTTP.onload = function () {
47147 var image = new Image();
47148 image.onload = function () {
47149 _this._spriteAtlasOperation$.next(function (atlas) {
47150 atlas.image = image;
47154 var blob = new Blob([imageXmlHTTP.response]);
47155 image.src = window.URL.createObjectURL(blob);
47157 imageXmlHTTP.onerror = function (error) {
47158 console.error(new Error("Failed to fetch sprite sheet (" + sprite + format + ".png)"));
47160 imageXmlHTTP.send();
47161 var jsonXmlHTTP = new XMLHttpRequest();
47162 jsonXmlHTTP.open("GET", sprite + format + ".json", true);
47163 jsonXmlHTTP.responseType = "text";
47164 jsonXmlHTTP.onload = function () {
47165 var json = JSON.parse(jsonXmlHTTP.response);
47166 _this._spriteAtlasOperation$.next(function (atlas) {
47171 jsonXmlHTTP.onerror = function (error) {
47172 console.error(new Error("Failed to fetch sheet (" + sprite + format + ".json)"));
47174 jsonXmlHTTP.send();
47176 Object.defineProperty(SpriteService.prototype, "spriteAtlas$", {
47178 return this._spriteAtlas$;
47183 return SpriteService;
47185 exports.SpriteService = SpriteService;
47186 exports.default = SpriteService;
47188 },{"../Viewer":301,"rxjs/Subject":34,"three":240,"virtual-dom":246}],448:[function(require,module,exports){
47190 Object.defineProperty(exports, "__esModule", { value: true });
47191 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
47192 var Observable_1 = require("rxjs/Observable");
47193 var Subject_1 = require("rxjs/Subject");
47194 var TouchService = /** @class */ (function () {
47195 function TouchService(canvasContainer, domContainer) {
47197 this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
47198 this._active$ = this._activeSubject$
47199 .distinctUntilChanged()
47202 Observable_1.Observable.fromEvent(domContainer, "touchmove")
47203 .subscribe(function (event) {
47204 event.preventDefault();
47206 this._touchStart$ = Observable_1.Observable.fromEvent(canvasContainer, "touchstart");
47207 this._touchMove$ = Observable_1.Observable.fromEvent(canvasContainer, "touchmove");
47208 this._touchEnd$ = Observable_1.Observable.fromEvent(canvasContainer, "touchend");
47209 this._touchCancel$ = Observable_1.Observable.fromEvent(canvasContainer, "touchcancel");
47210 var tapStart$ = this._touchStart$
47211 .filter(function (te) {
47212 return te.touches.length === 1 && te.targetTouches.length === 1;
47215 this._doubleTap$ = tapStart$
47216 .bufferWhen(function () {
47219 .switchMap(function (event) {
47220 return Observable_1.Observable
47226 .filter(function (events) {
47227 return events.length === 2;
47229 .map(function (events) {
47230 return events[events.length - 1];
47234 .subscribe(function (event) {
47235 event.preventDefault();
47237 this._singleTouchMove$ = this._touchMove$
47238 .filter(function (te) {
47239 return te.touches.length === 1 && te.targetTouches.length === 1;
47242 var singleTouchStart$ = Observable_1.Observable
47243 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
47244 .filter(function (te) {
47245 return te.touches.length === 1 && te.targetTouches.length === 1;
47247 var multipleTouchStart$ = Observable_1.Observable
47248 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
47249 .filter(function (te) {
47250 return te.touches.length >= 1;
47252 var touchStop$ = Observable_1.Observable
47253 .merge(this._touchEnd$, this._touchCancel$)
47254 .filter(function (te) {
47255 return te.touches.length === 0;
47257 this._singleTouchDragStart$ = singleTouchStart$
47258 .mergeMap(function (e) {
47259 return _this._singleTouchMove$
47260 .takeUntil(Observable_1.Observable.merge(touchStop$, multipleTouchStart$))
47263 this._singleTouchDragEnd$ = singleTouchStart$
47264 .mergeMap(function (e) {
47265 return Observable_1.Observable
47266 .merge(touchStop$, multipleTouchStart$)
47269 this._singleTouchDrag$ = singleTouchStart$
47270 .switchMap(function (te) {
47271 return _this._singleTouchMove$
47273 .takeUntil(Observable_1.Observable
47274 .merge(multipleTouchStart$, touchStop$));
47276 var touchesChanged$ = Observable_1.Observable
47277 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$);
47278 this._pinchStart$ = touchesChanged$
47279 .filter(function (te) {
47280 return te.touches.length === 2 && te.targetTouches.length === 2;
47282 this._pinchEnd$ = touchesChanged$
47283 .filter(function (te) {
47284 return te.touches.length !== 2 || te.targetTouches.length !== 2;
47286 this._pinchOperation$ = new Subject_1.Subject();
47287 this._pinch$ = this._pinchOperation$
47288 .scan(function (pinch, operation) {
47289 return operation(pinch);
47299 originalEvent: null,
47308 .filter(function (te) {
47309 return te.touches.length === 2 && te.targetTouches.length === 2;
47311 .map(function (te) {
47312 return function (previous) {
47313 var touch1 = te.touches[0];
47314 var touch2 = te.touches[1];
47315 var minX = Math.min(touch1.clientX, touch2.clientX);
47316 var maxX = Math.max(touch1.clientX, touch2.clientX);
47317 var minY = Math.min(touch1.clientY, touch2.clientY);
47318 var maxY = Math.max(touch1.clientY, touch2.clientY);
47319 var centerClientX = minX + (maxX - minX) / 2;
47320 var centerClientY = minY + (maxY - minY) / 2;
47321 var centerPageX = centerClientX + touch1.pageX - touch1.clientX;
47322 var centerPageY = centerClientY + touch1.pageY - touch1.clientY;
47323 var centerScreenX = centerClientX + touch1.screenX - touch1.clientX;
47324 var centerScreenY = centerClientY + touch1.screenY - touch1.clientY;
47325 var distanceX = Math.abs(touch1.clientX - touch2.clientX);
47326 var distanceY = Math.abs(touch1.clientY - touch2.clientY);
47327 var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
47328 var distanceChange = distance - previous.distance;
47329 var changeX = distanceX - previous.distanceX;
47330 var changeY = distanceY - previous.distanceY;
47334 clientX: centerClientX,
47335 clientY: centerClientY,
47336 distance: distance,
47337 distanceChange: distanceChange,
47338 distanceX: distanceX,
47339 distanceY: distanceY,
47341 pageX: centerPageX,
47342 pageY: centerPageY,
47343 screenX: centerScreenX,
47344 screenY: centerScreenY,
47351 .subscribe(this._pinchOperation$);
47352 this._pinchChange$ = this._pinchStart$
47353 .switchMap(function (te) {
47354 return _this._pinch$
47356 .takeUntil(_this._pinchEnd$);
47359 Object.defineProperty(TouchService.prototype, "active$", {
47361 return this._active$;
47366 Object.defineProperty(TouchService.prototype, "activate$", {
47368 return this._activeSubject$;
47373 Object.defineProperty(TouchService.prototype, "doubleTap$", {
47375 return this._doubleTap$;
47380 Object.defineProperty(TouchService.prototype, "touchStart$", {
47382 return this._touchStart$;
47387 Object.defineProperty(TouchService.prototype, "touchMove$", {
47389 return this._touchMove$;
47394 Object.defineProperty(TouchService.prototype, "touchEnd$", {
47396 return this._touchEnd$;
47401 Object.defineProperty(TouchService.prototype, "touchCancel$", {
47403 return this._touchCancel$;
47408 Object.defineProperty(TouchService.prototype, "singleTouchDragStart$", {
47410 return this._singleTouchDragStart$;
47415 Object.defineProperty(TouchService.prototype, "singleTouchDrag$", {
47417 return this._singleTouchDrag$;
47422 Object.defineProperty(TouchService.prototype, "singleTouchDragEnd$", {
47424 return this._singleTouchDragEnd$;
47429 Object.defineProperty(TouchService.prototype, "pinch$", {
47431 return this._pinchChange$;
47436 Object.defineProperty(TouchService.prototype, "pinchStart$", {
47438 return this._pinchStart$;
47443 Object.defineProperty(TouchService.prototype, "pinchEnd$", {
47445 return this._pinchEnd$;
47450 return TouchService;
47452 exports.TouchService = TouchService;
47454 },{"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/Subject":34}],449:[function(require,module,exports){
47456 /// <reference path="../../typings/index.d.ts" />
47457 var __extends = (this && this.__extends) || (function () {
47458 var extendStatics = Object.setPrototypeOf ||
47459 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
47460 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
47461 return function (d, b) {
47462 extendStatics(d, b);
47463 function __() { this.constructor = d; }
47464 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
47467 Object.defineProperty(exports, "__esModule", { value: true });
47468 var when = require("when");
47469 require("rxjs/add/observable/combineLatest");
47470 require("rxjs/add/observable/concat");
47471 require("rxjs/add/observable/defer");
47472 require("rxjs/add/observable/empty");
47473 require("rxjs/add/observable/merge");
47474 require("rxjs/add/observable/from");
47475 require("rxjs/add/observable/fromEvent");
47476 require("rxjs/add/observable/fromPromise");
47477 require("rxjs/add/observable/of");
47478 require("rxjs/add/observable/throw");
47479 require("rxjs/add/observable/timer");
47480 require("rxjs/add/observable/zip");
47481 require("rxjs/add/operator/auditTime");
47482 require("rxjs/add/operator/buffer");
47483 require("rxjs/add/operator/bufferCount");
47484 require("rxjs/add/operator/bufferWhen");
47485 require("rxjs/add/operator/catch");
47486 require("rxjs/add/operator/combineLatest");
47487 require("rxjs/add/operator/concat");
47488 require("rxjs/add/operator/count");
47489 require("rxjs/add/operator/debounceTime");
47490 require("rxjs/add/operator/delay");
47491 require("rxjs/add/operator/distinct");
47492 require("rxjs/add/operator/distinctUntilChanged");
47493 require("rxjs/add/operator/do");
47494 require("rxjs/add/operator/expand");
47495 require("rxjs/add/operator/filter");
47496 require("rxjs/add/operator/finally");
47497 require("rxjs/add/operator/first");
47498 require("rxjs/add/operator/last");
47499 require("rxjs/add/operator/map");
47500 require("rxjs/add/operator/merge");
47501 require("rxjs/add/operator/mergeMap");
47502 require("rxjs/add/operator/mergeAll");
47503 require("rxjs/add/operator/pairwise");
47504 require("rxjs/add/operator/pluck");
47505 require("rxjs/add/operator/publish");
47506 require("rxjs/add/operator/publishReplay");
47507 require("rxjs/add/operator/reduce");
47508 require("rxjs/add/operator/retry");
47509 require("rxjs/add/operator/sample");
47510 require("rxjs/add/operator/scan");
47511 require("rxjs/add/operator/share");
47512 require("rxjs/add/operator/skip");
47513 require("rxjs/add/operator/skipUntil");
47514 require("rxjs/add/operator/skipWhile");
47515 require("rxjs/add/operator/startWith");
47516 require("rxjs/add/operator/switchMap");
47517 require("rxjs/add/operator/take");
47518 require("rxjs/add/operator/takeUntil");
47519 require("rxjs/add/operator/takeWhile");
47520 require("rxjs/add/operator/timeout");
47521 require("rxjs/add/operator/withLatestFrom");
47522 require("rxjs/add/operator/zip");
47523 var Observable_1 = require("rxjs/Observable");
47524 var Viewer_1 = require("../Viewer");
47525 var Utils_1 = require("../Utils");
47529 * @classdesc The Viewer object represents the navigable image viewer.
47530 * Create a Viewer by specifying a container, client ID, image key and
47531 * other options. The viewer exposes methods and events for programmatic
47534 * The viewer works with a few different coordinate systems.
47536 * Container pixel coordinates
47538 * Pixel coordinates are coordinates on the viewer container. The origin is
47539 * in the top left corner of the container. The axes are
47540 * directed according to the following for a viewer container with a width
47541 * of 640 pixels and height of 480 pixels.
47545 * +------------------------>
47550 * (0, 480) (640, 480)
47553 * Basic image coordinates
47555 * Basic image coordinates represents points in the original image adjusted for
47556 * orientation. They range from 0 to 1 on both axes. The origin is in the top left
47557 * corner of the image and the axes are directed
47558 * according to the following for all image types.
47562 * +------------------------>
47570 * For every camera viewing direction it is possible to convert between these
47571 * two coordinate systems for the current node. The image can be panned and
47572 * zoomed independently of the size of the viewer container resulting in
47573 * different conversion results for different viewing directions.
47575 var Viewer = /** @class */ (function (_super) {
47576 __extends(Viewer, _super);
47578 * Create a new viewer instance.
47580 * @description It is possible to initialize the viewer with or
47583 * When you want to show a specific image in the viewer from
47584 * the start you should initialize it with a key.
47586 * When you do not know the first image key at implementation
47587 * time, e.g. in a map-viewer application you should initialize
47588 * the viewer without a key and call `moveToKey` instead.
47590 * When initializing with a key the viewer is bound to that key
47591 * until the node for that key has been successfully loaded.
47592 * Also, a cover with the image of the key will be shown.
47593 * If the data for that key can not be loaded because the key is
47594 * faulty or other errors occur it is not possible to navigate
47595 * to another key because the viewer is not navigable. The viewer
47596 * becomes navigable when the data for the key has been loaded and
47597 * the image is shown in the viewer. This way of initializing
47598 * the viewer is mostly for embedding in blog posts and similar
47599 * where one wants to show a specific image initially.
47601 * If the viewer is initialized without a key (with null or
47602 * undefined) it is not bound to any particular key and it is
47603 * possible to move to any key with `viewer.moveToKey("<my-image-key>")`.
47604 * If the first move to a key fails it is possible to move to another
47605 * key. The viewer will show a black background until a move
47606 * succeeds. This way of intitializing is suited for a map-viewer
47607 * application when the initial key is not known at implementation
47610 * @param {string} id - Required `id` of a DOM element which will
47611 * be transformed into the viewer.
47612 * @param {string} clientId - Required `Mapillary API ClientID`. Can
47613 * be obtained from https://www.mapillary.com/app/settings/developers.
47614 * @param {string} key - Optional `image-key` to start from. The key
47615 * can be any Mapillary image. If a key is provided the viewer is
47616 * bound to that key until it has been fully loaded. If null is provided
47617 * no image is loaded at viewer initialization and the viewer is not
47618 * bound to any particular key. Any image can then be navigated to
47619 * with e.g. `viewer.moveToKey("<my-image-key>")`.
47620 * @param {IViewerOptions} options - Optional configuration object
47621 * specifing Viewer's and the components' initial setup.
47622 * @param {string} token - Optional bearer token for API requests of
47623 * protected resources.
47627 * var viewer = new Mapillary.Viewer("<element-id>", "<client-id>", "<image-key>");
47630 function Viewer(id, clientId, key, options, token) {
47631 var _this = _super.call(this) || this;
47632 options = options != null ? options : {};
47633 Utils_1.Settings.setOptions(options);
47634 Utils_1.Urls.setOptions(options.url);
47635 _this._navigator = new Viewer_1.Navigator(clientId, options, token);
47636 _this._container = new Viewer_1.Container(id, _this._navigator.stateService, options);
47637 _this._observer = new Viewer_1.Observer(_this, _this._navigator, _this._container);
47638 _this._componentController = new Viewer_1.ComponentController(_this._container, _this._navigator, _this._observer, key, options.component);
47641 Object.defineProperty(Viewer.prototype, "isNavigable", {
47643 * Return a boolean indicating if the viewer is in a navigable state.
47645 * @description The navigable state indicates if the viewer supports
47646 * moving, i.e. calling the {@link moveToKey}, {@link moveDir`}
47647 * and {@link moveCloseTo} methods or changing the authentication state,
47648 * i.e. calling {@link setAuthToken}. The viewer will not be in a navigable
47649 * state if the cover is activated and the viewer has been supplied a key.
47650 * When the cover is deactivated or the viewer is activated without being
47651 * supplied a key it will be navigable.
47653 * @returns {boolean} Boolean indicating whether the viewer is navigable.
47656 return this._componentController.navigable;
47662 * Activate a component.
47664 * @param {string} name - Name of the component which will become active.
47668 * viewer.activateComponent("marker");
47671 Viewer.prototype.activateComponent = function (name) {
47672 this._componentController.activate(name);
47675 * Activate the cover (deactivates all other components).
47677 Viewer.prototype.activateCover = function () {
47678 this._componentController.activateCover();
47681 * Deactivate a component.
47683 * @param {string} name - Name of component which become inactive.
47687 * viewer.deactivateComponent("mouse");
47690 Viewer.prototype.deactivateComponent = function (name) {
47691 this._componentController.deactivate(name);
47694 * Deactivate the cover (activates all components marked as active).
47696 Viewer.prototype.deactivateCover = function () {
47697 this._componentController.deactivateCover();
47700 * Get the bearing of the current viewer camera.
47702 * @description The bearing depends on how the camera
47703 * is currently rotated and does not correspond
47704 * to the compass angle of the current node if the view
47707 * Bearing is measured in degrees clockwise with respect to
47710 * @returns {Promise<number>} Promise to the bearing
47711 * of the current viewer camera.
47715 * viewer.getBearing().then((b) => { console.log(b); });
47718 Viewer.prototype.getBearing = function () {
47720 return when.promise(function (resolve, reject) {
47721 _this._container.renderService.bearing$
47723 .subscribe(function (bearing) {
47725 }, function (error) {
47731 * Get the basic coordinates of the current image that is
47732 * at the center of the viewport.
47734 * @description Basic coordinates are 2D coordinates on the [0, 1] interval
47735 * and have the origin point, (0, 0), at the top left corner and the
47736 * maximum value, (1, 1), at the bottom right corner of the original
47739 * @returns {Promise<number[]>} Promise to the basic coordinates
47740 * of the current image at the center for the viewport.
47744 * viewer.getCenter().then((c) => { console.log(c); });
47747 Viewer.prototype.getCenter = function () {
47749 return when.promise(function (resolve, reject) {
47750 _this._navigator.stateService.getCenter()
47751 .subscribe(function (center) {
47753 }, function (error) {
47761 * @param {string} name - Name of component.
47762 * @returns {Component} The requested component.
47766 * var mouseComponent = viewer.getComponent("mouse");
47769 Viewer.prototype.getComponent = function (name) {
47770 return this._componentController.get(name);
47773 * Returns the viewer's containing HTML element.
47775 * @returns {HTMLElement} The viewer's container.
47777 Viewer.prototype.getContainer = function () {
47778 return this._container.element;
47781 * Get the image's current zoom level.
47783 * @returns {Promise<number>} Promise to the viewers's current
47788 * viewer.getZoom().then((z) => { console.log(z); });
47791 Viewer.prototype.getZoom = function () {
47793 return when.promise(function (resolve, reject) {
47794 _this._navigator.stateService.getZoom()
47795 .subscribe(function (zoom) {
47797 }, function (error) {
47803 * Move close to given latitude and longitude.
47805 * @description Because the method propagates IO errors, these potential errors
47806 * need to be handled by the method caller (see example).
47808 * @param {Number} lat - Latitude, in degrees.
47809 * @param {Number} lon - Longitude, in degrees.
47810 * @returns {Promise<Node>} Promise to the node that was navigated to.
47811 * @throws {Error} If no nodes exist close to provided latitude
47813 * @throws {Error} Propagates any IO errors to the caller.
47814 * @throws {Error} When viewer is not navigable.
47815 * @throws {AbortMapillaryError} When a subsequent move request is made
47816 * before the move close to call has completed.
47820 * viewer.moveCloseTo(0, 0).then(
47821 * (n) => { console.log(n); },
47822 * (e) => { console.error(e); });
47825 Viewer.prototype.moveCloseTo = function (lat, lon) {
47826 var moveCloseTo$ = this.isNavigable ?
47827 this._navigator.moveCloseTo$(lat, lon) :
47828 Observable_1.Observable.throw(new Error("Calling moveCloseTo is not supported when viewer is not navigable."));
47829 return when.promise(function (resolve, reject) {
47830 moveCloseTo$.subscribe(function (node) {
47832 }, function (error) {
47838 * Navigate in a given direction.
47840 * @description This method has to be called through EdgeDirection enumeration as in the example.
47842 * @param {EdgeDirection} dir - Direction in which which to move.
47843 * @returns {Promise<Node>} Promise to the node that was navigated to.
47844 * @throws {Error} If the current node does not have the edge direction
47845 * or the edges has not yet been cached.
47846 * @throws {Error} Propagates any IO errors to the caller.
47847 * @throws {Error} When viewer is not navigable.
47848 * @throws {AbortMapillaryError} When a subsequent move request is made
47849 * before the move dir call has completed.
47853 * viewer.moveDir(Mapillary.EdgeDirection.Next).then(
47854 * (n) => { console.log(n); },
47855 * (e) => { console.error(e); });
47858 Viewer.prototype.moveDir = function (dir) {
47859 var moveDir$ = this.isNavigable ?
47860 this._navigator.moveDir$(dir) :
47861 Observable_1.Observable.throw(new Error("Calling moveDir is not supported when viewer is not navigable."));
47862 return when.promise(function (resolve, reject) {
47863 moveDir$.subscribe(function (node) {
47865 }, function (error) {
47871 * Navigate to a given image key.
47873 * @param {string} key - A valid Mapillary image key.
47874 * @returns {Promise<Node>} Promise to the node that was navigated to.
47875 * @throws {Error} Propagates any IO errors to the caller.
47876 * @throws {Error} When viewer is not navigable.
47877 * @throws {AbortMapillaryError} When a subsequent move request is made
47878 * before the move to key call has completed.
47882 * viewer.moveToKey("<my key>").then(
47883 * (n) => { console.log(n); },
47884 * (e) => { console.error(e); });
47887 Viewer.prototype.moveToKey = function (key) {
47888 var moveToKey$ = this.isNavigable ?
47889 this._navigator.moveToKey$(key) :
47890 Observable_1.Observable.throw(new Error("Calling moveToKey is not supported when viewer is not navigable."));
47891 return when.promise(function (resolve, reject) {
47892 moveToKey$.subscribe(function (node) {
47894 }, function (error) {
47900 * Project basic image coordinates for the current node to canvas pixel
47903 * @description The basic image coordinates may not always correspond to a
47904 * pixel point that lies in the visible area of the viewer container.
47906 * @param {Array<number>} basicPoint - Basic images coordinates to project.
47907 * @returns {Promise<Array<number>>} Promise to the pixel coordinates corresponding
47908 * to the basic image point.
47912 * viewer.projectFromBasic([0.3, 0.7])
47913 * .then((pixelPoint) => { console.log(pixelPoint); });
47916 Viewer.prototype.projectFromBasic = function (basicPoint) {
47918 return when.promise(function (resolve, reject) {
47919 _this._observer.projectBasic$(basicPoint)
47920 .subscribe(function (pixelPoint) {
47921 resolve(pixelPoint);
47922 }, function (error) {
47928 * Detect the viewer's new width and height and resize it.
47930 * @description The components will also detect the viewer's
47931 * new size and resize their rendered elements if needed.
47938 Viewer.prototype.resize = function () {
47939 this._container.renderService.resize$.next(null);
47940 this._componentController.resize();
47943 * Set a bearer token for authenticated API requests of
47944 * protected resources.
47946 * @description When the supplied token is null or undefined,
47947 * any previously set bearer token will be cleared and the
47948 * viewer will make unauthenticated requests.
47950 * Calling setAuthToken aborts all outstanding move requests.
47951 * The promises of those move requests will be rejected with a
47952 * {@link AbortMapillaryError} the rejections need to be caught.
47954 * Calling setAuthToken also resets the complete viewer cache
47955 * so it should not be called repeatedly.
47957 * @param {string} [token] token - Bearer token.
47958 * @returns {Promise<void>} Promise that resolves after token
47961 * @throws {Error} When viewer is not navigable.
47965 * viewer.setAuthToken("<my token>")
47966 * .then(() => { console.log("token set"); });
47969 Viewer.prototype.setAuthToken = function (token) {
47970 var setToken$ = this.isNavigable ?
47971 this._navigator.setToken$(token) :
47972 Observable_1.Observable.throw(new Error("Calling setAuthToken is not supported when viewer is not navigable."));
47973 return when.promise(function (resolve, reject) {
47975 .subscribe(function () {
47976 resolve(undefined);
47977 }, function (error) {
47983 * Set the basic coordinates of the current image to be in the
47984 * center of the viewport.
47986 * @description Basic coordinates are 2D coordinates on the [0, 1] interval
47987 * and has the origin point, (0, 0), at the top left corner and the
47988 * maximum value, (1, 1), at the bottom right corner of the original
47991 * @param {number[]} The basic coordinates of the current
47992 * image to be at the center for the viewport.
47996 * viewer.setCenter([0.5, 0.5]);
47999 Viewer.prototype.setCenter = function (center) {
48000 this._navigator.stateService.setCenter(center);
48003 * Set the filter selecting nodes to use when calculating
48004 * the spatial edges.
48006 * @description The following filter types are supported:
48010 * `["==", key, value]` equality: `node[key] = value`
48012 * `["!=", key, value]` inequality: `node[key] ≠value`
48014 * `["<", key, value]` less than: `node[key] < value`
48016 * `["<=", key, value]` less than or equal: `node[key] ≤ value`
48018 * `[">", key, value]` greater than: `node[key] > value`
48020 * `[">=", key, value]` greater than or equal: `node[key] ≥ value`
48024 * `["in", key, v0, ..., vn]` set inclusion: `node[key] ∈ {v0, ..., vn}`
48026 * `["!in", key, v0, ..., vn]` set exclusion: `node[key] ∉ {v0, ..., vn}`
48030 * `["all", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`
48032 * A key must be a string that identifies a property name of a
48033 * simple {@link Node} property. A value must be a string, number, or
48034 * boolean. Strictly-typed comparisons are used. The values
48035 * `f0, ..., fn` of the combining filter must be filter expressions.
48037 * Clear the filter by setting it to null or empty array.
48039 * @param {FilterExpression} filter - The filter expression.
48040 * @returns {Promise<void>} Promise that resolves after filter is applied.
48044 * viewer.setFilter(["==", "sequenceKey", "<my sequence key>"]);
48047 Viewer.prototype.setFilter = function (filter) {
48049 return when.promise(function (resolve, reject) {
48050 _this._navigator.setFilter$(filter)
48051 .subscribe(function () {
48052 resolve(undefined);
48053 }, function (error) {
48059 * Set the viewer's render mode.
48061 * @param {RenderMode} renderMode - Render mode.
48065 * viewer.setRenderMode(Mapillary.RenderMode.Letterbox);
48068 Viewer.prototype.setRenderMode = function (renderMode) {
48069 this._container.renderService.renderMode$.next(renderMode);
48072 * Set the viewer's transition mode.
48074 * @param {TransitionMode} transitionMode - Transition mode.
48078 * viewer.setTransitionMode(Mapillary.TransitionMode.Instantaneous);
48081 Viewer.prototype.setTransitionMode = function (transitionMode) {
48082 this._navigator.stateService.setTransitionMode(transitionMode);
48085 * Set the image's current zoom level.
48087 * @description Possible zoom level values are on the [0, 3] interval.
48088 * Zero means zooming out to fit the image to the view whereas three
48089 * shows the highest level of detail.
48091 * @param {number} The image's current zoom level.
48095 * viewer.setZoom(2);
48098 Viewer.prototype.setZoom = function (zoom) {
48099 this._navigator.stateService.setZoom(zoom);
48102 * Unproject canvas pixel coordinates to an ILatLon representing geographical
48105 * @description The pixel point may not always correspond to geographical
48106 * coordinates. In the case of no correspondence the returned value will
48109 * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
48110 * @returns {Promise<ILatLon>} Promise to the latLon corresponding to the pixel point.
48114 * viewer.unproject([100, 100])
48115 * .then((latLon) => { console.log(latLon); });
48118 Viewer.prototype.unproject = function (pixelPoint) {
48120 return when.promise(function (resolve, reject) {
48121 _this._observer.unproject$(pixelPoint)
48122 .subscribe(function (latLon) {
48124 }, function (error) {
48130 * Unproject canvas pixel coordinates to basic image coordinates for the
48133 * @description The pixel point may not always correspond to basic image
48134 * coordinates. In the case of no correspondence the returned value will
48137 * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
48138 * @returns {Promise<ILatLon>} Promise to the basic coordinates corresponding
48139 * to the pixel point.
48143 * viewer.unprojectToBasic([100, 100])
48144 * .then((basicPoint) => { console.log(basicPoint); });
48147 Viewer.prototype.unprojectToBasic = function (pixelPoint) {
48149 return when.promise(function (resolve, reject) {
48150 _this._observer.unprojectBasic$(pixelPoint)
48151 .subscribe(function (basicPoint) {
48152 resolve(basicPoint);
48153 }, function (error) {
48159 * Fired when the viewing direction of the camera changes.
48161 * @description Related to the computed compass angle
48162 * ({@link Node.computedCa}) from SfM, not the original EXIF compass
48166 * @type {number} bearing - Value indicating the current bearing
48167 * measured in degrees clockwise with respect to north.
48169 Viewer.bearingchanged = "bearingchanged";
48171 * Fired when a pointing device (usually a mouse) is pressed and released at
48172 * the same point in the viewer.
48174 * @type {IViewerMouseEvent} event - Viewer mouse event data.
48176 Viewer.click = "click";
48178 * Fired when the right button of the mouse is clicked within the viewer.
48180 * @type {IViewerMouseEvent} event - Viewer mouse event data.
48182 Viewer.contextmenu = "contextmenu";
48184 * Fired when a pointing device (usually a mouse) is clicked twice at
48185 * the same point in the viewer.
48187 * @type {IViewerMouseEvent} event - Viewer mouse event data.
48189 Viewer.dblclick = "dblclick";
48191 * Fired when the viewer is loading more data.
48193 * @type {boolean} loading - Boolean indicating whether the viewer is loading.
48195 Viewer.loadingchanged = "loadingchanged";
48197 * Fired when a pointing device (usually a mouse) is pressed within the viewer.
48199 * @type {IViewerMouseEvent} event - Viewer mouse event data.
48201 Viewer.mousedown = "mousedown";
48203 * Fired when a pointing device (usually a mouse) is moved within the viewer.
48204 * @description Will not fire when the mouse is actively used, e.g. for drag pan.
48206 * @type {IViewerMouseEvent} event - Viewer mouse event data.
48208 Viewer.mousemove = "mousemove";
48210 * Fired when a pointing device (usually a mouse) leaves the viewer's canvas.
48212 * @type {IViewerMouseEvent} event - Viewer mouse event data.
48214 Viewer.mouseout = "mouseout";
48216 * Fired when a pointing device (usually a mouse) is moved onto the viewer's canvas.
48218 * @type {IViewerMouseEvent} event - Viewer mouse event data.
48220 Viewer.mouseover = "mouseover";
48222 * Fired when a pointing device (usually a mouse) is released within the viewer.
48224 * @type {IViewerMouseEvent} event - Viewer mouse event data.
48226 Viewer.mouseup = "mouseup";
48228 * Fired when the viewer motion stops and it is in a fixed
48229 * position with a fixed point of view.
48232 Viewer.moveend = "moveend";
48234 * Fired when the motion from one view to another start,
48235 * either by changing the position (e.g. when changing node) or
48236 * when changing point of view (e.g. by interaction such as pan and zoom).
48239 Viewer.movestart = "movestart";
48241 * Fired when the navigable state of the viewer changes.
48243 * @description The navigable state indicates if the viewer supports
48244 * moving, i.e. calling the `moveToKey`, `moveDir` and `moveCloseTo`
48245 * methods. The viewer will not be in a navigable state if the cover
48246 * is activated and the viewer has been supplied a key. When the cover
48247 * is deactivated or activated without being supplied a key it will
48251 * @type {boolean} navigable - Boolean indicating whether the viewer is navigable.
48253 Viewer.navigablechanged = "navigablechanged";
48255 * Fired every time the viewer navigates to a new node.
48257 * @type {Node} node - Current node.
48259 Viewer.nodechanged = "nodechanged";
48261 * Fired every time the sequence edges of the current node changes.
48263 * @type {IEdgeStatus} status - The edge status object.
48265 Viewer.sequenceedgeschanged = "sequenceedgeschanged";
48267 * Fired every time the spatial edges of the current node changes.
48269 * @type {IEdgeStatus} status - The edge status object.
48271 Viewer.spatialedgeschanged = "spatialedgeschanged";
48273 }(Utils_1.EventEmitter));
48274 exports.Viewer = Viewer;
48276 },{"../Utils":300,"../Viewer":301,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/concat":39,"rxjs/add/observable/defer":40,"rxjs/add/observable/empty":41,"rxjs/add/observable/from":42,"rxjs/add/observable/fromEvent":43,"rxjs/add/observable/fromPromise":44,"rxjs/add/observable/merge":45,"rxjs/add/observable/of":46,"rxjs/add/observable/throw":47,"rxjs/add/observable/timer":48,"rxjs/add/observable/zip":49,"rxjs/add/operator/auditTime":50,"rxjs/add/operator/buffer":51,"rxjs/add/operator/bufferCount":52,"rxjs/add/operator/bufferWhen":53,"rxjs/add/operator/catch":54,"rxjs/add/operator/combineLatest":55,"rxjs/add/operator/concat":56,"rxjs/add/operator/count":57,"rxjs/add/operator/debounceTime":58,"rxjs/add/operator/delay":59,"rxjs/add/operator/distinct":60,"rxjs/add/operator/distinctUntilChanged":61,"rxjs/add/operator/do":62,"rxjs/add/operator/expand":63,"rxjs/add/operator/filter":64,"rxjs/add/operator/finally":65,"rxjs/add/operator/first":66,"rxjs/add/operator/last":67,"rxjs/add/operator/map":68,"rxjs/add/operator/merge":69,"rxjs/add/operator/mergeAll":70,"rxjs/add/operator/mergeMap":71,"rxjs/add/operator/pairwise":72,"rxjs/add/operator/pluck":73,"rxjs/add/operator/publish":74,"rxjs/add/operator/publishReplay":75,"rxjs/add/operator/reduce":76,"rxjs/add/operator/retry":77,"rxjs/add/operator/sample":78,"rxjs/add/operator/scan":79,"rxjs/add/operator/share":80,"rxjs/add/operator/skip":81,"rxjs/add/operator/skipUntil":82,"rxjs/add/operator/skipWhile":83,"rxjs/add/operator/startWith":84,"rxjs/add/operator/switchMap":85,"rxjs/add/operator/take":86,"rxjs/add/operator/takeUntil":87,"rxjs/add/operator/takeWhile":88,"rxjs/add/operator/timeout":89,"rxjs/add/operator/withLatestFrom":90,"rxjs/add/operator/zip":91,"when":287}]},{},[295])(295)
48278 //# sourceMappingURL=mapillary.js.map