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":177}],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 <feross@feross.org> <http://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 (value instanceof ArrayBuffer) {
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) || string instanceof ArrayBuffer) {
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 // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
2378 function isArrayBufferView (obj) {
2379 return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
2382 function numberIsNaN (obj) {
2383 return obj !== obj // eslint-disable-line no-self-compare
2386 },{"base64-js":3,"ieee754":17}],8:[function(require,module,exports){
2389 module.exports = earcut;
2391 function earcut(data, holeIndices, dim) {
2395 var hasHoles = holeIndices && holeIndices.length,
2396 outerLen = hasHoles ? holeIndices[0] * dim : data.length,
2397 outerNode = linkedList(data, 0, outerLen, dim, true),
2400 if (!outerNode) return triangles;
2402 var minX, minY, maxX, maxY, x, y, size;
2404 if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
2406 // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
2407 if (data.length > 80 * dim) {
2408 minX = maxX = data[0];
2409 minY = maxY = data[1];
2411 for (var i = dim; i < outerLen; i += dim) {
2414 if (x < minX) minX = x;
2415 if (y < minY) minY = y;
2416 if (x > maxX) maxX = x;
2417 if (y > maxY) maxY = y;
2420 // minX, minY and size are later used to transform coords into integers for z-order calculation
2421 size = Math.max(maxX - minX, maxY - minY);
2424 earcutLinked(outerNode, triangles, dim, minX, minY, size);
2429 // create a circular doubly linked list from polygon points in the specified winding order
2430 function linkedList(data, start, end, dim, clockwise) {
2433 if (clockwise === (signedArea(data, start, end, dim) > 0)) {
2434 for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
2436 for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
2439 if (last && equals(last, last.next)) {
2447 // eliminate colinear or duplicate points
2448 function filterPoints(start, end) {
2449 if (!start) return start;
2450 if (!end) end = start;
2457 if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
2460 if (p === p.next) return null;
2466 } while (again || p !== end);
2471 // main ear slicing loop which triangulates a polygon (given as a linked list)
2472 function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
2475 // interlink polygon nodes in z-order
2476 if (!pass && size) indexCurve(ear, minX, minY, size);
2481 // iterate through ears, slicing them one by one
2482 while (ear.prev !== ear.next) {
2486 if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
2487 // cut off the triangle
2488 triangles.push(prev.i / dim);
2489 triangles.push(ear.i / dim);
2490 triangles.push(next.i / dim);
2494 // skipping the next vertice leads to less sliver triangles
2503 // if we looped through the whole remaining polygon and can't find any more ears
2505 // try filtering points and slicing again
2507 earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
2509 // if this didn't work, try curing all small self-intersections locally
2510 } else if (pass === 1) {
2511 ear = cureLocalIntersections(ear, triangles, dim);
2512 earcutLinked(ear, triangles, dim, minX, minY, size, 2);
2514 // as a last resort, try splitting the remaining polygon into two
2515 } else if (pass === 2) {
2516 splitEarcut(ear, triangles, dim, minX, minY, size);
2524 // check whether a polygon node forms a valid ear with adjacent nodes
2525 function isEar(ear) {
2530 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2532 // now make sure we don't have other points inside the potential ear
2533 var p = ear.next.next;
2535 while (p !== ear.prev) {
2536 if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2537 area(p.prev, p, p.next) >= 0) return false;
2544 function isEarHashed(ear, minX, minY, size) {
2549 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2551 // triangle bbox; min & max are calculated like this for speed
2552 var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
2553 minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
2554 maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
2555 maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
2557 // z-order range for the current triangle bbox;
2558 var minZ = zOrder(minTX, minTY, minX, minY, size),
2559 maxZ = zOrder(maxTX, maxTY, minX, minY, size);
2561 // first look for points inside the triangle in increasing z-order
2564 while (p && p.z <= maxZ) {
2565 if (p !== ear.prev && p !== ear.next &&
2566 pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2567 area(p.prev, p, p.next) >= 0) return false;
2571 // then look for points in decreasing z-order
2574 while (p && p.z >= minZ) {
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;
2584 // go through all polygon nodes and cure small local self-intersections
2585 function cureLocalIntersections(start, triangles, dim) {
2591 if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
2593 triangles.push(a.i / dim);
2594 triangles.push(p.i / dim);
2595 triangles.push(b.i / dim);
2597 // remove two nodes involved
2604 } while (p !== start);
2609 // try splitting polygon into two and triangulate them independently
2610 function splitEarcut(start, triangles, dim, minX, minY, size) {
2611 // look for a valid diagonal that divides the polygon into two
2614 var b = a.next.next;
2615 while (b !== a.prev) {
2616 if (a.i !== b.i && isValidDiagonal(a, b)) {
2617 // split the polygon in two by the diagonal
2618 var c = splitPolygon(a, b);
2620 // filter colinear points around the cuts
2621 a = filterPoints(a, a.next);
2622 c = filterPoints(c, c.next);
2624 // run earcut on each half
2625 earcutLinked(a, triangles, dim, minX, minY, size);
2626 earcutLinked(c, triangles, dim, minX, minY, size);
2632 } while (a !== start);
2635 // link every hole into the outer loop, producing a single-ring polygon without holes
2636 function eliminateHoles(data, holeIndices, outerNode, dim) {
2638 i, len, start, end, list;
2640 for (i = 0, len = holeIndices.length; i < len; i++) {
2641 start = holeIndices[i] * dim;
2642 end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2643 list = linkedList(data, start, end, dim, false);
2644 if (list === list.next) list.steiner = true;
2645 queue.push(getLeftmost(list));
2648 queue.sort(compareX);
2650 // process holes from left to right
2651 for (i = 0; i < queue.length; i++) {
2652 eliminateHole(queue[i], outerNode);
2653 outerNode = filterPoints(outerNode, outerNode.next);
2659 function compareX(a, b) {
2663 // find a bridge between vertices that connects hole with an outer ring and and link it
2664 function eliminateHole(hole, outerNode) {
2665 outerNode = findHoleBridge(hole, outerNode);
2667 var b = splitPolygon(outerNode, hole);
2668 filterPoints(b, b.next);
2672 // David Eberly's algorithm for finding a bridge between hole and outer polygon
2673 function findHoleBridge(hole, outerNode) {
2680 // find a segment intersected by a ray from the hole's leftmost point to the left;
2681 // segment's endpoint with lesser x will be potential connection point
2683 if (hy <= p.y && hy >= p.next.y) {
2684 var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
2685 if (x <= hx && x > qx) {
2688 if (hy === p.y) return p;
2689 if (hy === p.next.y) return p.next;
2691 m = p.x < p.next.x ? p : p.next;
2695 } while (p !== outerNode);
2697 if (!m) return null;
2699 if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
2701 // look for points inside the triangle of hole point, segment intersection and endpoint;
2702 // if there are no points found, we have a valid connection;
2703 // otherwise choose the point of the minimum angle with the ray as connection point
2713 while (p !== stop) {
2714 if (hx >= p.x && p.x >= mx &&
2715 pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
2717 tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
2719 if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
2731 // interlink polygon nodes in z-order
2732 function indexCurve(start, minX, minY, size) {
2735 if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size);
2739 } while (p !== start);
2741 p.prevZ.nextZ = null;
2747 // Simon Tatham's linked list merge sort algorithm
2748 // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
2749 function sortLinked(list) {
2750 var i, p, q, e, tail, numMerges, pSize, qSize,
2763 for (i = 0; i < inSize; i++) {
2771 while (pSize > 0 || (qSize > 0 && q)) {
2777 } else if (qSize === 0 || !q) {
2781 } else if (p.z <= q.z) {
2791 if (tail) tail.nextZ = e;
2804 } while (numMerges > 1);
2809 // z-order of a point given coords and size of the data bounding box
2810 function zOrder(x, y, minX, minY, size) {
2811 // coords are transformed into non-negative 15-bit integer range
2812 x = 32767 * (x - minX) / size;
2813 y = 32767 * (y - minY) / size;
2815 x = (x | (x << 8)) & 0x00FF00FF;
2816 x = (x | (x << 4)) & 0x0F0F0F0F;
2817 x = (x | (x << 2)) & 0x33333333;
2818 x = (x | (x << 1)) & 0x55555555;
2820 y = (y | (y << 8)) & 0x00FF00FF;
2821 y = (y | (y << 4)) & 0x0F0F0F0F;
2822 y = (y | (y << 2)) & 0x33333333;
2823 y = (y | (y << 1)) & 0x55555555;
2825 return x | (y << 1);
2828 // find the leftmost node of a polygon ring
2829 function getLeftmost(start) {
2833 if (p.x < leftmost.x) leftmost = p;
2835 } while (p !== start);
2840 // check if a point lies within a convex triangle
2841 function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
2842 return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
2843 (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
2844 (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
2847 // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
2848 function isValidDiagonal(a, b) {
2849 return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
2850 locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
2853 // signed area of a triangle
2854 function area(p, q, r) {
2855 return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
2858 // check if two points are equal
2859 function equals(p1, p2) {
2860 return p1.x === p2.x && p1.y === p2.y;
2863 // check if two segments intersect
2864 function intersects(p1, q1, p2, q2) {
2865 if ((equals(p1, q1) && equals(p2, q2)) ||
2866 (equals(p1, q2) && equals(p2, q1))) return true;
2867 return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
2868 area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
2871 // check if a polygon diagonal intersects any polygon segments
2872 function intersectsPolygon(a, b) {
2875 if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
2876 intersects(p, p.next, a, b)) return true;
2883 // check if a polygon diagonal is locally inside the polygon
2884 function locallyInside(a, b) {
2885 return area(a.prev, a, a.next) < 0 ?
2886 area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
2887 area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
2890 // check if the middle point of a polygon diagonal is inside the polygon
2891 function middleInside(a, b) {
2894 px = (a.x + b.x) / 2,
2895 py = (a.y + b.y) / 2;
2897 if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
2905 // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
2906 // if one belongs to the outer ring and another to a hole, it merges it into a single ring
2907 function splitPolygon(a, b) {
2908 var a2 = new Node(a.i, a.x, a.y),
2909 b2 = new Node(b.i, b.x, b.y),
2928 // create a node and optionally link it with previous one (in a circular doubly linked list)
2929 function insertNode(i, x, y, last) {
2930 var p = new Node(i, x, y);
2945 function removeNode(p) {
2946 p.next.prev = p.prev;
2947 p.prev.next = p.next;
2949 if (p.prevZ) p.prevZ.nextZ = p.nextZ;
2950 if (p.nextZ) p.nextZ.prevZ = p.prevZ;
2953 function Node(i, x, y) {
2954 // vertice index in coordinates array
2957 // vertex coordinates
2961 // previous and next vertice nodes in a polygon ring
2965 // z-order curve value
2968 // previous and next nodes in z-order
2972 // indicates whether this is a steiner point
2973 this.steiner = false;
2976 // return a percentage difference between the polygon area and its triangulation area;
2977 // used to verify correctness of triangulation
2978 earcut.deviation = function (data, holeIndices, dim, triangles) {
2979 var hasHoles = holeIndices && holeIndices.length;
2980 var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
2982 var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
2984 for (var i = 0, len = holeIndices.length; i < len; i++) {
2985 var start = holeIndices[i] * dim;
2986 var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2987 polygonArea -= Math.abs(signedArea(data, start, end, dim));
2991 var trianglesArea = 0;
2992 for (i = 0; i < triangles.length; i += 3) {
2993 var a = triangles[i] * dim;
2994 var b = triangles[i + 1] * dim;
2995 var c = triangles[i + 2] * dim;
2996 trianglesArea += Math.abs(
2997 (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
2998 (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
3001 return polygonArea === 0 && trianglesArea === 0 ? 0 :
3002 Math.abs((trianglesArea - polygonArea) / polygonArea);
3005 function signedArea(data, start, end, dim) {
3007 for (var i = start, j = end - dim; i < end; i += dim) {
3008 sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
3014 // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
3015 earcut.flatten = function (data) {
3016 var dim = data[0][0].length,
3017 result = {vertices: [], holes: [], dimensions: dim},
3020 for (var i = 0; i < data.length; i++) {
3021 for (var j = 0; j < data[i].length; j++) {
3022 for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
3025 holeIndex += data[i - 1].length;
3026 result.holes.push(holeIndex);
3032 },{}],9:[function(require,module,exports){
3035 var OneVersionConstraint = require('individual/one-version');
3037 var MY_VERSION = '7';
3038 OneVersionConstraint('ev-store', MY_VERSION);
3040 var hashKey = '__EV_STORE_KEY@' + MY_VERSION;
3042 module.exports = EvStore;
3044 function EvStore(elem) {
3045 var hash = elem[hashKey];
3048 hash = elem[hashKey] = {};
3054 },{"individual/one-version":19}],10:[function(require,module,exports){
3056 var request = require('./request');
3057 var buildQueryObject = require('./buildQueryObject');
3058 var isArray = Array.isArray;
3060 function simpleExtend(obj, obj2) {
3062 for (prop in obj2) {
3063 obj[prop] = obj2[prop];
3068 function XMLHttpSource(jsongUrl, config) {
3069 this._jsongUrl = jsongUrl;
3070 if (typeof config === 'number') {
3076 this._config = simpleExtend({
3082 XMLHttpSource.prototype = {
3083 // because javascript
3084 constructor: XMLHttpSource,
3086 * buildQueryObject helper
3088 buildQueryObject: buildQueryObject,
3091 * @inheritDoc DataSource#get
3093 get: function httpSourceGet(pathSet) {
3095 var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3099 var config = simpleExtend(queryObject, this._config);
3100 // pass context for onBeforeRequest callback
3102 return request(method, config, context);
3106 * @inheritDoc DataSource#set
3108 set: function httpSourceSet(jsongEnv) {
3109 var method = 'POST';
3110 var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3111 jsonGraph: jsongEnv,
3114 var config = simpleExtend(queryObject, this._config);
3115 config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3117 // pass context for onBeforeRequest callback
3119 return request(method, config, context);
3124 * @inheritDoc DataSource#call
3126 call: function httpSourceCall(callPath, args, pathSuffix, paths) {
3127 // arguments defaults
3129 pathSuffix = pathSuffix || [];
3130 paths = paths || [];
3132 var method = 'POST';
3134 queryData.push('method=call');
3135 queryData.push('callPath=' + encodeURIComponent(JSON.stringify(callPath)));
3136 queryData.push('arguments=' + encodeURIComponent(JSON.stringify(args)));
3137 queryData.push('pathSuffixes=' + encodeURIComponent(JSON.stringify(pathSuffix)));
3138 queryData.push('paths=' + encodeURIComponent(JSON.stringify(paths)));
3140 var queryObject = this.buildQueryObject(this._jsongUrl, method, queryData.join('&'));
3141 var config = simpleExtend(queryObject, this._config);
3142 config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3144 // pass context for onBeforeRequest callback
3146 return request(method, config, context);
3150 XMLHttpSource.XMLHttpSource = XMLHttpSource;
3151 XMLHttpSource['default'] = XMLHttpSource;
3153 module.exports = XMLHttpSource;
3155 },{"./buildQueryObject":11,"./request":14}],11:[function(require,module,exports){
3157 module.exports = function buildQueryObject(url, method, queryData) {
3160 var data = {url: url};
3161 var isQueryParamUrl = url.indexOf('?') !== -1;
3162 var startUrl = (isQueryParamUrl) ? '&' : '?';
3164 if (typeof queryData === 'string') {
3165 qData.push(queryData);
3168 keys = Object.keys(queryData);
3169 keys.forEach(function (k) {
3170 var value = (typeof queryData[k] === 'object') ? JSON.stringify(queryData[k]) : queryData[k];
3171 qData.push(k + '=' + encodeURIComponent(value));
3175 if (method === 'GET') {
3176 data.url += startUrl + qData.join('&');
3178 data.data = qData.join('&');
3184 },{}],12:[function(require,module,exports){
3187 // Get CORS support even for older IE
3188 module.exports = function getCORSRequest() {
3189 var xhr = new global.XMLHttpRequest();
3190 if ('withCredentials' in xhr) {
3192 } else if (!!global.XDomainRequest) {
3193 return new XDomainRequest();
3195 throw new Error('CORS is not supported by your browser');
3199 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3201 },{}],13:[function(require,module,exports){
3204 module.exports = function getXMLHttpRequest() {
3208 if (global.XMLHttpRequest) {
3209 return new global.XMLHttpRequest();
3212 progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
3213 for (i = 0; i < 3; i++) {
3215 progId = progIds[i];
3216 if (new global.ActiveXObject(progId)) {
3221 return new global.ActiveXObject(progId);
3223 throw new Error('XMLHttpRequest is not supported by your browser');
3228 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3230 },{}],14:[function(require,module,exports){
3232 var getXMLHttpRequest = require('./getXMLHttpRequest');
3233 var getCORSRequest = require('./getCORSRequest');
3234 var hasOwnProp = Object.prototype.hasOwnProperty;
3236 var noop = function() {};
3238 function Observable() {}
3240 Observable.create = function(subscribe) {
3241 var o = new Observable();
3243 o.subscribe = function(onNext, onError, onCompleted) {
3248 if (typeof onNext === 'function') {
3251 onError: (onError || noop),
3252 onCompleted: (onCompleted || noop)
3258 disposable = subscribe(observer);
3260 if (typeof disposable === 'function') {
3272 function request(method, options, context) {
3273 return Observable.create(function requestObserver(observer) {
3276 method: method || 'GET',
3280 responseType: 'json'
3289 for (prop in options) {
3290 if (hasOwnProp.call(options, prop)) {
3291 config[prop] = options[prop];
3295 // Add request with Headers
3296 if (!config.crossDomain && !config.headers['X-Requested-With']) {
3297 config.headers['X-Requested-With'] = 'XMLHttpRequest';
3300 // allow the user to mutate the config open
3301 if (context.onBeforeRequest != null) {
3302 context.onBeforeRequest(config);
3307 xhr = config.crossDomain ? getCORSRequest() : getXMLHttpRequest();
3309 observer.onError(err);
3312 // Takes the url and opens the connection
3314 xhr.open(config.method, config.url, config.async, config.user, config.password);
3316 xhr.open(config.method, config.url, config.async);
3319 // Sets timeout information
3320 xhr.timeout = config.timeout;
3322 // Anything but explicit false results in true.
3323 xhr.withCredentials = config.withCredentials !== false;
3325 // Fills the request headers
3326 headers = config.headers;
3327 for (header in headers) {
3328 if (hasOwnProp.call(headers, header)) {
3329 xhr.setRequestHeader(header, headers[header]);
3333 if (config.responseType) {
3335 xhr.responseType = config.responseType;
3337 // WebKit added support for the json responseType value on 09/03/2013
3338 // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
3339 // known to throw when setting the value "json" as the response type. Other older
3340 // browsers implementing the responseType
3342 // The json response type can be ignored if not supported, because JSON payloads are
3343 // parsed on the client-side regardless.
3344 if (config.responseType !== 'json') {
3350 xhr.onreadystatechange = function onreadystatechange(e) {
3352 if (xhr.readyState === 4) {
3355 onXhrLoad(observer, xhr, e);
3361 xhr.ontimeout = function ontimeout(e) {
3364 onXhrError(observer, xhr, 'timeout error', e);
3369 xhr.send(config.data);
3372 observer.onError(e);
3375 return function dispose() {
3376 // Doesn't work in IE9
3377 if (!isDone && xhr.readyState !== 4) {
3386 * General handling of ultimate failure (after appropriate retries)
3388 function _handleXhrError(observer, textStatus, errorThrown) {
3389 // IE9: cross-domain request may be considered errors
3391 errorThrown = new Error(textStatus);
3394 observer.onError(errorThrown);
3397 function onXhrLoad(observer, xhr, e) {
3402 // If there's no observer, the request has been (or is being) cancelled.
3403 if (xhr && observer) {
3404 responseType = xhr.responseType;
3405 // responseText is the old-school way of retrieving response (supported by IE8 & 9)
3406 // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
3407 responseData = ('response' in xhr) ? xhr.response : xhr.responseText;
3409 // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
3410 var status = (xhr.status === 1223) ? 204 : xhr.status;
3412 if (status >= 200 && status <= 399) {
3414 if (responseType !== 'json') {
3415 responseData = JSON.parse(responseData || '');
3417 if (typeof responseData === 'string') {
3418 responseData = JSON.parse(responseData || '');
3421 _handleXhrError(observer, 'invalid json', e);
3423 observer.onNext(responseData);
3424 observer.onCompleted();
3427 } else if (status === 401 || status === 403 || status === 407) {
3429 return _handleXhrError(observer, responseData);
3431 } else if (status === 410) {
3433 return _handleXhrError(observer, responseData);
3435 } else if (status === 408 || status === 504) {
3437 return _handleXhrError(observer, responseData);
3441 return _handleXhrError(observer, responseData || ('Response code ' + status));
3447 function onXhrError(observer, xhr, status, e) {
3448 _handleXhrError(observer, status || xhr.statusText || 'request error', e);
3451 module.exports = request;
3453 },{"./getCORSRequest":12,"./getXMLHttpRequest":13}],15:[function(require,module,exports){
3455 !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(){
3456 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);
3457 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(){
3458 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(){
3459 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)});
3460 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3462 },{}],16:[function(require,module,exports){
3464 var topLevel = typeof global !== 'undefined' ? global :
3465 typeof window !== 'undefined' ? window : {}
3466 var minDoc = require('min-document');
3470 if (typeof document !== 'undefined') {
3473 doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
3476 doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
3480 module.exports = doccy;
3482 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3484 },{"min-document":4}],17:[function(require,module,exports){
3485 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
3487 var eLen = nBytes * 8 - mLen - 1
3488 var eMax = (1 << eLen) - 1
3489 var eBias = eMax >> 1
3491 var i = isLE ? (nBytes - 1) : 0
3492 var d = isLE ? -1 : 1
3493 var s = buffer[offset + i]
3497 e = s & ((1 << (-nBits)) - 1)
3500 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3502 m = e & ((1 << (-nBits)) - 1)
3505 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3509 } else if (e === eMax) {
3510 return m ? NaN : ((s ? -1 : 1) * Infinity)
3512 m = m + Math.pow(2, mLen)
3515 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
3518 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
3520 var eLen = nBytes * 8 - mLen - 1
3521 var eMax = (1 << eLen) - 1
3522 var eBias = eMax >> 1
3523 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
3524 var i = isLE ? 0 : (nBytes - 1)
3525 var d = isLE ? 1 : -1
3526 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
3528 value = Math.abs(value)
3530 if (isNaN(value) || value === Infinity) {
3531 m = isNaN(value) ? 1 : 0
3534 e = Math.floor(Math.log(value) / Math.LN2)
3535 if (value * (c = Math.pow(2, -e)) < 1) {
3539 if (e + eBias >= 1) {
3542 value += rt * Math.pow(2, 1 - eBias)
3544 if (value * c >= 2) {
3549 if (e + eBias >= eMax) {
3552 } else if (e + eBias >= 1) {
3553 m = (value * c - 1) * Math.pow(2, mLen)
3556 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
3561 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
3565 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
3567 buffer[offset + i - d] |= s * 128
3570 },{}],18:[function(require,module,exports){
3574 /*global window, global*/
3576 var root = typeof window !== 'undefined' ?
3577 window : typeof global !== 'undefined' ?
3580 module.exports = Individual;
3582 function Individual(key, value) {
3592 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3594 },{}],19:[function(require,module,exports){
3597 var Individual = require('./index.js');
3599 module.exports = OneVersion;
3601 function OneVersion(moduleName, version, defaultValue) {
3602 var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName;
3603 var enforceKey = key + '_ENFORCE_SINGLETON';
3605 var versionValue = Individual(enforceKey, version);
3607 if (versionValue !== version) {
3608 throw new Error('Can only have one copy of ' +
3609 moduleName + '.\n' +
3610 'You already have version ' + versionValue +
3612 'This means you cannot install version ' + version);
3615 return Individual(key, defaultValue);
3618 },{"./index.js":18}],20:[function(require,module,exports){
3621 module.exports = function isObject(x) {
3622 return typeof x === "object" && x !== null;
3625 },{}],21:[function(require,module,exports){
3626 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3627 /* Geohash encoding/decoding and associated functions (c) Chris Veness 2014-2016 / MIT Licence */
3628 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3634 * Geohash encode, decode, bounds, neighbours.
3640 /* (Geohash-specific) Base32 map */
3641 Geohash.base32 = '0123456789bcdefghjkmnpqrstuvwxyz';
3644 * Encodes latitude/longitude to geohash, either to specified precision or to automatically
3645 * evaluated precision.
3647 * @param {number} lat - Latitude in degrees.
3648 * @param {number} lon - Longitude in degrees.
3649 * @param {number} [precision] - Number of characters in resulting geohash.
3650 * @returns {string} Geohash of supplied latitude/longitude.
3651 * @throws Invalid geohash.
3654 * var geohash = Geohash.encode(52.205, 0.119, 7); // geohash: 'u120fxw'
3656 Geohash.encode = function(lat, lon, precision) {
3658 if (typeof precision == 'undefined') {
3659 // refine geohash until it matches precision of supplied lat/lon
3660 for (var p=1; p<=12; p++) {
3661 var hash = Geohash.encode(lat, lon, p);
3662 var posn = Geohash.decode(hash);
3663 if (posn.lat==lat && posn.lon==lon) return hash;
3665 precision = 12; // set to maximum
3670 precision = Number(precision);
3672 if (isNaN(lat) || isNaN(lon) || isNaN(precision)) throw new Error('Invalid geohash');
3674 var idx = 0; // index into base32 map
3675 var bit = 0; // each char holds 5 bits
3679 var latMin = -90, latMax = 90;
3680 var lonMin = -180, lonMax = 180;
3682 while (geohash.length < precision) {
3684 // bisect E-W longitude
3685 var lonMid = (lonMin + lonMax) / 2;
3686 if (lon >= lonMid) {
3694 // bisect N-S latitude
3695 var latMid = (latMin + latMax) / 2;
3696 if (lat >= latMid) {
3707 // 5 bits gives us a character: append it and start over
3708 geohash += Geohash.base32.charAt(idx);
3719 * Decode geohash to latitude/longitude (location is approximate centre of geohash cell,
3720 * to reasonable precision).
3722 * @param {string} geohash - Geohash string to be converted to latitude/longitude.
3723 * @returns {{lat:number, lon:number}} (Center of) geohashed location.
3724 * @throws Invalid geohash.
3727 * var latlon = Geohash.decode('u120fxw'); // latlon: { lat: 52.205, lon: 0.1188 }
3729 Geohash.decode = function(geohash) {
3731 var bounds = Geohash.bounds(geohash); // <-- the hard work
3732 // now just determine the centre of the cell...
3734 var latMin = bounds.sw.lat, lonMin = bounds.sw.lon;
3735 var latMax = bounds.ne.lat, lonMax = bounds.ne.lon;
3738 var lat = (latMin + latMax)/2;
3739 var lon = (lonMin + lonMax)/2;
3741 // round to close to centre without excessive precision: ⌊2-log10(Δ°)⌋ decimal places
3742 lat = lat.toFixed(Math.floor(2-Math.log(latMax-latMin)/Math.LN10));
3743 lon = lon.toFixed(Math.floor(2-Math.log(lonMax-lonMin)/Math.LN10));
3745 return { lat: Number(lat), lon: Number(lon) };
3750 * Returns SW/NE latitude/longitude bounds of specified geohash.
3752 * @param {string} geohash - Cell that bounds are required of.
3753 * @returns {{sw: {lat: number, lon: number}, ne: {lat: number, lon: number}}}
3754 * @throws Invalid geohash.
3756 Geohash.bounds = function(geohash) {
3757 if (geohash.length === 0) throw new Error('Invalid geohash');
3759 geohash = geohash.toLowerCase();
3762 var latMin = -90, latMax = 90;
3763 var lonMin = -180, lonMax = 180;
3765 for (var i=0; i<geohash.length; i++) {
3766 var chr = geohash.charAt(i);
3767 var idx = Geohash.base32.indexOf(chr);
3768 if (idx == -1) throw new Error('Invalid geohash');
3770 for (var n=4; n>=0; n--) {
3771 var bitN = idx >> n & 1;
3774 var lonMid = (lonMin+lonMax) / 2;
3782 var latMid = (latMin+latMax) / 2;
3794 sw: { lat: latMin, lon: lonMin },
3795 ne: { lat: latMax, lon: lonMax },
3803 * Determines adjacent cell in given direction.
3805 * @param geohash - Cell to which adjacent cell is required.
3806 * @param direction - Direction from geohash (N/S/E/W).
3807 * @returns {string} Geocode of adjacent cell.
3808 * @throws Invalid geohash.
3810 Geohash.adjacent = function(geohash, direction) {
3811 // based on github.com/davetroy/geohash-js
3813 geohash = geohash.toLowerCase();
3814 direction = direction.toLowerCase();
3816 if (geohash.length === 0) throw new Error('Invalid geohash');
3817 if ('nsew'.indexOf(direction) == -1) throw new Error('Invalid direction');
3820 n: [ 'p0r21436x8zb9dcf5h7kjnmqesgutwvy', 'bc01fg45238967deuvhjyznpkmstqrwx' ],
3821 s: [ '14365h7k9dcfesgujnmqp0r2twvyx8zb', '238967debc01fg45kmstqrwxuvhjyznp' ],
3822 e: [ 'bc01fg45238967deuvhjyznpkmstqrwx', 'p0r21436x8zb9dcf5h7kjnmqesgutwvy' ],
3823 w: [ '238967debc01fg45kmstqrwxuvhjyznp', '14365h7k9dcfesgujnmqp0r2twvyx8zb' ],
3826 n: [ 'prxz', 'bcfguvyz' ],
3827 s: [ '028b', '0145hjnp' ],
3828 e: [ 'bcfguvyz', 'prxz' ],
3829 w: [ '0145hjnp', '028b' ],
3832 var lastCh = geohash.slice(-1); // last character of hash
3833 var parent = geohash.slice(0, -1); // hash without last character
3835 var type = geohash.length % 2;
3837 // check for edge-cases which don't share common prefix
3838 if (border[direction][type].indexOf(lastCh) != -1 && parent !== '') {
3839 parent = Geohash.adjacent(parent, direction);
3842 // append letter for direction to parent
3843 return parent + Geohash.base32.charAt(neighbour[direction][type].indexOf(lastCh));
3848 * Returns all 8 adjacent cells to specified geohash.
3850 * @param {string} geohash - Geohash neighbours are required of.
3851 * @returns {{n,ne,e,se,s,sw,w,nw: string}}
3852 * @throws Invalid geohash.
3854 Geohash.neighbours = function(geohash) {
3856 'n': Geohash.adjacent(geohash, 'n'),
3857 'ne': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'e'),
3858 'e': Geohash.adjacent(geohash, 'e'),
3859 'se': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'e'),
3860 's': Geohash.adjacent(geohash, 's'),
3861 'sw': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'w'),
3862 'w': Geohash.adjacent(geohash, 'w'),
3863 'nw': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'w'),
3868 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3869 if (typeof module != 'undefined' && module.exports) module.exports = Geohash; // CommonJS, node.js
3871 },{}],22:[function(require,module,exports){
3872 (function (process){
3873 // Copyright Joyent, Inc. and other Node contributors.
3875 // Permission is hereby granted, free of charge, to any person obtaining a
3876 // copy of this software and associated documentation files (the
3877 // "Software"), to deal in the Software without restriction, including
3878 // without limitation the rights to use, copy, modify, merge, publish,
3879 // distribute, sublicense, and/or sell copies of the Software, and to permit
3880 // persons to whom the Software is furnished to do so, subject to the
3881 // following conditions:
3883 // The above copyright notice and this permission notice shall be included
3884 // in all copies or substantial portions of the Software.
3886 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3887 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3888 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3889 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3890 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3891 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3892 // USE OR OTHER DEALINGS IN THE SOFTWARE.
3894 // resolves . and .. elements in a path array with directory names there
3895 // must be no slashes, empty elements, or device names (c:\) in the array
3896 // (so also no leading and trailing slashes - it does not distinguish
3897 // relative and absolute paths)
3898 function normalizeArray(parts, allowAboveRoot) {
3899 // if the path tries to go above the root, `up` ends up > 0
3901 for (var i = parts.length - 1; i >= 0; i--) {
3902 var last = parts[i];
3905 } else if (last === '..') {
3914 // if the path is allowed to go above the root, restore leading ..s
3915 if (allowAboveRoot) {
3917 parts.unshift('..');
3924 // Split a filename into [root, dir, basename, ext], unix version
3925 // 'root' is just a slash, or nothing.
3927 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
3928 var splitPath = function(filename) {
3929 return splitPathRe.exec(filename).slice(1);
3932 // path.resolve([from ...], to)
3934 exports.resolve = function() {
3935 var resolvedPath = '',
3936 resolvedAbsolute = false;
3938 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
3939 var path = (i >= 0) ? arguments[i] : process.cwd();
3941 // Skip empty and invalid entries
3942 if (typeof path !== 'string') {
3943 throw new TypeError('Arguments to path.resolve must be strings');
3948 resolvedPath = path + '/' + resolvedPath;
3949 resolvedAbsolute = path.charAt(0) === '/';
3952 // At this point the path should be resolved to a full absolute path, but
3953 // handle relative paths to be safe (might happen when process.cwd() fails)
3955 // Normalize the path
3956 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
3958 }), !resolvedAbsolute).join('/');
3960 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
3963 // path.normalize(path)
3965 exports.normalize = function(path) {
3966 var isAbsolute = exports.isAbsolute(path),
3967 trailingSlash = substr(path, -1) === '/';
3969 // Normalize the path
3970 path = normalizeArray(filter(path.split('/'), function(p) {
3972 }), !isAbsolute).join('/');
3974 if (!path && !isAbsolute) {
3977 if (path && trailingSlash) {
3981 return (isAbsolute ? '/' : '') + path;
3985 exports.isAbsolute = function(path) {
3986 return path.charAt(0) === '/';
3990 exports.join = function() {
3991 var paths = Array.prototype.slice.call(arguments, 0);
3992 return exports.normalize(filter(paths, function(p, index) {
3993 if (typeof p !== 'string') {
3994 throw new TypeError('Arguments to path.join must be strings');
4001 // path.relative(from, to)
4003 exports.relative = function(from, to) {
4004 from = exports.resolve(from).substr(1);
4005 to = exports.resolve(to).substr(1);
4007 function trim(arr) {
4009 for (; start < arr.length; start++) {
4010 if (arr[start] !== '') break;
4013 var end = arr.length - 1;
4014 for (; end >= 0; end--) {
4015 if (arr[end] !== '') break;
4018 if (start > end) return [];
4019 return arr.slice(start, end - start + 1);
4022 var fromParts = trim(from.split('/'));
4023 var toParts = trim(to.split('/'));
4025 var length = Math.min(fromParts.length, toParts.length);
4026 var samePartsLength = length;
4027 for (var i = 0; i < length; i++) {
4028 if (fromParts[i] !== toParts[i]) {
4029 samePartsLength = i;
4034 var outputParts = [];
4035 for (var i = samePartsLength; i < fromParts.length; i++) {
4036 outputParts.push('..');
4039 outputParts = outputParts.concat(toParts.slice(samePartsLength));
4041 return outputParts.join('/');
4045 exports.delimiter = ':';
4047 exports.dirname = function(path) {
4048 var result = splitPath(path),
4052 if (!root && !dir) {
4053 // No dirname whatsoever
4058 // It has a dirname, strip trailing slash
4059 dir = dir.substr(0, dir.length - 1);
4066 exports.basename = function(path, ext) {
4067 var f = splitPath(path)[2];
4068 // TODO: make this comparison case-insensitive on windows?
4069 if (ext && f.substr(-1 * ext.length) === ext) {
4070 f = f.substr(0, f.length - ext.length);
4076 exports.extname = function(path) {
4077 return splitPath(path)[3];
4080 function filter (xs, f) {
4081 if (xs.filter) return xs.filter(f);
4083 for (var i = 0; i < xs.length; i++) {
4084 if (f(xs[i], i, xs)) res.push(xs[i]);
4089 // String.prototype.substr - negative index don't work in IE8
4090 var substr = 'ab'.substr(-1) === 'b'
4091 ? function (str, start, len) { return str.substr(start, len) }
4092 : function (str, start, len) {
4093 if (start < 0) start = str.length + start;
4094 return str.substr(start, len);
4098 }).call(this,require('_process'))
4100 },{"_process":6}],23:[function(require,module,exports){
4103 module.exports = Pbf;
4105 var ieee754 = require('ieee754');
4108 this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);
4111 this.length = this.buf.length;
4114 Pbf.Varint = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum
4115 Pbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64
4116 Pbf.Bytes = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields
4117 Pbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32
4119 var SHIFT_LEFT_32 = (1 << 16) * (1 << 16),
4120 SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
4124 destroy: function() {
4128 // === READING =================================================================
4130 readFields: function(readField, result, end) {
4131 end = end || this.length;
4133 while (this.pos < end) {
4134 var val = this.readVarint(),
4136 startPos = this.pos;
4138 this.type = val & 0x7;
4139 readField(tag, result, this);
4141 if (this.pos === startPos) this.skip(val);
4146 readMessage: function(readField, result) {
4147 return this.readFields(readField, result, this.readVarint() + this.pos);
4150 readFixed32: function() {
4151 var val = readUInt32(this.buf, this.pos);
4156 readSFixed32: function() {
4157 var val = readInt32(this.buf, this.pos);
4162 // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)
4164 readFixed64: function() {
4165 var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4170 readSFixed64: function() {
4171 var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4176 readFloat: function() {
4177 var val = ieee754.read(this.buf, this.pos, true, 23, 4);
4182 readDouble: function() {
4183 var val = ieee754.read(this.buf, this.pos, true, 52, 8);
4188 readVarint: function(isSigned) {
4192 b = buf[this.pos++]; val = b & 0x7f; if (b < 0x80) return val;
4193 b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val;
4194 b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;
4195 b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;
4196 b = buf[this.pos]; val |= (b & 0x0f) << 28;
4198 return readVarintRemainder(val, isSigned, this);
4201 readVarint64: function() { // for compatibility with v2.0.1
4202 return this.readVarint(true);
4205 readSVarint: function() {
4206 var num = this.readVarint();
4207 return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding
4210 readBoolean: function() {
4211 return Boolean(this.readVarint());
4214 readString: function() {
4215 var end = this.readVarint() + this.pos,
4216 str = readUtf8(this.buf, this.pos, end);
4221 readBytes: function() {
4222 var end = this.readVarint() + this.pos,
4223 buffer = this.buf.subarray(this.pos, end);
4228 // verbose for performance reasons; doesn't affect gzipped size
4230 readPackedVarint: function(arr, isSigned) {
4231 var end = readPackedEnd(this);
4233 while (this.pos < end) arr.push(this.readVarint(isSigned));
4236 readPackedSVarint: function(arr) {
4237 var end = readPackedEnd(this);
4239 while (this.pos < end) arr.push(this.readSVarint());
4242 readPackedBoolean: function(arr) {
4243 var end = readPackedEnd(this);
4245 while (this.pos < end) arr.push(this.readBoolean());
4248 readPackedFloat: function(arr) {
4249 var end = readPackedEnd(this);
4251 while (this.pos < end) arr.push(this.readFloat());
4254 readPackedDouble: function(arr) {
4255 var end = readPackedEnd(this);
4257 while (this.pos < end) arr.push(this.readDouble());
4260 readPackedFixed32: function(arr) {
4261 var end = readPackedEnd(this);
4263 while (this.pos < end) arr.push(this.readFixed32());
4266 readPackedSFixed32: function(arr) {
4267 var end = readPackedEnd(this);
4269 while (this.pos < end) arr.push(this.readSFixed32());
4272 readPackedFixed64: function(arr) {
4273 var end = readPackedEnd(this);
4275 while (this.pos < end) arr.push(this.readFixed64());
4278 readPackedSFixed64: function(arr) {
4279 var end = readPackedEnd(this);
4281 while (this.pos < end) arr.push(this.readSFixed64());
4285 skip: function(val) {
4286 var type = val & 0x7;
4287 if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}
4288 else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos;
4289 else if (type === Pbf.Fixed32) this.pos += 4;
4290 else if (type === Pbf.Fixed64) this.pos += 8;
4291 else throw new Error('Unimplemented type: ' + type);
4294 // === WRITING =================================================================
4296 writeTag: function(tag, type) {
4297 this.writeVarint((tag << 3) | type);
4300 realloc: function(min) {
4301 var length = this.length || 16;
4303 while (length < this.pos + min) length *= 2;
4305 if (length !== this.length) {
4306 var buf = new Uint8Array(length);
4309 this.length = length;
4313 finish: function() {
4314 this.length = this.pos;
4316 return this.buf.subarray(0, this.length);
4319 writeFixed32: function(val) {
4321 writeInt32(this.buf, val, this.pos);
4325 writeSFixed32: function(val) {
4327 writeInt32(this.buf, val, this.pos);
4331 writeFixed64: function(val) {
4333 writeInt32(this.buf, val & -1, this.pos);
4334 writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4338 writeSFixed64: function(val) {
4340 writeInt32(this.buf, val & -1, this.pos);
4341 writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4345 writeVarint: function(val) {
4348 if (val > 0xfffffff || val < 0) {
4349 writeBigVarint(val, this);
4355 this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4356 this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4357 this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4358 this.buf[this.pos++] = (val >>> 7) & 0x7f;
4361 writeSVarint: function(val) {
4362 this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
4365 writeBoolean: function(val) {
4366 this.writeVarint(Boolean(val));
4369 writeString: function(str) {
4371 this.realloc(str.length * 4);
4373 this.pos++; // reserve 1 byte for short string length
4375 var startPos = this.pos;
4376 // write the string directly to the buffer and see how much was written
4377 this.pos = writeUtf8(this.buf, str, this.pos);
4378 var len = this.pos - startPos;
4380 if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4382 // finally, write the message length in the reserved place and restore the position
4383 this.pos = startPos - 1;
4384 this.writeVarint(len);
4388 writeFloat: function(val) {
4390 ieee754.write(this.buf, val, this.pos, true, 23, 4);
4394 writeDouble: function(val) {
4396 ieee754.write(this.buf, val, this.pos, true, 52, 8);
4400 writeBytes: function(buffer) {
4401 var len = buffer.length;
4402 this.writeVarint(len);
4404 for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];
4407 writeRawMessage: function(fn, obj) {
4408 this.pos++; // reserve 1 byte for short message length
4410 // write the message directly to the buffer and see how much was written
4411 var startPos = this.pos;
4413 var len = this.pos - startPos;
4415 if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4417 // finally, write the message length in the reserved place and restore the position
4418 this.pos = startPos - 1;
4419 this.writeVarint(len);
4423 writeMessage: function(tag, fn, obj) {
4424 this.writeTag(tag, Pbf.Bytes);
4425 this.writeRawMessage(fn, obj);
4428 writePackedVarint: function(tag, arr) { this.writeMessage(tag, writePackedVarint, arr); },
4429 writePackedSVarint: function(tag, arr) { this.writeMessage(tag, writePackedSVarint, arr); },
4430 writePackedBoolean: function(tag, arr) { this.writeMessage(tag, writePackedBoolean, arr); },
4431 writePackedFloat: function(tag, arr) { this.writeMessage(tag, writePackedFloat, arr); },
4432 writePackedDouble: function(tag, arr) { this.writeMessage(tag, writePackedDouble, arr); },
4433 writePackedFixed32: function(tag, arr) { this.writeMessage(tag, writePackedFixed32, arr); },
4434 writePackedSFixed32: function(tag, arr) { this.writeMessage(tag, writePackedSFixed32, arr); },
4435 writePackedFixed64: function(tag, arr) { this.writeMessage(tag, writePackedFixed64, arr); },
4436 writePackedSFixed64: function(tag, arr) { this.writeMessage(tag, writePackedSFixed64, arr); },
4438 writeBytesField: function(tag, buffer) {
4439 this.writeTag(tag, Pbf.Bytes);
4440 this.writeBytes(buffer);
4442 writeFixed32Field: function(tag, val) {
4443 this.writeTag(tag, Pbf.Fixed32);
4444 this.writeFixed32(val);
4446 writeSFixed32Field: function(tag, val) {
4447 this.writeTag(tag, Pbf.Fixed32);
4448 this.writeSFixed32(val);
4450 writeFixed64Field: function(tag, val) {
4451 this.writeTag(tag, Pbf.Fixed64);
4452 this.writeFixed64(val);
4454 writeSFixed64Field: function(tag, val) {
4455 this.writeTag(tag, Pbf.Fixed64);
4456 this.writeSFixed64(val);
4458 writeVarintField: function(tag, val) {
4459 this.writeTag(tag, Pbf.Varint);
4460 this.writeVarint(val);
4462 writeSVarintField: function(tag, val) {
4463 this.writeTag(tag, Pbf.Varint);
4464 this.writeSVarint(val);
4466 writeStringField: function(tag, str) {
4467 this.writeTag(tag, Pbf.Bytes);
4468 this.writeString(str);
4470 writeFloatField: function(tag, val) {
4471 this.writeTag(tag, Pbf.Fixed32);
4472 this.writeFloat(val);
4474 writeDoubleField: function(tag, val) {
4475 this.writeTag(tag, Pbf.Fixed64);
4476 this.writeDouble(val);
4478 writeBooleanField: function(tag, val) {
4479 this.writeVarintField(tag, Boolean(val));
4483 function readVarintRemainder(l, s, p) {
4487 b = buf[p.pos++]; h = (b & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s);
4488 b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s);
4489 b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);
4490 b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);
4491 b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);
4492 b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);
4494 throw new Error('Expected varint not more than 10 bytes');
4497 function readPackedEnd(pbf) {
4498 return pbf.type === Pbf.Bytes ?
4499 pbf.readVarint() + pbf.pos : pbf.pos + 1;
4502 function toNum(low, high, isSigned) {
4504 return high * 0x100000000 + (low >>> 0);
4507 return ((high >>> 0) * 0x100000000) + (low >>> 0);
4510 function writeBigVarint(val, pbf) {
4514 low = (val % 0x100000000) | 0;
4515 high = (val / 0x100000000) | 0;
4517 low = ~(-val % 0x100000000);
4518 high = ~(-val / 0x100000000);
4520 if (low ^ 0xffffffff) {
4521 low = (low + 1) | 0;
4524 high = (high + 1) | 0;
4528 if (val >= 0x10000000000000000 || val < -0x10000000000000000) {
4529 throw new Error('Given varint doesn\'t fit into 10 bytes');
4534 writeBigVarintLow(low, high, pbf);
4535 writeBigVarintHigh(high, pbf);
4538 function writeBigVarintLow(low, high, pbf) {
4539 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4540 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
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;
4546 function writeBigVarintHigh(high, pbf) {
4547 var lsb = (high & 0x07) << 4;
4549 pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return;
4550 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4551 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 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;
4557 function makeRoomForExtraLength(startPos, len, pbf) {
4560 len <= 0x1fffff ? 2 :
4561 len <= 0xfffffff ? 3 : Math.ceil(Math.log(len) / (Math.LN2 * 7));
4563 // if 1 byte isn't enough for encoding message length, shift the data to the right
4564 pbf.realloc(extraLen);
4565 for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];
4568 function writePackedVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]); }
4569 function writePackedSVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]); }
4570 function writePackedFloat(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]); }
4571 function writePackedDouble(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]); }
4572 function writePackedBoolean(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]); }
4573 function writePackedFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]); }
4574 function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); }
4575 function writePackedFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]); }
4576 function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); }
4578 // Buffer code below from https://github.com/feross/buffer, MIT-licensed
4580 function readUInt32(buf, pos) {
4581 return ((buf[pos]) |
4582 (buf[pos + 1] << 8) |
4583 (buf[pos + 2] << 16)) +
4584 (buf[pos + 3] * 0x1000000);
4587 function writeInt32(buf, val, pos) {
4589 buf[pos + 1] = (val >>> 8);
4590 buf[pos + 2] = (val >>> 16);
4591 buf[pos + 3] = (val >>> 24);
4594 function readInt32(buf, pos) {
4595 return ((buf[pos]) |
4596 (buf[pos + 1] << 8) |
4597 (buf[pos + 2] << 16)) +
4598 (buf[pos + 3] << 24);
4601 function readUtf8(buf, pos, end) {
4607 var c = null; // codepoint
4608 var bytesPerSequence =
4613 if (i + bytesPerSequence > end) break;
4617 if (bytesPerSequence === 1) {
4621 } else if (bytesPerSequence === 2) {
4623 if ((b1 & 0xC0) === 0x80) {
4624 c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);
4629 } else if (bytesPerSequence === 3) {
4632 if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {
4633 c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);
4634 if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {
4638 } else if (bytesPerSequence === 4) {
4642 if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
4643 c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);
4644 if (c <= 0xFFFF || c >= 0x110000) {
4652 bytesPerSequence = 1;
4654 } else if (c > 0xFFFF) {
4656 str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);
4657 c = 0xDC00 | c & 0x3FF;
4660 str += String.fromCharCode(c);
4661 i += bytesPerSequence;
4667 function writeUtf8(buf, str, pos) {
4668 for (var i = 0, c, lead; i < str.length; i++) {
4669 c = str.charCodeAt(i); // code point
4671 if (c > 0xD7FF && c < 0xE000) {
4680 c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;
4684 if (c > 0xDBFF || (i + 1 === str.length)) {
4704 buf[pos++] = c >> 0x6 | 0xC0;
4707 buf[pos++] = c >> 0xC | 0xE0;
4709 buf[pos++] = c >> 0x12 | 0xF0;
4710 buf[pos++] = c >> 0xC & 0x3F | 0x80;
4712 buf[pos++] = c >> 0x6 & 0x3F | 0x80;
4714 buf[pos++] = c & 0x3F | 0x80;
4720 },{"ieee754":17}],24:[function(require,module,exports){
4723 module.exports = partialSort;
4725 // Floyd-Rivest selection algorithm:
4726 // Rearrange items so that all items in the [left, k] range are smaller than all items in (k, right];
4727 // The k-th element will have the (k - left + 1)th smallest value in [left, right]
4729 function partialSort(arr, k, left, right, compare) {
4731 right = right || (arr.length - 1);
4732 compare = compare || defaultCompare;
4734 while (right > left) {
4735 if (right - left > 600) {
4736 var n = right - left + 1;
4737 var m = k - left + 1;
4738 var z = Math.log(n);
4739 var s = 0.5 * Math.exp(2 * z / 3);
4740 var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
4741 var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
4742 var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
4743 partialSort(arr, k, newLeft, newRight, compare);
4751 if (compare(arr[right], t) > 0) swap(arr, left, right);
4757 while (compare(arr[i], t) < 0) i++;
4758 while (compare(arr[j], t) > 0) j--;
4761 if (compare(arr[left], t) === 0) swap(arr, left, j);
4764 swap(arr, j, right);
4767 if (j <= k) left = j + 1;
4768 if (k <= j) right = j - 1;
4772 function swap(arr, i, j) {
4778 function defaultCompare(a, b) {
4779 return a < b ? -1 : a > b ? 1 : 0;
4782 },{}],25:[function(require,module,exports){
4785 module.exports = rbush;
4787 var quickselect = require('quickselect');
4789 function rbush(maxEntries, format) {
4790 if (!(this instanceof rbush)) return new rbush(maxEntries, format);
4792 // max entries in a node is 9 by default; min node fill is 40% for best performance
4793 this._maxEntries = Math.max(4, maxEntries || 9);
4794 this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
4797 this._initFormat(format);
4806 return this._all(this.data, []);
4809 search: function (bbox) {
4811 var node = this.data,
4813 toBBox = this.toBBox;
4815 if (!intersects(bbox, node)) return result;
4817 var nodesToSearch = [],
4818 i, len, child, childBBox;
4821 for (i = 0, len = node.children.length; i < len; i++) {
4823 child = node.children[i];
4824 childBBox = node.leaf ? toBBox(child) : child;
4826 if (intersects(bbox, childBBox)) {
4827 if (node.leaf) result.push(child);
4828 else if (contains(bbox, childBBox)) this._all(child, result);
4829 else nodesToSearch.push(child);
4832 node = nodesToSearch.pop();
4838 collides: function (bbox) {
4840 var node = this.data,
4841 toBBox = this.toBBox;
4843 if (!intersects(bbox, node)) return false;
4845 var nodesToSearch = [],
4846 i, len, child, childBBox;
4849 for (i = 0, len = node.children.length; i < len; i++) {
4851 child = node.children[i];
4852 childBBox = node.leaf ? toBBox(child) : child;
4854 if (intersects(bbox, childBBox)) {
4855 if (node.leaf || contains(bbox, childBBox)) return true;
4856 nodesToSearch.push(child);
4859 node = nodesToSearch.pop();
4865 load: function (data) {
4866 if (!(data && data.length)) return this;
4868 if (data.length < this._minEntries) {
4869 for (var i = 0, len = data.length; i < len; i++) {
4870 this.insert(data[i]);
4875 // recursively build the tree with the given data from stratch using OMT algorithm
4876 var node = this._build(data.slice(), 0, data.length - 1, 0);
4878 if (!this.data.children.length) {
4879 // save as is if tree is empty
4882 } else if (this.data.height === node.height) {
4883 // split root if trees have the same height
4884 this._splitRoot(this.data, node);
4887 if (this.data.height < node.height) {
4888 // swap trees if inserted one is bigger
4889 var tmpNode = this.data;
4894 // insert the small tree into the large tree at appropriate level
4895 this._insert(node, this.data.height - node.height - 1, true);
4901 insert: function (item) {
4902 if (item) this._insert(item, this.data.height - 1);
4906 clear: function () {
4907 this.data = createNode([]);
4911 remove: function (item, equalsFn) {
4912 if (!item) return this;
4914 var node = this.data,
4915 bbox = this.toBBox(item),
4918 i, parent, index, goingUp;
4920 // depth-first iterative tree traversal
4921 while (node || path.length) {
4923 if (!node) { // go up
4925 parent = path[path.length - 1];
4930 if (node.leaf) { // check current node
4931 index = findItem(item, node.children, equalsFn);
4934 // item found, remove the item and condense tree upwards
4935 node.children.splice(index, 1);
4937 this._condense(path);
4942 if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
4947 node = node.children[0];
4949 } else if (parent) { // go right
4951 node = parent.children[i];
4954 } else node = null; // nothing found
4960 toBBox: function (item) { return item; },
4962 compareMinX: compareNodeMinX,
4963 compareMinY: compareNodeMinY,
4965 toJSON: function () { return this.data; },
4967 fromJSON: function (data) {
4972 _all: function (node, result) {
4973 var nodesToSearch = [];
4975 if (node.leaf) result.push.apply(result, node.children);
4976 else nodesToSearch.push.apply(nodesToSearch, node.children);
4978 node = nodesToSearch.pop();
4983 _build: function (items, left, right, height) {
4985 var N = right - left + 1,
4986 M = this._maxEntries,
4990 // reached leaf level; return leaf
4991 node = createNode(items.slice(left, right + 1));
4992 calcBBox(node, this.toBBox);
4997 // target height of the bulk-loaded tree
4998 height = Math.ceil(Math.log(N) / Math.log(M));
5000 // target number of root entries to maximize storage utilization
5001 M = Math.ceil(N / Math.pow(M, height - 1));
5004 node = createNode([]);
5006 node.height = height;
5008 // split the items into M mostly square tiles
5010 var N2 = Math.ceil(N / M),
5011 N1 = N2 * Math.ceil(Math.sqrt(M)),
5012 i, j, right2, right3;
5014 multiSelect(items, left, right, N1, this.compareMinX);
5016 for (i = left; i <= right; i += N1) {
5018 right2 = Math.min(i + N1 - 1, right);
5020 multiSelect(items, i, right2, N2, this.compareMinY);
5022 for (j = i; j <= right2; j += N2) {
5024 right3 = Math.min(j + N2 - 1, right2);
5026 // pack each entry recursively
5027 node.children.push(this._build(items, j, right3, height - 1));
5031 calcBBox(node, this.toBBox);
5036 _chooseSubtree: function (bbox, node, level, path) {
5038 var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
5043 if (node.leaf || path.length - 1 === level) break;
5045 minArea = minEnlargement = Infinity;
5047 for (i = 0, len = node.children.length; i < len; i++) {
5048 child = node.children[i];
5049 area = bboxArea(child);
5050 enlargement = enlargedArea(bbox, child) - area;
5052 // choose entry with the least area enlargement
5053 if (enlargement < minEnlargement) {
5054 minEnlargement = enlargement;
5055 minArea = area < minArea ? area : minArea;
5058 } else if (enlargement === minEnlargement) {
5059 // otherwise choose one with the smallest area
5060 if (area < minArea) {
5067 node = targetNode || node.children[0];
5073 _insert: function (item, level, isNode) {
5075 var toBBox = this.toBBox,
5076 bbox = isNode ? item : toBBox(item),
5079 // find the best node for accommodating the item, saving all nodes along the path too
5080 var node = this._chooseSubtree(bbox, this.data, level, insertPath);
5082 // put the item into the node
5083 node.children.push(item);
5086 // split on node overflow; propagate upwards if necessary
5087 while (level >= 0) {
5088 if (insertPath[level].children.length > this._maxEntries) {
5089 this._split(insertPath, level);
5094 // adjust bboxes along the insertion path
5095 this._adjustParentBBoxes(bbox, insertPath, level);
5098 // split overflowed node into two
5099 _split: function (insertPath, level) {
5101 var node = insertPath[level],
5102 M = node.children.length,
5103 m = this._minEntries;
5105 this._chooseSplitAxis(node, m, M);
5107 var splitIndex = this._chooseSplitIndex(node, m, M);
5109 var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
5110 newNode.height = node.height;
5111 newNode.leaf = node.leaf;
5113 calcBBox(node, this.toBBox);
5114 calcBBox(newNode, this.toBBox);
5116 if (level) insertPath[level - 1].children.push(newNode);
5117 else this._splitRoot(node, newNode);
5120 _splitRoot: function (node, newNode) {
5122 this.data = createNode([node, newNode]);
5123 this.data.height = node.height + 1;
5124 this.data.leaf = false;
5125 calcBBox(this.data, this.toBBox);
5128 _chooseSplitIndex: function (node, m, M) {
5130 var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
5132 minOverlap = minArea = Infinity;
5134 for (i = m; i <= M - m; i++) {
5135 bbox1 = distBBox(node, 0, i, this.toBBox);
5136 bbox2 = distBBox(node, i, M, this.toBBox);
5138 overlap = intersectionArea(bbox1, bbox2);
5139 area = bboxArea(bbox1) + bboxArea(bbox2);
5141 // choose distribution with minimum overlap
5142 if (overlap < minOverlap) {
5143 minOverlap = overlap;
5146 minArea = area < minArea ? area : minArea;
5148 } else if (overlap === minOverlap) {
5149 // otherwise choose distribution with minimum area
5150 if (area < minArea) {
5160 // sorts node children by the best axis for split
5161 _chooseSplitAxis: function (node, m, M) {
5163 var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
5164 compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
5165 xMargin = this._allDistMargin(node, m, M, compareMinX),
5166 yMargin = this._allDistMargin(node, m, M, compareMinY);
5168 // if total distributions margin value is minimal for x, sort by minX,
5169 // otherwise it's already sorted by minY
5170 if (xMargin < yMargin) node.children.sort(compareMinX);
5173 // total margin of all possible split distributions where each node is at least m full
5174 _allDistMargin: function (node, m, M, compare) {
5176 node.children.sort(compare);
5178 var toBBox = this.toBBox,
5179 leftBBox = distBBox(node, 0, m, toBBox),
5180 rightBBox = distBBox(node, M - m, M, toBBox),
5181 margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
5184 for (i = m; i < M - m; i++) {
5185 child = node.children[i];
5186 extend(leftBBox, node.leaf ? toBBox(child) : child);
5187 margin += bboxMargin(leftBBox);
5190 for (i = M - m - 1; i >= m; i--) {
5191 child = node.children[i];
5192 extend(rightBBox, node.leaf ? toBBox(child) : child);
5193 margin += bboxMargin(rightBBox);
5199 _adjustParentBBoxes: function (bbox, path, level) {
5200 // adjust bboxes along the given tree path
5201 for (var i = level; i >= 0; i--) {
5202 extend(path[i], bbox);
5206 _condense: function (path) {
5207 // go through the path, removing empty nodes and updating bboxes
5208 for (var i = path.length - 1, siblings; i >= 0; i--) {
5209 if (path[i].children.length === 0) {
5211 siblings = path[i - 1].children;
5212 siblings.splice(siblings.indexOf(path[i]), 1);
5214 } else this.clear();
5216 } else calcBBox(path[i], this.toBBox);
5220 _initFormat: function (format) {
5221 // data format (minX, minY, maxX, maxY accessors)
5223 // uses eval-type function compilation instead of just accepting a toBBox function
5224 // because the algorithms are very sensitive to sorting functions performance,
5225 // so they should be dead simple and without inner calls
5227 var compareArr = ['return a', ' - b', ';'];
5229 this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
5230 this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
5232 this.toBBox = new Function('a',
5233 'return {minX: a' + format[0] +
5234 ', minY: a' + format[1] +
5235 ', maxX: a' + format[2] +
5236 ', maxY: a' + format[3] + '};');
5240 function findItem(item, items, equalsFn) {
5241 if (!equalsFn) return items.indexOf(item);
5243 for (var i = 0; i < items.length; i++) {
5244 if (equalsFn(item, items[i])) return i;
5249 // calculate node's bbox from bboxes of its children
5250 function calcBBox(node, toBBox) {
5251 distBBox(node, 0, node.children.length, toBBox, node);
5254 // min bounding rectangle of node children from k to p-1
5255 function distBBox(node, k, p, toBBox, destNode) {
5256 if (!destNode) destNode = createNode(null);
5257 destNode.minX = Infinity;
5258 destNode.minY = Infinity;
5259 destNode.maxX = -Infinity;
5260 destNode.maxY = -Infinity;
5262 for (var i = k, child; i < p; i++) {
5263 child = node.children[i];
5264 extend(destNode, node.leaf ? toBBox(child) : child);
5270 function extend(a, b) {
5271 a.minX = Math.min(a.minX, b.minX);
5272 a.minY = Math.min(a.minY, b.minY);
5273 a.maxX = Math.max(a.maxX, b.maxX);
5274 a.maxY = Math.max(a.maxY, b.maxY);
5278 function compareNodeMinX(a, b) { return a.minX - b.minX; }
5279 function compareNodeMinY(a, b) { return a.minY - b.minY; }
5281 function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); }
5282 function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
5284 function enlargedArea(a, b) {
5285 return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
5286 (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
5289 function intersectionArea(a, b) {
5290 var minX = Math.max(a.minX, b.minX),
5291 minY = Math.max(a.minY, b.minY),
5292 maxX = Math.min(a.maxX, b.maxX),
5293 maxY = Math.min(a.maxY, b.maxY);
5295 return Math.max(0, maxX - minX) *
5296 Math.max(0, maxY - minY);
5299 function contains(a, b) {
5300 return a.minX <= b.minX &&
5306 function intersects(a, b) {
5307 return b.minX <= a.maxX &&
5313 function createNode(children) {
5325 // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
5326 // combines selection algorithm with binary divide & conquer approach
5328 function multiSelect(arr, left, right, n, compare) {
5329 var stack = [left, right],
5332 while (stack.length) {
5333 right = stack.pop();
5336 if (right - left <= n) continue;
5338 mid = left + Math.ceil((right - left) / n / 2) * n;
5339 quickselect(arr, mid, left, right, compare);
5341 stack.push(left, mid, mid, right);
5345 },{"quickselect":24}],26:[function(require,module,exports){
5347 var __extends = (this && this.__extends) || function (d, b) {
5348 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5349 function __() { this.constructor = d; }
5350 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5352 var Subject_1 = require('./Subject');
5353 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5355 * @class BehaviorSubject<T>
5357 var BehaviorSubject = (function (_super) {
5358 __extends(BehaviorSubject, _super);
5359 function BehaviorSubject(_value) {
5361 this._value = _value;
5363 Object.defineProperty(BehaviorSubject.prototype, "value", {
5365 return this.getValue();
5370 BehaviorSubject.prototype._subscribe = function (subscriber) {
5371 var subscription = _super.prototype._subscribe.call(this, subscriber);
5372 if (subscription && !subscription.closed) {
5373 subscriber.next(this._value);
5375 return subscription;
5377 BehaviorSubject.prototype.getValue = function () {
5378 if (this.hasError) {
5379 throw this.thrownError;
5381 else if (this.closed) {
5382 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5388 BehaviorSubject.prototype.next = function (value) {
5389 _super.prototype.next.call(this, this._value = value);
5391 return BehaviorSubject;
5392 }(Subject_1.Subject));
5393 exports.BehaviorSubject = BehaviorSubject;
5395 },{"./Subject":34,"./util/ObjectUnsubscribedError":160}],27:[function(require,module,exports){
5397 var __extends = (this && this.__extends) || function (d, b) {
5398 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5399 function __() { this.constructor = d; }
5400 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5402 var Subscriber_1 = require('./Subscriber');
5404 * We need this JSDoc comment for affecting ESDoc.
5406 * @extends {Ignored}
5408 var InnerSubscriber = (function (_super) {
5409 __extends(InnerSubscriber, _super);
5410 function InnerSubscriber(parent, outerValue, outerIndex) {
5412 this.parent = parent;
5413 this.outerValue = outerValue;
5414 this.outerIndex = outerIndex;
5417 InnerSubscriber.prototype._next = function (value) {
5418 this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
5420 InnerSubscriber.prototype._error = function (error) {
5421 this.parent.notifyError(error, this);
5424 InnerSubscriber.prototype._complete = function () {
5425 this.parent.notifyComplete(this);
5428 return InnerSubscriber;
5429 }(Subscriber_1.Subscriber));
5430 exports.InnerSubscriber = InnerSubscriber;
5432 },{"./Subscriber":36}],28:[function(require,module,exports){
5434 var Observable_1 = require('./Observable');
5436 * Represents a push-based event or value that an {@link Observable} can emit.
5437 * This class is particularly useful for operators that manage notifications,
5438 * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and
5439 * others. Besides wrapping the actual delivered value, it also annotates it
5440 * with metadata of, for instance, what type of push message it is (`next`,
5441 * `error`, or `complete`).
5443 * @see {@link materialize}
5444 * @see {@link dematerialize}
5445 * @see {@link observeOn}
5447 * @class Notification<T>
5449 var Notification = (function () {
5450 function Notification(kind, value, error) {
5454 this.hasValue = kind === 'N';
5457 * Delivers to the given `observer` the value wrapped by this Notification.
5458 * @param {Observer} observer
5461 Notification.prototype.observe = function (observer) {
5462 switch (this.kind) {
5464 return observer.next && observer.next(this.value);
5466 return observer.error && observer.error(this.error);
5468 return observer.complete && observer.complete();
5472 * Given some {@link Observer} callbacks, deliver the value represented by the
5473 * current Notification to the correctly corresponding callback.
5474 * @param {function(value: T): void} next An Observer `next` callback.
5475 * @param {function(err: any): void} [error] An Observer `error` callback.
5476 * @param {function(): void} [complete] An Observer `complete` callback.
5479 Notification.prototype.do = function (next, error, complete) {
5480 var kind = this.kind;
5483 return next && next(this.value);
5485 return error && error(this.error);
5487 return complete && complete();
5491 * Takes an Observer or its individual callback functions, and calls `observe`
5492 * or `do` methods accordingly.
5493 * @param {Observer|function(value: T): void} nextOrObserver An Observer or
5494 * the `next` callback.
5495 * @param {function(err: any): void} [error] An Observer `error` callback.
5496 * @param {function(): void} [complete] An Observer `complete` callback.
5499 Notification.prototype.accept = function (nextOrObserver, error, complete) {
5500 if (nextOrObserver && typeof nextOrObserver.next === 'function') {
5501 return this.observe(nextOrObserver);
5504 return this.do(nextOrObserver, error, complete);
5508 * Returns a simple Observable that just delivers the notification represented
5509 * by this Notification instance.
5512 Notification.prototype.toObservable = function () {
5513 var kind = this.kind;
5516 return Observable_1.Observable.of(this.value);
5518 return Observable_1.Observable.throw(this.error);
5520 return Observable_1.Observable.empty();
5522 throw new Error('unexpected notification kind value');
5525 * A shortcut to create a Notification instance of the type `next` from a
5527 * @param {T} value The `next` value.
5528 * @return {Notification<T>} The "next" Notification representing the
5531 Notification.createNext = function (value) {
5532 if (typeof value !== 'undefined') {
5533 return new Notification('N', value);
5535 return this.undefinedValueNotification;
5538 * A shortcut to create a Notification instance of the type `error` from a
5540 * @param {any} [err] The `error` error.
5541 * @return {Notification<T>} The "error" Notification representing the
5544 Notification.createError = function (err) {
5545 return new Notification('E', undefined, err);
5548 * A shortcut to create a Notification instance of the type `complete`.
5549 * @return {Notification<any>} The valueless "complete" Notification.
5551 Notification.createComplete = function () {
5552 return this.completeNotification;
5554 Notification.completeNotification = new Notification('C');
5555 Notification.undefinedValueNotification = new Notification('N', undefined);
5556 return Notification;
5558 exports.Notification = Notification;
5560 },{"./Observable":29}],29:[function(require,module,exports){
5562 var root_1 = require('./util/root');
5563 var toSubscriber_1 = require('./util/toSubscriber');
5564 var observable_1 = require('./symbol/observable');
5566 * A representation of any set of values over any amount of time. This the most basic building block
5569 * @class Observable<T>
5571 var Observable = (function () {
5574 * @param {Function} subscribe the function that is called when the Observable is
5575 * initially subscribed to. This function is given a Subscriber, to which new values
5576 * can be `next`ed, or an `error` method can be called to raise an error, or
5577 * `complete` can be called to notify of a successful completion.
5579 function Observable(subscribe) {
5580 this._isScalar = false;
5582 this._subscribe = subscribe;
5586 * Creates a new Observable, with this Observable as the source, and the passed
5587 * operator defined as the new observable's operator.
5589 * @param {Operator} operator the operator defining the operation to take on the observable
5590 * @return {Observable} a new observable with the Operator applied
5592 Observable.prototype.lift = function (operator) {
5593 var observable = new Observable();
5594 observable.source = this;
5595 observable.operator = operator;
5599 * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
5601 * <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
5603 * `subscribe` is not a regular operator, but a method that calls Observables internal `subscribe` function. It
5604 * might be for example a function that you passed to a {@link create} static factory, but most of the time it is
5605 * a library implementation, which defines what and when will be emitted by an Observable. This means that calling
5606 * `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
5609 * Apart from starting the execution of an Observable, this method allows you to listen for values
5610 * that an Observable emits, as well as for when it completes or errors. You can achieve this in two
5613 * The first way is creating an object that implements {@link Observer} interface. It should have methods
5614 * defined by that interface, but note that it should be just a regular JavaScript object, which you can create
5615 * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do
5616 * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
5617 * that your object does not have to implement all methods. If you find yourself creating a method that doesn't
5618 * do anything, you can simply omit it. Note however, that if `error` method is not provided, all errors will
5621 * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
5622 * This means you can provide three functions as arguments to `subscribe`, where first function is equivalent
5623 * of a `next` method, second of an `error` method and third of a `complete` method. Just as in case of Observer,
5624 * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,
5625 * since `subscribe` recognizes these functions by where they were placed in function call. When it comes
5626 * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.
5628 * Whatever style of calling `subscribe` you use, in both cases it returns a Subscription object.
5629 * This object allows you to call `unsubscribe` on it, which in turn will stop work that an Observable does and will clean
5630 * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
5631 * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
5633 * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
5634 * It is an Observable itself that decides when these functions will be called. For example {@link of}
5635 * by default emits all its values synchronously. Always check documentation for how given Observable
5636 * will behave when subscribed and if its default behavior can be modified with a {@link Scheduler}.
5638 * @example <caption>Subscribe with an Observer</caption>
5639 * const sumObserver = {
5642 * console.log('Adding: ' + value);
5643 * this.sum = this.sum + value;
5645 * error() { // We actually could just remote this method,
5646 * }, // since we do not really care about errors right now.
5648 * console.log('Sum equals: ' + this.sum);
5652 * Rx.Observable.of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
5653 * .subscribe(sumObserver);
5659 * // "Sum equals: 6"
5662 * @example <caption>Subscribe with functions</caption>
5665 * Rx.Observable.of(1, 2, 3)
5668 * console.log('Adding: ' + value);
5669 * sum = sum + value;
5673 * console.log('Sum equals: ' + sum);
5681 * // "Sum equals: 6"
5684 * @example <caption>Cancel a subscription</caption>
5685 * const subscription = Rx.Observable.interval(1000).subscribe(
5686 * num => console.log(num),
5688 * () => console.log('completed!') // Will not be called, even
5689 * ); // when cancelling subscription
5692 * setTimeout(() => {
5693 * subscription.unsubscribe();
5694 * console.log('unsubscribed!');
5700 * // "unsubscribed!" after 2,5s
5703 * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,
5704 * or the first of three possible handlers, which is the handler for each value emitted from the subscribed
5706 * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,
5707 * the error will be thrown as unhandled.
5708 * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.
5709 * @return {ISubscription} a subscription reference to the registered handlers
5712 Observable.prototype.subscribe = function (observerOrNext, error, complete) {
5713 var operator = this.operator;
5714 var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
5716 operator.call(sink, this.source);
5719 sink.add(this.source ? this._subscribe(sink) : this._trySubscribe(sink));
5721 if (sink.syncErrorThrowable) {
5722 sink.syncErrorThrowable = false;
5723 if (sink.syncErrorThrown) {
5724 throw sink.syncErrorValue;
5729 Observable.prototype._trySubscribe = function (sink) {
5731 return this._subscribe(sink);
5734 sink.syncErrorThrown = true;
5735 sink.syncErrorValue = err;
5741 * @param {Function} next a handler for each value emitted by the observable
5742 * @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
5743 * @return {Promise} a promise that either resolves on observable completion or
5744 * rejects with the handled error
5746 Observable.prototype.forEach = function (next, PromiseCtor) {
5749 if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
5750 PromiseCtor = root_1.root.Rx.config.Promise;
5752 else if (root_1.root.Promise) {
5753 PromiseCtor = root_1.root.Promise;
5757 throw new Error('no Promise impl found');
5759 return new PromiseCtor(function (resolve, reject) {
5760 // Must be declared in a separate statement to avoid a RefernceError when
5761 // accessing subscription below in the closure due to Temporal Dead Zone.
5763 subscription = _this.subscribe(function (value) {
5765 // if there is a subscription, then we can surmise
5766 // the next handling is asynchronous. Any errors thrown
5767 // need to be rejected explicitly and unsubscribe must be
5774 subscription.unsubscribe();
5778 // if there is NO subscription, then we're getting a nexted
5779 // value synchronously during subscription. We can just call it.
5780 // If it errors, Observable's `subscribe` will ensure the
5781 // unsubscription logic is called, then synchronously rethrow the error.
5782 // After that, Promise will trap the error and send it
5783 // down the rejection path.
5786 }, reject, resolve);
5789 Observable.prototype._subscribe = function (subscriber) {
5790 return this.source.subscribe(subscriber);
5793 * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
5794 * @method Symbol.observable
5795 * @return {Observable} this instance of the observable
5797 Observable.prototype[observable_1.observable] = function () {
5800 // HACK: Since TypeScript inherits static properties too, we have to
5801 // fight against TypeScript here so Subject can have a different static create signature
5803 * Creates a new cold Observable by calling the Observable constructor
5807 * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
5808 * @return {Observable} a new cold observable
5810 Observable.create = function (subscribe) {
5811 return new Observable(subscribe);
5815 exports.Observable = Observable;
5817 },{"./symbol/observable":155,"./util/root":172,"./util/toSubscriber":174}],30:[function(require,module,exports){
5821 next: function (value) { },
5822 error: function (err) { throw err; },
5823 complete: function () { }
5826 },{}],31:[function(require,module,exports){
5828 var __extends = (this && this.__extends) || function (d, b) {
5829 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5830 function __() { this.constructor = d; }
5831 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5833 var Subscriber_1 = require('./Subscriber');
5835 * We need this JSDoc comment for affecting ESDoc.
5837 * @extends {Ignored}
5839 var OuterSubscriber = (function (_super) {
5840 __extends(OuterSubscriber, _super);
5841 function OuterSubscriber() {
5842 _super.apply(this, arguments);
5844 OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
5845 this.destination.next(innerValue);
5847 OuterSubscriber.prototype.notifyError = function (error, innerSub) {
5848 this.destination.error(error);
5850 OuterSubscriber.prototype.notifyComplete = function (innerSub) {
5851 this.destination.complete();
5853 return OuterSubscriber;
5854 }(Subscriber_1.Subscriber));
5855 exports.OuterSubscriber = OuterSubscriber;
5857 },{"./Subscriber":36}],32:[function(require,module,exports){
5859 var __extends = (this && this.__extends) || function (d, b) {
5860 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5861 function __() { this.constructor = d; }
5862 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5864 var Subject_1 = require('./Subject');
5865 var queue_1 = require('./scheduler/queue');
5866 var Subscription_1 = require('./Subscription');
5867 var observeOn_1 = require('./operator/observeOn');
5868 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5869 var SubjectSubscription_1 = require('./SubjectSubscription');
5871 * @class ReplaySubject<T>
5873 var ReplaySubject = (function (_super) {
5874 __extends(ReplaySubject, _super);
5875 function ReplaySubject(bufferSize, windowTime, scheduler) {
5876 if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
5877 if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
5879 this.scheduler = scheduler;
5881 this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
5882 this._windowTime = windowTime < 1 ? 1 : windowTime;
5884 ReplaySubject.prototype.next = function (value) {
5885 var now = this._getNow();
5886 this._events.push(new ReplayEvent(now, value));
5887 this._trimBufferThenGetEvents();
5888 _super.prototype.next.call(this, value);
5890 ReplaySubject.prototype._subscribe = function (subscriber) {
5891 var _events = this._trimBufferThenGetEvents();
5892 var scheduler = this.scheduler;
5895 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5897 else if (this.hasError) {
5898 subscription = Subscription_1.Subscription.EMPTY;
5900 else if (this.isStopped) {
5901 subscription = Subscription_1.Subscription.EMPTY;
5904 this.observers.push(subscriber);
5905 subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber);
5908 subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler));
5910 var len = _events.length;
5911 for (var i = 0; i < len && !subscriber.closed; i++) {
5912 subscriber.next(_events[i].value);
5914 if (this.hasError) {
5915 subscriber.error(this.thrownError);
5917 else if (this.isStopped) {
5918 subscriber.complete();
5920 return subscription;
5922 ReplaySubject.prototype._getNow = function () {
5923 return (this.scheduler || queue_1.queue).now();
5925 ReplaySubject.prototype._trimBufferThenGetEvents = function () {
5926 var now = this._getNow();
5927 var _bufferSize = this._bufferSize;
5928 var _windowTime = this._windowTime;
5929 var _events = this._events;
5930 var eventsCount = _events.length;
5931 var spliceCount = 0;
5932 // Trim events that fall out of the time window.
5933 // Start at the front of the list. Break early once
5934 // we encounter an event that falls within the window.
5935 while (spliceCount < eventsCount) {
5936 if ((now - _events[spliceCount].time) < _windowTime) {
5941 if (eventsCount > _bufferSize) {
5942 spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
5944 if (spliceCount > 0) {
5945 _events.splice(0, spliceCount);
5949 return ReplaySubject;
5950 }(Subject_1.Subject));
5951 exports.ReplaySubject = ReplaySubject;
5952 var ReplayEvent = (function () {
5953 function ReplayEvent(time, value) {
5960 },{"./Subject":34,"./SubjectSubscription":35,"./Subscription":37,"./operator/observeOn":129,"./scheduler/queue":153,"./util/ObjectUnsubscribedError":160}],33:[function(require,module,exports){
5963 * An execution context and a data structure to order tasks and schedule their
5964 * execution. Provides a notion of (potentially virtual) time, through the
5965 * `now()` getter method.
5967 * Each unit of work in a Scheduler is called an {@link Action}.
5972 * schedule(work, delay?, state?): Subscription;
5978 var Scheduler = (function () {
5979 function Scheduler(SchedulerAction, now) {
5980 if (now === void 0) { now = Scheduler.now; }
5981 this.SchedulerAction = SchedulerAction;
5985 * Schedules a function, `work`, for execution. May happen at some point in
5986 * the future, according to the `delay` parameter, if specified. May be passed
5987 * some context object, `state`, which will be passed to the `work` function.
5989 * The given arguments will be processed an stored as an Action object in a
5992 * @param {function(state: ?T): ?Subscription} work A function representing a
5993 * task, or some unit of work to be executed by the Scheduler.
5994 * @param {number} [delay] Time to wait before executing the work, where the
5995 * time unit is implicit and defined by the Scheduler itself.
5996 * @param {T} [state] Some contextual data that the `work` function uses when
5997 * called by the Scheduler.
5998 * @return {Subscription} A subscription in order to be able to unsubscribe
5999 * the scheduled work.
6001 Scheduler.prototype.schedule = function (work, delay, state) {
6002 if (delay === void 0) { delay = 0; }
6003 return new this.SchedulerAction(this, work).schedule(state, delay);
6005 Scheduler.now = Date.now ? Date.now : function () { return +new Date(); };
6008 exports.Scheduler = Scheduler;
6010 },{}],34:[function(require,module,exports){
6012 var __extends = (this && this.__extends) || function (d, b) {
6013 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6014 function __() { this.constructor = d; }
6015 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6017 var Observable_1 = require('./Observable');
6018 var Subscriber_1 = require('./Subscriber');
6019 var Subscription_1 = require('./Subscription');
6020 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
6021 var SubjectSubscription_1 = require('./SubjectSubscription');
6022 var rxSubscriber_1 = require('./symbol/rxSubscriber');
6024 * @class SubjectSubscriber<T>
6026 var SubjectSubscriber = (function (_super) {
6027 __extends(SubjectSubscriber, _super);
6028 function SubjectSubscriber(destination) {
6029 _super.call(this, destination);
6030 this.destination = destination;
6032 return SubjectSubscriber;
6033 }(Subscriber_1.Subscriber));
6034 exports.SubjectSubscriber = SubjectSubscriber;
6038 var Subject = (function (_super) {
6039 __extends(Subject, _super);
6040 function Subject() {
6042 this.observers = [];
6043 this.closed = false;
6044 this.isStopped = false;
6045 this.hasError = false;
6046 this.thrownError = null;
6048 Subject.prototype[rxSubscriber_1.rxSubscriber] = function () {
6049 return new SubjectSubscriber(this);
6051 Subject.prototype.lift = function (operator) {
6052 var subject = new AnonymousSubject(this, this);
6053 subject.operator = operator;
6056 Subject.prototype.next = function (value) {
6058 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6060 if (!this.isStopped) {
6061 var observers = this.observers;
6062 var len = observers.length;
6063 var copy = observers.slice();
6064 for (var i = 0; i < len; i++) {
6065 copy[i].next(value);
6069 Subject.prototype.error = function (err) {
6071 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6073 this.hasError = true;
6074 this.thrownError = err;
6075 this.isStopped = true;
6076 var observers = this.observers;
6077 var len = observers.length;
6078 var copy = observers.slice();
6079 for (var i = 0; i < len; i++) {
6082 this.observers.length = 0;
6084 Subject.prototype.complete = function () {
6086 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6088 this.isStopped = true;
6089 var observers = this.observers;
6090 var len = observers.length;
6091 var copy = observers.slice();
6092 for (var i = 0; i < len; i++) {
6095 this.observers.length = 0;
6097 Subject.prototype.unsubscribe = function () {
6098 this.isStopped = true;
6100 this.observers = null;
6102 Subject.prototype._trySubscribe = function (subscriber) {
6104 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6107 return _super.prototype._trySubscribe.call(this, subscriber);
6110 Subject.prototype._subscribe = function (subscriber) {
6112 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6114 else if (this.hasError) {
6115 subscriber.error(this.thrownError);
6116 return Subscription_1.Subscription.EMPTY;
6118 else if (this.isStopped) {
6119 subscriber.complete();
6120 return Subscription_1.Subscription.EMPTY;
6123 this.observers.push(subscriber);
6124 return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
6127 Subject.prototype.asObservable = function () {
6128 var observable = new Observable_1.Observable();
6129 observable.source = this;
6132 Subject.create = function (destination, source) {
6133 return new AnonymousSubject(destination, source);
6136 }(Observable_1.Observable));
6137 exports.Subject = Subject;
6139 * @class AnonymousSubject<T>
6141 var AnonymousSubject = (function (_super) {
6142 __extends(AnonymousSubject, _super);
6143 function AnonymousSubject(destination, source) {
6145 this.destination = destination;
6146 this.source = source;
6148 AnonymousSubject.prototype.next = function (value) {
6149 var destination = this.destination;
6150 if (destination && destination.next) {
6151 destination.next(value);
6154 AnonymousSubject.prototype.error = function (err) {
6155 var destination = this.destination;
6156 if (destination && destination.error) {
6157 this.destination.error(err);
6160 AnonymousSubject.prototype.complete = function () {
6161 var destination = this.destination;
6162 if (destination && destination.complete) {
6163 this.destination.complete();
6166 AnonymousSubject.prototype._subscribe = function (subscriber) {
6167 var source = this.source;
6169 return this.source.subscribe(subscriber);
6172 return Subscription_1.Subscription.EMPTY;
6175 return AnonymousSubject;
6177 exports.AnonymousSubject = AnonymousSubject;
6179 },{"./Observable":29,"./SubjectSubscription":35,"./Subscriber":36,"./Subscription":37,"./symbol/rxSubscriber":156,"./util/ObjectUnsubscribedError":160}],35:[function(require,module,exports){
6181 var __extends = (this && this.__extends) || function (d, b) {
6182 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6183 function __() { this.constructor = d; }
6184 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6186 var Subscription_1 = require('./Subscription');
6188 * We need this JSDoc comment for affecting ESDoc.
6190 * @extends {Ignored}
6192 var SubjectSubscription = (function (_super) {
6193 __extends(SubjectSubscription, _super);
6194 function SubjectSubscription(subject, subscriber) {
6196 this.subject = subject;
6197 this.subscriber = subscriber;
6198 this.closed = false;
6200 SubjectSubscription.prototype.unsubscribe = function () {
6205 var subject = this.subject;
6206 var observers = subject.observers;
6207 this.subject = null;
6208 if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
6211 var subscriberIndex = observers.indexOf(this.subscriber);
6212 if (subscriberIndex !== -1) {
6213 observers.splice(subscriberIndex, 1);
6216 return SubjectSubscription;
6217 }(Subscription_1.Subscription));
6218 exports.SubjectSubscription = SubjectSubscription;
6220 },{"./Subscription":37}],36:[function(require,module,exports){
6222 var __extends = (this && this.__extends) || function (d, b) {
6223 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6224 function __() { this.constructor = d; }
6225 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6227 var isFunction_1 = require('./util/isFunction');
6228 var Subscription_1 = require('./Subscription');
6229 var Observer_1 = require('./Observer');
6230 var rxSubscriber_1 = require('./symbol/rxSubscriber');
6232 * Implements the {@link Observer} interface and extends the
6233 * {@link Subscription} class. While the {@link Observer} is the public API for
6234 * consuming the values of an {@link Observable}, all Observers get converted to
6235 * a Subscriber, in order to provide Subscription-like capabilities such as
6236 * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
6237 * implementing operators, but it is rarely used as a public API.
6239 * @class Subscriber<T>
6241 var Subscriber = (function (_super) {
6242 __extends(Subscriber, _super);
6244 * @param {Observer|function(value: T): void} [destinationOrNext] A partially
6245 * defined Observer or a `next` callback function.
6246 * @param {function(e: ?any): void} [error] The `error` callback of an
6248 * @param {function(): void} [complete] The `complete` callback of an
6251 function Subscriber(destinationOrNext, error, complete) {
6253 this.syncErrorValue = null;
6254 this.syncErrorThrown = false;
6255 this.syncErrorThrowable = false;
6256 this.isStopped = false;
6257 switch (arguments.length) {
6259 this.destination = Observer_1.empty;
6262 if (!destinationOrNext) {
6263 this.destination = Observer_1.empty;
6266 if (typeof destinationOrNext === 'object') {
6267 if (destinationOrNext instanceof Subscriber) {
6268 this.destination = destinationOrNext;
6269 this.destination.add(this);
6272 this.syncErrorThrowable = true;
6273 this.destination = new SafeSubscriber(this, destinationOrNext);
6278 this.syncErrorThrowable = true;
6279 this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
6283 Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function () { return this; };
6285 * A static factory for a Subscriber, given a (potentially partial) definition
6287 * @param {function(x: ?T): void} [next] The `next` callback of an Observer.
6288 * @param {function(e: ?any): void} [error] The `error` callback of an
6290 * @param {function(): void} [complete] The `complete` callback of an
6292 * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
6293 * Observer represented by the given arguments.
6295 Subscriber.create = function (next, error, complete) {
6296 var subscriber = new Subscriber(next, error, complete);
6297 subscriber.syncErrorThrowable = false;
6301 * The {@link Observer} callback to receive notifications of type `next` from
6302 * the Observable, with a value. The Observable may call this method 0 or more
6304 * @param {T} [value] The `next` value.
6307 Subscriber.prototype.next = function (value) {
6308 if (!this.isStopped) {
6313 * The {@link Observer} callback to receive notifications of type `error` from
6314 * the Observable, with an attached {@link Error}. Notifies the Observer that
6315 * the Observable has experienced an error condition.
6316 * @param {any} [err] The `error` exception.
6319 Subscriber.prototype.error = function (err) {
6320 if (!this.isStopped) {
6321 this.isStopped = true;
6326 * The {@link Observer} callback to receive a valueless notification of type
6327 * `complete` from the Observable. Notifies the Observer that the Observable
6328 * has finished sending push-based notifications.
6331 Subscriber.prototype.complete = function () {
6332 if (!this.isStopped) {
6333 this.isStopped = true;
6337 Subscriber.prototype.unsubscribe = function () {
6341 this.isStopped = true;
6342 _super.prototype.unsubscribe.call(this);
6344 Subscriber.prototype._next = function (value) {
6345 this.destination.next(value);
6347 Subscriber.prototype._error = function (err) {
6348 this.destination.error(err);
6351 Subscriber.prototype._complete = function () {
6352 this.destination.complete();
6355 Subscriber.prototype._unsubscribeAndRecycle = function () {
6356 var _a = this, _parent = _a._parent, _parents = _a._parents;
6357 this._parent = null;
6358 this._parents = null;
6360 this.closed = false;
6361 this.isStopped = false;
6362 this._parent = _parent;
6363 this._parents = _parents;
6367 }(Subscription_1.Subscription));
6368 exports.Subscriber = Subscriber;
6370 * We need this JSDoc comment for affecting ESDoc.
6372 * @extends {Ignored}
6374 var SafeSubscriber = (function (_super) {
6375 __extends(SafeSubscriber, _super);
6376 function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
6378 this._parentSubscriber = _parentSubscriber;
6381 if (isFunction_1.isFunction(observerOrNext)) {
6382 next = observerOrNext;
6384 else if (observerOrNext) {
6385 next = observerOrNext.next;
6386 error = observerOrNext.error;
6387 complete = observerOrNext.complete;
6388 if (observerOrNext !== Observer_1.empty) {
6389 context = Object.create(observerOrNext);
6390 if (isFunction_1.isFunction(context.unsubscribe)) {
6391 this.add(context.unsubscribe.bind(context));
6393 context.unsubscribe = this.unsubscribe.bind(this);
6396 this._context = context;
6398 this._error = error;
6399 this._complete = complete;
6401 SafeSubscriber.prototype.next = function (value) {
6402 if (!this.isStopped && this._next) {
6403 var _parentSubscriber = this._parentSubscriber;
6404 if (!_parentSubscriber.syncErrorThrowable) {
6405 this.__tryOrUnsub(this._next, value);
6407 else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
6412 SafeSubscriber.prototype.error = function (err) {
6413 if (!this.isStopped) {
6414 var _parentSubscriber = this._parentSubscriber;
6416 if (!_parentSubscriber.syncErrorThrowable) {
6417 this.__tryOrUnsub(this._error, err);
6421 this.__tryOrSetError(_parentSubscriber, this._error, err);
6425 else if (!_parentSubscriber.syncErrorThrowable) {
6430 _parentSubscriber.syncErrorValue = err;
6431 _parentSubscriber.syncErrorThrown = true;
6436 SafeSubscriber.prototype.complete = function () {
6438 if (!this.isStopped) {
6439 var _parentSubscriber = this._parentSubscriber;
6440 if (this._complete) {
6441 var wrappedComplete = function () { return _this._complete.call(_this._context); };
6442 if (!_parentSubscriber.syncErrorThrowable) {
6443 this.__tryOrUnsub(wrappedComplete);
6447 this.__tryOrSetError(_parentSubscriber, wrappedComplete);
6456 SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
6458 fn.call(this._context, value);
6465 SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
6467 fn.call(this._context, value);
6470 parent.syncErrorValue = err;
6471 parent.syncErrorThrown = true;
6476 SafeSubscriber.prototype._unsubscribe = function () {
6477 var _parentSubscriber = this._parentSubscriber;
6478 this._context = null;
6479 this._parentSubscriber = null;
6480 _parentSubscriber.unsubscribe();
6482 return SafeSubscriber;
6485 },{"./Observer":30,"./Subscription":37,"./symbol/rxSubscriber":156,"./util/isFunction":167}],37:[function(require,module,exports){
6487 var isArray_1 = require('./util/isArray');
6488 var isObject_1 = require('./util/isObject');
6489 var isFunction_1 = require('./util/isFunction');
6490 var tryCatch_1 = require('./util/tryCatch');
6491 var errorObject_1 = require('./util/errorObject');
6492 var UnsubscriptionError_1 = require('./util/UnsubscriptionError');
6494 * Represents a disposable resource, such as the execution of an Observable. A
6495 * Subscription has one important method, `unsubscribe`, that takes no argument
6496 * and just disposes the resource held by the subscription.
6498 * Additionally, subscriptions may be grouped together through the `add()`
6499 * method, which will attach a child Subscription to the current Subscription.
6500 * When a Subscription is unsubscribed, all its children (and its grandchildren)
6501 * will be unsubscribed as well.
6503 * @class Subscription
6505 var Subscription = (function () {
6507 * @param {function(): void} [unsubscribe] A function describing how to
6508 * perform the disposal of resources when the `unsubscribe` method is called.
6510 function Subscription(unsubscribe) {
6512 * A flag to indicate whether this Subscription has already been unsubscribed.
6515 this.closed = false;
6516 this._parent = null;
6517 this._parents = null;
6518 this._subscriptions = null;
6520 this._unsubscribe = unsubscribe;
6524 * Disposes the resources held by the subscription. May, for instance, cancel
6525 * an ongoing Observable execution or cancel any other type of work that
6526 * started when the Subscription was created.
6529 Subscription.prototype.unsubscribe = function () {
6530 var hasErrors = false;
6535 var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
6537 this._parent = null;
6538 this._parents = null;
6539 // null out _subscriptions first so any child subscriptions that attempt
6540 // to remove themselves from this subscription will noop
6541 this._subscriptions = null;
6543 var len = _parents ? _parents.length : 0;
6544 // if this._parent is null, then so is this._parents, and we
6545 // don't have to remove ourselves from any parent subscriptions.
6547 _parent.remove(this);
6548 // if this._parents is null or index >= len,
6549 // then _parent is set to null, and the loop exits
6550 _parent = ++index < len && _parents[index] || null;
6552 if (isFunction_1.isFunction(_unsubscribe)) {
6553 var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
6554 if (trial === errorObject_1.errorObject) {
6556 errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ?
6557 flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]);
6560 if (isArray_1.isArray(_subscriptions)) {
6562 len = _subscriptions.length;
6563 while (++index < len) {
6564 var sub = _subscriptions[index];
6565 if (isObject_1.isObject(sub)) {
6566 var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
6567 if (trial === errorObject_1.errorObject) {
6569 errors = errors || [];
6570 var err = errorObject_1.errorObject.e;
6571 if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
6572 errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
6582 throw new UnsubscriptionError_1.UnsubscriptionError(errors);
6586 * Adds a tear down to be called during the unsubscribe() of this
6589 * If the tear down being added is a subscription that is already
6590 * unsubscribed, is the same reference `add` is being called on, or is
6591 * `Subscription.EMPTY`, it will not be added.
6593 * If this subscription is already in an `closed` state, the passed
6594 * tear down logic will be executed immediately.
6596 * @param {TeardownLogic} teardown The additional logic to execute on
6598 * @return {Subscription} Returns the Subscription used or created to be
6599 * added to the inner subscriptions list. This Subscription can be used with
6600 * `remove()` to remove the passed teardown logic from the inner subscriptions
6603 Subscription.prototype.add = function (teardown) {
6604 if (!teardown || (teardown === Subscription.EMPTY)) {
6605 return Subscription.EMPTY;
6607 if (teardown === this) {
6610 var subscription = teardown;
6611 switch (typeof teardown) {
6613 subscription = new Subscription(teardown);
6615 if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
6616 return subscription;
6618 else if (this.closed) {
6619 subscription.unsubscribe();
6620 return subscription;
6622 else if (typeof subscription._addParent !== 'function' /* quack quack */) {
6623 var tmp = subscription;
6624 subscription = new Subscription();
6625 subscription._subscriptions = [tmp];
6629 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
6631 var subscriptions = this._subscriptions || (this._subscriptions = []);
6632 subscriptions.push(subscription);
6633 subscription._addParent(this);
6634 return subscription;
6637 * Removes a Subscription from the internal list of subscriptions that will
6638 * unsubscribe during the unsubscribe process of this Subscription.
6639 * @param {Subscription} subscription The subscription to remove.
6642 Subscription.prototype.remove = function (subscription) {
6643 var subscriptions = this._subscriptions;
6644 if (subscriptions) {
6645 var subscriptionIndex = subscriptions.indexOf(subscription);
6646 if (subscriptionIndex !== -1) {
6647 subscriptions.splice(subscriptionIndex, 1);
6651 Subscription.prototype._addParent = function (parent) {
6652 var _a = this, _parent = _a._parent, _parents = _a._parents;
6653 if (!_parent || _parent === parent) {
6654 // If we don't have a parent, or the new parent is the same as the
6655 // current parent, then set this._parent to the new parent.
6656 this._parent = parent;
6658 else if (!_parents) {
6659 // If there's already one parent, but not multiple, allocate an Array to
6660 // store the rest of the parent Subscriptions.
6661 this._parents = [parent];
6663 else if (_parents.indexOf(parent) === -1) {
6664 // Only add the new parent to the _parents list if it's not already there.
6665 _parents.push(parent);
6668 Subscription.EMPTY = (function (empty) {
6669 empty.closed = true;
6671 }(new Subscription()));
6672 return Subscription;
6674 exports.Subscription = Subscription;
6675 function flattenUnsubscriptionErrors(errors) {
6676 return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []);
6679 },{"./util/UnsubscriptionError":162,"./util/errorObject":163,"./util/isArray":164,"./util/isFunction":167,"./util/isObject":169,"./util/tryCatch":175}],38:[function(require,module,exports){
6681 var Observable_1 = require('../../Observable');
6682 var combineLatest_1 = require('../../observable/combineLatest');
6683 Observable_1.Observable.combineLatest = combineLatest_1.combineLatest;
6685 },{"../../Observable":29,"../../observable/combineLatest":97}],39:[function(require,module,exports){
6687 var Observable_1 = require('../../Observable');
6688 var defer_1 = require('../../observable/defer');
6689 Observable_1.Observable.defer = defer_1.defer;
6691 },{"../../Observable":29,"../../observable/defer":98}],40:[function(require,module,exports){
6693 var Observable_1 = require('../../Observable');
6694 var empty_1 = require('../../observable/empty');
6695 Observable_1.Observable.empty = empty_1.empty;
6697 },{"../../Observable":29,"../../observable/empty":99}],41:[function(require,module,exports){
6699 var Observable_1 = require('../../Observable');
6700 var from_1 = require('../../observable/from');
6701 Observable_1.Observable.from = from_1.from;
6703 },{"../../Observable":29,"../../observable/from":100}],42:[function(require,module,exports){
6705 var Observable_1 = require('../../Observable');
6706 var fromEvent_1 = require('../../observable/fromEvent');
6707 Observable_1.Observable.fromEvent = fromEvent_1.fromEvent;
6709 },{"../../Observable":29,"../../observable/fromEvent":101}],43:[function(require,module,exports){
6711 var Observable_1 = require('../../Observable');
6712 var fromPromise_1 = require('../../observable/fromPromise');
6713 Observable_1.Observable.fromPromise = fromPromise_1.fromPromise;
6715 },{"../../Observable":29,"../../observable/fromPromise":102}],44:[function(require,module,exports){
6717 var Observable_1 = require('../../Observable');
6718 var merge_1 = require('../../observable/merge');
6719 Observable_1.Observable.merge = merge_1.merge;
6721 },{"../../Observable":29,"../../observable/merge":103}],45:[function(require,module,exports){
6723 var Observable_1 = require('../../Observable');
6724 var of_1 = require('../../observable/of');
6725 Observable_1.Observable.of = of_1.of;
6727 },{"../../Observable":29,"../../observable/of":104}],46:[function(require,module,exports){
6729 var Observable_1 = require('../../Observable');
6730 var throw_1 = require('../../observable/throw');
6731 Observable_1.Observable.throw = throw_1._throw;
6733 },{"../../Observable":29,"../../observable/throw":105}],47:[function(require,module,exports){
6735 var Observable_1 = require('../../Observable');
6736 var timer_1 = require('../../observable/timer');
6737 Observable_1.Observable.timer = timer_1.timer;
6739 },{"../../Observable":29,"../../observable/timer":106}],48:[function(require,module,exports){
6741 var Observable_1 = require('../../Observable');
6742 var zip_1 = require('../../observable/zip');
6743 Observable_1.Observable.zip = zip_1.zip;
6745 },{"../../Observable":29,"../../observable/zip":107}],49:[function(require,module,exports){
6747 var Observable_1 = require('../../Observable');
6748 var buffer_1 = require('../../operator/buffer');
6749 Observable_1.Observable.prototype.buffer = buffer_1.buffer;
6751 },{"../../Observable":29,"../../operator/buffer":108}],50:[function(require,module,exports){
6753 var Observable_1 = require('../../Observable');
6754 var bufferCount_1 = require('../../operator/bufferCount');
6755 Observable_1.Observable.prototype.bufferCount = bufferCount_1.bufferCount;
6757 },{"../../Observable":29,"../../operator/bufferCount":109}],51:[function(require,module,exports){
6759 var Observable_1 = require('../../Observable');
6760 var bufferWhen_1 = require('../../operator/bufferWhen');
6761 Observable_1.Observable.prototype.bufferWhen = bufferWhen_1.bufferWhen;
6763 },{"../../Observable":29,"../../operator/bufferWhen":110}],52:[function(require,module,exports){
6765 var Observable_1 = require('../../Observable');
6766 var catch_1 = require('../../operator/catch');
6767 Observable_1.Observable.prototype.catch = catch_1._catch;
6768 Observable_1.Observable.prototype._catch = catch_1._catch;
6770 },{"../../Observable":29,"../../operator/catch":111}],53:[function(require,module,exports){
6772 var Observable_1 = require('../../Observable');
6773 var combineLatest_1 = require('../../operator/combineLatest');
6774 Observable_1.Observable.prototype.combineLatest = combineLatest_1.combineLatest;
6776 },{"../../Observable":29,"../../operator/combineLatest":112}],54:[function(require,module,exports){
6778 var Observable_1 = require('../../Observable');
6779 var concat_1 = require('../../operator/concat');
6780 Observable_1.Observable.prototype.concat = concat_1.concat;
6782 },{"../../Observable":29,"../../operator/concat":113}],55:[function(require,module,exports){
6784 var Observable_1 = require('../../Observable');
6785 var debounceTime_1 = require('../../operator/debounceTime');
6786 Observable_1.Observable.prototype.debounceTime = debounceTime_1.debounceTime;
6788 },{"../../Observable":29,"../../operator/debounceTime":114}],56:[function(require,module,exports){
6790 var Observable_1 = require('../../Observable');
6791 var delay_1 = require('../../operator/delay');
6792 Observable_1.Observable.prototype.delay = delay_1.delay;
6794 },{"../../Observable":29,"../../operator/delay":115}],57:[function(require,module,exports){
6796 var Observable_1 = require('../../Observable');
6797 var distinct_1 = require('../../operator/distinct');
6798 Observable_1.Observable.prototype.distinct = distinct_1.distinct;
6800 },{"../../Observable":29,"../../operator/distinct":116}],58:[function(require,module,exports){
6802 var Observable_1 = require('../../Observable');
6803 var distinctUntilChanged_1 = require('../../operator/distinctUntilChanged');
6804 Observable_1.Observable.prototype.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged;
6806 },{"../../Observable":29,"../../operator/distinctUntilChanged":117}],59:[function(require,module,exports){
6808 var Observable_1 = require('../../Observable');
6809 var do_1 = require('../../operator/do');
6810 Observable_1.Observable.prototype.do = do_1._do;
6811 Observable_1.Observable.prototype._do = do_1._do;
6813 },{"../../Observable":29,"../../operator/do":118}],60:[function(require,module,exports){
6815 var Observable_1 = require('../../Observable');
6816 var expand_1 = require('../../operator/expand');
6817 Observable_1.Observable.prototype.expand = expand_1.expand;
6819 },{"../../Observable":29,"../../operator/expand":119}],61:[function(require,module,exports){
6821 var Observable_1 = require('../../Observable');
6822 var filter_1 = require('../../operator/filter');
6823 Observable_1.Observable.prototype.filter = filter_1.filter;
6825 },{"../../Observable":29,"../../operator/filter":120}],62:[function(require,module,exports){
6827 var Observable_1 = require('../../Observable');
6828 var finally_1 = require('../../operator/finally');
6829 Observable_1.Observable.prototype.finally = finally_1._finally;
6830 Observable_1.Observable.prototype._finally = finally_1._finally;
6832 },{"../../Observable":29,"../../operator/finally":121}],63:[function(require,module,exports){
6834 var Observable_1 = require('../../Observable');
6835 var first_1 = require('../../operator/first');
6836 Observable_1.Observable.prototype.first = first_1.first;
6838 },{"../../Observable":29,"../../operator/first":122}],64:[function(require,module,exports){
6840 var Observable_1 = require('../../Observable');
6841 var last_1 = require('../../operator/last');
6842 Observable_1.Observable.prototype.last = last_1.last;
6844 },{"../../Observable":29,"../../operator/last":123}],65:[function(require,module,exports){
6846 var Observable_1 = require('../../Observable');
6847 var map_1 = require('../../operator/map');
6848 Observable_1.Observable.prototype.map = map_1.map;
6850 },{"../../Observable":29,"../../operator/map":124}],66:[function(require,module,exports){
6852 var Observable_1 = require('../../Observable');
6853 var merge_1 = require('../../operator/merge');
6854 Observable_1.Observable.prototype.merge = merge_1.merge;
6856 },{"../../Observable":29,"../../operator/merge":125}],67:[function(require,module,exports){
6858 var Observable_1 = require('../../Observable');
6859 var mergeAll_1 = require('../../operator/mergeAll');
6860 Observable_1.Observable.prototype.mergeAll = mergeAll_1.mergeAll;
6862 },{"../../Observable":29,"../../operator/mergeAll":126}],68:[function(require,module,exports){
6864 var Observable_1 = require('../../Observable');
6865 var mergeMap_1 = require('../../operator/mergeMap');
6866 Observable_1.Observable.prototype.mergeMap = mergeMap_1.mergeMap;
6867 Observable_1.Observable.prototype.flatMap = mergeMap_1.mergeMap;
6869 },{"../../Observable":29,"../../operator/mergeMap":127}],69:[function(require,module,exports){
6871 var Observable_1 = require('../../Observable');
6872 var pairwise_1 = require('../../operator/pairwise');
6873 Observable_1.Observable.prototype.pairwise = pairwise_1.pairwise;
6875 },{"../../Observable":29,"../../operator/pairwise":130}],70:[function(require,module,exports){
6877 var Observable_1 = require('../../Observable');
6878 var pluck_1 = require('../../operator/pluck');
6879 Observable_1.Observable.prototype.pluck = pluck_1.pluck;
6881 },{"../../Observable":29,"../../operator/pluck":131}],71:[function(require,module,exports){
6883 var Observable_1 = require('../../Observable');
6884 var publish_1 = require('../../operator/publish');
6885 Observable_1.Observable.prototype.publish = publish_1.publish;
6887 },{"../../Observable":29,"../../operator/publish":132}],72:[function(require,module,exports){
6889 var Observable_1 = require('../../Observable');
6890 var publishReplay_1 = require('../../operator/publishReplay');
6891 Observable_1.Observable.prototype.publishReplay = publishReplay_1.publishReplay;
6893 },{"../../Observable":29,"../../operator/publishReplay":133}],73:[function(require,module,exports){
6895 var Observable_1 = require('../../Observable');
6896 var scan_1 = require('../../operator/scan');
6897 Observable_1.Observable.prototype.scan = scan_1.scan;
6899 },{"../../Observable":29,"../../operator/scan":134}],74:[function(require,module,exports){
6901 var Observable_1 = require('../../Observable');
6902 var share_1 = require('../../operator/share');
6903 Observable_1.Observable.prototype.share = share_1.share;
6905 },{"../../Observable":29,"../../operator/share":135}],75:[function(require,module,exports){
6907 var Observable_1 = require('../../Observable');
6908 var skip_1 = require('../../operator/skip');
6909 Observable_1.Observable.prototype.skip = skip_1.skip;
6911 },{"../../Observable":29,"../../operator/skip":136}],76:[function(require,module,exports){
6913 var Observable_1 = require('../../Observable');
6914 var skipUntil_1 = require('../../operator/skipUntil');
6915 Observable_1.Observable.prototype.skipUntil = skipUntil_1.skipUntil;
6917 },{"../../Observable":29,"../../operator/skipUntil":137}],77:[function(require,module,exports){
6919 var Observable_1 = require('../../Observable');
6920 var skipWhile_1 = require('../../operator/skipWhile');
6921 Observable_1.Observable.prototype.skipWhile = skipWhile_1.skipWhile;
6923 },{"../../Observable":29,"../../operator/skipWhile":138}],78:[function(require,module,exports){
6925 var Observable_1 = require('../../Observable');
6926 var startWith_1 = require('../../operator/startWith');
6927 Observable_1.Observable.prototype.startWith = startWith_1.startWith;
6929 },{"../../Observable":29,"../../operator/startWith":139}],79:[function(require,module,exports){
6931 var Observable_1 = require('../../Observable');
6932 var switchMap_1 = require('../../operator/switchMap');
6933 Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap;
6935 },{"../../Observable":29,"../../operator/switchMap":140}],80:[function(require,module,exports){
6937 var Observable_1 = require('../../Observable');
6938 var take_1 = require('../../operator/take');
6939 Observable_1.Observable.prototype.take = take_1.take;
6941 },{"../../Observable":29,"../../operator/take":141}],81:[function(require,module,exports){
6943 var Observable_1 = require('../../Observable');
6944 var takeUntil_1 = require('../../operator/takeUntil');
6945 Observable_1.Observable.prototype.takeUntil = takeUntil_1.takeUntil;
6947 },{"../../Observable":29,"../../operator/takeUntil":142}],82:[function(require,module,exports){
6949 var Observable_1 = require('../../Observable');
6950 var throttleTime_1 = require('../../operator/throttleTime');
6951 Observable_1.Observable.prototype.throttleTime = throttleTime_1.throttleTime;
6953 },{"../../Observable":29,"../../operator/throttleTime":144}],83:[function(require,module,exports){
6955 var Observable_1 = require('../../Observable');
6956 var withLatestFrom_1 = require('../../operator/withLatestFrom');
6957 Observable_1.Observable.prototype.withLatestFrom = withLatestFrom_1.withLatestFrom;
6959 },{"../../Observable":29,"../../operator/withLatestFrom":145}],84:[function(require,module,exports){
6961 var Observable_1 = require('../../Observable');
6962 var zip_1 = require('../../operator/zip');
6963 Observable_1.Observable.prototype.zip = zip_1.zipProto;
6965 },{"../../Observable":29,"../../operator/zip":146}],85:[function(require,module,exports){
6967 var __extends = (this && this.__extends) || function (d, b) {
6968 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6969 function __() { this.constructor = d; }
6970 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6972 var Observable_1 = require('../Observable');
6973 var ScalarObservable_1 = require('./ScalarObservable');
6974 var EmptyObservable_1 = require('./EmptyObservable');
6976 * We need this JSDoc comment for affecting ESDoc.
6977 * @extends {Ignored}
6980 var ArrayLikeObservable = (function (_super) {
6981 __extends(ArrayLikeObservable, _super);
6982 function ArrayLikeObservable(arrayLike, scheduler) {
6984 this.arrayLike = arrayLike;
6985 this.scheduler = scheduler;
6986 if (!scheduler && arrayLike.length === 1) {
6987 this._isScalar = true;
6988 this.value = arrayLike[0];
6991 ArrayLikeObservable.create = function (arrayLike, scheduler) {
6992 var length = arrayLike.length;
6994 return new EmptyObservable_1.EmptyObservable();
6996 else if (length === 1) {
6997 return new ScalarObservable_1.ScalarObservable(arrayLike[0], scheduler);
7000 return new ArrayLikeObservable(arrayLike, scheduler);
7003 ArrayLikeObservable.dispatch = function (state) {
7004 var arrayLike = state.arrayLike, index = state.index, length = state.length, subscriber = state.subscriber;
7005 if (subscriber.closed) {
7008 if (index >= length) {
7009 subscriber.complete();
7012 subscriber.next(arrayLike[index]);
7013 state.index = index + 1;
7014 this.schedule(state);
7016 ArrayLikeObservable.prototype._subscribe = function (subscriber) {
7018 var _a = this, arrayLike = _a.arrayLike, scheduler = _a.scheduler;
7019 var length = arrayLike.length;
7021 return scheduler.schedule(ArrayLikeObservable.dispatch, 0, {
7022 arrayLike: arrayLike, index: index, length: length, subscriber: subscriber
7026 for (var i = 0; i < length && !subscriber.closed; i++) {
7027 subscriber.next(arrayLike[i]);
7029 subscriber.complete();
7032 return ArrayLikeObservable;
7033 }(Observable_1.Observable));
7034 exports.ArrayLikeObservable = ArrayLikeObservable;
7036 },{"../Observable":29,"./EmptyObservable":89,"./ScalarObservable":95}],86:[function(require,module,exports){
7038 var __extends = (this && this.__extends) || function (d, b) {
7039 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7040 function __() { this.constructor = d; }
7041 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7043 var Observable_1 = require('../Observable');
7044 var ScalarObservable_1 = require('./ScalarObservable');
7045 var EmptyObservable_1 = require('./EmptyObservable');
7046 var isScheduler_1 = require('../util/isScheduler');
7048 * We need this JSDoc comment for affecting ESDoc.
7049 * @extends {Ignored}
7052 var ArrayObservable = (function (_super) {
7053 __extends(ArrayObservable, _super);
7054 function ArrayObservable(array, scheduler) {
7057 this.scheduler = scheduler;
7058 if (!scheduler && array.length === 1) {
7059 this._isScalar = true;
7060 this.value = array[0];
7063 ArrayObservable.create = function (array, scheduler) {
7064 return new ArrayObservable(array, scheduler);
7067 * Creates an Observable that emits some values you specify as arguments,
7068 * immediately one after the other, and then emits a complete notification.
7070 * <span class="informal">Emits the arguments you provide, then completes.
7073 * <img src="./img/of.png" width="100%">
7075 * This static operator is useful for creating a simple Observable that only
7076 * emits the arguments given, and the complete notification thereafter. It can
7077 * be used for composing with other Observables, such as with {@link concat}.
7078 * By default, it uses a `null` IScheduler, which means the `next`
7079 * notifications are sent synchronously, although with a different IScheduler
7080 * it is possible to determine when those notifications will be delivered.
7082 * @example <caption>Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second.</caption>
7083 * var numbers = Rx.Observable.of(10, 20, 30);
7084 * var letters = Rx.Observable.of('a', 'b', 'c');
7085 * var interval = Rx.Observable.interval(1000);
7086 * var result = numbers.concat(letters).concat(interval);
7087 * result.subscribe(x => console.log(x));
7089 * @see {@link create}
7090 * @see {@link empty}
7091 * @see {@link never}
7092 * @see {@link throw}
7094 * @param {...T} values Arguments that represent `next` values to be emitted.
7095 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7096 * the emissions of the `next` notifications.
7097 * @return {Observable<T>} An Observable that emits each given input value.
7102 ArrayObservable.of = function () {
7104 for (var _i = 0; _i < arguments.length; _i++) {
7105 array[_i - 0] = arguments[_i];
7107 var scheduler = array[array.length - 1];
7108 if (isScheduler_1.isScheduler(scheduler)) {
7114 var len = array.length;
7116 return new ArrayObservable(array, scheduler);
7118 else if (len === 1) {
7119 return new ScalarObservable_1.ScalarObservable(array[0], scheduler);
7122 return new EmptyObservable_1.EmptyObservable(scheduler);
7125 ArrayObservable.dispatch = function (state) {
7126 var array = state.array, index = state.index, count = state.count, subscriber = state.subscriber;
7127 if (index >= count) {
7128 subscriber.complete();
7131 subscriber.next(array[index]);
7132 if (subscriber.closed) {
7135 state.index = index + 1;
7136 this.schedule(state);
7138 ArrayObservable.prototype._subscribe = function (subscriber) {
7140 var array = this.array;
7141 var count = array.length;
7142 var scheduler = this.scheduler;
7144 return scheduler.schedule(ArrayObservable.dispatch, 0, {
7145 array: array, index: index, count: count, subscriber: subscriber
7149 for (var i = 0; i < count && !subscriber.closed; i++) {
7150 subscriber.next(array[i]);
7152 subscriber.complete();
7155 return ArrayObservable;
7156 }(Observable_1.Observable));
7157 exports.ArrayObservable = ArrayObservable;
7159 },{"../Observable":29,"../util/isScheduler":171,"./EmptyObservable":89,"./ScalarObservable":95}],87:[function(require,module,exports){
7161 var __extends = (this && this.__extends) || function (d, b) {
7162 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7163 function __() { this.constructor = d; }
7164 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7166 var Subject_1 = require('../Subject');
7167 var Observable_1 = require('../Observable');
7168 var Subscriber_1 = require('../Subscriber');
7169 var Subscription_1 = require('../Subscription');
7171 * @class ConnectableObservable<T>
7173 var ConnectableObservable = (function (_super) {
7174 __extends(ConnectableObservable, _super);
7175 function ConnectableObservable(source, subjectFactory) {
7177 this.source = source;
7178 this.subjectFactory = subjectFactory;
7180 this._isComplete = false;
7182 ConnectableObservable.prototype._subscribe = function (subscriber) {
7183 return this.getSubject().subscribe(subscriber);
7185 ConnectableObservable.prototype.getSubject = function () {
7186 var subject = this._subject;
7187 if (!subject || subject.isStopped) {
7188 this._subject = this.subjectFactory();
7190 return this._subject;
7192 ConnectableObservable.prototype.connect = function () {
7193 var connection = this._connection;
7195 this._isComplete = false;
7196 connection = this._connection = new Subscription_1.Subscription();
7197 connection.add(this.source
7198 .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
7199 if (connection.closed) {
7200 this._connection = null;
7201 connection = Subscription_1.Subscription.EMPTY;
7204 this._connection = connection;
7209 ConnectableObservable.prototype.refCount = function () {
7210 return this.lift(new RefCountOperator(this));
7212 return ConnectableObservable;
7213 }(Observable_1.Observable));
7214 exports.ConnectableObservable = ConnectableObservable;
7215 var connectableProto = ConnectableObservable.prototype;
7216 exports.connectableObservableDescriptor = {
7217 operator: { value: null },
7218 _refCount: { value: 0, writable: true },
7219 _subject: { value: null, writable: true },
7220 _connection: { value: null, writable: true },
7221 _subscribe: { value: connectableProto._subscribe },
7222 _isComplete: { value: connectableProto._isComplete, writable: true },
7223 getSubject: { value: connectableProto.getSubject },
7224 connect: { value: connectableProto.connect },
7225 refCount: { value: connectableProto.refCount }
7227 var ConnectableSubscriber = (function (_super) {
7228 __extends(ConnectableSubscriber, _super);
7229 function ConnectableSubscriber(destination, connectable) {
7230 _super.call(this, destination);
7231 this.connectable = connectable;
7233 ConnectableSubscriber.prototype._error = function (err) {
7234 this._unsubscribe();
7235 _super.prototype._error.call(this, err);
7237 ConnectableSubscriber.prototype._complete = function () {
7238 this.connectable._isComplete = true;
7239 this._unsubscribe();
7240 _super.prototype._complete.call(this);
7242 ConnectableSubscriber.prototype._unsubscribe = function () {
7243 var connectable = this.connectable;
7245 this.connectable = null;
7246 var connection = connectable._connection;
7247 connectable._refCount = 0;
7248 connectable._subject = null;
7249 connectable._connection = null;
7251 connection.unsubscribe();
7255 return ConnectableSubscriber;
7256 }(Subject_1.SubjectSubscriber));
7257 var RefCountOperator = (function () {
7258 function RefCountOperator(connectable) {
7259 this.connectable = connectable;
7261 RefCountOperator.prototype.call = function (subscriber, source) {
7262 var connectable = this.connectable;
7263 connectable._refCount++;
7264 var refCounter = new RefCountSubscriber(subscriber, connectable);
7265 var subscription = source.subscribe(refCounter);
7266 if (!refCounter.closed) {
7267 refCounter.connection = connectable.connect();
7269 return subscription;
7271 return RefCountOperator;
7273 var RefCountSubscriber = (function (_super) {
7274 __extends(RefCountSubscriber, _super);
7275 function RefCountSubscriber(destination, connectable) {
7276 _super.call(this, destination);
7277 this.connectable = connectable;
7279 RefCountSubscriber.prototype._unsubscribe = function () {
7280 var connectable = this.connectable;
7282 this.connection = null;
7285 this.connectable = null;
7286 var refCount = connectable._refCount;
7287 if (refCount <= 0) {
7288 this.connection = null;
7291 connectable._refCount = refCount - 1;
7293 this.connection = null;
7297 // Compare the local RefCountSubscriber's connection Subscription to the
7298 // connection Subscription on the shared ConnectableObservable. In cases
7299 // where the ConnectableObservable source synchronously emits values, and
7300 // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
7301 // execution continues to here before the RefCountOperator has a chance to
7302 // supply the RefCountSubscriber with the shared connection Subscription.
7305 // Observable.range(0, 10)
7311 // In order to account for this case, RefCountSubscriber should only dispose
7312 // the ConnectableObservable's shared connection Subscription if the
7313 // connection Subscription exists, *and* either:
7314 // a. RefCountSubscriber doesn't have a reference to the shared connection
7315 // Subscription yet, or,
7316 // b. RefCountSubscriber's connection Subscription reference is identical
7317 // to the shared connection Subscription
7319 var connection = this.connection;
7320 var sharedConnection = connectable._connection;
7321 this.connection = null;
7322 if (sharedConnection && (!connection || sharedConnection === connection)) {
7323 sharedConnection.unsubscribe();
7326 return RefCountSubscriber;
7327 }(Subscriber_1.Subscriber));
7329 },{"../Observable":29,"../Subject":34,"../Subscriber":36,"../Subscription":37}],88:[function(require,module,exports){
7331 var __extends = (this && this.__extends) || function (d, b) {
7332 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7333 function __() { this.constructor = d; }
7334 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7336 var Observable_1 = require('../Observable');
7337 var subscribeToResult_1 = require('../util/subscribeToResult');
7338 var OuterSubscriber_1 = require('../OuterSubscriber');
7340 * We need this JSDoc comment for affecting ESDoc.
7341 * @extends {Ignored}
7344 var DeferObservable = (function (_super) {
7345 __extends(DeferObservable, _super);
7346 function DeferObservable(observableFactory) {
7348 this.observableFactory = observableFactory;
7351 * Creates an Observable that, on subscribe, calls an Observable factory to
7352 * make an Observable for each new Observer.
7354 * <span class="informal">Creates the Observable lazily, that is, only when it
7358 * <img src="./img/defer.png" width="100%">
7360 * `defer` allows you to create the Observable only when the Observer
7361 * subscribes, and create a fresh Observable for each Observer. It waits until
7362 * an Observer subscribes to it, and then it generates an Observable,
7363 * typically with an Observable factory function. It does this afresh for each
7364 * subscriber, so although each subscriber may think it is subscribing to the
7365 * same Observable, in fact each subscriber gets its own individual
7368 * @example <caption>Subscribe to either an Observable of clicks or an Observable of interval, at random</caption>
7369 * var clicksOrInterval = Rx.Observable.defer(function () {
7370 * if (Math.random() > 0.5) {
7371 * return Rx.Observable.fromEvent(document, 'click');
7373 * return Rx.Observable.interval(1000);
7376 * clicksOrInterval.subscribe(x => console.log(x));
7378 * // Results in the following behavior:
7379 * // If the result of Math.random() is greater than 0.5 it will listen
7380 * // for clicks anywhere on the "document"; when document is clicked it
7381 * // will log a MouseEvent object to the console. If the result is less
7382 * // than 0.5 it will emit ascending numbers, one every second(1000ms).
7384 * @see {@link create}
7386 * @param {function(): SubscribableOrPromise} observableFactory The Observable
7387 * factory function to invoke for each Observer that subscribes to the output
7388 * Observable. May also return a Promise, which will be converted on the fly
7390 * @return {Observable} An Observable whose Observers' subscriptions trigger
7391 * an invocation of the given Observable factory function.
7396 DeferObservable.create = function (observableFactory) {
7397 return new DeferObservable(observableFactory);
7399 DeferObservable.prototype._subscribe = function (subscriber) {
7400 return new DeferSubscriber(subscriber, this.observableFactory);
7402 return DeferObservable;
7403 }(Observable_1.Observable));
7404 exports.DeferObservable = DeferObservable;
7405 var DeferSubscriber = (function (_super) {
7406 __extends(DeferSubscriber, _super);
7407 function DeferSubscriber(destination, factory) {
7408 _super.call(this, destination);
7409 this.factory = factory;
7412 DeferSubscriber.prototype.tryDefer = function () {
7414 this._callFactory();
7420 DeferSubscriber.prototype._callFactory = function () {
7421 var result = this.factory();
7423 this.add(subscribeToResult_1.subscribeToResult(this, result));
7426 return DeferSubscriber;
7427 }(OuterSubscriber_1.OuterSubscriber));
7429 },{"../Observable":29,"../OuterSubscriber":31,"../util/subscribeToResult":173}],89:[function(require,module,exports){
7431 var __extends = (this && this.__extends) || function (d, b) {
7432 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7433 function __() { this.constructor = d; }
7434 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7436 var Observable_1 = require('../Observable');
7438 * We need this JSDoc comment for affecting ESDoc.
7439 * @extends {Ignored}
7442 var EmptyObservable = (function (_super) {
7443 __extends(EmptyObservable, _super);
7444 function EmptyObservable(scheduler) {
7446 this.scheduler = scheduler;
7449 * Creates an Observable that emits no items to the Observer and immediately
7450 * emits a complete notification.
7452 * <span class="informal">Just emits 'complete', and nothing else.
7455 * <img src="./img/empty.png" width="100%">
7457 * This static operator is useful for creating a simple Observable that only
7458 * emits the complete notification. It can be used for composing with other
7459 * Observables, such as in a {@link mergeMap}.
7461 * @example <caption>Emit the number 7, then complete.</caption>
7462 * var result = Rx.Observable.empty().startWith(7);
7463 * result.subscribe(x => console.log(x));
7465 * @example <caption>Map and flatten only odd numbers to the sequence 'a', 'b', 'c'</caption>
7466 * var interval = Rx.Observable.interval(1000);
7467 * var result = interval.mergeMap(x =>
7468 * x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.empty()
7470 * result.subscribe(x => console.log(x));
7472 * // Results in the following to the console:
7473 * // x is equal to the count on the interval eg(0,1,2,3,...)
7474 * // x will occur every 1000ms
7475 * // if x % 2 is equal to 1 print abc
7476 * // if x % 2 is not equal to 1 nothing will be output
7478 * @see {@link create}
7479 * @see {@link never}
7481 * @see {@link throw}
7483 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7484 * the emission of the complete notification.
7485 * @return {Observable} An "empty" Observable: emits only the complete
7491 EmptyObservable.create = function (scheduler) {
7492 return new EmptyObservable(scheduler);
7494 EmptyObservable.dispatch = function (arg) {
7495 var subscriber = arg.subscriber;
7496 subscriber.complete();
7498 EmptyObservable.prototype._subscribe = function (subscriber) {
7499 var scheduler = this.scheduler;
7501 return scheduler.schedule(EmptyObservable.dispatch, 0, { subscriber: subscriber });
7504 subscriber.complete();
7507 return EmptyObservable;
7508 }(Observable_1.Observable));
7509 exports.EmptyObservable = EmptyObservable;
7511 },{"../Observable":29}],90:[function(require,module,exports){
7513 var __extends = (this && this.__extends) || function (d, b) {
7514 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7515 function __() { this.constructor = d; }
7516 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7518 var Observable_1 = require('../Observable');
7520 * We need this JSDoc comment for affecting ESDoc.
7521 * @extends {Ignored}
7524 var ErrorObservable = (function (_super) {
7525 __extends(ErrorObservable, _super);
7526 function ErrorObservable(error, scheduler) {
7529 this.scheduler = scheduler;
7532 * Creates an Observable that emits no items to the Observer and immediately
7533 * emits an error notification.
7535 * <span class="informal">Just emits 'error', and nothing else.
7538 * <img src="./img/throw.png" width="100%">
7540 * This static operator is useful for creating a simple Observable that only
7541 * emits the error notification. It can be used for composing with other
7542 * Observables, such as in a {@link mergeMap}.
7544 * @example <caption>Emit the number 7, then emit an error.</caption>
7545 * var result = Rx.Observable.throw(new Error('oops!')).startWith(7);
7546 * result.subscribe(x => console.log(x), e => console.error(e));
7548 * @example <caption>Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 13</caption>
7549 * var interval = Rx.Observable.interval(1000);
7550 * var result = interval.mergeMap(x =>
7552 * Rx.Observable.throw('Thirteens are bad') :
7553 * Rx.Observable.of('a', 'b', 'c')
7555 * result.subscribe(x => console.log(x), e => console.error(e));
7557 * @see {@link create}
7558 * @see {@link empty}
7559 * @see {@link never}
7562 * @param {any} error The particular Error to pass to the error notification.
7563 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7564 * the emission of the error notification.
7565 * @return {Observable} An error Observable: emits only the error notification
7566 * using the given error argument.
7571 ErrorObservable.create = function (error, scheduler) {
7572 return new ErrorObservable(error, scheduler);
7574 ErrorObservable.dispatch = function (arg) {
7575 var error = arg.error, subscriber = arg.subscriber;
7576 subscriber.error(error);
7578 ErrorObservable.prototype._subscribe = function (subscriber) {
7579 var error = this.error;
7580 var scheduler = this.scheduler;
7581 subscriber.syncErrorThrowable = true;
7583 return scheduler.schedule(ErrorObservable.dispatch, 0, {
7584 error: error, subscriber: subscriber
7588 subscriber.error(error);
7591 return ErrorObservable;
7592 }(Observable_1.Observable));
7593 exports.ErrorObservable = ErrorObservable;
7595 },{"../Observable":29}],91:[function(require,module,exports){
7597 var __extends = (this && this.__extends) || function (d, b) {
7598 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7599 function __() { this.constructor = d; }
7600 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7602 var Observable_1 = require('../Observable');
7603 var tryCatch_1 = require('../util/tryCatch');
7604 var isFunction_1 = require('../util/isFunction');
7605 var errorObject_1 = require('../util/errorObject');
7606 var Subscription_1 = require('../Subscription');
7607 var toString = Object.prototype.toString;
7608 function isNodeStyleEventEmitter(sourceObj) {
7609 return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
7611 function isJQueryStyleEventEmitter(sourceObj) {
7612 return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
7614 function isNodeList(sourceObj) {
7615 return !!sourceObj && toString.call(sourceObj) === '[object NodeList]';
7617 function isHTMLCollection(sourceObj) {
7618 return !!sourceObj && toString.call(sourceObj) === '[object HTMLCollection]';
7620 function isEventTarget(sourceObj) {
7621 return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
7624 * We need this JSDoc comment for affecting ESDoc.
7625 * @extends {Ignored}
7628 var FromEventObservable = (function (_super) {
7629 __extends(FromEventObservable, _super);
7630 function FromEventObservable(sourceObj, eventName, selector, options) {
7632 this.sourceObj = sourceObj;
7633 this.eventName = eventName;
7634 this.selector = selector;
7635 this.options = options;
7637 /* tslint:enable:max-line-length */
7639 * Creates an Observable that emits events of a specific type coming from the
7640 * given event target.
7642 * <span class="informal">Creates an Observable from DOM events, or Node
7643 * EventEmitter events or others.</span>
7645 * <img src="./img/fromEvent.png" width="100%">
7647 * Creates an Observable by attaching an event listener to an "event target",
7648 * which may be an object with `addEventListener` and `removeEventListener`,
7649 * a Node.js EventEmitter, a jQuery style EventEmitter, a NodeList from the
7650 * DOM, or an HTMLCollection from the DOM. The event handler is attached when
7651 * the output Observable is subscribed, and removed when the Subscription is
7654 * @example <caption>Emits clicks happening on the DOM document</caption>
7655 * var clicks = Rx.Observable.fromEvent(document, 'click');
7656 * clicks.subscribe(x => console.log(x));
7659 * // MouseEvent object logged to console everytime a click
7660 * // occurs on the document.
7663 * @see {@link fromEventPattern}
7665 * @param {EventTargetLike} target The DOMElement, event target, Node.js
7666 * EventEmitter, NodeList or HTMLCollection to attach the event handler to.
7667 * @param {string} eventName The event name of interest, being emitted by the
7669 * @param {EventListenerOptions} [options] Options to pass through to addEventListener
7670 * @param {SelectorMethodSignature<T>} [selector] An optional function to
7671 * post-process results. It takes the arguments from the event handler and
7672 * should return a single value.
7673 * @return {Observable<T>}
7678 FromEventObservable.create = function (target, eventName, options, selector) {
7679 if (isFunction_1.isFunction(options)) {
7681 options = undefined;
7683 return new FromEventObservable(target, eventName, selector, options);
7685 FromEventObservable.setupSubscription = function (sourceObj, eventName, handler, subscriber, options) {
7687 if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
7688 for (var i = 0, len = sourceObj.length; i < len; i++) {
7689 FromEventObservable.setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
7692 else if (isEventTarget(sourceObj)) {
7693 var source_1 = sourceObj;
7694 sourceObj.addEventListener(eventName, handler, options);
7695 unsubscribe = function () { return source_1.removeEventListener(eventName, handler); };
7697 else if (isJQueryStyleEventEmitter(sourceObj)) {
7698 var source_2 = sourceObj;
7699 sourceObj.on(eventName, handler);
7700 unsubscribe = function () { return source_2.off(eventName, handler); };
7702 else if (isNodeStyleEventEmitter(sourceObj)) {
7703 var source_3 = sourceObj;
7704 sourceObj.addListener(eventName, handler);
7705 unsubscribe = function () { return source_3.removeListener(eventName, handler); };
7708 throw new TypeError('Invalid event target');
7710 subscriber.add(new Subscription_1.Subscription(unsubscribe));
7712 FromEventObservable.prototype._subscribe = function (subscriber) {
7713 var sourceObj = this.sourceObj;
7714 var eventName = this.eventName;
7715 var options = this.options;
7716 var selector = this.selector;
7717 var handler = selector ? function () {
7719 for (var _i = 0; _i < arguments.length; _i++) {
7720 args[_i - 0] = arguments[_i];
7722 var result = tryCatch_1.tryCatch(selector).apply(void 0, args);
7723 if (result === errorObject_1.errorObject) {
7724 subscriber.error(errorObject_1.errorObject.e);
7727 subscriber.next(result);
7729 } : function (e) { return subscriber.next(e); };
7730 FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber, options);
7732 return FromEventObservable;
7733 }(Observable_1.Observable));
7734 exports.FromEventObservable = FromEventObservable;
7736 },{"../Observable":29,"../Subscription":37,"../util/errorObject":163,"../util/isFunction":167,"../util/tryCatch":175}],92:[function(require,module,exports){
7738 var __extends = (this && this.__extends) || function (d, b) {
7739 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7740 function __() { this.constructor = d; }
7741 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7743 var isArray_1 = require('../util/isArray');
7744 var isArrayLike_1 = require('../util/isArrayLike');
7745 var isPromise_1 = require('../util/isPromise');
7746 var PromiseObservable_1 = require('./PromiseObservable');
7747 var IteratorObservable_1 = require('./IteratorObservable');
7748 var ArrayObservable_1 = require('./ArrayObservable');
7749 var ArrayLikeObservable_1 = require('./ArrayLikeObservable');
7750 var iterator_1 = require('../symbol/iterator');
7751 var Observable_1 = require('../Observable');
7752 var observeOn_1 = require('../operator/observeOn');
7753 var observable_1 = require('../symbol/observable');
7755 * We need this JSDoc comment for affecting ESDoc.
7756 * @extends {Ignored}
7759 var FromObservable = (function (_super) {
7760 __extends(FromObservable, _super);
7761 function FromObservable(ish, scheduler) {
7762 _super.call(this, null);
7764 this.scheduler = scheduler;
7767 * Creates an Observable from an Array, an array-like object, a Promise, an
7768 * iterable object, or an Observable-like object.
7770 * <span class="informal">Converts almost anything to an Observable.</span>
7772 * <img src="./img/from.png" width="100%">
7774 * Convert various other objects and data types into Observables. `from`
7775 * converts a Promise or an array-like or an
7776 * [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)
7777 * object into an Observable that emits the items in that promise or array or
7778 * iterable. A String, in this context, is treated as an array of characters.
7779 * Observable-like objects (contains a function named with the ES2015 Symbol
7780 * for Observable) can also be converted through this operator.
7782 * @example <caption>Converts an array to an Observable</caption>
7783 * var array = [10, 20, 30];
7784 * var result = Rx.Observable.from(array);
7785 * result.subscribe(x => console.log(x));
7787 * // Results in the following:
7790 * @example <caption>Convert an infinite iterable (from a generator) to an Observable</caption>
7791 * function* generateDoubles(seed) {
7795 * i = 2 * i; // double it
7799 * var iterator = generateDoubles(3);
7800 * var result = Rx.Observable.from(iterator).take(10);
7801 * result.subscribe(x => console.log(x));
7803 * // Results in the following:
7804 * // 3 6 12 24 48 96 192 384 768 1536
7806 * @see {@link create}
7807 * @see {@link fromEvent}
7808 * @see {@link fromEventPattern}
7809 * @see {@link fromPromise}
7811 * @param {ObservableInput<T>} ish A subscribable object, a Promise, an
7812 * Observable-like, an Array, an iterable or an array-like object to be
7814 * @param {Scheduler} [scheduler] The scheduler on which to schedule the
7815 * emissions of values.
7816 * @return {Observable<T>} The Observable whose values are originally from the
7817 * input object that was converted.
7822 FromObservable.create = function (ish, scheduler) {
7824 if (typeof ish[observable_1.observable] === 'function') {
7825 if (ish instanceof Observable_1.Observable && !scheduler) {
7828 return new FromObservable(ish, scheduler);
7830 else if (isArray_1.isArray(ish)) {
7831 return new ArrayObservable_1.ArrayObservable(ish, scheduler);
7833 else if (isPromise_1.isPromise(ish)) {
7834 return new PromiseObservable_1.PromiseObservable(ish, scheduler);
7836 else if (typeof ish[iterator_1.iterator] === 'function' || typeof ish === 'string') {
7837 return new IteratorObservable_1.IteratorObservable(ish, scheduler);
7839 else if (isArrayLike_1.isArrayLike(ish)) {
7840 return new ArrayLikeObservable_1.ArrayLikeObservable(ish, scheduler);
7843 throw new TypeError((ish !== null && typeof ish || ish) + ' is not observable');
7845 FromObservable.prototype._subscribe = function (subscriber) {
7847 var scheduler = this.scheduler;
7848 if (scheduler == null) {
7849 return ish[observable_1.observable]().subscribe(subscriber);
7852 return ish[observable_1.observable]().subscribe(new observeOn_1.ObserveOnSubscriber(subscriber, scheduler, 0));
7855 return FromObservable;
7856 }(Observable_1.Observable));
7857 exports.FromObservable = FromObservable;
7859 },{"../Observable":29,"../operator/observeOn":129,"../symbol/iterator":154,"../symbol/observable":155,"../util/isArray":164,"../util/isArrayLike":165,"../util/isPromise":170,"./ArrayLikeObservable":85,"./ArrayObservable":86,"./IteratorObservable":93,"./PromiseObservable":94}],93:[function(require,module,exports){
7861 var __extends = (this && this.__extends) || function (d, b) {
7862 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7863 function __() { this.constructor = d; }
7864 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7866 var root_1 = require('../util/root');
7867 var Observable_1 = require('../Observable');
7868 var iterator_1 = require('../symbol/iterator');
7870 * We need this JSDoc comment for affecting ESDoc.
7871 * @extends {Ignored}
7874 var IteratorObservable = (function (_super) {
7875 __extends(IteratorObservable, _super);
7876 function IteratorObservable(iterator, scheduler) {
7878 this.scheduler = scheduler;
7879 if (iterator == null) {
7880 throw new Error('iterator cannot be null.');
7882 this.iterator = getIterator(iterator);
7884 IteratorObservable.create = function (iterator, scheduler) {
7885 return new IteratorObservable(iterator, scheduler);
7887 IteratorObservable.dispatch = function (state) {
7888 var index = state.index, hasError = state.hasError, iterator = state.iterator, subscriber = state.subscriber;
7890 subscriber.error(state.error);
7893 var result = iterator.next();
7895 subscriber.complete();
7898 subscriber.next(result.value);
7899 state.index = index + 1;
7900 if (subscriber.closed) {
7901 if (typeof iterator.return === 'function') {
7906 this.schedule(state);
7908 IteratorObservable.prototype._subscribe = function (subscriber) {
7910 var _a = this, iterator = _a.iterator, scheduler = _a.scheduler;
7912 return scheduler.schedule(IteratorObservable.dispatch, 0, {
7913 index: index, iterator: iterator, subscriber: subscriber
7918 var result = iterator.next();
7920 subscriber.complete();
7924 subscriber.next(result.value);
7926 if (subscriber.closed) {
7927 if (typeof iterator.return === 'function') {
7935 return IteratorObservable;
7936 }(Observable_1.Observable));
7937 exports.IteratorObservable = IteratorObservable;
7938 var StringIterator = (function () {
7939 function StringIterator(str, idx, len) {
7940 if (idx === void 0) { idx = 0; }
7941 if (len === void 0) { len = str.length; }
7946 StringIterator.prototype[iterator_1.iterator] = function () { return (this); };
7947 StringIterator.prototype.next = function () {
7948 return this.idx < this.len ? {
7950 value: this.str.charAt(this.idx++)
7956 return StringIterator;
7958 var ArrayIterator = (function () {
7959 function ArrayIterator(arr, idx, len) {
7960 if (idx === void 0) { idx = 0; }
7961 if (len === void 0) { len = toLength(arr); }
7966 ArrayIterator.prototype[iterator_1.iterator] = function () { return this; };
7967 ArrayIterator.prototype.next = function () {
7968 return this.idx < this.len ? {
7970 value: this.arr[this.idx++]
7976 return ArrayIterator;
7978 function getIterator(obj) {
7979 var i = obj[iterator_1.iterator];
7980 if (!i && typeof obj === 'string') {
7981 return new StringIterator(obj);
7983 if (!i && obj.length !== undefined) {
7984 return new ArrayIterator(obj);
7987 throw new TypeError('object is not iterable');
7989 return obj[iterator_1.iterator]();
7991 var maxSafeInteger = Math.pow(2, 53) - 1;
7992 function toLength(o) {
7993 var len = +o.length;
7997 if (len === 0 || !numberIsFinite(len)) {
8000 len = sign(len) * Math.floor(Math.abs(len));
8004 if (len > maxSafeInteger) {
8005 return maxSafeInteger;
8009 function numberIsFinite(value) {
8010 return typeof value === 'number' && root_1.root.isFinite(value);
8012 function sign(value) {
8013 var valueAsNumber = +value;
8014 if (valueAsNumber === 0) {
8015 return valueAsNumber;
8017 if (isNaN(valueAsNumber)) {
8018 return valueAsNumber;
8020 return valueAsNumber < 0 ? -1 : 1;
8023 },{"../Observable":29,"../symbol/iterator":154,"../util/root":172}],94:[function(require,module,exports){
8025 var __extends = (this && this.__extends) || function (d, b) {
8026 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8027 function __() { this.constructor = d; }
8028 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8030 var root_1 = require('../util/root');
8031 var Observable_1 = require('../Observable');
8033 * We need this JSDoc comment for affecting ESDoc.
8034 * @extends {Ignored}
8037 var PromiseObservable = (function (_super) {
8038 __extends(PromiseObservable, _super);
8039 function PromiseObservable(promise, scheduler) {
8041 this.promise = promise;
8042 this.scheduler = scheduler;
8045 * Converts a Promise to an Observable.
8047 * <span class="informal">Returns an Observable that just emits the Promise's
8048 * resolved value, then completes.</span>
8050 * Converts an ES2015 Promise or a Promises/A+ spec compliant Promise to an
8051 * Observable. If the Promise resolves with a value, the output Observable
8052 * emits that resolved value as a `next`, and then completes. If the Promise
8053 * is rejected, then the output Observable emits the corresponding Error.
8055 * @example <caption>Convert the Promise returned by Fetch to an Observable</caption>
8056 * var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
8057 * result.subscribe(x => console.log(x), e => console.error(e));
8059 * @see {@link bindCallback}
8062 * @param {PromiseLike<T>} promise The promise to be converted.
8063 * @param {Scheduler} [scheduler] An optional IScheduler to use for scheduling
8064 * the delivery of the resolved value (or the rejection).
8065 * @return {Observable<T>} An Observable which wraps the Promise.
8070 PromiseObservable.create = function (promise, scheduler) {
8071 return new PromiseObservable(promise, scheduler);
8073 PromiseObservable.prototype._subscribe = function (subscriber) {
8075 var promise = this.promise;
8076 var scheduler = this.scheduler;
8077 if (scheduler == null) {
8078 if (this._isScalar) {
8079 if (!subscriber.closed) {
8080 subscriber.next(this.value);
8081 subscriber.complete();
8085 promise.then(function (value) {
8086 _this.value = value;
8087 _this._isScalar = true;
8088 if (!subscriber.closed) {
8089 subscriber.next(value);
8090 subscriber.complete();
8093 if (!subscriber.closed) {
8094 subscriber.error(err);
8097 .then(null, function (err) {
8098 // escape the promise trap, throw unhandled errors
8099 root_1.root.setTimeout(function () { throw err; });
8104 if (this._isScalar) {
8105 if (!subscriber.closed) {
8106 return scheduler.schedule(dispatchNext, 0, { value: this.value, subscriber: subscriber });
8110 promise.then(function (value) {
8111 _this.value = value;
8112 _this._isScalar = true;
8113 if (!subscriber.closed) {
8114 subscriber.add(scheduler.schedule(dispatchNext, 0, { value: value, subscriber: subscriber }));
8117 if (!subscriber.closed) {
8118 subscriber.add(scheduler.schedule(dispatchError, 0, { err: err, subscriber: subscriber }));
8121 .then(null, function (err) {
8122 // escape the promise trap, throw unhandled errors
8123 root_1.root.setTimeout(function () { throw err; });
8128 return PromiseObservable;
8129 }(Observable_1.Observable));
8130 exports.PromiseObservable = PromiseObservable;
8131 function dispatchNext(arg) {
8132 var value = arg.value, subscriber = arg.subscriber;
8133 if (!subscriber.closed) {
8134 subscriber.next(value);
8135 subscriber.complete();
8138 function dispatchError(arg) {
8139 var err = arg.err, subscriber = arg.subscriber;
8140 if (!subscriber.closed) {
8141 subscriber.error(err);
8145 },{"../Observable":29,"../util/root":172}],95:[function(require,module,exports){
8147 var __extends = (this && this.__extends) || function (d, b) {
8148 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8149 function __() { this.constructor = d; }
8150 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8152 var Observable_1 = require('../Observable');
8154 * We need this JSDoc comment for affecting ESDoc.
8155 * @extends {Ignored}
8158 var ScalarObservable = (function (_super) {
8159 __extends(ScalarObservable, _super);
8160 function ScalarObservable(value, scheduler) {
8163 this.scheduler = scheduler;
8164 this._isScalar = true;
8166 this._isScalar = false;
8169 ScalarObservable.create = function (value, scheduler) {
8170 return new ScalarObservable(value, scheduler);
8172 ScalarObservable.dispatch = function (state) {
8173 var done = state.done, value = state.value, subscriber = state.subscriber;
8175 subscriber.complete();
8178 subscriber.next(value);
8179 if (subscriber.closed) {
8183 this.schedule(state);
8185 ScalarObservable.prototype._subscribe = function (subscriber) {
8186 var value = this.value;
8187 var scheduler = this.scheduler;
8189 return scheduler.schedule(ScalarObservable.dispatch, 0, {
8190 done: false, value: value, subscriber: subscriber
8194 subscriber.next(value);
8195 if (!subscriber.closed) {
8196 subscriber.complete();
8200 return ScalarObservable;
8201 }(Observable_1.Observable));
8202 exports.ScalarObservable = ScalarObservable;
8204 },{"../Observable":29}],96:[function(require,module,exports){
8206 var __extends = (this && this.__extends) || function (d, b) {
8207 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8208 function __() { this.constructor = d; }
8209 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8211 var isNumeric_1 = require('../util/isNumeric');
8212 var Observable_1 = require('../Observable');
8213 var async_1 = require('../scheduler/async');
8214 var isScheduler_1 = require('../util/isScheduler');
8215 var isDate_1 = require('../util/isDate');
8217 * We need this JSDoc comment for affecting ESDoc.
8218 * @extends {Ignored}
8221 var TimerObservable = (function (_super) {
8222 __extends(TimerObservable, _super);
8223 function TimerObservable(dueTime, period, scheduler) {
8224 if (dueTime === void 0) { dueTime = 0; }
8228 if (isNumeric_1.isNumeric(period)) {
8229 this.period = Number(period) < 1 && 1 || Number(period);
8231 else if (isScheduler_1.isScheduler(period)) {
8234 if (!isScheduler_1.isScheduler(scheduler)) {
8235 scheduler = async_1.async;
8237 this.scheduler = scheduler;
8238 this.dueTime = isDate_1.isDate(dueTime) ?
8239 (+dueTime - this.scheduler.now()) :
8243 * Creates an Observable that starts emitting after an `initialDelay` and
8244 * emits ever increasing numbers after each `period` of time thereafter.
8246 * <span class="informal">Its like {@link interval}, but you can specify when
8247 * should the emissions start.</span>
8249 * <img src="./img/timer.png" width="100%">
8251 * `timer` returns an Observable that emits an infinite sequence of ascending
8252 * integers, with a constant interval of time, `period` of your choosing
8253 * between those emissions. The first emission happens after the specified
8254 * `initialDelay`. The initial delay may be a {@link Date}. By default, this
8255 * operator uses the `async` IScheduler to provide a notion of time, but you
8256 * may pass any IScheduler to it. If `period` is not specified, the output
8257 * Observable emits only one value, `0`. Otherwise, it emits an infinite
8260 * @example <caption>Emits ascending numbers, one every second (1000ms), starting after 3 seconds</caption>
8261 * var numbers = Rx.Observable.timer(3000, 1000);
8262 * numbers.subscribe(x => console.log(x));
8264 * @example <caption>Emits one number after five seconds</caption>
8265 * var numbers = Rx.Observable.timer(5000);
8266 * numbers.subscribe(x => console.log(x));
8268 * @see {@link interval}
8269 * @see {@link delay}
8271 * @param {number|Date} initialDelay The initial delay time to wait before
8272 * emitting the first value of `0`.
8273 * @param {number} [period] The period of time between emissions of the
8274 * subsequent numbers.
8275 * @param {Scheduler} [scheduler=async] The IScheduler to use for scheduling
8276 * the emission of values, and providing a notion of "time".
8277 * @return {Observable} An Observable that emits a `0` after the
8278 * `initialDelay` and ever increasing numbers after each `period` of time
8284 TimerObservable.create = function (initialDelay, period, scheduler) {
8285 if (initialDelay === void 0) { initialDelay = 0; }
8286 return new TimerObservable(initialDelay, period, scheduler);
8288 TimerObservable.dispatch = function (state) {
8289 var index = state.index, period = state.period, subscriber = state.subscriber;
8291 subscriber.next(index);
8292 if (subscriber.closed) {
8295 else if (period === -1) {
8296 return subscriber.complete();
8298 state.index = index + 1;
8299 action.schedule(state, period);
8301 TimerObservable.prototype._subscribe = function (subscriber) {
8303 var _a = this, period = _a.period, dueTime = _a.dueTime, scheduler = _a.scheduler;
8304 return scheduler.schedule(TimerObservable.dispatch, dueTime, {
8305 index: index, period: period, subscriber: subscriber
8308 return TimerObservable;
8309 }(Observable_1.Observable));
8310 exports.TimerObservable = TimerObservable;
8312 },{"../Observable":29,"../scheduler/async":152,"../util/isDate":166,"../util/isNumeric":168,"../util/isScheduler":171}],97:[function(require,module,exports){
8314 var isScheduler_1 = require('../util/isScheduler');
8315 var isArray_1 = require('../util/isArray');
8316 var ArrayObservable_1 = require('./ArrayObservable');
8317 var combineLatest_1 = require('../operator/combineLatest');
8318 /* tslint:enable:max-line-length */
8320 * Combines multiple Observables to create an Observable whose values are
8321 * calculated from the latest values of each of its input Observables.
8323 * <span class="informal">Whenever any input Observable emits a value, it
8324 * computes a formula using the latest values from all the inputs, then emits
8325 * the output of that formula.</span>
8327 * <img src="./img/combineLatest.png" width="100%">
8329 * `combineLatest` combines the values from all the Observables passed as
8330 * arguments. This is done by subscribing to each Observable in order and,
8331 * whenever any Observable emits, collecting an array of the most recent
8332 * values from each Observable. So if you pass `n` Observables to operator,
8333 * returned Observable will always emit an array of `n` values, in order
8334 * corresponding to order of passed Observables (value from the first Observable
8335 * on the first place and so on).
8337 * Static version of `combineLatest` accepts either an array of Observables
8338 * or each Observable can be put directly as an argument. Note that array of
8339 * Observables is good choice, if you don't know beforehand how many Observables
8340 * you will combine. Passing empty array will result in Observable that
8341 * completes immediately.
8343 * To ensure output array has always the same length, `combineLatest` will
8344 * actually wait for all input Observables to emit at least once,
8345 * before it starts emitting results. This means if some Observable emits
8346 * values before other Observables started emitting, all that values but last
8347 * will be lost. On the other hand, is some Observable does not emit value but
8348 * completes, resulting Observable will complete at the same moment without
8349 * emitting anything, since it will be now impossible to include value from
8350 * completed Observable in resulting array. Also, if some input Observable does
8351 * not emit any value and never completes, `combineLatest` will also never emit
8352 * and never complete, since, again, it will wait for all streams to emit some
8355 * If at least one Observable was passed to `combineLatest` and all passed Observables
8356 * emitted something, resulting Observable will complete when all combined
8357 * streams complete. So even if some Observable completes, result of
8358 * `combineLatest` will still emit values when other Observables do. In case
8359 * of completed Observable, its value from now on will always be the last
8360 * emitted value. On the other hand, if any Observable errors, `combineLatest`
8361 * will error immediately as well, and all other Observables will be unsubscribed.
8363 * `combineLatest` accepts as optional parameter `project` function, which takes
8364 * as arguments all values that would normally be emitted by resulting Observable.
8365 * `project` can return any kind of value, which will be then emitted by Observable
8366 * instead of default array. Note that `project` does not take as argument that array
8367 * of values, but values themselves. That means default `project` can be imagined
8368 * as function that takes all its arguments and puts them into an array.
8371 * @example <caption>Combine two timer Observables</caption>
8372 * const firstTimer = Rx.Observable.timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
8373 * const secondTimer = Rx.Observable.timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now
8374 * const combinedTimers = Rx.Observable.combineLatest(firstTimer, secondTimer);
8375 * combinedTimers.subscribe(value => console.log(value));
8377 * // [0, 0] after 0.5s
8378 * // [1, 0] after 1s
8379 * // [1, 1] after 1.5s
8380 * // [2, 1] after 2s
8383 * @example <caption>Combine an array of Observables</caption>
8384 * const observables = [1, 5, 10].map(
8385 * n => Rx.Observable.of(n).delay(n * 1000).startWith(0) // emit 0 and then emit n after n seconds
8387 * const combined = Rx.Observable.combineLatest(observables);
8388 * combined.subscribe(value => console.log(value));
8390 * // [0, 0, 0] immediately
8391 * // [1, 0, 0] after 1s
8392 * // [1, 5, 0] after 5s
8393 * // [1, 5, 10] after 10s
8396 * @example <caption>Use project function to dynamically calculate the Body-Mass Index</caption>
8397 * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8398 * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8399 * var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => w / (h * h));
8400 * bmi.subscribe(x => console.log('BMI is ' + x));
8402 * // With output to console:
8403 * // BMI is 24.212293388429753
8404 * // BMI is 23.93948099205209
8405 * // BMI is 23.671253629592222
8408 * @see {@link combineAll}
8409 * @see {@link merge}
8410 * @see {@link withLatestFrom}
8412 * @param {ObservableInput} observable1 An input Observable to combine with other Observables.
8413 * @param {ObservableInput} observable2 An input Observable to combine with other Observables.
8414 * More than one input Observables may be given as arguments
8415 * or an array of Observables may be given as the first argument.
8416 * @param {function} [project] An optional function to project the values from
8417 * the combined latest values into a new value on the output Observable.
8418 * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
8419 * each input Observable.
8420 * @return {Observable} An Observable of projected values from the most recent
8421 * values from each input Observable, or an array of the most recent values from
8422 * each input Observable.
8424 * @name combineLatest
8427 function combineLatest() {
8428 var observables = [];
8429 for (var _i = 0; _i < arguments.length; _i++) {
8430 observables[_i - 0] = arguments[_i];
8433 var scheduler = null;
8434 if (isScheduler_1.isScheduler(observables[observables.length - 1])) {
8435 scheduler = observables.pop();
8437 if (typeof observables[observables.length - 1] === 'function') {
8438 project = observables.pop();
8440 // if the first and only other argument besides the resultSelector is an array
8441 // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
8442 if (observables.length === 1 && isArray_1.isArray(observables[0])) {
8443 observables = observables[0];
8445 return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new combineLatest_1.CombineLatestOperator(project));
8447 exports.combineLatest = combineLatest;
8449 },{"../operator/combineLatest":112,"../util/isArray":164,"../util/isScheduler":171,"./ArrayObservable":86}],98:[function(require,module,exports){
8451 var DeferObservable_1 = require('./DeferObservable');
8452 exports.defer = DeferObservable_1.DeferObservable.create;
8454 },{"./DeferObservable":88}],99:[function(require,module,exports){
8456 var EmptyObservable_1 = require('./EmptyObservable');
8457 exports.empty = EmptyObservable_1.EmptyObservable.create;
8459 },{"./EmptyObservable":89}],100:[function(require,module,exports){
8461 var FromObservable_1 = require('./FromObservable');
8462 exports.from = FromObservable_1.FromObservable.create;
8464 },{"./FromObservable":92}],101:[function(require,module,exports){
8466 var FromEventObservable_1 = require('./FromEventObservable');
8467 exports.fromEvent = FromEventObservable_1.FromEventObservable.create;
8469 },{"./FromEventObservable":91}],102:[function(require,module,exports){
8471 var PromiseObservable_1 = require('./PromiseObservable');
8472 exports.fromPromise = PromiseObservable_1.PromiseObservable.create;
8474 },{"./PromiseObservable":94}],103:[function(require,module,exports){
8476 var merge_1 = require('../operator/merge');
8477 exports.merge = merge_1.mergeStatic;
8479 },{"../operator/merge":125}],104:[function(require,module,exports){
8481 var ArrayObservable_1 = require('./ArrayObservable');
8482 exports.of = ArrayObservable_1.ArrayObservable.of;
8484 },{"./ArrayObservable":86}],105:[function(require,module,exports){
8486 var ErrorObservable_1 = require('./ErrorObservable');
8487 exports._throw = ErrorObservable_1.ErrorObservable.create;
8489 },{"./ErrorObservable":90}],106:[function(require,module,exports){
8491 var TimerObservable_1 = require('./TimerObservable');
8492 exports.timer = TimerObservable_1.TimerObservable.create;
8494 },{"./TimerObservable":96}],107:[function(require,module,exports){
8496 var zip_1 = require('../operator/zip');
8497 exports.zip = zip_1.zipStatic;
8499 },{"../operator/zip":146}],108:[function(require,module,exports){
8501 var __extends = (this && this.__extends) || function (d, b) {
8502 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8503 function __() { this.constructor = d; }
8504 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8506 var OuterSubscriber_1 = require('../OuterSubscriber');
8507 var subscribeToResult_1 = require('../util/subscribeToResult');
8509 * Buffers the source Observable values until `closingNotifier` emits.
8511 * <span class="informal">Collects values from the past as an array, and emits
8512 * that array only when another Observable emits.</span>
8514 * <img src="./img/buffer.png" width="100%">
8516 * Buffers the incoming Observable values until the given `closingNotifier`
8517 * Observable emits a value, at which point it emits the buffer on the output
8518 * Observable and starts a new buffer internally, awaiting the next time
8519 * `closingNotifier` emits.
8521 * @example <caption>On every click, emit array of most recent interval events</caption>
8522 * var clicks = Rx.Observable.fromEvent(document, 'click');
8523 * var interval = Rx.Observable.interval(1000);
8524 * var buffered = interval.buffer(clicks);
8525 * buffered.subscribe(x => console.log(x));
8527 * @see {@link bufferCount}
8528 * @see {@link bufferTime}
8529 * @see {@link bufferToggle}
8530 * @see {@link bufferWhen}
8531 * @see {@link window}
8533 * @param {Observable<any>} closingNotifier An Observable that signals the
8534 * buffer to be emitted on the output Observable.
8535 * @return {Observable<T[]>} An Observable of buffers, which are arrays of
8540 function buffer(closingNotifier) {
8541 return this.lift(new BufferOperator(closingNotifier));
8543 exports.buffer = buffer;
8544 var BufferOperator = (function () {
8545 function BufferOperator(closingNotifier) {
8546 this.closingNotifier = closingNotifier;
8548 BufferOperator.prototype.call = function (subscriber, source) {
8549 return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
8551 return BufferOperator;
8554 * We need this JSDoc comment for affecting ESDoc.
8556 * @extends {Ignored}
8558 var BufferSubscriber = (function (_super) {
8559 __extends(BufferSubscriber, _super);
8560 function BufferSubscriber(destination, closingNotifier) {
8561 _super.call(this, destination);
8563 this.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
8565 BufferSubscriber.prototype._next = function (value) {
8566 this.buffer.push(value);
8568 BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8569 var buffer = this.buffer;
8571 this.destination.next(buffer);
8573 return BufferSubscriber;
8574 }(OuterSubscriber_1.OuterSubscriber));
8576 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],109:[function(require,module,exports){
8578 var __extends = (this && this.__extends) || function (d, b) {
8579 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8580 function __() { this.constructor = d; }
8581 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8583 var Subscriber_1 = require('../Subscriber');
8585 * Buffers the source Observable values until the size hits the maximum
8586 * `bufferSize` given.
8588 * <span class="informal">Collects values from the past as an array, and emits
8589 * that array only when its size reaches `bufferSize`.</span>
8591 * <img src="./img/bufferCount.png" width="100%">
8593 * Buffers a number of values from the source Observable by `bufferSize` then
8594 * emits the buffer and clears it, and starts a new buffer each
8595 * `startBufferEvery` values. If `startBufferEvery` is not provided or is
8596 * `null`, then new buffers are started immediately at the start of the source
8597 * and when each buffer closes and is emitted.
8599 * @example <caption>Emit the last two click events as an array</caption>
8600 * var clicks = Rx.Observable.fromEvent(document, 'click');
8601 * var buffered = clicks.bufferCount(2);
8602 * buffered.subscribe(x => console.log(x));
8604 * @example <caption>On every click, emit the last two click events as an array</caption>
8605 * var clicks = Rx.Observable.fromEvent(document, 'click');
8606 * var buffered = clicks.bufferCount(2, 1);
8607 * buffered.subscribe(x => console.log(x));
8609 * @see {@link buffer}
8610 * @see {@link bufferTime}
8611 * @see {@link bufferToggle}
8612 * @see {@link bufferWhen}
8613 * @see {@link pairwise}
8614 * @see {@link windowCount}
8616 * @param {number} bufferSize The maximum size of the buffer emitted.
8617 * @param {number} [startBufferEvery] Interval at which to start a new buffer.
8618 * For example if `startBufferEvery` is `2`, then a new buffer will be started
8619 * on every other value from the source. A new buffer is started at the
8620 * beginning of the source by default.
8621 * @return {Observable<T[]>} An Observable of arrays of buffered values.
8622 * @method bufferCount
8625 function bufferCount(bufferSize, startBufferEvery) {
8626 if (startBufferEvery === void 0) { startBufferEvery = null; }
8627 return this.lift(new BufferCountOperator(bufferSize, startBufferEvery));
8629 exports.bufferCount = bufferCount;
8630 var BufferCountOperator = (function () {
8631 function BufferCountOperator(bufferSize, startBufferEvery) {
8632 this.bufferSize = bufferSize;
8633 this.startBufferEvery = startBufferEvery;
8634 if (!startBufferEvery || bufferSize === startBufferEvery) {
8635 this.subscriberClass = BufferCountSubscriber;
8638 this.subscriberClass = BufferSkipCountSubscriber;
8641 BufferCountOperator.prototype.call = function (subscriber, source) {
8642 return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
8644 return BufferCountOperator;
8647 * We need this JSDoc comment for affecting ESDoc.
8649 * @extends {Ignored}
8651 var BufferCountSubscriber = (function (_super) {
8652 __extends(BufferCountSubscriber, _super);
8653 function BufferCountSubscriber(destination, bufferSize) {
8654 _super.call(this, destination);
8655 this.bufferSize = bufferSize;
8658 BufferCountSubscriber.prototype._next = function (value) {
8659 var buffer = this.buffer;
8661 if (buffer.length == this.bufferSize) {
8662 this.destination.next(buffer);
8666 BufferCountSubscriber.prototype._complete = function () {
8667 var buffer = this.buffer;
8668 if (buffer.length > 0) {
8669 this.destination.next(buffer);
8671 _super.prototype._complete.call(this);
8673 return BufferCountSubscriber;
8674 }(Subscriber_1.Subscriber));
8676 * We need this JSDoc comment for affecting ESDoc.
8678 * @extends {Ignored}
8680 var BufferSkipCountSubscriber = (function (_super) {
8681 __extends(BufferSkipCountSubscriber, _super);
8682 function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) {
8683 _super.call(this, destination);
8684 this.bufferSize = bufferSize;
8685 this.startBufferEvery = startBufferEvery;
8689 BufferSkipCountSubscriber.prototype._next = function (value) {
8690 var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count;
8692 if (count % startBufferEvery === 0) {
8695 for (var i = buffers.length; i--;) {
8696 var buffer = buffers[i];
8698 if (buffer.length === bufferSize) {
8699 buffers.splice(i, 1);
8700 this.destination.next(buffer);
8704 BufferSkipCountSubscriber.prototype._complete = function () {
8705 var _a = this, buffers = _a.buffers, destination = _a.destination;
8706 while (buffers.length > 0) {
8707 var buffer = buffers.shift();
8708 if (buffer.length > 0) {
8709 destination.next(buffer);
8712 _super.prototype._complete.call(this);
8714 return BufferSkipCountSubscriber;
8715 }(Subscriber_1.Subscriber));
8717 },{"../Subscriber":36}],110:[function(require,module,exports){
8719 var __extends = (this && this.__extends) || function (d, b) {
8720 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8721 function __() { this.constructor = d; }
8722 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8724 var Subscription_1 = require('../Subscription');
8725 var tryCatch_1 = require('../util/tryCatch');
8726 var errorObject_1 = require('../util/errorObject');
8727 var OuterSubscriber_1 = require('../OuterSubscriber');
8728 var subscribeToResult_1 = require('../util/subscribeToResult');
8730 * Buffers the source Observable values, using a factory function of closing
8731 * Observables to determine when to close, emit, and reset the buffer.
8733 * <span class="informal">Collects values from the past as an array. When it
8734 * starts collecting values, it calls a function that returns an Observable that
8735 * tells when to close the buffer and restart collecting.</span>
8737 * <img src="./img/bufferWhen.png" width="100%">
8739 * Opens a buffer immediately, then closes the buffer when the observable
8740 * returned by calling `closingSelector` function emits a value. When it closes
8741 * the buffer, it immediately opens a new buffer and repeats the process.
8743 * @example <caption>Emit an array of the last clicks every [1-5] random seconds</caption>
8744 * var clicks = Rx.Observable.fromEvent(document, 'click');
8745 * var buffered = clicks.bufferWhen(() =>
8746 * Rx.Observable.interval(1000 + Math.random() * 4000)
8748 * buffered.subscribe(x => console.log(x));
8750 * @see {@link buffer}
8751 * @see {@link bufferCount}
8752 * @see {@link bufferTime}
8753 * @see {@link bufferToggle}
8754 * @see {@link windowWhen}
8756 * @param {function(): Observable} closingSelector A function that takes no
8757 * arguments and returns an Observable that signals buffer closure.
8758 * @return {Observable<T[]>} An observable of arrays of buffered values.
8759 * @method bufferWhen
8762 function bufferWhen(closingSelector) {
8763 return this.lift(new BufferWhenOperator(closingSelector));
8765 exports.bufferWhen = bufferWhen;
8766 var BufferWhenOperator = (function () {
8767 function BufferWhenOperator(closingSelector) {
8768 this.closingSelector = closingSelector;
8770 BufferWhenOperator.prototype.call = function (subscriber, source) {
8771 return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
8773 return BufferWhenOperator;
8776 * We need this JSDoc comment for affecting ESDoc.
8778 * @extends {Ignored}
8780 var BufferWhenSubscriber = (function (_super) {
8781 __extends(BufferWhenSubscriber, _super);
8782 function BufferWhenSubscriber(destination, closingSelector) {
8783 _super.call(this, destination);
8784 this.closingSelector = closingSelector;
8785 this.subscribing = false;
8788 BufferWhenSubscriber.prototype._next = function (value) {
8789 this.buffer.push(value);
8791 BufferWhenSubscriber.prototype._complete = function () {
8792 var buffer = this.buffer;
8794 this.destination.next(buffer);
8796 _super.prototype._complete.call(this);
8798 BufferWhenSubscriber.prototype._unsubscribe = function () {
8800 this.subscribing = false;
8802 BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8805 BufferWhenSubscriber.prototype.notifyComplete = function () {
8806 if (this.subscribing) {
8813 BufferWhenSubscriber.prototype.openBuffer = function () {
8814 var closingSubscription = this.closingSubscription;
8815 if (closingSubscription) {
8816 this.remove(closingSubscription);
8817 closingSubscription.unsubscribe();
8819 var buffer = this.buffer;
8821 this.destination.next(buffer);
8824 var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)();
8825 if (closingNotifier === errorObject_1.errorObject) {
8826 this.error(errorObject_1.errorObject.e);
8829 closingSubscription = new Subscription_1.Subscription();
8830 this.closingSubscription = closingSubscription;
8831 this.add(closingSubscription);
8832 this.subscribing = true;
8833 closingSubscription.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
8834 this.subscribing = false;
8837 return BufferWhenSubscriber;
8838 }(OuterSubscriber_1.OuterSubscriber));
8840 },{"../OuterSubscriber":31,"../Subscription":37,"../util/errorObject":163,"../util/subscribeToResult":173,"../util/tryCatch":175}],111:[function(require,module,exports){
8842 var __extends = (this && this.__extends) || function (d, b) {
8843 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8844 function __() { this.constructor = d; }
8845 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8847 var OuterSubscriber_1 = require('../OuterSubscriber');
8848 var subscribeToResult_1 = require('../util/subscribeToResult');
8850 * Catches errors on the observable to be handled by returning a new observable or throwing an error.
8852 * <img src="./img/catch.png" width="100%">
8854 * @example <caption>Continues with a different Observable when there's an error</caption>
8856 * Observable.of(1, 2, 3, 4, 5)
8863 * .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
8864 * .subscribe(x => console.log(x));
8865 * // 1, 2, 3, I, II, III, IV, V
8867 * @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
8869 * Observable.of(1, 2, 3, 4, 5)
8876 * .catch((err, caught) => caught)
8878 * .subscribe(x => console.log(x));
8879 * // 1, 2, 3, 1, 2, 3, ...
8881 * @example <caption>Throws a new error when the source Observable throws an error</caption>
8883 * Observable.of(1, 2, 3, 4, 5)
8891 * throw 'error in source. Details: ' + err;
8894 * x => console.log(x),
8895 * err => console.log(err)
8897 * // 1, 2, 3, error in source. Details: four!
8899 * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
8900 * is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
8901 * is returned by the `selector` will be used to continue the observable chain.
8902 * @return {Observable} An observable that originates from either the source or the observable returned by the
8903 * catch `selector` function.
8908 function _catch(selector) {
8909 var operator = new CatchOperator(selector);
8910 var caught = this.lift(operator);
8911 return (operator.caught = caught);
8913 exports._catch = _catch;
8914 var CatchOperator = (function () {
8915 function CatchOperator(selector) {
8916 this.selector = selector;
8918 CatchOperator.prototype.call = function (subscriber, source) {
8919 return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
8921 return CatchOperator;
8924 * We need this JSDoc comment for affecting ESDoc.
8926 * @extends {Ignored}
8928 var CatchSubscriber = (function (_super) {
8929 __extends(CatchSubscriber, _super);
8930 function CatchSubscriber(destination, selector, caught) {
8931 _super.call(this, destination);
8932 this.selector = selector;
8933 this.caught = caught;
8935 // NOTE: overriding `error` instead of `_error` because we don't want
8936 // to have this flag this subscriber as `isStopped`. We can mimic the
8937 // behavior of the RetrySubscriber (from the `retry` operator), where
8938 // we unsubscribe from our source chain, reset our Subscriber flags,
8939 // then subscribe to the selector result.
8940 CatchSubscriber.prototype.error = function (err) {
8941 if (!this.isStopped) {
8942 var result = void 0;
8944 result = this.selector(err, this.caught);
8947 _super.prototype.error.call(this, err2);
8950 this._unsubscribeAndRecycle();
8951 this.add(subscribeToResult_1.subscribeToResult(this, result));
8954 return CatchSubscriber;
8955 }(OuterSubscriber_1.OuterSubscriber));
8957 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],112:[function(require,module,exports){
8959 var __extends = (this && this.__extends) || function (d, b) {
8960 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8961 function __() { this.constructor = d; }
8962 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8964 var ArrayObservable_1 = require('../observable/ArrayObservable');
8965 var isArray_1 = require('../util/isArray');
8966 var OuterSubscriber_1 = require('../OuterSubscriber');
8967 var subscribeToResult_1 = require('../util/subscribeToResult');
8969 /* tslint:enable:max-line-length */
8971 * Combines multiple Observables to create an Observable whose values are
8972 * calculated from the latest values of each of its input Observables.
8974 * <span class="informal">Whenever any input Observable emits a value, it
8975 * computes a formula using the latest values from all the inputs, then emits
8976 * the output of that formula.</span>
8978 * <img src="./img/combineLatest.png" width="100%">
8980 * `combineLatest` combines the values from this Observable with values from
8981 * Observables passed as arguments. This is done by subscribing to each
8982 * Observable, in order, and collecting an array of each of the most recent
8983 * values any time any of the input Observables emits, then either taking that
8984 * array and passing it as arguments to an optional `project` function and
8985 * emitting the return value of that, or just emitting the array of recent
8986 * values directly if there is no `project` function.
8988 * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
8989 * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8990 * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8991 * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
8992 * bmi.subscribe(x => console.log('BMI is ' + x));
8994 * // With output to console:
8995 * // BMI is 24.212293388429753
8996 * // BMI is 23.93948099205209
8997 * // BMI is 23.671253629592222
8999 * @see {@link combineAll}
9000 * @see {@link merge}
9001 * @see {@link withLatestFrom}
9003 * @param {ObservableInput} other An input Observable to combine with the source
9004 * Observable. More than one input Observables may be given as argument.
9005 * @param {function} [project] An optional function to project the values from
9006 * the combined latest values into a new value on the output Observable.
9007 * @return {Observable} An Observable of projected values from the most recent
9008 * values from each input Observable, or an array of the most recent values from
9009 * each input Observable.
9010 * @method combineLatest
9013 function combineLatest() {
9014 var observables = [];
9015 for (var _i = 0; _i < arguments.length; _i++) {
9016 observables[_i - 0] = arguments[_i];
9019 if (typeof observables[observables.length - 1] === 'function') {
9020 project = observables.pop();
9022 // if the first and only other argument besides the resultSelector is an array
9023 // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
9024 if (observables.length === 1 && isArray_1.isArray(observables[0])) {
9025 observables = observables[0].slice();
9027 observables.unshift(this);
9028 return this.lift.call(new ArrayObservable_1.ArrayObservable(observables), new CombineLatestOperator(project));
9030 exports.combineLatest = combineLatest;
9031 var CombineLatestOperator = (function () {
9032 function CombineLatestOperator(project) {
9033 this.project = project;
9035 CombineLatestOperator.prototype.call = function (subscriber, source) {
9036 return source.subscribe(new CombineLatestSubscriber(subscriber, this.project));
9038 return CombineLatestOperator;
9040 exports.CombineLatestOperator = CombineLatestOperator;
9042 * We need this JSDoc comment for affecting ESDoc.
9044 * @extends {Ignored}
9046 var CombineLatestSubscriber = (function (_super) {
9047 __extends(CombineLatestSubscriber, _super);
9048 function CombineLatestSubscriber(destination, project) {
9049 _super.call(this, destination);
9050 this.project = project;
9053 this.observables = [];
9055 CombineLatestSubscriber.prototype._next = function (observable) {
9056 this.values.push(none);
9057 this.observables.push(observable);
9059 CombineLatestSubscriber.prototype._complete = function () {
9060 var observables = this.observables;
9061 var len = observables.length;
9063 this.destination.complete();
9067 this.toRespond = len;
9068 for (var i = 0; i < len; i++) {
9069 var observable = observables[i];
9070 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
9074 CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
9075 if ((this.active -= 1) === 0) {
9076 this.destination.complete();
9079 CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9080 var values = this.values;
9081 var oldVal = values[outerIndex];
9082 var toRespond = !this.toRespond
9084 : oldVal === none ? --this.toRespond : this.toRespond;
9085 values[outerIndex] = innerValue;
9086 if (toRespond === 0) {
9088 this._tryProject(values);
9091 this.destination.next(values.slice());
9095 CombineLatestSubscriber.prototype._tryProject = function (values) {
9098 result = this.project.apply(this, values);
9101 this.destination.error(err);
9104 this.destination.next(result);
9106 return CombineLatestSubscriber;
9107 }(OuterSubscriber_1.OuterSubscriber));
9108 exports.CombineLatestSubscriber = CombineLatestSubscriber;
9110 },{"../OuterSubscriber":31,"../observable/ArrayObservable":86,"../util/isArray":164,"../util/subscribeToResult":173}],113:[function(require,module,exports){
9112 var Observable_1 = require('../Observable');
9113 var isScheduler_1 = require('../util/isScheduler');
9114 var ArrayObservable_1 = require('../observable/ArrayObservable');
9115 var mergeAll_1 = require('./mergeAll');
9116 /* tslint:enable:max-line-length */
9118 * Creates an output Observable which sequentially emits all values from every
9119 * given input Observable after the current Observable.
9121 * <span class="informal">Concatenates multiple Observables together by
9122 * sequentially emitting their values, one Observable after the other.</span>
9124 * <img src="./img/concat.png" width="100%">
9126 * Joins this Observable with multiple other Observables by subscribing to them
9127 * one at a time, starting with the source, and merging their results into the
9128 * output Observable. Will wait for each Observable to complete before moving
9131 * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
9132 * var timer = Rx.Observable.interval(1000).take(4);
9133 * var sequence = Rx.Observable.range(1, 10);
9134 * var result = timer.concat(sequence);
9135 * result.subscribe(x => console.log(x));
9138 * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
9140 * @example <caption>Concatenate 3 Observables</caption>
9141 * var timer1 = Rx.Observable.interval(1000).take(10);
9142 * var timer2 = Rx.Observable.interval(2000).take(6);
9143 * var timer3 = Rx.Observable.interval(500).take(10);
9144 * var result = timer1.concat(timer2, timer3);
9145 * result.subscribe(x => console.log(x));
9147 * // results in the following:
9148 * // (Prints to console sequentially)
9149 * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
9150 * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
9151 * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
9153 * @see {@link concatAll}
9154 * @see {@link concatMap}
9155 * @see {@link concatMapTo}
9157 * @param {ObservableInput} other An input Observable to concatenate after the source
9158 * Observable. More than one input Observables may be given as argument.
9159 * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
9160 * Observable subscription on.
9161 * @return {Observable} All values of each passed Observable merged into a
9162 * single Observable, in order, in serial fashion.
9167 var observables = [];
9168 for (var _i = 0; _i < arguments.length; _i++) {
9169 observables[_i - 0] = arguments[_i];
9171 return this.lift.call(concatStatic.apply(void 0, [this].concat(observables)));
9173 exports.concat = concat;
9174 /* tslint:enable:max-line-length */
9176 * Creates an output Observable which sequentially emits all values from given
9177 * Observable and then moves on to the next.
9179 * <span class="informal">Concatenates multiple Observables together by
9180 * sequentially emitting their values, one Observable after the other.</span>
9182 * <img src="./img/concat.png" width="100%">
9184 * `concat` joins multiple Observables together, by subscribing to them one at a time and
9185 * merging their results into the output Observable. You can pass either an array of
9186 * Observables, or put them directly as arguments. Passing an empty array will result
9187 * in Observable that completes immediately.
9189 * `concat` will subscribe to first input Observable and emit all its values, without
9190 * changing or affecting them in any way. When that Observable completes, it will
9191 * subscribe to then next Observable passed and, again, emit its values. This will be
9192 * repeated, until the operator runs out of Observables. When last input Observable completes,
9193 * `concat` will complete as well. At any given moment only one Observable passed to operator
9194 * emits values. If you would like to emit values from passed Observables concurrently, check out
9195 * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,
9196 * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.
9198 * Note that if some input Observable never completes, `concat` will also never complete
9199 * and Observables following the one that did not complete will never be subscribed. On the other
9200 * hand, if some Observable simply completes immediately after it is subscribed, it will be
9201 * invisible for `concat`, which will just move on to the next Observable.
9203 * If any Observable in chain errors, instead of passing control to the next Observable,
9204 * `concat` will error immediately as well. Observables that would be subscribed after
9205 * the one that emitted error, never will.
9207 * If you pass to `concat` the same Observable many times, its stream of values
9208 * will be "replayed" on every subscription, which means you can repeat given Observable
9209 * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,
9210 * you can always use {@link repeat}.
9212 * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
9213 * var timer = Rx.Observable.interval(1000).take(4);
9214 * var sequence = Rx.Observable.range(1, 10);
9215 * var result = Rx.Observable.concat(timer, sequence);
9216 * result.subscribe(x => console.log(x));
9219 * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
9222 * @example <caption>Concatenate an array of 3 Observables</caption>
9223 * var timer1 = Rx.Observable.interval(1000).take(10);
9224 * var timer2 = Rx.Observable.interval(2000).take(6);
9225 * var timer3 = Rx.Observable.interval(500).take(10);
9226 * var result = Rx.Observable.concat([timer1, timer2, timer3]); // note that array is passed
9227 * result.subscribe(x => console.log(x));
9229 * // results in the following:
9230 * // (Prints to console sequentially)
9231 * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
9232 * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
9233 * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
9236 * @example <caption>Concatenate the same Observable to repeat it</caption>
9237 * const timer = Rx.Observable.interval(1000).take(2);
9239 * Rx.Observable.concat(timer, timer) // concating the same Observable!
9241 * value => console.log(value),
9243 * () => console.log('...and it is done!')
9251 * // "...and it is done!" also after 4s
9253 * @see {@link concatAll}
9254 * @see {@link concatMap}
9255 * @see {@link concatMapTo}
9257 * @param {ObservableInput} input1 An input Observable to concatenate with others.
9258 * @param {ObservableInput} input2 An input Observable to concatenate with others.
9259 * More than one input Observables may be given as argument.
9260 * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
9261 * Observable subscription on.
9262 * @return {Observable} All values of each passed Observable merged into a
9263 * single Observable, in order, in serial fashion.
9268 function concatStatic() {
9269 var observables = [];
9270 for (var _i = 0; _i < arguments.length; _i++) {
9271 observables[_i - 0] = arguments[_i];
9273 var scheduler = null;
9274 var args = observables;
9275 if (isScheduler_1.isScheduler(args[observables.length - 1])) {
9276 scheduler = args.pop();
9278 if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
9279 return observables[0];
9281 return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(1));
9283 exports.concatStatic = concatStatic;
9285 },{"../Observable":29,"../observable/ArrayObservable":86,"../util/isScheduler":171,"./mergeAll":126}],114:[function(require,module,exports){
9287 var __extends = (this && this.__extends) || function (d, b) {
9288 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9289 function __() { this.constructor = d; }
9290 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9292 var Subscriber_1 = require('../Subscriber');
9293 var async_1 = require('../scheduler/async');
9295 * Emits a value from the source Observable only after a particular time span
9296 * has passed without another source emission.
9298 * <span class="informal">It's like {@link delay}, but passes only the most
9299 * recent value from each burst of emissions.</span>
9301 * <img src="./img/debounceTime.png" width="100%">
9303 * `debounceTime` delays values emitted by the source Observable, but drops
9304 * previous pending delayed emissions if a new value arrives on the source
9305 * Observable. This operator keeps track of the most recent value from the
9306 * source Observable, and emits that only when `dueTime` enough time has passed
9307 * without any other value appearing on the source Observable. If a new value
9308 * appears before `dueTime` silence occurs, the previous value will be dropped
9309 * and will not be emitted on the output Observable.
9311 * This is a rate-limiting operator, because it is impossible for more than one
9312 * value to be emitted in any time window of duration `dueTime`, but it is also
9313 * a delay-like operator since output emissions do not occur at the same time as
9314 * they did on the source Observable. Optionally takes a {@link IScheduler} for
9317 * @example <caption>Emit the most recent click after a burst of clicks</caption>
9318 * var clicks = Rx.Observable.fromEvent(document, 'click');
9319 * var result = clicks.debounceTime(1000);
9320 * result.subscribe(x => console.log(x));
9322 * @see {@link auditTime}
9323 * @see {@link debounce}
9324 * @see {@link delay}
9325 * @see {@link sampleTime}
9326 * @see {@link throttleTime}
9328 * @param {number} dueTime The timeout duration in milliseconds (or the time
9329 * unit determined internally by the optional `scheduler`) for the window of
9330 * time required to wait for emission silence before emitting the most recent
9332 * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
9333 * managing the timers that handle the timeout for each value.
9334 * @return {Observable} An Observable that delays the emissions of the source
9335 * Observable by the specified `dueTime`, and may drop some values if they occur
9337 * @method debounceTime
9340 function debounceTime(dueTime, scheduler) {
9341 if (scheduler === void 0) { scheduler = async_1.async; }
9342 return this.lift(new DebounceTimeOperator(dueTime, scheduler));
9344 exports.debounceTime = debounceTime;
9345 var DebounceTimeOperator = (function () {
9346 function DebounceTimeOperator(dueTime, scheduler) {
9347 this.dueTime = dueTime;
9348 this.scheduler = scheduler;
9350 DebounceTimeOperator.prototype.call = function (subscriber, source) {
9351 return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
9353 return DebounceTimeOperator;
9356 * We need this JSDoc comment for affecting ESDoc.
9358 * @extends {Ignored}
9360 var DebounceTimeSubscriber = (function (_super) {
9361 __extends(DebounceTimeSubscriber, _super);
9362 function DebounceTimeSubscriber(destination, dueTime, scheduler) {
9363 _super.call(this, destination);
9364 this.dueTime = dueTime;
9365 this.scheduler = scheduler;
9366 this.debouncedSubscription = null;
9367 this.lastValue = null;
9368 this.hasValue = false;
9370 DebounceTimeSubscriber.prototype._next = function (value) {
9371 this.clearDebounce();
9372 this.lastValue = value;
9373 this.hasValue = true;
9374 this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
9376 DebounceTimeSubscriber.prototype._complete = function () {
9377 this.debouncedNext();
9378 this.destination.complete();
9380 DebounceTimeSubscriber.prototype.debouncedNext = function () {
9381 this.clearDebounce();
9382 if (this.hasValue) {
9383 this.destination.next(this.lastValue);
9384 this.lastValue = null;
9385 this.hasValue = false;
9388 DebounceTimeSubscriber.prototype.clearDebounce = function () {
9389 var debouncedSubscription = this.debouncedSubscription;
9390 if (debouncedSubscription !== null) {
9391 this.remove(debouncedSubscription);
9392 debouncedSubscription.unsubscribe();
9393 this.debouncedSubscription = null;
9396 return DebounceTimeSubscriber;
9397 }(Subscriber_1.Subscriber));
9398 function dispatchNext(subscriber) {
9399 subscriber.debouncedNext();
9402 },{"../Subscriber":36,"../scheduler/async":152}],115:[function(require,module,exports){
9404 var __extends = (this && this.__extends) || function (d, b) {
9405 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9406 function __() { this.constructor = d; }
9407 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9409 var async_1 = require('../scheduler/async');
9410 var isDate_1 = require('../util/isDate');
9411 var Subscriber_1 = require('../Subscriber');
9412 var Notification_1 = require('../Notification');
9414 * Delays the emission of items from the source Observable by a given timeout or
9415 * until a given Date.
9417 * <span class="informal">Time shifts each item by some specified amount of
9418 * milliseconds.</span>
9420 * <img src="./img/delay.png" width="100%">
9422 * If the delay argument is a Number, this operator time shifts the source
9423 * Observable by that amount of time expressed in milliseconds. The relative
9424 * time intervals between the values are preserved.
9426 * If the delay argument is a Date, this operator time shifts the start of the
9427 * Observable execution until the given date occurs.
9429 * @example <caption>Delay each click by one second</caption>
9430 * var clicks = Rx.Observable.fromEvent(document, 'click');
9431 * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
9432 * delayedClicks.subscribe(x => console.log(x));
9434 * @example <caption>Delay all clicks until a future date happens</caption>
9435 * var clicks = Rx.Observable.fromEvent(document, 'click');
9436 * var date = new Date('March 15, 2050 12:00:00'); // in the future
9437 * var delayedClicks = clicks.delay(date); // click emitted only after that date
9438 * delayedClicks.subscribe(x => console.log(x));
9440 * @see {@link debounceTime}
9441 * @see {@link delayWhen}
9443 * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
9444 * a `Date` until which the emission of the source items is delayed.
9445 * @param {Scheduler} [scheduler=async] The IScheduler to use for
9446 * managing the timers that handle the time-shift for each item.
9447 * @return {Observable} An Observable that delays the emissions of the source
9448 * Observable by the specified timeout or Date.
9452 function delay(delay, scheduler) {
9453 if (scheduler === void 0) { scheduler = async_1.async; }
9454 var absoluteDelay = isDate_1.isDate(delay);
9455 var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
9456 return this.lift(new DelayOperator(delayFor, scheduler));
9458 exports.delay = delay;
9459 var DelayOperator = (function () {
9460 function DelayOperator(delay, scheduler) {
9462 this.scheduler = scheduler;
9464 DelayOperator.prototype.call = function (subscriber, source) {
9465 return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
9467 return DelayOperator;
9470 * We need this JSDoc comment for affecting ESDoc.
9472 * @extends {Ignored}
9474 var DelaySubscriber = (function (_super) {
9475 __extends(DelaySubscriber, _super);
9476 function DelaySubscriber(destination, delay, scheduler) {
9477 _super.call(this, destination);
9479 this.scheduler = scheduler;
9481 this.active = false;
9482 this.errored = false;
9484 DelaySubscriber.dispatch = function (state) {
9485 var source = state.source;
9486 var queue = source.queue;
9487 var scheduler = state.scheduler;
9488 var destination = state.destination;
9489 while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
9490 queue.shift().notification.observe(destination);
9492 if (queue.length > 0) {
9493 var delay_1 = Math.max(0, queue[0].time - scheduler.now());
9494 this.schedule(state, delay_1);
9497 source.active = false;
9500 DelaySubscriber.prototype._schedule = function (scheduler) {
9502 this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
9503 source: this, destination: this.destination, scheduler: scheduler
9506 DelaySubscriber.prototype.scheduleNotification = function (notification) {
9507 if (this.errored === true) {
9510 var scheduler = this.scheduler;
9511 var message = new DelayMessage(scheduler.now() + this.delay, notification);
9512 this.queue.push(message);
9513 if (this.active === false) {
9514 this._schedule(scheduler);
9517 DelaySubscriber.prototype._next = function (value) {
9518 this.scheduleNotification(Notification_1.Notification.createNext(value));
9520 DelaySubscriber.prototype._error = function (err) {
9521 this.errored = true;
9523 this.destination.error(err);
9525 DelaySubscriber.prototype._complete = function () {
9526 this.scheduleNotification(Notification_1.Notification.createComplete());
9528 return DelaySubscriber;
9529 }(Subscriber_1.Subscriber));
9530 var DelayMessage = (function () {
9531 function DelayMessage(time, notification) {
9533 this.notification = notification;
9535 return DelayMessage;
9538 },{"../Notification":28,"../Subscriber":36,"../scheduler/async":152,"../util/isDate":166}],116:[function(require,module,exports){
9540 var __extends = (this && this.__extends) || function (d, b) {
9541 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9542 function __() { this.constructor = d; }
9543 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9545 var OuterSubscriber_1 = require('../OuterSubscriber');
9546 var subscribeToResult_1 = require('../util/subscribeToResult');
9547 var Set_1 = require('../util/Set');
9549 * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
9551 * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
9552 * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
9553 * source observable directly with an equality check against previous values.
9555 * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
9557 * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
9558 * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
9559 * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
9560 * that the internal `Set` can be "flushed", basically clearing it of values.
9562 * @example <caption>A simple example with numbers</caption>
9563 * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
9565 * .subscribe(x => console.log(x)); // 1, 2, 3, 4
9567 * @example <caption>An example using a keySelector function</caption>
9568 * interface Person {
9573 * Observable.of<Person>(
9574 * { age: 4, name: 'Foo'},
9575 * { age: 7, name: 'Bar'},
9576 * { age: 5, name: 'Foo'})
9577 * .distinct((p: Person) => p.name)
9578 * .subscribe(x => console.log(x));
9581 * // { age: 4, name: 'Foo' }
9582 * // { age: 7, name: 'Bar' }
9584 * @see {@link distinctUntilChanged}
9585 * @see {@link distinctUntilKeyChanged}
9587 * @param {function} [keySelector] Optional function to select which value you want to check as distinct.
9588 * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.
9589 * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9593 function distinct(keySelector, flushes) {
9594 return this.lift(new DistinctOperator(keySelector, flushes));
9596 exports.distinct = distinct;
9597 var DistinctOperator = (function () {
9598 function DistinctOperator(keySelector, flushes) {
9599 this.keySelector = keySelector;
9600 this.flushes = flushes;
9602 DistinctOperator.prototype.call = function (subscriber, source) {
9603 return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
9605 return DistinctOperator;
9608 * We need this JSDoc comment for affecting ESDoc.
9610 * @extends {Ignored}
9612 var DistinctSubscriber = (function (_super) {
9613 __extends(DistinctSubscriber, _super);
9614 function DistinctSubscriber(destination, keySelector, flushes) {
9615 _super.call(this, destination);
9616 this.keySelector = keySelector;
9617 this.values = new Set_1.Set();
9619 this.add(subscribeToResult_1.subscribeToResult(this, flushes));
9622 DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9623 this.values.clear();
9625 DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
9628 DistinctSubscriber.prototype._next = function (value) {
9629 if (this.keySelector) {
9630 this._useKeySelector(value);
9633 this._finalizeNext(value, value);
9636 DistinctSubscriber.prototype._useKeySelector = function (value) {
9638 var destination = this.destination;
9640 key = this.keySelector(value);
9643 destination.error(err);
9646 this._finalizeNext(key, value);
9648 DistinctSubscriber.prototype._finalizeNext = function (key, value) {
9649 var values = this.values;
9650 if (!values.has(key)) {
9652 this.destination.next(value);
9655 return DistinctSubscriber;
9656 }(OuterSubscriber_1.OuterSubscriber));
9657 exports.DistinctSubscriber = DistinctSubscriber;
9659 },{"../OuterSubscriber":31,"../util/Set":161,"../util/subscribeToResult":173}],117:[function(require,module,exports){
9661 var __extends = (this && this.__extends) || function (d, b) {
9662 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9663 function __() { this.constructor = d; }
9664 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9666 var Subscriber_1 = require('../Subscriber');
9667 var tryCatch_1 = require('../util/tryCatch');
9668 var errorObject_1 = require('../util/errorObject');
9669 /* tslint:enable:max-line-length */
9671 * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
9673 * 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.
9675 * If a comparator function is not provided, an equality check is used by default.
9677 * @example <caption>A simple example with numbers</caption>
9678 * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
9679 * .distinctUntilChanged()
9680 * .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
9682 * @example <caption>An example using a compare function</caption>
9683 * interface Person {
9688 * Observable.of<Person>(
9689 * { age: 4, name: 'Foo'},
9690 * { age: 7, name: 'Bar'},
9691 * { age: 5, name: 'Foo'})
9692 * { age: 6, name: 'Foo'})
9693 * .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
9694 * .subscribe(x => console.log(x));
9697 * // { age: 4, name: 'Foo' }
9698 * // { age: 7, name: 'Bar' }
9699 * // { age: 5, name: 'Foo' }
9701 * @see {@link distinct}
9702 * @see {@link distinctUntilKeyChanged}
9704 * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
9705 * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9706 * @method distinctUntilChanged
9709 function distinctUntilChanged(compare, keySelector) {
9710 return this.lift(new DistinctUntilChangedOperator(compare, keySelector));
9712 exports.distinctUntilChanged = distinctUntilChanged;
9713 var DistinctUntilChangedOperator = (function () {
9714 function DistinctUntilChangedOperator(compare, keySelector) {
9715 this.compare = compare;
9716 this.keySelector = keySelector;
9718 DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
9719 return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
9721 return DistinctUntilChangedOperator;
9724 * We need this JSDoc comment for affecting ESDoc.
9726 * @extends {Ignored}
9728 var DistinctUntilChangedSubscriber = (function (_super) {
9729 __extends(DistinctUntilChangedSubscriber, _super);
9730 function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
9731 _super.call(this, destination);
9732 this.keySelector = keySelector;
9733 this.hasKey = false;
9734 if (typeof compare === 'function') {
9735 this.compare = compare;
9738 DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
9741 DistinctUntilChangedSubscriber.prototype._next = function (value) {
9742 var keySelector = this.keySelector;
9745 key = tryCatch_1.tryCatch(this.keySelector)(value);
9746 if (key === errorObject_1.errorObject) {
9747 return this.destination.error(errorObject_1.errorObject.e);
9752 result = tryCatch_1.tryCatch(this.compare)(this.key, key);
9753 if (result === errorObject_1.errorObject) {
9754 return this.destination.error(errorObject_1.errorObject.e);
9760 if (Boolean(result) === false) {
9762 this.destination.next(value);
9765 return DistinctUntilChangedSubscriber;
9766 }(Subscriber_1.Subscriber));
9768 },{"../Subscriber":36,"../util/errorObject":163,"../util/tryCatch":175}],118:[function(require,module,exports){
9770 var __extends = (this && this.__extends) || function (d, b) {
9771 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9772 function __() { this.constructor = d; }
9773 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9775 var Subscriber_1 = require('../Subscriber');
9776 /* tslint:enable:max-line-length */
9778 * Perform a side effect for every emission on the source Observable, but return
9779 * an Observable that is identical to the source.
9781 * <span class="informal">Intercepts each emission on the source and runs a
9782 * function, but returns an output which is identical to the source as long as errors don't occur.</span>
9784 * <img src="./img/do.png" width="100%">
9786 * Returns a mirrored Observable of the source Observable, but modified so that
9787 * the provided Observer is called to perform a side effect for every value,
9788 * error, and completion emitted by the source. Any errors that are thrown in
9789 * the aforementioned Observer or handlers are safely sent down the error path
9790 * of the output Observable.
9792 * This operator is useful for debugging your Observables for the correct values
9793 * or performing other side effects.
9795 * Note: this is different to a `subscribe` on the Observable. If the Observable
9796 * returned by `do` is not subscribed, the side effects specified by the
9797 * Observer will never happen. `do` therefore simply spies on existing
9798 * execution, it does not trigger an execution to happen like `subscribe` does.
9800 * @example <caption>Map every click to the clientX position of that click, while also logging the click event</caption>
9801 * var clicks = Rx.Observable.fromEvent(document, 'click');
9802 * var positions = clicks
9803 * .do(ev => console.log(ev))
9804 * .map(ev => ev.clientX);
9805 * positions.subscribe(x => console.log(x));
9808 * @see {@link subscribe}
9810 * @param {Observer|function} [nextOrObserver] A normal Observer object or a
9811 * callback for `next`.
9812 * @param {function} [error] Callback for errors in the source.
9813 * @param {function} [complete] Callback for the completion of the source.
9814 * @return {Observable} An Observable identical to the source, but runs the
9815 * specified Observer or callback(s) for each item.
9820 function _do(nextOrObserver, error, complete) {
9821 return this.lift(new DoOperator(nextOrObserver, error, complete));
9824 var DoOperator = (function () {
9825 function DoOperator(nextOrObserver, error, complete) {
9826 this.nextOrObserver = nextOrObserver;
9828 this.complete = complete;
9830 DoOperator.prototype.call = function (subscriber, source) {
9831 return source.subscribe(new DoSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
9836 * We need this JSDoc comment for affecting ESDoc.
9838 * @extends {Ignored}
9840 var DoSubscriber = (function (_super) {
9841 __extends(DoSubscriber, _super);
9842 function DoSubscriber(destination, nextOrObserver, error, complete) {
9843 _super.call(this, destination);
9844 var safeSubscriber = new Subscriber_1.Subscriber(nextOrObserver, error, complete);
9845 safeSubscriber.syncErrorThrowable = true;
9846 this.add(safeSubscriber);
9847 this.safeSubscriber = safeSubscriber;
9849 DoSubscriber.prototype._next = function (value) {
9850 var safeSubscriber = this.safeSubscriber;
9851 safeSubscriber.next(value);
9852 if (safeSubscriber.syncErrorThrown) {
9853 this.destination.error(safeSubscriber.syncErrorValue);
9856 this.destination.next(value);
9859 DoSubscriber.prototype._error = function (err) {
9860 var safeSubscriber = this.safeSubscriber;
9861 safeSubscriber.error(err);
9862 if (safeSubscriber.syncErrorThrown) {
9863 this.destination.error(safeSubscriber.syncErrorValue);
9866 this.destination.error(err);
9869 DoSubscriber.prototype._complete = function () {
9870 var safeSubscriber = this.safeSubscriber;
9871 safeSubscriber.complete();
9872 if (safeSubscriber.syncErrorThrown) {
9873 this.destination.error(safeSubscriber.syncErrorValue);
9876 this.destination.complete();
9879 return DoSubscriber;
9880 }(Subscriber_1.Subscriber));
9882 },{"../Subscriber":36}],119:[function(require,module,exports){
9884 var __extends = (this && this.__extends) || function (d, b) {
9885 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9886 function __() { this.constructor = d; }
9887 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9889 var tryCatch_1 = require('../util/tryCatch');
9890 var errorObject_1 = require('../util/errorObject');
9891 var OuterSubscriber_1 = require('../OuterSubscriber');
9892 var subscribeToResult_1 = require('../util/subscribeToResult');
9893 /* tslint:enable:max-line-length */
9895 * Recursively projects each source value to an Observable which is merged in
9896 * the output Observable.
9898 * <span class="informal">It's similar to {@link mergeMap}, but applies the
9899 * projection function to every source value as well as every output value.
9900 * It's recursive.</span>
9902 * <img src="./img/expand.png" width="100%">
9904 * Returns an Observable that emits items based on applying a function that you
9905 * supply to each item emitted by the source Observable, where that function
9906 * returns an Observable, and then merging those resulting Observables and
9907 * emitting the results of this merger. *Expand* will re-emit on the output
9908 * Observable every source value. Then, each output value is given to the
9909 * `project` function which returns an inner Observable to be merged on the
9910 * output Observable. Those output values resulting from the projection are also
9911 * given to the `project` function to produce new output values. This is how
9912 * *expand* behaves recursively.
9914 * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
9915 * var clicks = Rx.Observable.fromEvent(document, 'click');
9916 * var powersOfTwo = clicks
9918 * .expand(x => Rx.Observable.of(2 * x).delay(1000))
9920 * powersOfTwo.subscribe(x => console.log(x));
9922 * @see {@link mergeMap}
9923 * @see {@link mergeScan}
9925 * @param {function(value: T, index: number) => Observable} project A function
9926 * that, when applied to an item emitted by the source or the output Observable,
9927 * returns an Observable.
9928 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9929 * Observables being subscribed to concurrently.
9930 * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
9931 * each projected inner Observable.
9932 * @return {Observable} An Observable that emits the source values and also
9933 * result of applying the projection function to each value emitted on the
9934 * output Observable and and merging the results of the Observables obtained
9935 * from this transformation.
9939 function expand(project, concurrent, scheduler) {
9940 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9941 if (scheduler === void 0) { scheduler = undefined; }
9942 concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
9943 return this.lift(new ExpandOperator(project, concurrent, scheduler));
9945 exports.expand = expand;
9946 var ExpandOperator = (function () {
9947 function ExpandOperator(project, concurrent, scheduler) {
9948 this.project = project;
9949 this.concurrent = concurrent;
9950 this.scheduler = scheduler;
9952 ExpandOperator.prototype.call = function (subscriber, source) {
9953 return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
9955 return ExpandOperator;
9957 exports.ExpandOperator = ExpandOperator;
9959 * We need this JSDoc comment for affecting ESDoc.
9961 * @extends {Ignored}
9963 var ExpandSubscriber = (function (_super) {
9964 __extends(ExpandSubscriber, _super);
9965 function ExpandSubscriber(destination, project, concurrent, scheduler) {
9966 _super.call(this, destination);
9967 this.project = project;
9968 this.concurrent = concurrent;
9969 this.scheduler = scheduler;
9972 this.hasCompleted = false;
9973 if (concurrent < Number.POSITIVE_INFINITY) {
9977 ExpandSubscriber.dispatch = function (arg) {
9978 var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
9979 subscriber.subscribeToProjection(result, value, index);
9981 ExpandSubscriber.prototype._next = function (value) {
9982 var destination = this.destination;
9983 if (destination.closed) {
9987 var index = this.index++;
9988 if (this.active < this.concurrent) {
9989 destination.next(value);
9990 var result = tryCatch_1.tryCatch(this.project)(value, index);
9991 if (result === errorObject_1.errorObject) {
9992 destination.error(errorObject_1.errorObject.e);
9994 else if (!this.scheduler) {
9995 this.subscribeToProjection(result, value, index);
9998 var state = { subscriber: this, result: result, value: value, index: index };
9999 this.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
10003 this.buffer.push(value);
10006 ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
10008 this.add(subscribeToResult_1.subscribeToResult(this, result, value, index));
10010 ExpandSubscriber.prototype._complete = function () {
10011 this.hasCompleted = true;
10012 if (this.hasCompleted && this.active === 0) {
10013 this.destination.complete();
10016 ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10017 this._next(innerValue);
10019 ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
10020 var buffer = this.buffer;
10021 this.remove(innerSub);
10023 if (buffer && buffer.length > 0) {
10024 this._next(buffer.shift());
10026 if (this.hasCompleted && this.active === 0) {
10027 this.destination.complete();
10030 return ExpandSubscriber;
10031 }(OuterSubscriber_1.OuterSubscriber));
10032 exports.ExpandSubscriber = ExpandSubscriber;
10034 },{"../OuterSubscriber":31,"../util/errorObject":163,"../util/subscribeToResult":173,"../util/tryCatch":175}],120:[function(require,module,exports){
10036 var __extends = (this && this.__extends) || function (d, b) {
10037 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10038 function __() { this.constructor = d; }
10039 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10041 var Subscriber_1 = require('../Subscriber');
10042 /* tslint:enable:max-line-length */
10044 * Filter items emitted by the source Observable by only emitting those that
10045 * satisfy a specified predicate.
10047 * <span class="informal">Like
10048 * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
10049 * it only emits a value from the source if it passes a criterion function.</span>
10051 * <img src="./img/filter.png" width="100%">
10053 * Similar to the well-known `Array.prototype.filter` method, this operator
10054 * takes values from the source Observable, passes them through a `predicate`
10055 * function and only emits those values that yielded `true`.
10057 * @example <caption>Emit only click events whose target was a DIV element</caption>
10058 * var clicks = Rx.Observable.fromEvent(document, 'click');
10059 * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
10060 * clicksOnDivs.subscribe(x => console.log(x));
10062 * @see {@link distinct}
10063 * @see {@link distinctUntilChanged}
10064 * @see {@link distinctUntilKeyChanged}
10065 * @see {@link ignoreElements}
10066 * @see {@link partition}
10067 * @see {@link skip}
10069 * @param {function(value: T, index: number): boolean} predicate A function that
10070 * evaluates each value emitted by the source Observable. If it returns `true`,
10071 * the value is emitted, if `false` the value is not passed to the output
10072 * Observable. The `index` parameter is the number `i` for the i-th source
10073 * emission that has happened since the subscription, starting from the number
10075 * @param {any} [thisArg] An optional argument to determine the value of `this`
10076 * in the `predicate` function.
10077 * @return {Observable} An Observable of values from the source that were
10078 * allowed by the `predicate` function.
10080 * @owner Observable
10082 function filter(predicate, thisArg) {
10083 return this.lift(new FilterOperator(predicate, thisArg));
10085 exports.filter = filter;
10086 var FilterOperator = (function () {
10087 function FilterOperator(predicate, thisArg) {
10088 this.predicate = predicate;
10089 this.thisArg = thisArg;
10091 FilterOperator.prototype.call = function (subscriber, source) {
10092 return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
10094 return FilterOperator;
10097 * We need this JSDoc comment for affecting ESDoc.
10099 * @extends {Ignored}
10101 var FilterSubscriber = (function (_super) {
10102 __extends(FilterSubscriber, _super);
10103 function FilterSubscriber(destination, predicate, thisArg) {
10104 _super.call(this, destination);
10105 this.predicate = predicate;
10106 this.thisArg = thisArg;
10108 this.predicate = predicate;
10110 // the try catch block below is left specifically for
10111 // optimization and perf reasons. a tryCatcher is not necessary here.
10112 FilterSubscriber.prototype._next = function (value) {
10115 result = this.predicate.call(this.thisArg, value, this.count++);
10118 this.destination.error(err);
10122 this.destination.next(value);
10125 return FilterSubscriber;
10126 }(Subscriber_1.Subscriber));
10128 },{"../Subscriber":36}],121:[function(require,module,exports){
10130 var __extends = (this && this.__extends) || function (d, b) {
10131 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10132 function __() { this.constructor = d; }
10133 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10135 var Subscriber_1 = require('../Subscriber');
10136 var Subscription_1 = require('../Subscription');
10138 * Returns an Observable that mirrors the source Observable, but will call a specified function when
10139 * the source terminates on complete or error.
10140 * @param {function} callback Function to be called when source terminates.
10141 * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.
10143 * @owner Observable
10145 function _finally(callback) {
10146 return this.lift(new FinallyOperator(callback));
10148 exports._finally = _finally;
10149 var FinallyOperator = (function () {
10150 function FinallyOperator(callback) {
10151 this.callback = callback;
10153 FinallyOperator.prototype.call = function (subscriber, source) {
10154 return source.subscribe(new FinallySubscriber(subscriber, this.callback));
10156 return FinallyOperator;
10159 * We need this JSDoc comment for affecting ESDoc.
10161 * @extends {Ignored}
10163 var FinallySubscriber = (function (_super) {
10164 __extends(FinallySubscriber, _super);
10165 function FinallySubscriber(destination, callback) {
10166 _super.call(this, destination);
10167 this.add(new Subscription_1.Subscription(callback));
10169 return FinallySubscriber;
10170 }(Subscriber_1.Subscriber));
10172 },{"../Subscriber":36,"../Subscription":37}],122:[function(require,module,exports){
10174 var __extends = (this && this.__extends) || function (d, b) {
10175 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10176 function __() { this.constructor = d; }
10177 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10179 var Subscriber_1 = require('../Subscriber');
10180 var EmptyError_1 = require('../util/EmptyError');
10182 * Emits only the first value (or the first value that meets some condition)
10183 * emitted by the source Observable.
10185 * <span class="informal">Emits only the first value. Or emits only the first
10186 * value that passes some test.</span>
10188 * <img src="./img/first.png" width="100%">
10190 * If called with no arguments, `first` emits the first value of the source
10191 * Observable, then completes. If called with a `predicate` function, `first`
10192 * emits the first value of the source that matches the specified condition. It
10193 * may also take a `resultSelector` function to produce the output value from
10194 * the input value, and a `defaultValue` to emit in case the source completes
10195 * before it is able to emit a valid value. Throws an error if `defaultValue`
10196 * was not provided and a matching element is not found.
10198 * @example <caption>Emit only the first click that happens on the DOM</caption>
10199 * var clicks = Rx.Observable.fromEvent(document, 'click');
10200 * var result = clicks.first();
10201 * result.subscribe(x => console.log(x));
10203 * @example <caption>Emits the first click that happens on a DIV</caption>
10204 * var clicks = Rx.Observable.fromEvent(document, 'click');
10205 * var result = clicks.first(ev => ev.target.tagName === 'DIV');
10206 * result.subscribe(x => console.log(x));
10208 * @see {@link filter}
10209 * @see {@link find}
10210 * @see {@link take}
10212 * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
10213 * callback if the Observable completes before any `next` notification was sent.
10215 * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
10216 * An optional function called with each item to test for condition matching.
10217 * @param {function(value: T, index: number): R} [resultSelector] A function to
10218 * produce the value on the output Observable based on the values
10219 * and the indices of the source Observable. The arguments passed to this
10221 * - `value`: the value that was emitted on the source.
10222 * - `index`: the "index" of the value from the source.
10223 * @param {R} [defaultValue] The default value emitted in case no valid value
10224 * was found on the source.
10225 * @return {Observable<T|R>} An Observable of the first item that matches the
10228 * @owner Observable
10230 function first(predicate, resultSelector, defaultValue) {
10231 return this.lift(new FirstOperator(predicate, resultSelector, defaultValue, this));
10233 exports.first = first;
10234 var FirstOperator = (function () {
10235 function FirstOperator(predicate, resultSelector, defaultValue, source) {
10236 this.predicate = predicate;
10237 this.resultSelector = resultSelector;
10238 this.defaultValue = defaultValue;
10239 this.source = source;
10241 FirstOperator.prototype.call = function (observer, source) {
10242 return source.subscribe(new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
10244 return FirstOperator;
10247 * We need this JSDoc comment for affecting ESDoc.
10249 * @extends {Ignored}
10251 var FirstSubscriber = (function (_super) {
10252 __extends(FirstSubscriber, _super);
10253 function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) {
10254 _super.call(this, destination);
10255 this.predicate = predicate;
10256 this.resultSelector = resultSelector;
10257 this.defaultValue = defaultValue;
10258 this.source = source;
10260 this.hasCompleted = false;
10261 this._emitted = false;
10263 FirstSubscriber.prototype._next = function (value) {
10264 var index = this.index++;
10265 if (this.predicate) {
10266 this._tryPredicate(value, index);
10269 this._emit(value, index);
10272 FirstSubscriber.prototype._tryPredicate = function (value, index) {
10275 result = this.predicate(value, index, this.source);
10278 this.destination.error(err);
10282 this._emit(value, index);
10285 FirstSubscriber.prototype._emit = function (value, index) {
10286 if (this.resultSelector) {
10287 this._tryResultSelector(value, index);
10290 this._emitFinal(value);
10292 FirstSubscriber.prototype._tryResultSelector = function (value, index) {
10295 result = this.resultSelector(value, index);
10298 this.destination.error(err);
10301 this._emitFinal(result);
10303 FirstSubscriber.prototype._emitFinal = function (value) {
10304 var destination = this.destination;
10305 if (!this._emitted) {
10306 this._emitted = true;
10307 destination.next(value);
10308 destination.complete();
10309 this.hasCompleted = true;
10312 FirstSubscriber.prototype._complete = function () {
10313 var destination = this.destination;
10314 if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') {
10315 destination.next(this.defaultValue);
10316 destination.complete();
10318 else if (!this.hasCompleted) {
10319 destination.error(new EmptyError_1.EmptyError);
10322 return FirstSubscriber;
10323 }(Subscriber_1.Subscriber));
10325 },{"../Subscriber":36,"../util/EmptyError":159}],123:[function(require,module,exports){
10327 var __extends = (this && this.__extends) || function (d, b) {
10328 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10329 function __() { this.constructor = d; }
10330 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10332 var Subscriber_1 = require('../Subscriber');
10333 var EmptyError_1 = require('../util/EmptyError');
10334 /* tslint:enable:max-line-length */
10336 * Returns an Observable that emits only the last item emitted by the source Observable.
10337 * It optionally takes a predicate function as a parameter, in which case, rather than emitting
10338 * the last item from the source Observable, the resulting Observable will emit the last item
10339 * from the source Observable that satisfies the predicate.
10341 * <img src="./img/last.png" width="100%">
10343 * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
10344 * callback if the Observable completes before any `next` notification was sent.
10345 * @param {function} predicate - The condition any source emitted item has to satisfy.
10346 * @return {Observable} An Observable that emits only the last item satisfying the given condition
10347 * from the source, or an NoSuchElementException if no such items are emitted.
10348 * @throws - Throws if no items that match the predicate are emitted by the source Observable.
10350 * @owner Observable
10352 function last(predicate, resultSelector, defaultValue) {
10353 return this.lift(new LastOperator(predicate, resultSelector, defaultValue, this));
10355 exports.last = last;
10356 var LastOperator = (function () {
10357 function LastOperator(predicate, resultSelector, defaultValue, source) {
10358 this.predicate = predicate;
10359 this.resultSelector = resultSelector;
10360 this.defaultValue = defaultValue;
10361 this.source = source;
10363 LastOperator.prototype.call = function (observer, source) {
10364 return source.subscribe(new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
10366 return LastOperator;
10369 * We need this JSDoc comment for affecting ESDoc.
10371 * @extends {Ignored}
10373 var LastSubscriber = (function (_super) {
10374 __extends(LastSubscriber, _super);
10375 function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) {
10376 _super.call(this, destination);
10377 this.predicate = predicate;
10378 this.resultSelector = resultSelector;
10379 this.defaultValue = defaultValue;
10380 this.source = source;
10381 this.hasValue = false;
10383 if (typeof defaultValue !== 'undefined') {
10384 this.lastValue = defaultValue;
10385 this.hasValue = true;
10388 LastSubscriber.prototype._next = function (value) {
10389 var index = this.index++;
10390 if (this.predicate) {
10391 this._tryPredicate(value, index);
10394 if (this.resultSelector) {
10395 this._tryResultSelector(value, index);
10398 this.lastValue = value;
10399 this.hasValue = true;
10402 LastSubscriber.prototype._tryPredicate = function (value, index) {
10405 result = this.predicate(value, index, this.source);
10408 this.destination.error(err);
10412 if (this.resultSelector) {
10413 this._tryResultSelector(value, index);
10416 this.lastValue = value;
10417 this.hasValue = true;
10420 LastSubscriber.prototype._tryResultSelector = function (value, index) {
10423 result = this.resultSelector(value, index);
10426 this.destination.error(err);
10429 this.lastValue = result;
10430 this.hasValue = true;
10432 LastSubscriber.prototype._complete = function () {
10433 var destination = this.destination;
10434 if (this.hasValue) {
10435 destination.next(this.lastValue);
10436 destination.complete();
10439 destination.error(new EmptyError_1.EmptyError);
10442 return LastSubscriber;
10443 }(Subscriber_1.Subscriber));
10445 },{"../Subscriber":36,"../util/EmptyError":159}],124:[function(require,module,exports){
10447 var __extends = (this && this.__extends) || function (d, b) {
10448 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10449 function __() { this.constructor = d; }
10450 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10452 var Subscriber_1 = require('../Subscriber');
10454 * Applies a given `project` function to each value emitted by the source
10455 * Observable, and emits the resulting values as an Observable.
10457 * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
10458 * it passes each source value through a transformation function to get
10459 * corresponding output values.</span>
10461 * <img src="./img/map.png" width="100%">
10463 * Similar to the well known `Array.prototype.map` function, this operator
10464 * applies a projection to each value and emits that projection in the output
10467 * @example <caption>Map every click to the clientX position of that click</caption>
10468 * var clicks = Rx.Observable.fromEvent(document, 'click');
10469 * var positions = clicks.map(ev => ev.clientX);
10470 * positions.subscribe(x => console.log(x));
10472 * @see {@link mapTo}
10473 * @see {@link pluck}
10475 * @param {function(value: T, index: number): R} project The function to apply
10476 * to each `value` emitted by the source Observable. The `index` parameter is
10477 * the number `i` for the i-th emission that has happened since the
10478 * subscription, starting from the number `0`.
10479 * @param {any} [thisArg] An optional argument to define what `this` is in the
10480 * `project` function.
10481 * @return {Observable<R>} An Observable that emits the values from the source
10482 * Observable transformed by the given `project` function.
10484 * @owner Observable
10486 function map(project, thisArg) {
10487 if (typeof project !== 'function') {
10488 throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
10490 return this.lift(new MapOperator(project, thisArg));
10493 var MapOperator = (function () {
10494 function MapOperator(project, thisArg) {
10495 this.project = project;
10496 this.thisArg = thisArg;
10498 MapOperator.prototype.call = function (subscriber, source) {
10499 return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
10501 return MapOperator;
10503 exports.MapOperator = MapOperator;
10505 * We need this JSDoc comment for affecting ESDoc.
10507 * @extends {Ignored}
10509 var MapSubscriber = (function (_super) {
10510 __extends(MapSubscriber, _super);
10511 function MapSubscriber(destination, project, thisArg) {
10512 _super.call(this, destination);
10513 this.project = project;
10515 this.thisArg = thisArg || this;
10517 // NOTE: This looks unoptimized, but it's actually purposefully NOT
10518 // using try/catch optimizations.
10519 MapSubscriber.prototype._next = function (value) {
10522 result = this.project.call(this.thisArg, value, this.count++);
10525 this.destination.error(err);
10528 this.destination.next(result);
10530 return MapSubscriber;
10531 }(Subscriber_1.Subscriber));
10533 },{"../Subscriber":36}],125:[function(require,module,exports){
10535 var Observable_1 = require('../Observable');
10536 var ArrayObservable_1 = require('../observable/ArrayObservable');
10537 var mergeAll_1 = require('./mergeAll');
10538 var isScheduler_1 = require('../util/isScheduler');
10539 /* tslint:enable:max-line-length */
10541 * Creates an output Observable which concurrently emits all values from every
10542 * given input Observable.
10544 * <span class="informal">Flattens multiple Observables together by blending
10545 * their values into one Observable.</span>
10547 * <img src="./img/merge.png" width="100%">
10549 * `merge` subscribes to each given input Observable (either the source or an
10550 * Observable given as argument), and simply forwards (without doing any
10551 * transformation) all the values from all the input Observables to the output
10552 * Observable. The output Observable only completes once all input Observables
10553 * have completed. Any error delivered by an input Observable will be immediately
10554 * emitted on the output Observable.
10556 * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
10557 * var clicks = Rx.Observable.fromEvent(document, 'click');
10558 * var timer = Rx.Observable.interval(1000);
10559 * var clicksOrTimer = clicks.merge(timer);
10560 * clicksOrTimer.subscribe(x => console.log(x));
10562 * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
10563 * var timer1 = Rx.Observable.interval(1000).take(10);
10564 * var timer2 = Rx.Observable.interval(2000).take(6);
10565 * var timer3 = Rx.Observable.interval(500).take(10);
10566 * var concurrent = 2; // the argument
10567 * var merged = timer1.merge(timer2, timer3, concurrent);
10568 * merged.subscribe(x => console.log(x));
10570 * @see {@link mergeAll}
10571 * @see {@link mergeMap}
10572 * @see {@link mergeMapTo}
10573 * @see {@link mergeScan}
10575 * @param {ObservableInput} other An input Observable to merge with the source
10576 * Observable. More than one input Observables may be given as argument.
10577 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10578 * Observables being subscribed to concurrently.
10579 * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
10580 * concurrency of input Observables.
10581 * @return {Observable} An Observable that emits items that are the result of
10582 * every input Observable.
10584 * @owner Observable
10587 var observables = [];
10588 for (var _i = 0; _i < arguments.length; _i++) {
10589 observables[_i - 0] = arguments[_i];
10591 return this.lift.call(mergeStatic.apply(void 0, [this].concat(observables)));
10593 exports.merge = merge;
10594 /* tslint:enable:max-line-length */
10596 * Creates an output Observable which concurrently emits all values from every
10597 * given input Observable.
10599 * <span class="informal">Flattens multiple Observables together by blending
10600 * their values into one Observable.</span>
10602 * <img src="./img/merge.png" width="100%">
10604 * `merge` subscribes to each given input Observable (as arguments), and simply
10605 * forwards (without doing any transformation) all the values from all the input
10606 * Observables to the output Observable. The output Observable only completes
10607 * once all input Observables have completed. Any error delivered by an input
10608 * Observable will be immediately emitted on the output Observable.
10610 * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
10611 * var clicks = Rx.Observable.fromEvent(document, 'click');
10612 * var timer = Rx.Observable.interval(1000);
10613 * var clicksOrTimer = Rx.Observable.merge(clicks, timer);
10614 * clicksOrTimer.subscribe(x => console.log(x));
10616 * // Results in the following:
10617 * // timer will emit ascending values, one every second(1000ms) to console
10618 * // clicks logs MouseEvents to console everytime the "document" is clicked
10619 * // Since the two streams are merged you see these happening
10620 * // as they occur.
10622 * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
10623 * var timer1 = Rx.Observable.interval(1000).take(10);
10624 * var timer2 = Rx.Observable.interval(2000).take(6);
10625 * var timer3 = Rx.Observable.interval(500).take(10);
10626 * var concurrent = 2; // the argument
10627 * var merged = Rx.Observable.merge(timer1, timer2, timer3, concurrent);
10628 * merged.subscribe(x => console.log(x));
10630 * // Results in the following:
10631 * // - First timer1 and timer2 will run concurrently
10632 * // - timer1 will emit a value every 1000ms for 10 iterations
10633 * // - timer2 will emit a value every 2000ms for 6 iterations
10634 * // - after timer1 hits it's max iteration, timer2 will
10635 * // continue, and timer3 will start to run concurrently with timer2
10636 * // - when timer2 hits it's max iteration it terminates, and
10637 * // timer3 will continue to emit a value every 500ms until it is complete
10639 * @see {@link mergeAll}
10640 * @see {@link mergeMap}
10641 * @see {@link mergeMapTo}
10642 * @see {@link mergeScan}
10644 * @param {...ObservableInput} observables Input Observables to merge together.
10645 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10646 * Observables being subscribed to concurrently.
10647 * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
10648 * concurrency of input Observables.
10649 * @return {Observable} an Observable that emits items that are the result of
10650 * every input Observable.
10653 * @owner Observable
10655 function mergeStatic() {
10656 var observables = [];
10657 for (var _i = 0; _i < arguments.length; _i++) {
10658 observables[_i - 0] = arguments[_i];
10660 var concurrent = Number.POSITIVE_INFINITY;
10661 var scheduler = null;
10662 var last = observables[observables.length - 1];
10663 if (isScheduler_1.isScheduler(last)) {
10664 scheduler = observables.pop();
10665 if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
10666 concurrent = observables.pop();
10669 else if (typeof last === 'number') {
10670 concurrent = observables.pop();
10672 if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
10673 return observables[0];
10675 return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(concurrent));
10677 exports.mergeStatic = mergeStatic;
10679 },{"../Observable":29,"../observable/ArrayObservable":86,"../util/isScheduler":171,"./mergeAll":126}],126:[function(require,module,exports){
10681 var __extends = (this && this.__extends) || function (d, b) {
10682 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10683 function __() { this.constructor = d; }
10684 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10686 var OuterSubscriber_1 = require('../OuterSubscriber');
10687 var subscribeToResult_1 = require('../util/subscribeToResult');
10689 * Converts a higher-order Observable into a first-order Observable which
10690 * concurrently delivers all values that are emitted on the inner Observables.
10692 * <span class="informal">Flattens an Observable-of-Observables.</span>
10694 * <img src="./img/mergeAll.png" width="100%">
10696 * `mergeAll` subscribes to an Observable that emits Observables, also known as
10697 * a higher-order Observable. Each time it observes one of these emitted inner
10698 * Observables, it subscribes to that and delivers all the values from the
10699 * inner Observable on the output Observable. The output Observable only
10700 * completes once all inner Observables have completed. Any error delivered by
10701 * a inner Observable will be immediately emitted on the output Observable.
10703 * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
10704 * var clicks = Rx.Observable.fromEvent(document, 'click');
10705 * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
10706 * var firstOrder = higherOrder.mergeAll();
10707 * firstOrder.subscribe(x => console.log(x));
10709 * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
10710 * var clicks = Rx.Observable.fromEvent(document, 'click');
10711 * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
10712 * var firstOrder = higherOrder.mergeAll(2);
10713 * firstOrder.subscribe(x => console.log(x));
10715 * @see {@link combineAll}
10716 * @see {@link concatAll}
10717 * @see {@link exhaust}
10718 * @see {@link merge}
10719 * @see {@link mergeMap}
10720 * @see {@link mergeMapTo}
10721 * @see {@link mergeScan}
10722 * @see {@link switch}
10723 * @see {@link zipAll}
10725 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
10726 * Observables being subscribed to concurrently.
10727 * @return {Observable} An Observable that emits values coming from all the
10728 * inner Observables emitted by the source Observable.
10730 * @owner Observable
10732 function mergeAll(concurrent) {
10733 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10734 return this.lift(new MergeAllOperator(concurrent));
10736 exports.mergeAll = mergeAll;
10737 var MergeAllOperator = (function () {
10738 function MergeAllOperator(concurrent) {
10739 this.concurrent = concurrent;
10741 MergeAllOperator.prototype.call = function (observer, source) {
10742 return source.subscribe(new MergeAllSubscriber(observer, this.concurrent));
10744 return MergeAllOperator;
10746 exports.MergeAllOperator = MergeAllOperator;
10748 * We need this JSDoc comment for affecting ESDoc.
10750 * @extends {Ignored}
10752 var MergeAllSubscriber = (function (_super) {
10753 __extends(MergeAllSubscriber, _super);
10754 function MergeAllSubscriber(destination, concurrent) {
10755 _super.call(this, destination);
10756 this.concurrent = concurrent;
10757 this.hasCompleted = false;
10761 MergeAllSubscriber.prototype._next = function (observable) {
10762 if (this.active < this.concurrent) {
10764 this.add(subscribeToResult_1.subscribeToResult(this, observable));
10767 this.buffer.push(observable);
10770 MergeAllSubscriber.prototype._complete = function () {
10771 this.hasCompleted = true;
10772 if (this.active === 0 && this.buffer.length === 0) {
10773 this.destination.complete();
10776 MergeAllSubscriber.prototype.notifyComplete = function (innerSub) {
10777 var buffer = this.buffer;
10778 this.remove(innerSub);
10780 if (buffer.length > 0) {
10781 this._next(buffer.shift());
10783 else if (this.active === 0 && this.hasCompleted) {
10784 this.destination.complete();
10787 return MergeAllSubscriber;
10788 }(OuterSubscriber_1.OuterSubscriber));
10789 exports.MergeAllSubscriber = MergeAllSubscriber;
10791 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],127:[function(require,module,exports){
10793 var __extends = (this && this.__extends) || function (d, b) {
10794 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10795 function __() { this.constructor = d; }
10796 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10798 var subscribeToResult_1 = require('../util/subscribeToResult');
10799 var OuterSubscriber_1 = require('../OuterSubscriber');
10800 /* tslint:enable:max-line-length */
10802 * Projects each source value to an Observable which is merged in the output
10805 * <span class="informal">Maps each value to an Observable, then flattens all of
10806 * these inner Observables using {@link mergeAll}.</span>
10808 * <img src="./img/mergeMap.png" width="100%">
10810 * Returns an Observable that emits items based on applying a function that you
10811 * supply to each item emitted by the source Observable, where that function
10812 * returns an Observable, and then merging those resulting Observables and
10813 * emitting the results of this merger.
10815 * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
10816 * var letters = Rx.Observable.of('a', 'b', 'c');
10817 * var result = letters.mergeMap(x =>
10818 * Rx.Observable.interval(1000).map(i => x+i)
10820 * result.subscribe(x => console.log(x));
10822 * // Results in the following:
10829 * // continues to list a,b,c with respective ascending integers
10831 * @see {@link concatMap}
10832 * @see {@link exhaustMap}
10833 * @see {@link merge}
10834 * @see {@link mergeAll}
10835 * @see {@link mergeMapTo}
10836 * @see {@link mergeScan}
10837 * @see {@link switchMap}
10839 * @param {function(value: T, ?index: number): ObservableInput} project A function
10840 * that, when applied to an item emitted by the source Observable, returns an
10842 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
10843 * A function to produce the value on the output Observable based on the values
10844 * and the indices of the source (outer) emission and the inner Observable
10845 * emission. The arguments passed to this function are:
10846 * - `outerValue`: the value that came from the source
10847 * - `innerValue`: the value that came from the projected Observable
10848 * - `outerIndex`: the "index" of the value that came from the source
10849 * - `innerIndex`: the "index" of the value from the projected Observable
10850 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10851 * Observables being subscribed to concurrently.
10852 * @return {Observable} An Observable that emits the result of applying the
10853 * projection function (and the optional `resultSelector`) to each item emitted
10854 * by the source Observable and merging the results of the Observables obtained
10855 * from this transformation.
10857 * @owner Observable
10859 function mergeMap(project, resultSelector, concurrent) {
10860 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10861 if (typeof resultSelector === 'number') {
10862 concurrent = resultSelector;
10863 resultSelector = null;
10865 return this.lift(new MergeMapOperator(project, resultSelector, concurrent));
10867 exports.mergeMap = mergeMap;
10868 var MergeMapOperator = (function () {
10869 function MergeMapOperator(project, resultSelector, concurrent) {
10870 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10871 this.project = project;
10872 this.resultSelector = resultSelector;
10873 this.concurrent = concurrent;
10875 MergeMapOperator.prototype.call = function (observer, source) {
10876 return source.subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent));
10878 return MergeMapOperator;
10880 exports.MergeMapOperator = MergeMapOperator;
10882 * We need this JSDoc comment for affecting ESDoc.
10884 * @extends {Ignored}
10886 var MergeMapSubscriber = (function (_super) {
10887 __extends(MergeMapSubscriber, _super);
10888 function MergeMapSubscriber(destination, project, resultSelector, concurrent) {
10889 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10890 _super.call(this, destination);
10891 this.project = project;
10892 this.resultSelector = resultSelector;
10893 this.concurrent = concurrent;
10894 this.hasCompleted = false;
10899 MergeMapSubscriber.prototype._next = function (value) {
10900 if (this.active < this.concurrent) {
10901 this._tryNext(value);
10904 this.buffer.push(value);
10907 MergeMapSubscriber.prototype._tryNext = function (value) {
10909 var index = this.index++;
10911 result = this.project(value, index);
10914 this.destination.error(err);
10918 this._innerSub(result, value, index);
10920 MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
10921 this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index));
10923 MergeMapSubscriber.prototype._complete = function () {
10924 this.hasCompleted = true;
10925 if (this.active === 0 && this.buffer.length === 0) {
10926 this.destination.complete();
10929 MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10930 if (this.resultSelector) {
10931 this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex);
10934 this.destination.next(innerValue);
10937 MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
10940 result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
10943 this.destination.error(err);
10946 this.destination.next(result);
10948 MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
10949 var buffer = this.buffer;
10950 this.remove(innerSub);
10952 if (buffer.length > 0) {
10953 this._next(buffer.shift());
10955 else if (this.active === 0 && this.hasCompleted) {
10956 this.destination.complete();
10959 return MergeMapSubscriber;
10960 }(OuterSubscriber_1.OuterSubscriber));
10961 exports.MergeMapSubscriber = MergeMapSubscriber;
10963 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],128:[function(require,module,exports){
10965 var ConnectableObservable_1 = require('../observable/ConnectableObservable');
10966 /* tslint:enable:max-line-length */
10968 * Returns an Observable that emits the results of invoking a specified selector on items
10969 * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.
10971 * <img src="./img/multicast.png" width="100%">
10973 * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through
10974 * which the source sequence's elements will be multicast to the selector function
10975 * or Subject to push source elements into.
10976 * @param {Function} [selector] - Optional selector function that can use the multicasted source stream
10977 * as many times as needed, without causing multiple subscriptions to the source stream.
10978 * Subscribers to the given source will receive all notifications of the source from the
10979 * time of the subscription forward.
10980 * @return {Observable} An Observable that emits the results of invoking the selector
10981 * on the items emitted by a `ConnectableObservable` that shares a single subscription to
10982 * the underlying stream.
10983 * @method multicast
10984 * @owner Observable
10986 function multicast(subjectOrSubjectFactory, selector) {
10987 var subjectFactory;
10988 if (typeof subjectOrSubjectFactory === 'function') {
10989 subjectFactory = subjectOrSubjectFactory;
10992 subjectFactory = function subjectFactory() {
10993 return subjectOrSubjectFactory;
10996 if (typeof selector === 'function') {
10997 return this.lift(new MulticastOperator(subjectFactory, selector));
10999 var connectable = Object.create(this, ConnectableObservable_1.connectableObservableDescriptor);
11000 connectable.source = this;
11001 connectable.subjectFactory = subjectFactory;
11002 return connectable;
11004 exports.multicast = multicast;
11005 var MulticastOperator = (function () {
11006 function MulticastOperator(subjectFactory, selector) {
11007 this.subjectFactory = subjectFactory;
11008 this.selector = selector;
11010 MulticastOperator.prototype.call = function (subscriber, source) {
11011 var selector = this.selector;
11012 var subject = this.subjectFactory();
11013 var subscription = selector(subject).subscribe(subscriber);
11014 subscription.add(source.subscribe(subject));
11015 return subscription;
11017 return MulticastOperator;
11019 exports.MulticastOperator = MulticastOperator;
11021 },{"../observable/ConnectableObservable":87}],129:[function(require,module,exports){
11023 var __extends = (this && this.__extends) || function (d, b) {
11024 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11025 function __() { this.constructor = d; }
11026 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11028 var Subscriber_1 = require('../Subscriber');
11029 var Notification_1 = require('../Notification');
11032 * Re-emits all notifications from source Observable with specified scheduler.
11034 * <span class="informal">Ensure a specific scheduler is used, from outside of an Observable.</span>
11036 * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule
11037 * notifications emitted by the source Observable. It might be useful, if you do not have control over
11038 * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless.
11040 * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable,
11041 * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal
11042 * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits
11043 * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`.
11044 * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split
11045 * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source
11046 * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a
11047 * little bit more, to ensure that they are emitted at expected moments.
11049 * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications
11050 * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn`
11051 * will delay all notifications - including error notifications - while `delay` will pass through error
11052 * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator
11053 * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used
11054 * for notification emissions in general.
11056 * @example <caption>Ensure values in subscribe are called just before browser repaint.</caption>
11057 * const intervals = Rx.Observable.interval(10); // Intervals are scheduled
11058 * // with async scheduler by default...
11061 * .observeOn(Rx.Scheduler.animationFrame) // ...but we will observe on animationFrame
11062 * .subscribe(val => { // scheduler to ensure smooth animation.
11063 * someDiv.style.height = val + 'px';
11066 * @see {@link delay}
11068 * @param {IScheduler} scheduler Scheduler that will be used to reschedule notifications from source Observable.
11069 * @param {number} [delay] Number of milliseconds that states with what delay every notification should be rescheduled.
11070 * @return {Observable<T>} Observable that emits the same notifications as the source Observable,
11071 * but with provided scheduler.
11073 * @method observeOn
11074 * @owner Observable
11076 function observeOn(scheduler, delay) {
11077 if (delay === void 0) { delay = 0; }
11078 return this.lift(new ObserveOnOperator(scheduler, delay));
11080 exports.observeOn = observeOn;
11081 var ObserveOnOperator = (function () {
11082 function ObserveOnOperator(scheduler, delay) {
11083 if (delay === void 0) { delay = 0; }
11084 this.scheduler = scheduler;
11085 this.delay = delay;
11087 ObserveOnOperator.prototype.call = function (subscriber, source) {
11088 return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
11090 return ObserveOnOperator;
11092 exports.ObserveOnOperator = ObserveOnOperator;
11094 * We need this JSDoc comment for affecting ESDoc.
11096 * @extends {Ignored}
11098 var ObserveOnSubscriber = (function (_super) {
11099 __extends(ObserveOnSubscriber, _super);
11100 function ObserveOnSubscriber(destination, scheduler, delay) {
11101 if (delay === void 0) { delay = 0; }
11102 _super.call(this, destination);
11103 this.scheduler = scheduler;
11104 this.delay = delay;
11106 ObserveOnSubscriber.dispatch = function (arg) {
11107 var notification = arg.notification, destination = arg.destination;
11108 notification.observe(destination);
11109 this.unsubscribe();
11111 ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
11112 this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
11114 ObserveOnSubscriber.prototype._next = function (value) {
11115 this.scheduleMessage(Notification_1.Notification.createNext(value));
11117 ObserveOnSubscriber.prototype._error = function (err) {
11118 this.scheduleMessage(Notification_1.Notification.createError(err));
11120 ObserveOnSubscriber.prototype._complete = function () {
11121 this.scheduleMessage(Notification_1.Notification.createComplete());
11123 return ObserveOnSubscriber;
11124 }(Subscriber_1.Subscriber));
11125 exports.ObserveOnSubscriber = ObserveOnSubscriber;
11126 var ObserveOnMessage = (function () {
11127 function ObserveOnMessage(notification, destination) {
11128 this.notification = notification;
11129 this.destination = destination;
11131 return ObserveOnMessage;
11133 exports.ObserveOnMessage = ObserveOnMessage;
11135 },{"../Notification":28,"../Subscriber":36}],130:[function(require,module,exports){
11137 var __extends = (this && this.__extends) || function (d, b) {
11138 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11139 function __() { this.constructor = d; }
11140 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11142 var Subscriber_1 = require('../Subscriber');
11144 * Groups pairs of consecutive emissions together and emits them as an array of
11147 * <span class="informal">Puts the current value and previous value together as
11148 * an array, and emits that.</span>
11150 * <img src="./img/pairwise.png" width="100%">
11152 * The Nth emission from the source Observable will cause the output Observable
11153 * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
11154 * pair. For this reason, `pairwise` emits on the second and subsequent
11155 * emissions from the source Observable, but not on the first emission, because
11156 * there is no previous value in that case.
11158 * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
11159 * var clicks = Rx.Observable.fromEvent(document, 'click');
11160 * var pairs = clicks.pairwise();
11161 * var distance = pairs.map(pair => {
11162 * var x0 = pair[0].clientX;
11163 * var y0 = pair[0].clientY;
11164 * var x1 = pair[1].clientX;
11165 * var y1 = pair[1].clientY;
11166 * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
11168 * distance.subscribe(x => console.log(x));
11170 * @see {@link buffer}
11171 * @see {@link bufferCount}
11173 * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
11174 * consecutive values from the source Observable.
11176 * @owner Observable
11178 function pairwise() {
11179 return this.lift(new PairwiseOperator());
11181 exports.pairwise = pairwise;
11182 var PairwiseOperator = (function () {
11183 function PairwiseOperator() {
11185 PairwiseOperator.prototype.call = function (subscriber, source) {
11186 return source.subscribe(new PairwiseSubscriber(subscriber));
11188 return PairwiseOperator;
11191 * We need this JSDoc comment for affecting ESDoc.
11193 * @extends {Ignored}
11195 var PairwiseSubscriber = (function (_super) {
11196 __extends(PairwiseSubscriber, _super);
11197 function PairwiseSubscriber(destination) {
11198 _super.call(this, destination);
11199 this.hasPrev = false;
11201 PairwiseSubscriber.prototype._next = function (value) {
11202 if (this.hasPrev) {
11203 this.destination.next([this.prev, value]);
11206 this.hasPrev = true;
11210 return PairwiseSubscriber;
11211 }(Subscriber_1.Subscriber));
11213 },{"../Subscriber":36}],131:[function(require,module,exports){
11215 var map_1 = require('./map');
11217 * Maps each source value (an object) to its specified nested property.
11219 * <span class="informal">Like {@link map}, but meant only for picking one of
11220 * the nested properties of every emitted object.</span>
11222 * <img src="./img/pluck.png" width="100%">
11224 * Given a list of strings describing a path to an object property, retrieves
11225 * the value of a specified nested property from all values in the source
11226 * Observable. If a property can't be resolved, it will return `undefined` for
11229 * @example <caption>Map every click to the tagName of the clicked target element</caption>
11230 * var clicks = Rx.Observable.fromEvent(document, 'click');
11231 * var tagNames = clicks.pluck('target', 'tagName');
11232 * tagNames.subscribe(x => console.log(x));
11236 * @param {...string} properties The nested properties to pluck from each source
11237 * value (an object).
11238 * @return {Observable} A new Observable of property values from the source values.
11240 * @owner Observable
11243 var properties = [];
11244 for (var _i = 0; _i < arguments.length; _i++) {
11245 properties[_i - 0] = arguments[_i];
11247 var length = properties.length;
11248 if (length === 0) {
11249 throw new Error('list of properties cannot be empty.');
11251 return map_1.map.call(this, plucker(properties, length));
11253 exports.pluck = pluck;
11254 function plucker(props, length) {
11255 var mapper = function (x) {
11256 var currentProp = x;
11257 for (var i = 0; i < length; i++) {
11258 var p = currentProp[props[i]];
11259 if (typeof p !== 'undefined') {
11266 return currentProp;
11271 },{"./map":124}],132:[function(require,module,exports){
11273 var Subject_1 = require('../Subject');
11274 var multicast_1 = require('./multicast');
11275 /* tslint:enable:max-line-length */
11277 * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
11278 * before it begins emitting items to those Observers that have subscribed to it.
11280 * <img src="./img/publish.png" width="100%">
11282 * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
11283 * as needed, without causing multiple subscriptions to the source sequence.
11284 * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
11285 * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
11287 * @owner Observable
11289 function publish(selector) {
11290 return selector ? multicast_1.multicast.call(this, function () { return new Subject_1.Subject(); }, selector) :
11291 multicast_1.multicast.call(this, new Subject_1.Subject());
11293 exports.publish = publish;
11295 },{"../Subject":34,"./multicast":128}],133:[function(require,module,exports){
11297 var ReplaySubject_1 = require('../ReplaySubject');
11298 var multicast_1 = require('./multicast');
11300 * @param bufferSize
11301 * @param windowTime
11303 * @return {ConnectableObservable<T>}
11304 * @method publishReplay
11305 * @owner Observable
11307 function publishReplay(bufferSize, windowTime, scheduler) {
11308 if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
11309 if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
11310 return multicast_1.multicast.call(this, new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler));
11312 exports.publishReplay = publishReplay;
11314 },{"../ReplaySubject":32,"./multicast":128}],134:[function(require,module,exports){
11316 var __extends = (this && this.__extends) || function (d, b) {
11317 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11318 function __() { this.constructor = d; }
11319 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11321 var Subscriber_1 = require('../Subscriber');
11322 /* tslint:enable:max-line-length */
11324 * Applies an accumulator function over the source Observable, and returns each
11325 * intermediate result, with an optional seed value.
11327 * <span class="informal">It's like {@link reduce}, but emits the current
11328 * accumulation whenever the source emits a value.</span>
11330 * <img src="./img/scan.png" width="100%">
11332 * Combines together all values emitted on the source, using an accumulator
11333 * function that knows how to join a new source value into the accumulation from
11334 * the past. Is similar to {@link reduce}, but emits the intermediate
11337 * Returns an Observable that applies a specified `accumulator` function to each
11338 * item emitted by the source Observable. If a `seed` value is specified, then
11339 * that value will be used as the initial value for the accumulator. If no seed
11340 * value is specified, the first item of the source is used as the seed.
11342 * @example <caption>Count the number of click events</caption>
11343 * var clicks = Rx.Observable.fromEvent(document, 'click');
11344 * var ones = clicks.mapTo(1);
11346 * var count = ones.scan((acc, one) => acc + one, seed);
11347 * count.subscribe(x => console.log(x));
11349 * @see {@link expand}
11350 * @see {@link mergeScan}
11351 * @see {@link reduce}
11353 * @param {function(acc: R, value: T, index: number): R} accumulator
11354 * The accumulator function called on each source value.
11355 * @param {T|R} [seed] The initial accumulation value.
11356 * @return {Observable<R>} An observable of the accumulated values.
11358 * @owner Observable
11360 function scan(accumulator, seed) {
11361 var hasSeed = false;
11362 // providing a seed of `undefined` *should* be valid and trigger
11363 // hasSeed! so don't use `seed !== undefined` checks!
11364 // For this reason, we have to check it here at the original call site
11365 // otherwise inside Operator/Subscriber we won't know if `undefined`
11366 // means they didn't provide anything or if they literally provided `undefined`
11367 if (arguments.length >= 2) {
11370 return this.lift(new ScanOperator(accumulator, seed, hasSeed));
11372 exports.scan = scan;
11373 var ScanOperator = (function () {
11374 function ScanOperator(accumulator, seed, hasSeed) {
11375 if (hasSeed === void 0) { hasSeed = false; }
11376 this.accumulator = accumulator;
11378 this.hasSeed = hasSeed;
11380 ScanOperator.prototype.call = function (subscriber, source) {
11381 return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
11383 return ScanOperator;
11386 * We need this JSDoc comment for affecting ESDoc.
11388 * @extends {Ignored}
11390 var ScanSubscriber = (function (_super) {
11391 __extends(ScanSubscriber, _super);
11392 function ScanSubscriber(destination, accumulator, _seed, hasSeed) {
11393 _super.call(this, destination);
11394 this.accumulator = accumulator;
11395 this._seed = _seed;
11396 this.hasSeed = hasSeed;
11399 Object.defineProperty(ScanSubscriber.prototype, "seed", {
11403 set: function (value) {
11404 this.hasSeed = true;
11405 this._seed = value;
11410 ScanSubscriber.prototype._next = function (value) {
11411 if (!this.hasSeed) {
11413 this.destination.next(value);
11416 return this._tryNext(value);
11419 ScanSubscriber.prototype._tryNext = function (value) {
11420 var index = this.index++;
11423 result = this.accumulator(this.seed, value, index);
11426 this.destination.error(err);
11428 this.seed = result;
11429 this.destination.next(result);
11431 return ScanSubscriber;
11432 }(Subscriber_1.Subscriber));
11434 },{"../Subscriber":36}],135:[function(require,module,exports){
11436 var multicast_1 = require('./multicast');
11437 var Subject_1 = require('../Subject');
11438 function shareSubjectFactory() {
11439 return new Subject_1.Subject();
11442 * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
11443 * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
11444 * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
11445 * This is an alias for .publish().refCount().
11447 * <img src="./img/share.png" width="100%">
11449 * @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.
11451 * @owner Observable
11454 return multicast_1.multicast.call(this, shareSubjectFactory).refCount();
11456 exports.share = share;
11459 },{"../Subject":34,"./multicast":128}],136:[function(require,module,exports){
11461 var __extends = (this && this.__extends) || function (d, b) {
11462 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11463 function __() { this.constructor = d; }
11464 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11466 var Subscriber_1 = require('../Subscriber');
11468 * Returns an Observable that skips the first `count` items emitted by the source Observable.
11470 * <img src="./img/skip.png" width="100%">
11472 * @param {Number} count - The number of times, items emitted by source Observable should be skipped.
11473 * @return {Observable} An Observable that skips values emitted by the source Observable.
11476 * @owner Observable
11478 function skip(count) {
11479 return this.lift(new SkipOperator(count));
11481 exports.skip = skip;
11482 var SkipOperator = (function () {
11483 function SkipOperator(total) {
11484 this.total = total;
11486 SkipOperator.prototype.call = function (subscriber, source) {
11487 return source.subscribe(new SkipSubscriber(subscriber, this.total));
11489 return SkipOperator;
11492 * We need this JSDoc comment for affecting ESDoc.
11494 * @extends {Ignored}
11496 var SkipSubscriber = (function (_super) {
11497 __extends(SkipSubscriber, _super);
11498 function SkipSubscriber(destination, total) {
11499 _super.call(this, destination);
11500 this.total = total;
11503 SkipSubscriber.prototype._next = function (x) {
11504 if (++this.count > this.total) {
11505 this.destination.next(x);
11508 return SkipSubscriber;
11509 }(Subscriber_1.Subscriber));
11511 },{"../Subscriber":36}],137:[function(require,module,exports){
11513 var __extends = (this && this.__extends) || function (d, b) {
11514 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11515 function __() { this.constructor = d; }
11516 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11518 var OuterSubscriber_1 = require('../OuterSubscriber');
11519 var subscribeToResult_1 = require('../util/subscribeToResult');
11521 * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
11523 * <img src="./img/skipUntil.png" width="100%">
11525 * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to
11526 * be mirrored by the resulting Observable.
11527 * @return {Observable<T>} An Observable that skips items from the source Observable until the second Observable emits
11528 * an item, then emits the remaining items.
11529 * @method skipUntil
11530 * @owner Observable
11532 function skipUntil(notifier) {
11533 return this.lift(new SkipUntilOperator(notifier));
11535 exports.skipUntil = skipUntil;
11536 var SkipUntilOperator = (function () {
11537 function SkipUntilOperator(notifier) {
11538 this.notifier = notifier;
11540 SkipUntilOperator.prototype.call = function (subscriber, source) {
11541 return source.subscribe(new SkipUntilSubscriber(subscriber, this.notifier));
11543 return SkipUntilOperator;
11546 * We need this JSDoc comment for affecting ESDoc.
11548 * @extends {Ignored}
11550 var SkipUntilSubscriber = (function (_super) {
11551 __extends(SkipUntilSubscriber, _super);
11552 function SkipUntilSubscriber(destination, notifier) {
11553 _super.call(this, destination);
11554 this.hasValue = false;
11555 this.isInnerStopped = false;
11556 this.add(subscribeToResult_1.subscribeToResult(this, notifier));
11558 SkipUntilSubscriber.prototype._next = function (value) {
11559 if (this.hasValue) {
11560 _super.prototype._next.call(this, value);
11563 SkipUntilSubscriber.prototype._complete = function () {
11564 if (this.isInnerStopped) {
11565 _super.prototype._complete.call(this);
11568 this.unsubscribe();
11571 SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11572 this.hasValue = true;
11574 SkipUntilSubscriber.prototype.notifyComplete = function () {
11575 this.isInnerStopped = true;
11576 if (this.isStopped) {
11577 _super.prototype._complete.call(this);
11580 return SkipUntilSubscriber;
11581 }(OuterSubscriber_1.OuterSubscriber));
11583 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],138:[function(require,module,exports){
11585 var __extends = (this && this.__extends) || function (d, b) {
11586 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11587 function __() { this.constructor = d; }
11588 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11590 var Subscriber_1 = require('../Subscriber');
11592 * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
11593 * true, but emits all further source items as soon as the condition becomes false.
11595 * <img src="./img/skipWhile.png" width="100%">
11597 * @param {Function} predicate - A function to test each item emitted from the source Observable.
11598 * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the
11599 * specified predicate becomes false.
11600 * @method skipWhile
11601 * @owner Observable
11603 function skipWhile(predicate) {
11604 return this.lift(new SkipWhileOperator(predicate));
11606 exports.skipWhile = skipWhile;
11607 var SkipWhileOperator = (function () {
11608 function SkipWhileOperator(predicate) {
11609 this.predicate = predicate;
11611 SkipWhileOperator.prototype.call = function (subscriber, source) {
11612 return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
11614 return SkipWhileOperator;
11617 * We need this JSDoc comment for affecting ESDoc.
11619 * @extends {Ignored}
11621 var SkipWhileSubscriber = (function (_super) {
11622 __extends(SkipWhileSubscriber, _super);
11623 function SkipWhileSubscriber(destination, predicate) {
11624 _super.call(this, destination);
11625 this.predicate = predicate;
11626 this.skipping = true;
11629 SkipWhileSubscriber.prototype._next = function (value) {
11630 var destination = this.destination;
11631 if (this.skipping) {
11632 this.tryCallPredicate(value);
11634 if (!this.skipping) {
11635 destination.next(value);
11638 SkipWhileSubscriber.prototype.tryCallPredicate = function (value) {
11640 var result = this.predicate(value, this.index++);
11641 this.skipping = Boolean(result);
11644 this.destination.error(err);
11647 return SkipWhileSubscriber;
11648 }(Subscriber_1.Subscriber));
11650 },{"../Subscriber":36}],139:[function(require,module,exports){
11652 var ArrayObservable_1 = require('../observable/ArrayObservable');
11653 var ScalarObservable_1 = require('../observable/ScalarObservable');
11654 var EmptyObservable_1 = require('../observable/EmptyObservable');
11655 var concat_1 = require('./concat');
11656 var isScheduler_1 = require('../util/isScheduler');
11657 /* tslint:enable:max-line-length */
11659 * Returns an Observable that emits the items you specify as arguments before it begins to emit
11660 * items emitted by the source Observable.
11662 * <img src="./img/startWith.png" width="100%">
11664 * @param {...T} values - Items you want the modified Observable to emit first.
11665 * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling
11666 * the emissions of the `next` notifications.
11667 * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items
11668 * emitted by the source Observable.
11669 * @method startWith
11670 * @owner Observable
11672 function startWith() {
11674 for (var _i = 0; _i < arguments.length; _i++) {
11675 array[_i - 0] = arguments[_i];
11677 var scheduler = array[array.length - 1];
11678 if (isScheduler_1.isScheduler(scheduler)) {
11684 var len = array.length;
11686 return concat_1.concatStatic(new ScalarObservable_1.ScalarObservable(array[0], scheduler), this);
11688 else if (len > 1) {
11689 return concat_1.concatStatic(new ArrayObservable_1.ArrayObservable(array, scheduler), this);
11692 return concat_1.concatStatic(new EmptyObservable_1.EmptyObservable(scheduler), this);
11695 exports.startWith = startWith;
11697 },{"../observable/ArrayObservable":86,"../observable/EmptyObservable":89,"../observable/ScalarObservable":95,"../util/isScheduler":171,"./concat":113}],140:[function(require,module,exports){
11699 var __extends = (this && this.__extends) || function (d, b) {
11700 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11701 function __() { this.constructor = d; }
11702 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11704 var OuterSubscriber_1 = require('../OuterSubscriber');
11705 var subscribeToResult_1 = require('../util/subscribeToResult');
11706 /* tslint:enable:max-line-length */
11708 * Projects each source value to an Observable which is merged in the output
11709 * Observable, emitting values only from the most recently projected Observable.
11711 * <span class="informal">Maps each value to an Observable, then flattens all of
11712 * these inner Observables using {@link switch}.</span>
11714 * <img src="./img/switchMap.png" width="100%">
11716 * Returns an Observable that emits items based on applying a function that you
11717 * supply to each item emitted by the source Observable, where that function
11718 * returns an (so-called "inner") Observable. Each time it observes one of these
11719 * inner Observables, the output Observable begins emitting the items emitted by
11720 * that inner Observable. When a new inner Observable is emitted, `switchMap`
11721 * stops emitting items from the earlier-emitted inner Observable and begins
11722 * emitting items from the new one. It continues to behave like this for
11723 * subsequent inner Observables.
11725 * @example <caption>Rerun an interval Observable on every click event</caption>
11726 * var clicks = Rx.Observable.fromEvent(document, 'click');
11727 * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
11728 * result.subscribe(x => console.log(x));
11730 * @see {@link concatMap}
11731 * @see {@link exhaustMap}
11732 * @see {@link mergeMap}
11733 * @see {@link switch}
11734 * @see {@link switchMapTo}
11736 * @param {function(value: T, ?index: number): ObservableInput} project A function
11737 * that, when applied to an item emitted by the source Observable, returns an
11739 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
11740 * A function to produce the value on the output Observable based on the values
11741 * and the indices of the source (outer) emission and the inner Observable
11742 * emission. The arguments passed to this function are:
11743 * - `outerValue`: the value that came from the source
11744 * - `innerValue`: the value that came from the projected Observable
11745 * - `outerIndex`: the "index" of the value that came from the source
11746 * - `innerIndex`: the "index" of the value from the projected Observable
11747 * @return {Observable} An Observable that emits the result of applying the
11748 * projection function (and the optional `resultSelector`) to each item emitted
11749 * by the source Observable and taking only the values from the most recently
11750 * projected inner Observable.
11751 * @method switchMap
11752 * @owner Observable
11754 function switchMap(project, resultSelector) {
11755 return this.lift(new SwitchMapOperator(project, resultSelector));
11757 exports.switchMap = switchMap;
11758 var SwitchMapOperator = (function () {
11759 function SwitchMapOperator(project, resultSelector) {
11760 this.project = project;
11761 this.resultSelector = resultSelector;
11763 SwitchMapOperator.prototype.call = function (subscriber, source) {
11764 return source.subscribe(new SwitchMapSubscriber(subscriber, this.project, this.resultSelector));
11766 return SwitchMapOperator;
11769 * We need this JSDoc comment for affecting ESDoc.
11771 * @extends {Ignored}
11773 var SwitchMapSubscriber = (function (_super) {
11774 __extends(SwitchMapSubscriber, _super);
11775 function SwitchMapSubscriber(destination, project, resultSelector) {
11776 _super.call(this, destination);
11777 this.project = project;
11778 this.resultSelector = resultSelector;
11781 SwitchMapSubscriber.prototype._next = function (value) {
11783 var index = this.index++;
11785 result = this.project(value, index);
11788 this.destination.error(error);
11791 this._innerSub(result, value, index);
11793 SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
11794 var innerSubscription = this.innerSubscription;
11795 if (innerSubscription) {
11796 innerSubscription.unsubscribe();
11798 this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index));
11800 SwitchMapSubscriber.prototype._complete = function () {
11801 var innerSubscription = this.innerSubscription;
11802 if (!innerSubscription || innerSubscription.closed) {
11803 _super.prototype._complete.call(this);
11806 SwitchMapSubscriber.prototype._unsubscribe = function () {
11807 this.innerSubscription = null;
11809 SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
11810 this.remove(innerSub);
11811 this.innerSubscription = null;
11812 if (this.isStopped) {
11813 _super.prototype._complete.call(this);
11816 SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11817 if (this.resultSelector) {
11818 this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex);
11821 this.destination.next(innerValue);
11824 SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
11827 result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
11830 this.destination.error(err);
11833 this.destination.next(result);
11835 return SwitchMapSubscriber;
11836 }(OuterSubscriber_1.OuterSubscriber));
11838 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],141:[function(require,module,exports){
11840 var __extends = (this && this.__extends) || function (d, b) {
11841 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11842 function __() { this.constructor = d; }
11843 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11845 var Subscriber_1 = require('../Subscriber');
11846 var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError');
11847 var EmptyObservable_1 = require('../observable/EmptyObservable');
11849 * Emits only the first `count` values emitted by the source Observable.
11851 * <span class="informal">Takes the first `count` values from the source, then
11852 * completes.</span>
11854 * <img src="./img/take.png" width="100%">
11856 * `take` returns an Observable that emits only the first `count` values emitted
11857 * by the source Observable. If the source emits fewer than `count` values then
11858 * all of its values are emitted. After that, it completes, regardless if the
11859 * source completes.
11861 * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
11862 * var interval = Rx.Observable.interval(1000);
11863 * var five = interval.take(5);
11864 * five.subscribe(x => console.log(x));
11866 * @see {@link takeLast}
11867 * @see {@link takeUntil}
11868 * @see {@link takeWhile}
11869 * @see {@link skip}
11871 * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
11872 * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
11874 * @param {number} count The maximum number of `next` values to emit.
11875 * @return {Observable<T>} An Observable that emits only the first `count`
11876 * values emitted by the source Observable, or all of the values from the source
11877 * if the source emits fewer than `count` values.
11879 * @owner Observable
11881 function take(count) {
11883 return new EmptyObservable_1.EmptyObservable();
11886 return this.lift(new TakeOperator(count));
11889 exports.take = take;
11890 var TakeOperator = (function () {
11891 function TakeOperator(total) {
11892 this.total = total;
11893 if (this.total < 0) {
11894 throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
11897 TakeOperator.prototype.call = function (subscriber, source) {
11898 return source.subscribe(new TakeSubscriber(subscriber, this.total));
11900 return TakeOperator;
11903 * We need this JSDoc comment for affecting ESDoc.
11905 * @extends {Ignored}
11907 var TakeSubscriber = (function (_super) {
11908 __extends(TakeSubscriber, _super);
11909 function TakeSubscriber(destination, total) {
11910 _super.call(this, destination);
11911 this.total = total;
11914 TakeSubscriber.prototype._next = function (value) {
11915 var total = this.total;
11916 var count = ++this.count;
11917 if (count <= total) {
11918 this.destination.next(value);
11919 if (count === total) {
11920 this.destination.complete();
11921 this.unsubscribe();
11925 return TakeSubscriber;
11926 }(Subscriber_1.Subscriber));
11928 },{"../Subscriber":36,"../observable/EmptyObservable":89,"../util/ArgumentOutOfRangeError":158}],142:[function(require,module,exports){
11930 var __extends = (this && this.__extends) || function (d, b) {
11931 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11932 function __() { this.constructor = d; }
11933 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11935 var OuterSubscriber_1 = require('../OuterSubscriber');
11936 var subscribeToResult_1 = require('../util/subscribeToResult');
11938 * Emits the values emitted by the source Observable until a `notifier`
11939 * Observable emits a value.
11941 * <span class="informal">Lets values pass until a second Observable,
11942 * `notifier`, emits something. Then, it completes.</span>
11944 * <img src="./img/takeUntil.png" width="100%">
11946 * `takeUntil` subscribes and begins mirroring the source Observable. It also
11947 * monitors a second Observable, `notifier` that you provide. If the `notifier`
11948 * emits a value or a complete notification, the output Observable stops
11949 * mirroring the source Observable and completes.
11951 * @example <caption>Tick every second until the first click happens</caption>
11952 * var interval = Rx.Observable.interval(1000);
11953 * var clicks = Rx.Observable.fromEvent(document, 'click');
11954 * var result = interval.takeUntil(clicks);
11955 * result.subscribe(x => console.log(x));
11957 * @see {@link take}
11958 * @see {@link takeLast}
11959 * @see {@link takeWhile}
11960 * @see {@link skip}
11962 * @param {Observable} notifier The Observable whose first emitted value will
11963 * cause the output Observable of `takeUntil` to stop emitting values from the
11964 * source Observable.
11965 * @return {Observable<T>} An Observable that emits the values from the source
11966 * Observable until such time as `notifier` emits its first value.
11967 * @method takeUntil
11968 * @owner Observable
11970 function takeUntil(notifier) {
11971 return this.lift(new TakeUntilOperator(notifier));
11973 exports.takeUntil = takeUntil;
11974 var TakeUntilOperator = (function () {
11975 function TakeUntilOperator(notifier) {
11976 this.notifier = notifier;
11978 TakeUntilOperator.prototype.call = function (subscriber, source) {
11979 return source.subscribe(new TakeUntilSubscriber(subscriber, this.notifier));
11981 return TakeUntilOperator;
11984 * We need this JSDoc comment for affecting ESDoc.
11986 * @extends {Ignored}
11988 var TakeUntilSubscriber = (function (_super) {
11989 __extends(TakeUntilSubscriber, _super);
11990 function TakeUntilSubscriber(destination, notifier) {
11991 _super.call(this, destination);
11992 this.notifier = notifier;
11993 this.add(subscribeToResult_1.subscribeToResult(this, notifier));
11995 TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11998 TakeUntilSubscriber.prototype.notifyComplete = function () {
12001 return TakeUntilSubscriber;
12002 }(OuterSubscriber_1.OuterSubscriber));
12004 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],143:[function(require,module,exports){
12006 var __extends = (this && this.__extends) || function (d, b) {
12007 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12008 function __() { this.constructor = d; }
12009 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12011 var OuterSubscriber_1 = require('../OuterSubscriber');
12012 var subscribeToResult_1 = require('../util/subscribeToResult');
12013 exports.defaultThrottleConfig = {
12018 * Emits a value from the source Observable, then ignores subsequent source
12019 * values for a duration determined by another Observable, then repeats this
12022 * <span class="informal">It's like {@link throttleTime}, but the silencing
12023 * duration is determined by a second Observable.</span>
12025 * <img src="./img/throttle.png" width="100%">
12027 * `throttle` emits the source Observable values on the output Observable
12028 * when its internal timer is disabled, and ignores source values when the timer
12029 * is enabled. Initially, the timer is disabled. As soon as the first source
12030 * value arrives, it is forwarded to the output Observable, and then the timer
12031 * is enabled by calling the `durationSelector` function with the source value,
12032 * which returns the "duration" Observable. When the duration Observable emits a
12033 * value or completes, the timer is disabled, and this process repeats for the
12034 * next source value.
12036 * @example <caption>Emit clicks at a rate of at most one click per second</caption>
12037 * var clicks = Rx.Observable.fromEvent(document, 'click');
12038 * var result = clicks.throttle(ev => Rx.Observable.interval(1000));
12039 * result.subscribe(x => console.log(x));
12041 * @see {@link audit}
12042 * @see {@link debounce}
12043 * @see {@link delayWhen}
12044 * @see {@link sample}
12045 * @see {@link throttleTime}
12047 * @param {function(value: T): SubscribableOrPromise} durationSelector A function
12048 * that receives a value from the source Observable, for computing the silencing
12049 * duration for each source value, returned as an Observable or a Promise.
12050 * @param {Object} config a configuration object to define `leading` and `trailing` behavior. Defaults
12051 * to `{ leading: true, trailing: false }`.
12052 * @return {Observable<T>} An Observable that performs the throttle operation to
12053 * limit the rate of emissions from the source.
12055 * @owner Observable
12057 function throttle(durationSelector, config) {
12058 if (config === void 0) { config = exports.defaultThrottleConfig; }
12059 return this.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing));
12061 exports.throttle = throttle;
12062 var ThrottleOperator = (function () {
12063 function ThrottleOperator(durationSelector, leading, trailing) {
12064 this.durationSelector = durationSelector;
12065 this.leading = leading;
12066 this.trailing = trailing;
12068 ThrottleOperator.prototype.call = function (subscriber, source) {
12069 return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
12071 return ThrottleOperator;
12074 * We need this JSDoc comment for affecting ESDoc
12076 * @extends {Ignored}
12078 var ThrottleSubscriber = (function (_super) {
12079 __extends(ThrottleSubscriber, _super);
12080 function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) {
12081 _super.call(this, destination);
12082 this.destination = destination;
12083 this.durationSelector = durationSelector;
12084 this._leading = _leading;
12085 this._trailing = _trailing;
12086 this._hasTrailingValue = false;
12088 ThrottleSubscriber.prototype._next = function (value) {
12089 if (this.throttled) {
12090 if (this._trailing) {
12091 this._hasTrailingValue = true;
12092 this._trailingValue = value;
12096 var duration = this.tryDurationSelector(value);
12098 this.add(this.throttled = subscribeToResult_1.subscribeToResult(this, duration));
12100 if (this._leading) {
12101 this.destination.next(value);
12102 if (this._trailing) {
12103 this._hasTrailingValue = true;
12104 this._trailingValue = value;
12109 ThrottleSubscriber.prototype.tryDurationSelector = function (value) {
12111 return this.durationSelector(value);
12114 this.destination.error(err);
12118 ThrottleSubscriber.prototype._unsubscribe = function () {
12119 var _a = this, throttled = _a.throttled, _trailingValue = _a._trailingValue, _hasTrailingValue = _a._hasTrailingValue, _trailing = _a._trailing;
12120 this._trailingValue = null;
12121 this._hasTrailingValue = false;
12123 this.remove(throttled);
12124 this.throttled = null;
12125 throttled.unsubscribe();
12128 ThrottleSubscriber.prototype._sendTrailing = function () {
12129 var _a = this, destination = _a.destination, throttled = _a.throttled, _trailing = _a._trailing, _trailingValue = _a._trailingValue, _hasTrailingValue = _a._hasTrailingValue;
12130 if (throttled && _trailing && _hasTrailingValue) {
12131 destination.next(_trailingValue);
12132 this._trailingValue = null;
12133 this._hasTrailingValue = false;
12136 ThrottleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12137 this._sendTrailing();
12138 this._unsubscribe();
12140 ThrottleSubscriber.prototype.notifyComplete = function () {
12141 this._sendTrailing();
12142 this._unsubscribe();
12144 return ThrottleSubscriber;
12145 }(OuterSubscriber_1.OuterSubscriber));
12147 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],144:[function(require,module,exports){
12149 var __extends = (this && this.__extends) || function (d, b) {
12150 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12151 function __() { this.constructor = d; }
12152 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12154 var Subscriber_1 = require('../Subscriber');
12155 var async_1 = require('../scheduler/async');
12156 var throttle_1 = require('./throttle');
12158 * Emits a value from the source Observable, then ignores subsequent source
12159 * values for `duration` milliseconds, then repeats this process.
12161 * <span class="informal">Lets a value pass, then ignores source values for the
12162 * next `duration` milliseconds.</span>
12164 * <img src="./img/throttleTime.png" width="100%">
12166 * `throttleTime` emits the source Observable values on the output Observable
12167 * when its internal timer is disabled, and ignores source values when the timer
12168 * is enabled. Initially, the timer is disabled. As soon as the first source
12169 * value arrives, it is forwarded to the output Observable, and then the timer
12170 * is enabled. After `duration` milliseconds (or the time unit determined
12171 * internally by the optional `scheduler`) has passed, the timer is disabled,
12172 * and this process repeats for the next source value. Optionally takes a
12173 * {@link IScheduler} for managing timers.
12175 * @example <caption>Emit clicks at a rate of at most one click per second</caption>
12176 * var clicks = Rx.Observable.fromEvent(document, 'click');
12177 * var result = clicks.throttleTime(1000);
12178 * result.subscribe(x => console.log(x));
12180 * @see {@link auditTime}
12181 * @see {@link debounceTime}
12182 * @see {@link delay}
12183 * @see {@link sampleTime}
12184 * @see {@link throttle}
12186 * @param {number} duration Time to wait before emitting another value after
12187 * emitting the last value, measured in milliseconds or the time unit determined
12188 * internally by the optional `scheduler`.
12189 * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
12190 * managing the timers that handle the throttling.
12191 * @return {Observable<T>} An Observable that performs the throttle operation to
12192 * limit the rate of emissions from the source.
12193 * @method throttleTime
12194 * @owner Observable
12196 function throttleTime(duration, scheduler, config) {
12197 if (scheduler === void 0) { scheduler = async_1.async; }
12198 if (config === void 0) { config = throttle_1.defaultThrottleConfig; }
12199 return this.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing));
12201 exports.throttleTime = throttleTime;
12202 var ThrottleTimeOperator = (function () {
12203 function ThrottleTimeOperator(duration, scheduler, leading, trailing) {
12204 this.duration = duration;
12205 this.scheduler = scheduler;
12206 this.leading = leading;
12207 this.trailing = trailing;
12209 ThrottleTimeOperator.prototype.call = function (subscriber, source) {
12210 return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
12212 return ThrottleTimeOperator;
12215 * We need this JSDoc comment for affecting ESDoc.
12217 * @extends {Ignored}
12219 var ThrottleTimeSubscriber = (function (_super) {
12220 __extends(ThrottleTimeSubscriber, _super);
12221 function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) {
12222 _super.call(this, destination);
12223 this.duration = duration;
12224 this.scheduler = scheduler;
12225 this.leading = leading;
12226 this.trailing = trailing;
12227 this._hasTrailingValue = false;
12228 this._trailingValue = null;
12230 ThrottleTimeSubscriber.prototype._next = function (value) {
12231 if (this.throttled) {
12232 if (this.trailing) {
12233 this._trailingValue = value;
12234 this._hasTrailingValue = true;
12238 this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
12239 if (this.leading) {
12240 this.destination.next(value);
12244 ThrottleTimeSubscriber.prototype.clearThrottle = function () {
12245 var throttled = this.throttled;
12247 if (this.trailing && this._hasTrailingValue) {
12248 this.destination.next(this._trailingValue);
12249 this._trailingValue = null;
12250 this._hasTrailingValue = false;
12252 throttled.unsubscribe();
12253 this.remove(throttled);
12254 this.throttled = null;
12257 return ThrottleTimeSubscriber;
12258 }(Subscriber_1.Subscriber));
12259 function dispatchNext(arg) {
12260 var subscriber = arg.subscriber;
12261 subscriber.clearThrottle();
12264 },{"../Subscriber":36,"../scheduler/async":152,"./throttle":143}],145:[function(require,module,exports){
12266 var __extends = (this && this.__extends) || function (d, b) {
12267 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12268 function __() { this.constructor = d; }
12269 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12271 var OuterSubscriber_1 = require('../OuterSubscriber');
12272 var subscribeToResult_1 = require('../util/subscribeToResult');
12273 /* tslint:enable:max-line-length */
12275 * Combines the source Observable with other Observables to create an Observable
12276 * whose values are calculated from the latest values of each, only when the
12279 * <span class="informal">Whenever the source Observable emits a value, it
12280 * computes a formula using that value plus the latest values from other input
12281 * Observables, then emits the output of that formula.</span>
12283 * <img src="./img/withLatestFrom.png" width="100%">
12285 * `withLatestFrom` combines each value from the source Observable (the
12286 * instance) with the latest values from the other input Observables only when
12287 * the source emits a value, optionally using a `project` function to determine
12288 * the value to be emitted on the output Observable. All input Observables must
12289 * emit at least one value before the output Observable will emit a value.
12291 * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
12292 * var clicks = Rx.Observable.fromEvent(document, 'click');
12293 * var timer = Rx.Observable.interval(1000);
12294 * var result = clicks.withLatestFrom(timer);
12295 * result.subscribe(x => console.log(x));
12297 * @see {@link combineLatest}
12299 * @param {ObservableInput} other An input Observable to combine with the source
12300 * Observable. More than one input Observables may be given as argument.
12301 * @param {Function} [project] Projection function for combining values
12302 * together. Receives all values in order of the Observables passed, where the
12303 * first parameter is a value from the source Observable. (e.g.
12304 * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
12305 * passed, arrays will be emitted on the output Observable.
12306 * @return {Observable} An Observable of projected values from the most recent
12307 * values from each input Observable, or an array of the most recent values from
12308 * each input Observable.
12309 * @method withLatestFrom
12310 * @owner Observable
12312 function withLatestFrom() {
12314 for (var _i = 0; _i < arguments.length; _i++) {
12315 args[_i - 0] = arguments[_i];
12318 if (typeof args[args.length - 1] === 'function') {
12319 project = args.pop();
12321 var observables = args;
12322 return this.lift(new WithLatestFromOperator(observables, project));
12324 exports.withLatestFrom = withLatestFrom;
12325 var WithLatestFromOperator = (function () {
12326 function WithLatestFromOperator(observables, project) {
12327 this.observables = observables;
12328 this.project = project;
12330 WithLatestFromOperator.prototype.call = function (subscriber, source) {
12331 return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
12333 return WithLatestFromOperator;
12336 * We need this JSDoc comment for affecting ESDoc.
12338 * @extends {Ignored}
12340 var WithLatestFromSubscriber = (function (_super) {
12341 __extends(WithLatestFromSubscriber, _super);
12342 function WithLatestFromSubscriber(destination, observables, project) {
12343 _super.call(this, destination);
12344 this.observables = observables;
12345 this.project = project;
12346 this.toRespond = [];
12347 var len = observables.length;
12348 this.values = new Array(len);
12349 for (var i = 0; i < len; i++) {
12350 this.toRespond.push(i);
12352 for (var i = 0; i < len; i++) {
12353 var observable = observables[i];
12354 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
12357 WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12358 this.values[outerIndex] = innerValue;
12359 var toRespond = this.toRespond;
12360 if (toRespond.length > 0) {
12361 var found = toRespond.indexOf(outerIndex);
12362 if (found !== -1) {
12363 toRespond.splice(found, 1);
12367 WithLatestFromSubscriber.prototype.notifyComplete = function () {
12370 WithLatestFromSubscriber.prototype._next = function (value) {
12371 if (this.toRespond.length === 0) {
12372 var args = [value].concat(this.values);
12373 if (this.project) {
12374 this._tryProject(args);
12377 this.destination.next(args);
12381 WithLatestFromSubscriber.prototype._tryProject = function (args) {
12384 result = this.project.apply(this, args);
12387 this.destination.error(err);
12390 this.destination.next(result);
12392 return WithLatestFromSubscriber;
12393 }(OuterSubscriber_1.OuterSubscriber));
12395 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],146:[function(require,module,exports){
12397 var __extends = (this && this.__extends) || function (d, b) {
12398 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12399 function __() { this.constructor = d; }
12400 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12402 var ArrayObservable_1 = require('../observable/ArrayObservable');
12403 var isArray_1 = require('../util/isArray');
12404 var Subscriber_1 = require('../Subscriber');
12405 var OuterSubscriber_1 = require('../OuterSubscriber');
12406 var subscribeToResult_1 = require('../util/subscribeToResult');
12407 var iterator_1 = require('../symbol/iterator');
12408 /* tslint:enable:max-line-length */
12410 * @param observables
12411 * @return {Observable<R>}
12413 * @owner Observable
12415 function zipProto() {
12416 var observables = [];
12417 for (var _i = 0; _i < arguments.length; _i++) {
12418 observables[_i - 0] = arguments[_i];
12420 return this.lift.call(zipStatic.apply(void 0, [this].concat(observables)));
12422 exports.zipProto = zipProto;
12423 /* tslint:enable:max-line-length */
12425 * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each
12426 * of its input Observables.
12428 * If the latest parameter is a function, this function is used to compute the created value from the input values.
12429 * Otherwise, an array of the input values is returned.
12431 * @example <caption>Combine age and name from different sources</caption>
12433 * let age$ = Observable.of<number>(27, 25, 29);
12434 * let name$ = Observable.of<string>('Foo', 'Bar', 'Beer');
12435 * let isDev$ = Observable.of<boolean>(true, true, false);
12441 * (age: number, name: string, isDev: boolean) => ({ age, name, isDev }))
12442 * .subscribe(x => console.log(x));
12445 * // { age: 27, name: 'Foo', isDev: true }
12446 * // { age: 25, name: 'Bar', isDev: true }
12447 * // { age: 29, name: 'Beer', isDev: false }
12449 * @param observables
12450 * @return {Observable<R>}
12453 * @owner Observable
12455 function zipStatic() {
12456 var observables = [];
12457 for (var _i = 0; _i < arguments.length; _i++) {
12458 observables[_i - 0] = arguments[_i];
12460 var project = observables[observables.length - 1];
12461 if (typeof project === 'function') {
12464 return new ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project));
12466 exports.zipStatic = zipStatic;
12467 var ZipOperator = (function () {
12468 function ZipOperator(project) {
12469 this.project = project;
12471 ZipOperator.prototype.call = function (subscriber, source) {
12472 return source.subscribe(new ZipSubscriber(subscriber, this.project));
12474 return ZipOperator;
12476 exports.ZipOperator = ZipOperator;
12478 * We need this JSDoc comment for affecting ESDoc.
12480 * @extends {Ignored}
12482 var ZipSubscriber = (function (_super) {
12483 __extends(ZipSubscriber, _super);
12484 function ZipSubscriber(destination, project, values) {
12485 if (values === void 0) { values = Object.create(null); }
12486 _super.call(this, destination);
12487 this.iterators = [];
12489 this.project = (typeof project === 'function') ? project : null;
12490 this.values = values;
12492 ZipSubscriber.prototype._next = function (value) {
12493 var iterators = this.iterators;
12494 if (isArray_1.isArray(value)) {
12495 iterators.push(new StaticArrayIterator(value));
12497 else if (typeof value[iterator_1.iterator] === 'function') {
12498 iterators.push(new StaticIterator(value[iterator_1.iterator]()));
12501 iterators.push(new ZipBufferIterator(this.destination, this, value));
12504 ZipSubscriber.prototype._complete = function () {
12505 var iterators = this.iterators;
12506 var len = iterators.length;
12508 this.destination.complete();
12512 for (var i = 0; i < len; i++) {
12513 var iterator = iterators[i];
12514 if (iterator.stillUnsubscribed) {
12515 this.add(iterator.subscribe(iterator, i));
12518 this.active--; // not an observable
12522 ZipSubscriber.prototype.notifyInactive = function () {
12524 if (this.active === 0) {
12525 this.destination.complete();
12528 ZipSubscriber.prototype.checkIterators = function () {
12529 var iterators = this.iterators;
12530 var len = iterators.length;
12531 var destination = this.destination;
12532 // abort if not all of them have values
12533 for (var i = 0; i < len; i++) {
12534 var iterator = iterators[i];
12535 if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
12539 var shouldComplete = false;
12541 for (var i = 0; i < len; i++) {
12542 var iterator = iterators[i];
12543 var result = iterator.next();
12544 // check to see if it's completed now that you've gotten
12546 if (iterator.hasCompleted()) {
12547 shouldComplete = true;
12550 destination.complete();
12553 args.push(result.value);
12555 if (this.project) {
12556 this._tryProject(args);
12559 destination.next(args);
12561 if (shouldComplete) {
12562 destination.complete();
12565 ZipSubscriber.prototype._tryProject = function (args) {
12568 result = this.project.apply(this, args);
12571 this.destination.error(err);
12574 this.destination.next(result);
12576 return ZipSubscriber;
12577 }(Subscriber_1.Subscriber));
12578 exports.ZipSubscriber = ZipSubscriber;
12579 var StaticIterator = (function () {
12580 function StaticIterator(iterator) {
12581 this.iterator = iterator;
12582 this.nextResult = iterator.next();
12584 StaticIterator.prototype.hasValue = function () {
12587 StaticIterator.prototype.next = function () {
12588 var result = this.nextResult;
12589 this.nextResult = this.iterator.next();
12592 StaticIterator.prototype.hasCompleted = function () {
12593 var nextResult = this.nextResult;
12594 return nextResult && nextResult.done;
12596 return StaticIterator;
12598 var StaticArrayIterator = (function () {
12599 function StaticArrayIterator(array) {
12600 this.array = array;
12603 this.length = array.length;
12605 StaticArrayIterator.prototype[iterator_1.iterator] = function () {
12608 StaticArrayIterator.prototype.next = function (value) {
12609 var i = this.index++;
12610 var array = this.array;
12611 return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
12613 StaticArrayIterator.prototype.hasValue = function () {
12614 return this.array.length > this.index;
12616 StaticArrayIterator.prototype.hasCompleted = function () {
12617 return this.array.length === this.index;
12619 return StaticArrayIterator;
12622 * We need this JSDoc comment for affecting ESDoc.
12624 * @extends {Ignored}
12626 var ZipBufferIterator = (function (_super) {
12627 __extends(ZipBufferIterator, _super);
12628 function ZipBufferIterator(destination, parent, observable) {
12629 _super.call(this, destination);
12630 this.parent = parent;
12631 this.observable = observable;
12632 this.stillUnsubscribed = true;
12634 this.isComplete = false;
12636 ZipBufferIterator.prototype[iterator_1.iterator] = function () {
12639 // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next
12640 // this is legit because `next()` will never be called by a subscription in this case.
12641 ZipBufferIterator.prototype.next = function () {
12642 var buffer = this.buffer;
12643 if (buffer.length === 0 && this.isComplete) {
12644 return { value: null, done: true };
12647 return { value: buffer.shift(), done: false };
12650 ZipBufferIterator.prototype.hasValue = function () {
12651 return this.buffer.length > 0;
12653 ZipBufferIterator.prototype.hasCompleted = function () {
12654 return this.buffer.length === 0 && this.isComplete;
12656 ZipBufferIterator.prototype.notifyComplete = function () {
12657 if (this.buffer.length > 0) {
12658 this.isComplete = true;
12659 this.parent.notifyInactive();
12662 this.destination.complete();
12665 ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12666 this.buffer.push(innerValue);
12667 this.parent.checkIterators();
12669 ZipBufferIterator.prototype.subscribe = function (value, index) {
12670 return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
12672 return ZipBufferIterator;
12673 }(OuterSubscriber_1.OuterSubscriber));
12675 },{"../OuterSubscriber":31,"../Subscriber":36,"../observable/ArrayObservable":86,"../symbol/iterator":154,"../util/isArray":164,"../util/subscribeToResult":173}],147:[function(require,module,exports){
12677 var __extends = (this && this.__extends) || function (d, b) {
12678 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12679 function __() { this.constructor = d; }
12680 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12682 var Subscription_1 = require('../Subscription');
12684 * A unit of work to be executed in a {@link Scheduler}. An action is typically
12685 * created from within a Scheduler and an RxJS user does not need to concern
12686 * themselves about creating and manipulating an Action.
12689 * class Action<T> extends Subscription {
12690 * new (scheduler: Scheduler, work: (state?: T) => void);
12691 * schedule(state?: T, delay: number = 0): Subscription;
12697 var Action = (function (_super) {
12698 __extends(Action, _super);
12699 function Action(scheduler, work) {
12703 * Schedules this action on its parent Scheduler for execution. May be passed
12704 * some context object, `state`. May happen at some point in the future,
12705 * according to the `delay` parameter, if specified.
12706 * @param {T} [state] Some contextual data that the `work` function uses when
12707 * called by the Scheduler.
12708 * @param {number} [delay] Time to wait before executing the work, where the
12709 * time unit is implicit and defined by the Scheduler.
12712 Action.prototype.schedule = function (state, delay) {
12713 if (delay === void 0) { delay = 0; }
12717 }(Subscription_1.Subscription));
12718 exports.Action = Action;
12720 },{"../Subscription":37}],148:[function(require,module,exports){
12722 var __extends = (this && this.__extends) || function (d, b) {
12723 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12724 function __() { this.constructor = d; }
12725 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12727 var root_1 = require('../util/root');
12728 var Action_1 = require('./Action');
12730 * We need this JSDoc comment for affecting ESDoc.
12732 * @extends {Ignored}
12734 var AsyncAction = (function (_super) {
12735 __extends(AsyncAction, _super);
12736 function AsyncAction(scheduler, work) {
12737 _super.call(this, scheduler, work);
12738 this.scheduler = scheduler;
12740 this.pending = false;
12742 AsyncAction.prototype.schedule = function (state, delay) {
12743 if (delay === void 0) { delay = 0; }
12747 // Always replace the current state with the new state.
12748 this.state = state;
12749 // Set the pending flag indicating that this action has been scheduled, or
12750 // has recursively rescheduled itself.
12751 this.pending = true;
12753 var scheduler = this.scheduler;
12755 // Important implementation note:
12757 // Actions only execute once by default, unless rescheduled from within the
12758 // scheduled callback. This allows us to implement single and repeat
12759 // actions via the same code path, without adding API surface area, as well
12760 // as mimic traditional recursion but across asynchronous boundaries.
12762 // However, JS runtimes and timers distinguish between intervals achieved by
12763 // serial `setTimeout` calls vs. a single `setInterval` call. An interval of
12764 // serial `setTimeout` calls can be individually delayed, which delays
12765 // scheduling the next `setTimeout`, and so on. `setInterval` attempts to
12766 // guarantee the interval callback will be invoked more precisely to the
12767 // interval period, regardless of load.
12769 // Therefore, we use `setInterval` to schedule single and repeat actions.
12770 // If the action reschedules itself with the same delay, the interval is not
12771 // canceled. If the action doesn't reschedule, or reschedules with a
12772 // different delay, the interval will be canceled after scheduled callback
12776 this.id = this.recycleAsyncId(scheduler, id, delay);
12778 this.delay = delay;
12779 // If this action has already an async Id, don't request a new one.
12780 this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
12783 AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
12784 if (delay === void 0) { delay = 0; }
12785 return root_1.root.setInterval(scheduler.flush.bind(scheduler, this), delay);
12787 AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
12788 if (delay === void 0) { delay = 0; }
12789 // If this action is rescheduled with the same delay time, don't clear the interval id.
12790 if (delay !== null && this.delay === delay && this.pending === false) {
12793 // Otherwise, if the action's delay time is different from the current delay,
12794 // or the action has been rescheduled before it's executed, clear the interval id
12795 return root_1.root.clearInterval(id) && undefined || undefined;
12798 * Immediately executes this action and the `work` it contains.
12801 AsyncAction.prototype.execute = function (state, delay) {
12803 return new Error('executing a cancelled action');
12805 this.pending = false;
12806 var error = this._execute(state, delay);
12810 else if (this.pending === false && this.id != null) {
12811 // Dequeue if the action didn't reschedule itself. Don't call
12812 // unsubscribe(), because the action could reschedule later.
12815 // scheduler.schedule(function doWork(counter) {
12816 // /* ... I'm a busy worker bee ... */
12817 // var originalAction = this;
12818 // /* wait 100ms before rescheduling the action */
12819 // setTimeout(function () {
12820 // originalAction.schedule(counter + 1);
12824 this.id = this.recycleAsyncId(this.scheduler, this.id, null);
12827 AsyncAction.prototype._execute = function (state, delay) {
12828 var errored = false;
12829 var errorValue = undefined;
12835 errorValue = !!e && e || new Error(e);
12838 this.unsubscribe();
12842 AsyncAction.prototype._unsubscribe = function () {
12844 var scheduler = this.scheduler;
12845 var actions = scheduler.actions;
12846 var index = actions.indexOf(this);
12849 this.pending = false;
12850 this.scheduler = null;
12851 if (index !== -1) {
12852 actions.splice(index, 1);
12855 this.id = this.recycleAsyncId(scheduler, id, null);
12859 return AsyncAction;
12860 }(Action_1.Action));
12861 exports.AsyncAction = AsyncAction;
12863 },{"../util/root":172,"./Action":147}],149:[function(require,module,exports){
12865 var __extends = (this && this.__extends) || function (d, b) {
12866 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12867 function __() { this.constructor = d; }
12868 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12870 var Scheduler_1 = require('../Scheduler');
12871 var AsyncScheduler = (function (_super) {
12872 __extends(AsyncScheduler, _super);
12873 function AsyncScheduler() {
12874 _super.apply(this, arguments);
12877 * A flag to indicate whether the Scheduler is currently executing a batch of
12881 this.active = false;
12883 * An internal ID used to track the latest asynchronous task such as those
12884 * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
12888 this.scheduled = undefined;
12890 AsyncScheduler.prototype.flush = function (action) {
12891 var actions = this.actions;
12893 actions.push(action);
12897 this.active = true;
12899 if (error = action.execute(action.state, action.delay)) {
12902 } while (action = actions.shift()); // exhaust the scheduler queue
12903 this.active = false;
12905 while (action = actions.shift()) {
12906 action.unsubscribe();
12911 return AsyncScheduler;
12912 }(Scheduler_1.Scheduler));
12913 exports.AsyncScheduler = AsyncScheduler;
12915 },{"../Scheduler":33}],150:[function(require,module,exports){
12917 var __extends = (this && this.__extends) || function (d, b) {
12918 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12919 function __() { this.constructor = d; }
12920 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12922 var AsyncAction_1 = require('./AsyncAction');
12924 * We need this JSDoc comment for affecting ESDoc.
12926 * @extends {Ignored}
12928 var QueueAction = (function (_super) {
12929 __extends(QueueAction, _super);
12930 function QueueAction(scheduler, work) {
12931 _super.call(this, scheduler, work);
12932 this.scheduler = scheduler;
12935 QueueAction.prototype.schedule = function (state, delay) {
12936 if (delay === void 0) { delay = 0; }
12938 return _super.prototype.schedule.call(this, state, delay);
12940 this.delay = delay;
12941 this.state = state;
12942 this.scheduler.flush(this);
12945 QueueAction.prototype.execute = function (state, delay) {
12946 return (delay > 0 || this.closed) ?
12947 _super.prototype.execute.call(this, state, delay) :
12948 this._execute(state, delay);
12950 QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
12951 if (delay === void 0) { delay = 0; }
12952 // If delay exists and is greater than 0, or if the delay is null (the
12953 // action wasn't rescheduled) but was originally scheduled as an async
12954 // action, then recycle as an async action.
12955 if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
12956 return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
12958 // Otherwise flush the scheduler starting with this action.
12959 return scheduler.flush(this);
12961 return QueueAction;
12962 }(AsyncAction_1.AsyncAction));
12963 exports.QueueAction = QueueAction;
12965 },{"./AsyncAction":148}],151:[function(require,module,exports){
12967 var __extends = (this && this.__extends) || function (d, b) {
12968 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12969 function __() { this.constructor = d; }
12970 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12972 var AsyncScheduler_1 = require('./AsyncScheduler');
12973 var QueueScheduler = (function (_super) {
12974 __extends(QueueScheduler, _super);
12975 function QueueScheduler() {
12976 _super.apply(this, arguments);
12978 return QueueScheduler;
12979 }(AsyncScheduler_1.AsyncScheduler));
12980 exports.QueueScheduler = QueueScheduler;
12982 },{"./AsyncScheduler":149}],152:[function(require,module,exports){
12984 var AsyncAction_1 = require('./AsyncAction');
12985 var AsyncScheduler_1 = require('./AsyncScheduler');
12990 * <span class="informal">Schedule task as if you used setTimeout(task, duration)</span>
12992 * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript
12993 * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating
12996 * If you just want to "defer" task, that is to perform it right after currently
12997 * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),
12998 * better choice will be the {@link asap} scheduler.
13000 * @example <caption>Use async scheduler to delay task</caption>
13001 * const task = () => console.log('it works!');
13003 * Rx.Scheduler.async.schedule(task, 2000);
13005 * // After 2 seconds logs:
13009 * @example <caption>Use async scheduler to repeat task in intervals</caption>
13010 * function task(state) {
13011 * console.log(state);
13012 * this.schedule(state + 1, 1000); // `this` references currently executing Action,
13013 * // which we reschedule with new state and delay
13016 * Rx.Scheduler.async.schedule(task, 3000, 0);
13028 exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
13030 },{"./AsyncAction":148,"./AsyncScheduler":149}],153:[function(require,module,exports){
13032 var QueueAction_1 = require('./QueueAction');
13033 var QueueScheduler_1 = require('./QueueScheduler');
13038 * <span class="informal">Put every next task on a queue, instead of executing it immediately</span>
13040 * `queue` scheduler, when used with delay, behaves the same as {@link async} scheduler.
13042 * When used without delay, it schedules given task synchronously - executes it right when
13043 * it is scheduled. However when called recursively, that is when inside the scheduled task,
13044 * another task is scheduled with queue scheduler, instead of executing immediately as well,
13045 * that task will be put on a queue and wait for current one to finish.
13047 * This means that when you execute task with `queue` scheduler, you are sure it will end
13048 * before any other task scheduled with that scheduler will start.
13050 * @examples <caption>Schedule recursively first, then do something</caption>
13052 * Rx.Scheduler.queue.schedule(() => {
13053 * Rx.Scheduler.queue.schedule(() => console.log('second')); // will not happen now, but will be put on a queue
13055 * console.log('first');
13063 * @example <caption>Reschedule itself recursively</caption>
13065 * Rx.Scheduler.queue.schedule(function(state) {
13066 * if (state !== 0) {
13067 * console.log('before', state);
13068 * this.schedule(state - 1); // `this` references currently executing Action,
13069 * // which we reschedule with new state
13070 * console.log('after', state);
13074 * // In scheduler that runs recursively, you would expect:
13082 * // But with queue it logs:
13095 exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
13097 },{"./QueueAction":150,"./QueueScheduler":151}],154:[function(require,module,exports){
13099 var root_1 = require('../util/root');
13100 function symbolIteratorPonyfill(root) {
13101 var Symbol = root.Symbol;
13102 if (typeof Symbol === 'function') {
13103 if (!Symbol.iterator) {
13104 Symbol.iterator = Symbol('iterator polyfill');
13106 return Symbol.iterator;
13109 // [for Mozilla Gecko 27-35:](https://mzl.la/2ewE1zC)
13110 var Set_1 = root.Set;
13111 if (Set_1 && typeof new Set_1()['@@iterator'] === 'function') {
13112 return '@@iterator';
13114 var Map_1 = root.Map;
13115 // required for compatability with es6-shim
13117 var keys = Object.getOwnPropertyNames(Map_1.prototype);
13118 for (var i = 0; i < keys.length; ++i) {
13120 // according to spec, Map.prototype[@@iterator] and Map.orototype.entries must be equal.
13121 if (key !== 'entries' && key !== 'size' && Map_1.prototype[key] === Map_1.prototype['entries']) {
13126 return '@@iterator';
13129 exports.symbolIteratorPonyfill = symbolIteratorPonyfill;
13130 exports.iterator = symbolIteratorPonyfill(root_1.root);
13132 * @deprecated use iterator instead
13134 exports.$$iterator = exports.iterator;
13136 },{"../util/root":172}],155:[function(require,module,exports){
13138 var root_1 = require('../util/root');
13139 function getSymbolObservable(context) {
13141 var Symbol = context.Symbol;
13142 if (typeof Symbol === 'function') {
13143 if (Symbol.observable) {
13144 $$observable = Symbol.observable;
13147 $$observable = Symbol('observable');
13148 Symbol.observable = $$observable;
13152 $$observable = '@@observable';
13154 return $$observable;
13156 exports.getSymbolObservable = getSymbolObservable;
13157 exports.observable = getSymbolObservable(root_1.root);
13159 * @deprecated use observable instead
13161 exports.$$observable = exports.observable;
13163 },{"../util/root":172}],156:[function(require,module,exports){
13165 var root_1 = require('../util/root');
13166 var Symbol = root_1.root.Symbol;
13167 exports.rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ?
13168 Symbol.for('rxSubscriber') : '@@rxSubscriber';
13170 * @deprecated use rxSubscriber instead
13172 exports.$$rxSubscriber = exports.rxSubscriber;
13174 },{"../util/root":172}],157:[function(require,module,exports){
13176 var root_1 = require('./root');
13177 var RequestAnimationFrameDefinition = (function () {
13178 function RequestAnimationFrameDefinition(root) {
13179 if (root.requestAnimationFrame) {
13180 this.cancelAnimationFrame = root.cancelAnimationFrame.bind(root);
13181 this.requestAnimationFrame = root.requestAnimationFrame.bind(root);
13183 else if (root.mozRequestAnimationFrame) {
13184 this.cancelAnimationFrame = root.mozCancelAnimationFrame.bind(root);
13185 this.requestAnimationFrame = root.mozRequestAnimationFrame.bind(root);
13187 else if (root.webkitRequestAnimationFrame) {
13188 this.cancelAnimationFrame = root.webkitCancelAnimationFrame.bind(root);
13189 this.requestAnimationFrame = root.webkitRequestAnimationFrame.bind(root);
13191 else if (root.msRequestAnimationFrame) {
13192 this.cancelAnimationFrame = root.msCancelAnimationFrame.bind(root);
13193 this.requestAnimationFrame = root.msRequestAnimationFrame.bind(root);
13195 else if (root.oRequestAnimationFrame) {
13196 this.cancelAnimationFrame = root.oCancelAnimationFrame.bind(root);
13197 this.requestAnimationFrame = root.oRequestAnimationFrame.bind(root);
13200 this.cancelAnimationFrame = root.clearTimeout.bind(root);
13201 this.requestAnimationFrame = function (cb) { return root.setTimeout(cb, 1000 / 60); };
13204 return RequestAnimationFrameDefinition;
13206 exports.RequestAnimationFrameDefinition = RequestAnimationFrameDefinition;
13207 exports.AnimationFrame = new RequestAnimationFrameDefinition(root_1.root);
13209 },{"./root":172}],158:[function(require,module,exports){
13211 var __extends = (this && this.__extends) || function (d, b) {
13212 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13213 function __() { this.constructor = d; }
13214 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13217 * An error thrown when an element was queried at a certain index of an
13218 * Observable, but no such index or position exists in that sequence.
13220 * @see {@link elementAt}
13221 * @see {@link take}
13222 * @see {@link takeLast}
13224 * @class ArgumentOutOfRangeError
13226 var ArgumentOutOfRangeError = (function (_super) {
13227 __extends(ArgumentOutOfRangeError, _super);
13228 function ArgumentOutOfRangeError() {
13229 var err = _super.call(this, 'argument out of range');
13230 this.name = err.name = 'ArgumentOutOfRangeError';
13231 this.stack = err.stack;
13232 this.message = err.message;
13234 return ArgumentOutOfRangeError;
13236 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError;
13238 },{}],159:[function(require,module,exports){
13240 var __extends = (this && this.__extends) || function (d, b) {
13241 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13242 function __() { this.constructor = d; }
13243 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13246 * An error thrown when an Observable or a sequence was queried but has no
13249 * @see {@link first}
13250 * @see {@link last}
13251 * @see {@link single}
13253 * @class EmptyError
13255 var EmptyError = (function (_super) {
13256 __extends(EmptyError, _super);
13257 function EmptyError() {
13258 var err = _super.call(this, 'no elements in sequence');
13259 this.name = err.name = 'EmptyError';
13260 this.stack = err.stack;
13261 this.message = err.message;
13265 exports.EmptyError = EmptyError;
13267 },{}],160:[function(require,module,exports){
13269 var __extends = (this && this.__extends) || function (d, b) {
13270 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13271 function __() { this.constructor = d; }
13272 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13275 * An error thrown when an action is invalid because the object has been
13278 * @see {@link Subject}
13279 * @see {@link BehaviorSubject}
13281 * @class ObjectUnsubscribedError
13283 var ObjectUnsubscribedError = (function (_super) {
13284 __extends(ObjectUnsubscribedError, _super);
13285 function ObjectUnsubscribedError() {
13286 var err = _super.call(this, 'object unsubscribed');
13287 this.name = err.name = 'ObjectUnsubscribedError';
13288 this.stack = err.stack;
13289 this.message = err.message;
13291 return ObjectUnsubscribedError;
13293 exports.ObjectUnsubscribedError = ObjectUnsubscribedError;
13295 },{}],161:[function(require,module,exports){
13297 var root_1 = require('./root');
13298 function minimalSetImpl() {
13299 // THIS IS NOT a full impl of Set, this is just the minimum
13300 // bits of functionality we need for this library.
13301 return (function () {
13302 function MinimalSet() {
13305 MinimalSet.prototype.add = function (value) {
13306 if (!this.has(value)) {
13307 this._values.push(value);
13310 MinimalSet.prototype.has = function (value) {
13311 return this._values.indexOf(value) !== -1;
13313 Object.defineProperty(MinimalSet.prototype, "size", {
13315 return this._values.length;
13320 MinimalSet.prototype.clear = function () {
13321 this._values.length = 0;
13326 exports.minimalSetImpl = minimalSetImpl;
13327 exports.Set = root_1.root.Set || minimalSetImpl();
13329 },{"./root":172}],162:[function(require,module,exports){
13331 var __extends = (this && this.__extends) || function (d, b) {
13332 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13333 function __() { this.constructor = d; }
13334 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13337 * An error thrown when one or more errors have occurred during the
13338 * `unsubscribe` of a {@link Subscription}.
13340 var UnsubscriptionError = (function (_super) {
13341 __extends(UnsubscriptionError, _super);
13342 function UnsubscriptionError(errors) {
13344 this.errors = errors;
13345 var err = Error.call(this, errors ?
13346 errors.length + " errors occurred during unsubscription:\n " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n ') : '');
13347 this.name = err.name = 'UnsubscriptionError';
13348 this.stack = err.stack;
13349 this.message = err.message;
13351 return UnsubscriptionError;
13353 exports.UnsubscriptionError = UnsubscriptionError;
13355 },{}],163:[function(require,module,exports){
13357 // typeof any so that it we don't have to cast when comparing a result to the error object
13358 exports.errorObject = { e: {} };
13360 },{}],164:[function(require,module,exports){
13362 exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
13364 },{}],165:[function(require,module,exports){
13366 exports.isArrayLike = (function (x) { return x && typeof x.length === 'number'; });
13368 },{}],166:[function(require,module,exports){
13370 function isDate(value) {
13371 return value instanceof Date && !isNaN(+value);
13373 exports.isDate = isDate;
13375 },{}],167:[function(require,module,exports){
13377 function isFunction(x) {
13378 return typeof x === 'function';
13380 exports.isFunction = isFunction;
13382 },{}],168:[function(require,module,exports){
13384 var isArray_1 = require('../util/isArray');
13385 function isNumeric(val) {
13386 // parseFloat NaNs numeric-cast false positives (null|true|false|"")
13387 // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
13388 // subtraction forces infinities to NaN
13389 // adding 1 corrects loss of precision from parseFloat (#15100)
13390 return !isArray_1.isArray(val) && (val - parseFloat(val) + 1) >= 0;
13392 exports.isNumeric = isNumeric;
13395 },{"../util/isArray":164}],169:[function(require,module,exports){
13397 function isObject(x) {
13398 return x != null && typeof x === 'object';
13400 exports.isObject = isObject;
13402 },{}],170:[function(require,module,exports){
13404 function isPromise(value) {
13405 return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
13407 exports.isPromise = isPromise;
13409 },{}],171:[function(require,module,exports){
13411 function isScheduler(value) {
13412 return value && typeof value.schedule === 'function';
13414 exports.isScheduler = isScheduler;
13416 },{}],172:[function(require,module,exports){
13417 (function (global){
13419 // CommonJS / Node have global context exposed as "global" variable.
13420 // We don't want to include the whole node.d.ts this this compilation unit so we'll just fake
13421 // the global "global" var for now.
13422 var __window = typeof window !== 'undefined' && window;
13423 var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
13424 self instanceof WorkerGlobalScope && self;
13425 var __global = typeof global !== 'undefined' && global;
13426 var _root = __window || __global || __self;
13427 exports.root = _root;
13428 // Workaround Closure Compiler restriction: The body of a goog.module cannot use throw.
13429 // This is needed when used with angular/tsickle which inserts a goog.module statement.
13433 throw new Error('RxJS could not find any global context (window, self, global)');
13437 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
13439 },{}],173:[function(require,module,exports){
13441 var root_1 = require('./root');
13442 var isArrayLike_1 = require('./isArrayLike');
13443 var isPromise_1 = require('./isPromise');
13444 var isObject_1 = require('./isObject');
13445 var Observable_1 = require('../Observable');
13446 var iterator_1 = require('../symbol/iterator');
13447 var InnerSubscriber_1 = require('../InnerSubscriber');
13448 var observable_1 = require('../symbol/observable');
13449 function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) {
13450 var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex);
13451 if (destination.closed) {
13454 if (result instanceof Observable_1.Observable) {
13455 if (result._isScalar) {
13456 destination.next(result.value);
13457 destination.complete();
13461 return result.subscribe(destination);
13464 else if (isArrayLike_1.isArrayLike(result)) {
13465 for (var i = 0, len = result.length; i < len && !destination.closed; i++) {
13466 destination.next(result[i]);
13468 if (!destination.closed) {
13469 destination.complete();
13472 else if (isPromise_1.isPromise(result)) {
13473 result.then(function (value) {
13474 if (!destination.closed) {
13475 destination.next(value);
13476 destination.complete();
13478 }, function (err) { return destination.error(err); })
13479 .then(null, function (err) {
13480 // Escaping the Promise trap: globally throw unhandled errors
13481 root_1.root.setTimeout(function () { throw err; });
13483 return destination;
13485 else if (result && typeof result[iterator_1.iterator] === 'function') {
13486 var iterator = result[iterator_1.iterator]();
13488 var item = iterator.next();
13490 destination.complete();
13493 destination.next(item.value);
13494 if (destination.closed) {
13499 else if (result && typeof result[observable_1.observable] === 'function') {
13500 var obs = result[observable_1.observable]();
13501 if (typeof obs.subscribe !== 'function') {
13502 destination.error(new TypeError('Provided object does not correctly implement Symbol.observable'));
13505 return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex));
13509 var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'";
13510 var msg = ("You provided " + value + " where a stream was expected.")
13511 + ' You can provide an Observable, Promise, Array, or Iterable.';
13512 destination.error(new TypeError(msg));
13516 exports.subscribeToResult = subscribeToResult;
13518 },{"../InnerSubscriber":27,"../Observable":29,"../symbol/iterator":154,"../symbol/observable":155,"./isArrayLike":165,"./isObject":169,"./isPromise":170,"./root":172}],174:[function(require,module,exports){
13520 var Subscriber_1 = require('../Subscriber');
13521 var rxSubscriber_1 = require('../symbol/rxSubscriber');
13522 var Observer_1 = require('../Observer');
13523 function toSubscriber(nextOrObserver, error, complete) {
13524 if (nextOrObserver) {
13525 if (nextOrObserver instanceof Subscriber_1.Subscriber) {
13526 return nextOrObserver;
13528 if (nextOrObserver[rxSubscriber_1.rxSubscriber]) {
13529 return nextOrObserver[rxSubscriber_1.rxSubscriber]();
13532 if (!nextOrObserver && !error && !complete) {
13533 return new Subscriber_1.Subscriber(Observer_1.empty);
13535 return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
13537 exports.toSubscriber = toSubscriber;
13539 },{"../Observer":30,"../Subscriber":36,"../symbol/rxSubscriber":156}],175:[function(require,module,exports){
13541 var errorObject_1 = require('./errorObject');
13542 var tryCatchTarget;
13543 function tryCatcher() {
13545 return tryCatchTarget.apply(this, arguments);
13548 errorObject_1.errorObject.e = e;
13549 return errorObject_1.errorObject;
13552 function tryCatch(fn) {
13553 tryCatchTarget = fn;
13556 exports.tryCatch = tryCatch;
13559 },{"./errorObject":163}],176:[function(require,module,exports){
13560 // threejs.org/license
13561 (function(l,sa){"object"===typeof exports&&"undefined"!==typeof module?sa(exports):"function"===typeof define&&define.amd?define(["exports"],sa):sa(l.THREE=l.THREE||{})})(this,function(l){function sa(){}function D(a,b){this.x=a||0;this.y=b||0}function X(a,b,c,d,e,f,g,h,k,m){Object.defineProperty(this,"id",{value:jf++});this.uuid=Y.generateUUID();this.name="";this.image=void 0!==a?a:X.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=void 0!==b?b:X.DEFAULT_MAPPING;this.wrapS=void 0!==c?c:1001;this.wrapT=
13562 void 0!==d?d:1001;this.magFilter=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 D(0,0);this.repeat=new D(1,1);this.generateMipmaps=!0;this.premultiplyAlpha=!1;this.flipY=!0;this.unpackAlignment=4;this.encoding=void 0!==m?m:3E3;this.version=0;this.onUpdate=null}function ga(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=void 0!==d?d:1}function Db(a,b,c){this.uuid=Y.generateUUID();this.width=
13563 a;this.height=b;this.scissor=new ga(0,0,a,b);this.scissorTest=!1;this.viewport=new ga(0,0,a,b);c=c||{};void 0===c.minFilter&&(c.minFilter=1006);this.texture=new X(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 Eb(a,b,c){Db.call(this,a,b,c);this.activeMipMapLevel=
13564 this.activeCubeFace=0}function qa(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._w=void 0!==d?d:1}function p(a,b,c){this.x=a||0;this.y=b||0;this.z=c||0}function J(){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 eb(a,b,c,d,e,f,g,h,k,m,u,q){X.call(this,null,f,g,h,k,m,d,e,u,q);this.image={data:a,width:b,height:c};this.magFilter=void 0!==k?k:1003;this.minFilter=void 0!==
13565 m?m:1003;this.flipY=this.generateMipmaps=!1;this.unpackAlignment=1}function Za(a,b,c,d,e,f,g,h,k,m){a=void 0!==a?a:[];X.call(this,a,void 0!==b?b:301,c,d,e,f,g,h,k,m);this.flipY=!1}function Fb(a,b,c){var d=a[0];if(0>=d||0<d)return a;var e=b*c,f=ye[e];void 0===f&&(f=new Float32Array(e),ye[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 ze(a,b){var c=Ae[b];void 0===c&&(c=new Int32Array(b),Ae[b]=c);for(var d=0;d!==b;++d)c[d]=a.allocTextureUnit();return c}function kf(a,
13566 b){a.uniform1f(this.addr,b)}function lf(a,b){a.uniform1i(this.addr,b)}function mf(a,b){void 0===b.x?a.uniform2fv(this.addr,b):a.uniform2f(this.addr,b.x,b.y)}function nf(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,b)}function of(a,b){void 0===b.x?a.uniform4fv(this.addr,b):a.uniform4f(this.addr,b.x,b.y,b.z,b.w)}function pf(a,b){a.uniformMatrix2fv(this.addr,!1,b.elements||b)}function qf(a,b){void 0===b.elements?a.uniformMatrix3fv(this.addr,
13567 !1,b):(Be.set(b.elements),a.uniformMatrix3fv(this.addr,!1,Be))}function rf(a,b){void 0===b.elements?a.uniformMatrix4fv(this.addr,!1,b):(Ce.set(b.elements),a.uniformMatrix4fv(this.addr,!1,Ce))}function sf(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTexture2D(b||De,d)}function tf(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTextureCube(b||Ee,d)}function Fe(a,b){a.uniform2iv(this.addr,b)}function Ge(a,b){a.uniform3iv(this.addr,b)}function He(a,b){a.uniform4iv(this.addr,
13568 b)}function uf(a){switch(a){case 5126:return kf;case 35664:return mf;case 35665:return nf;case 35666:return of;case 35674:return pf;case 35675:return qf;case 35676:return rf;case 35678:return sf;case 35680:return tf;case 5124:case 35670:return lf;case 35667:case 35671:return Fe;case 35668:case 35672:return Ge;case 35669:case 35673:return He}}function vf(a,b){a.uniform1fv(this.addr,b)}function wf(a,b){a.uniform1iv(this.addr,b)}function xf(a,b){a.uniform2fv(this.addr,Fb(b,this.size,2))}function yf(a,
13569 b){a.uniform3fv(this.addr,Fb(b,this.size,3))}function zf(a,b){a.uniform4fv(this.addr,Fb(b,this.size,4))}function Af(a,b){a.uniformMatrix2fv(this.addr,!1,Fb(b,this.size,4))}function Bf(a,b){a.uniformMatrix3fv(this.addr,!1,Fb(b,this.size,9))}function Cf(a,b){a.uniformMatrix4fv(this.addr,!1,Fb(b,this.size,16))}function Df(a,b,c){var d=b.length,e=ze(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTexture2D(b[a]||De,e[a])}function Ef(a,b,c){var d=b.length,e=ze(c,d);a.uniform1iv(this.addr,e);for(a=
13570 0;a!==d;++a)c.setTextureCube(b[a]||Ee,e[a])}function Ff(a){switch(a){case 5126:return vf;case 35664:return xf;case 35665:return yf;case 35666:return zf;case 35674:return Af;case 35675:return Bf;case 35676:return Cf;case 35678:return Df;case 35680:return Ef;case 5124:case 35670:return wf;case 35667:case 35671:return Fe;case 35668:case 35672:return Ge;case 35669:case 35673:return He}}function Gf(a,b,c){this.id=a;this.addr=c;this.setValue=uf(b.type)}function Hf(a,b,c){this.id=a;this.addr=c;this.size=
13571 b.size;this.setValue=Ff(b.type)}function Ie(a){this.id=a;this.seq=[];this.map={}}function fb(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=h.length;for(Qd.lastIndex=0;;){var m=Qd.exec(h),u=Qd.lastIndex,q=m[1],n=m[3];"]"===m[2]&&(q|=0);if(void 0===n||"["===n&&u+2===k){h=g;e=void 0===n?new Gf(q,e,f):new Hf(q,e,f);h.seq.push(e);h.map[e.id]=e;break}else n=
13572 g.map[q],void 0===n&&(n=new Ie(q),q=g,g=n,q.seq.push(g),q.map[g.id]=g),g=n}}}function H(a,b,c){return void 0===b&&void 0===c?this.set(a):this.setRGB(a,b,c)}function id(a,b){this.min=void 0!==a?a:new D(Infinity,Infinity);this.max=void 0!==b?b:new D(-Infinity,-Infinity)}function If(a,b){var c,d,e,f,g,h,k,m,u,q,n=a.context,r=a.state,l,t,y,x,v,G;this.render=function(w,O,S){if(0!==b.length){w=new p;var E=S.w/S.z,F=.5*S.z,aa=.5*S.w,R=16/S.w,ca=new D(R*E,R),la=new p(1,1,0),gb=new D(1,1),Gb=new id;Gb.min.set(S.x,
13573 S.y);Gb.max.set(S.x+(S.z-16),S.y+(S.w-16));if(void 0===x){var R=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),ja=new Uint16Array([0,1,2,0,2,3]);l=n.createBuffer();t=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,l);n.bufferData(n.ARRAY_BUFFER,R,n.STATIC_DRAW);n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t);n.bufferData(n.ELEMENT_ARRAY_BUFFER,ja,n.STATIC_DRAW);v=n.createTexture();G=n.createTexture();r.bindTexture(n.TEXTURE_2D,v);n.texImage2D(n.TEXTURE_2D,0,n.RGB,16,16,0,n.RGB,n.UNSIGNED_BYTE,null);
13574 n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST);r.bindTexture(n.TEXTURE_2D,G);n.texImage2D(n.TEXTURE_2D,0,n.RGBA,16,16,0,n.RGBA,n.UNSIGNED_BYTE,null);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE);n.texParameteri(n.TEXTURE_2D,
13575 n.TEXTURE_MAG_FILTER,n.NEAREST);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST);var R=y={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() {\nvUV = uv;\nvec2 pos = position;\nif ( renderType == 2 ) {\nvec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );\nvVisibility = visibility.r / 9.0;\nvVisibility *= 1.0 - visibility.g / 9.0;\nvVisibility *= visibility.b / 9.0;\nvVisibility *= 1.0 - visibility.a / 9.0;\npos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;\npos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;\n}\ngl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );\n}",
13576 fragmentShader:"uniform lowp int renderType;\nuniform sampler2D map;\nuniform float opacity;\nuniform vec3 color;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\nif ( renderType == 0 ) {\ngl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );\n} else if ( renderType == 1 ) {\ngl_FragColor = texture2D( map, vUV );\n} else {\nvec4 texture = texture2D( map, vUV );\ntexture.a *= opacity * vVisibility;\ngl_FragColor = texture;\ngl_FragColor.rgb *= color;\n}\n}"},ja=n.createProgram(),P=n.createShader(n.FRAGMENT_SHADER),
13577 K=n.createShader(n.VERTEX_SHADER),W="precision "+a.getPrecision()+" float;\n";n.shaderSource(P,W+R.fragmentShader);n.shaderSource(K,W+R.vertexShader);n.compileShader(P);n.compileShader(K);n.attachShader(ja,P);n.attachShader(ja,K);n.linkProgram(ja);x=ja;u=n.getAttribLocation(x,"position");q=n.getAttribLocation(x,"uv");c=n.getUniformLocation(x,"renderType");d=n.getUniformLocation(x,"map");e=n.getUniformLocation(x,"occlusionMap");f=n.getUniformLocation(x,"opacity");g=n.getUniformLocation(x,"color");
13578 h=n.getUniformLocation(x,"scale");k=n.getUniformLocation(x,"rotation");m=n.getUniformLocation(x,"screenPosition")}n.useProgram(x);r.initAttributes();r.enableAttribute(u);r.enableAttribute(q);r.disableUnusedAttributes();n.uniform1i(e,0);n.uniform1i(d,1);n.bindBuffer(n.ARRAY_BUFFER,l);n.vertexAttribPointer(u,2,n.FLOAT,!1,16,0);n.vertexAttribPointer(q,2,n.FLOAT,!1,16,8);n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t);r.disable(n.CULL_FACE);r.buffers.depth.setMask(!1);ja=0;for(P=b.length;ja<P;ja++)if(R=16/S.w,
13579 ca.set(R*E,R),K=b[ja],w.set(K.matrixWorld.elements[12],K.matrixWorld.elements[13],K.matrixWorld.elements[14]),w.applyMatrix4(O.matrixWorldInverse),w.applyMatrix4(O.projectionMatrix),la.copy(w),gb.x=S.x+la.x*F+F-8,gb.y=S.y+la.y*aa+aa-8,!0===Gb.containsPoint(gb)){r.activeTexture(n.TEXTURE0);r.bindTexture(n.TEXTURE_2D,null);r.activeTexture(n.TEXTURE1);r.bindTexture(n.TEXTURE_2D,v);n.copyTexImage2D(n.TEXTURE_2D,0,n.RGB,gb.x,gb.y,16,16,0);n.uniform1i(c,0);n.uniform2f(h,ca.x,ca.y);n.uniform3f(m,la.x,la.y,
13580 la.z);r.disable(n.BLEND);r.enable(n.DEPTH_TEST);n.drawElements(n.TRIANGLES,6,n.UNSIGNED_SHORT,0);r.activeTexture(n.TEXTURE0);r.bindTexture(n.TEXTURE_2D,G);n.copyTexImage2D(n.TEXTURE_2D,0,n.RGBA,gb.x,gb.y,16,16,0);n.uniform1i(c,1);r.disable(n.DEPTH_TEST);r.activeTexture(n.TEXTURE1);r.bindTexture(n.TEXTURE_2D,v);n.drawElements(n.TRIANGLES,6,n.UNSIGNED_SHORT,0);K.positionScreen.copy(la);K.customUpdateCallback?K.customUpdateCallback(K):K.updateLensFlares();n.uniform1i(c,2);r.enable(n.BLEND);for(var W=
13581 0,ba=K.lensFlares.length;W<ba;W++){var T=K.lensFlares[W];.001<T.opacity&&.001<T.scale&&(la.x=T.x,la.y=T.y,la.z=T.z,R=T.size*T.scale/S.w,ca.x=R*E,ca.y=R,n.uniform3f(m,la.x,la.y,la.z),n.uniform2f(h,ca.x,ca.y),n.uniform1f(k,T.rotation),n.uniform1f(f,T.opacity),n.uniform3f(g,T.color.r,T.color.g,T.color.b),r.setBlending(T.blending,T.blendEquation,T.blendSrc,T.blendDst),a.setTexture2D(T.texture,1),n.drawElements(n.TRIANGLES,6,n.UNSIGNED_SHORT,0))}}r.enable(n.CULL_FACE);r.enable(n.DEPTH_TEST);r.buffers.depth.setMask(!0);
13582 a.resetGLState()}}}function Jf(a,b){var c,d,e,f,g,h,k,m,u,q,n,r,l,t,y,x,v;function G(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:b.id-a.id}var w=a.context,O=a.state,S,E,F,aa,R=new p,ca=new qa,la=new p;this.render=function(p,Gb){if(0!==b.length){if(void 0===F){var ja=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),P=new Uint16Array([0,1,2,0,2,3]);S=w.createBuffer();E=w.createBuffer();w.bindBuffer(w.ARRAY_BUFFER,S);w.bufferData(w.ARRAY_BUFFER,
13583 ja,w.STATIC_DRAW);w.bindBuffer(w.ELEMENT_ARRAY_BUFFER,E);w.bufferData(w.ELEMENT_ARRAY_BUFFER,P,w.STATIC_DRAW);var ja=w.createProgram(),P=w.createShader(w.VERTEX_SHADER),K=w.createShader(w.FRAGMENT_SHADER);w.shaderSource(P,["precision "+a.getPrecision()+" float;","uniform 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;\nvoid main() {\nvUV = uvOffset + uv * uvScale;\nvec2 alignedPosition = position * scale;\nvec2 rotatedPosition;\nrotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\nrotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\nvec4 finalPosition;\nfinalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\nfinalPosition.xy += rotatedPosition;\nfinalPosition = projectionMatrix * finalPosition;\ngl_Position = finalPosition;\n}"].join("\n"));
13584 w.shaderSource(K,["precision "+a.getPrecision()+" float;","uniform 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;\nvoid main() {\nvec4 texture = texture2D( map, vUV );\nif ( texture.a < alphaTest ) discard;\ngl_FragColor = vec4( color * texture.xyz, texture.a * opacity );\nif ( fogType > 0 ) {\nfloat depth = gl_FragCoord.z / gl_FragCoord.w;\nfloat fogFactor = 0.0;\nif ( fogType == 1 ) {\nfogFactor = smoothstep( fogNear, fogFar, depth );\n} else {\nconst float LOG2 = 1.442695;\nfogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );\nfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n}\ngl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );\n}\n}"].join("\n"));
13585 w.compileShader(P);w.compileShader(K);w.attachShader(ja,P);w.attachShader(ja,K);w.linkProgram(ja);F=ja;x=w.getAttribLocation(F,"position");v=w.getAttribLocation(F,"uv");c=w.getUniformLocation(F,"uvOffset");d=w.getUniformLocation(F,"uvScale");e=w.getUniformLocation(F,"rotation");f=w.getUniformLocation(F,"scale");g=w.getUniformLocation(F,"color");h=w.getUniformLocation(F,"map");k=w.getUniformLocation(F,"opacity");m=w.getUniformLocation(F,"modelViewMatrix");u=w.getUniformLocation(F,"projectionMatrix");
13586 q=w.getUniformLocation(F,"fogType");n=w.getUniformLocation(F,"fogDensity");r=w.getUniformLocation(F,"fogNear");l=w.getUniformLocation(F,"fogFar");t=w.getUniformLocation(F,"fogColor");y=w.getUniformLocation(F,"alphaTest");ja=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");ja.width=8;ja.height=8;P=ja.getContext("2d");P.fillStyle="white";P.fillRect(0,0,8,8);aa=new X(ja);aa.needsUpdate=!0}w.useProgram(F);O.initAttributes();O.enableAttribute(x);O.enableAttribute(v);O.disableUnusedAttributes();
13587 O.disable(w.CULL_FACE);O.enable(w.BLEND);w.bindBuffer(w.ARRAY_BUFFER,S);w.vertexAttribPointer(x,2,w.FLOAT,!1,16,0);w.vertexAttribPointer(v,2,w.FLOAT,!1,16,8);w.bindBuffer(w.ELEMENT_ARRAY_BUFFER,E);w.uniformMatrix4fv(u,!1,Gb.projectionMatrix.elements);O.activeTexture(w.TEXTURE0);w.uniform1i(h,0);P=ja=0;(K=p.fog)?(w.uniform3f(t,K.color.r,K.color.g,K.color.b),K.isFog?(w.uniform1f(r,K.near),w.uniform1f(l,K.far),w.uniform1i(q,1),P=ja=1):K.isFogExp2&&(w.uniform1f(n,K.density),w.uniform1i(q,2),P=ja=2)):
13588 (w.uniform1i(q,0),P=ja=0);for(var K=0,W=b.length;K<W;K++){var ba=b[K];ba.modelViewMatrix.multiplyMatrices(Gb.matrixWorldInverse,ba.matrixWorld);ba.z=-ba.modelViewMatrix.elements[14]}b.sort(G);for(var T=[],K=0,W=b.length;K<W;K++){var ba=b[K],Q=ba.material;!1!==Q.visible&&(w.uniform1f(y,Q.alphaTest),w.uniformMatrix4fv(m,!1,ba.modelViewMatrix.elements),ba.matrixWorld.decompose(R,ca,la),T[0]=la.x,T[1]=la.y,ba=0,p.fog&&Q.fog&&(ba=P),ja!==ba&&(w.uniform1i(q,ba),ja=ba),null!==Q.map?(w.uniform2f(c,Q.map.offset.x,
13589 Q.map.offset.y),w.uniform2f(d,Q.map.repeat.x,Q.map.repeat.y)):(w.uniform2f(c,0,0),w.uniform2f(d,1,1)),w.uniform1f(k,Q.opacity),w.uniform3f(g,Q.color.r,Q.color.g,Q.color.b),w.uniform1f(e,Q.rotation),w.uniform2fv(f,T),O.setBlending(Q.blending,Q.blendEquation,Q.blendSrc,Q.blendDst),O.buffers.depth.setTest(Q.depthTest),O.buffers.depth.setMask(Q.depthWrite),Q.map?a.setTexture2D(Q.map,0):a.setTexture2D(aa,0),w.drawElements(w.TRIANGLES,6,w.UNSIGNED_SHORT,0))}O.enable(w.CULL_FACE);a.resetGLState()}}}function Z(){Object.defineProperty(this,
13590 "id",{value:Kf++});this.uuid=Y.generateUUID();this.name="";this.type="Material";this.lights=this.fog=!0;this.blending=1;this.side=0;this.shading=2;this.vertexColors=0;this.opacity=1;this.transparent=!1;this.blendSrc=204;this.blendDst=205;this.blendEquation=100;this.blendEquationAlpha=this.blendDstAlpha=this.blendSrcAlpha=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=
13591 !1;this.polygonOffsetUnits=this.polygonOffsetFactor=0;this.dithering=!1;this.alphaTest=0;this.premultipliedAlpha=!1;this.overdraw=0;this.needsUpdate=this.visible=!0}function Ea(a){Z.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=
13592 1;this.morphNormals=this.morphTargets=this.skinning=this.clipping=this.lights=this.fog=!1;this.extensions={derivatives:!1,fragDepth:!1,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 $a(a){Z.call(this);this.type="MeshDepthMaterial";this.depthPacking=
13593 3200;this.morphTargets=this.skinning=!1;this.displacementMap=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 Ta(a,b){this.min=void 0!==a?a:new p(Infinity,Infinity,Infinity);this.max=void 0!==b?b:new p(-Infinity,-Infinity,-Infinity)}function Ga(a,b){this.center=void 0!==a?a:new p;this.radius=void 0!==b?b:0}function Ka(){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.")}
13594 function wa(a,b){this.normal=void 0!==a?a:new p(1,0,0);this.constant=void 0!==b?b:0}function jd(a,b,c,d,e,f){this.planes=[void 0!==a?a:new wa,void 0!==b?b:new wa,void 0!==c?c:new wa,void 0!==d?d:new wa,void 0!==e?e:new wa,void 0!==f?f:new wa]}function Je(a,b,c,d){function e(b,c,d,e){var f=b.geometry,g;g=t;var h=b.customDepthMaterial;d&&(g=y,h=b.customDistanceMaterial);h?g=h:(h=!1,c.morphTargets&&(f&&f.isBufferGeometry?h=f.morphAttributes&&f.morphAttributes.position&&0<f.morphAttributes.position.length:
13595 f&&f.isGeometry&&(h=f.morphTargets&&0<f.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,f=0,h&&(f|=1),b&&(f|=2),g=g[f]);a.localClippingEnabled&&!0===c.clipShadows&&0!==c.clippingPlanes.length&&(f=g.uuid,h=c.uuid,b=x[f],void 0===b&&(b={},x[f]=b),f=b[h],void 0===f&&(f=g.clone(),b[h]=f),g=f);g.visible=c.visible;g.wireframe=c.wireframe;h=c.side;R.renderSingleSided&&2==h&&
13596 (h=0);R.renderReverseSided&&(0===h?h=1:1===h&&(h=0));g.side=h;g.clipShadows=c.clipShadows;g.clippingPlanes=c.clippingPlanes;g.wireframeLinewidth=c.wireframeLinewidth;g.linewidth=c.linewidth;d&&void 0!==g.uniforms.lightPos&&g.uniforms.lightPos.value.copy(e);return g}function f(b,d,g,h){if(!1!==b.visible){if(b.layers.test(d.layers)&&(b.isMesh||b.isLine||b.isPoints)&&b.castShadow&&(!b.frustumCulled||k.intersectsObject(b))){b.modelViewMatrix.multiplyMatrices(g.matrixWorldInverse,b.matrixWorld);var m=
13597 c.update(b),n=b.material;if(Array.isArray(n))for(var u=m.groups,q=0,r=u.length;q<r;q++){var x=u[q],v=n[x.materialIndex];v&&v.visible&&(v=e(b,v,h,l),a.renderBufferDirect(g,null,m,v,b,x))}else n.visible&&(v=e(b,n,h,l),a.renderBufferDirect(g,null,m,v,b,null))}b=b.children;m=0;for(n=b.length;m<n;m++)f(b[m],d,g,h)}}var g=a.context,h=a.state,k=new jd,m=new J,u=b.shadows,q=new D,n=new D(d.maxTextureSize,d.maxTextureSize),r=new p,l=new p,t=Array(4),y=Array(4),x={},v=[new p(1,0,0),new p(-1,0,0),new p(0,0,
13598 1),new p(0,0,-1),new p(0,1,0),new p(0,-1,0)],G=[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 ga,new ga,new ga,new ga,new ga,new ga];b=new $a;b.depthPacking=3201;b.clipping=!0;d=ab.distanceRGBA;for(var O=Ha.clone(d.uniforms),S=0;4!==S;++S){var E=0!==(S&1),F=0!==(S&2),aa=b.clone();aa.morphTargets=E;aa.skinning=F;t[S]=aa;E=new Ea({defines:{USE_SHADOWMAP:""},uniforms:O,vertexShader:d.vertexShader,fragmentShader:d.fragmentShader,morphTargets:E,skinning:F,clipping:!0});
13599 y[S]=E}var R=this;this.enabled=!1;this.autoUpdate=!0;this.needsUpdate=!1;this.type=1;this.renderSingleSided=this.renderReverseSided=!0;this.render=function(b,c){if(!1!==R.enabled&&(!1!==R.autoUpdate||!1!==R.needsUpdate)&&0!==u.length){h.disable(g.BLEND);h.buffers.color.setClear(1,1,1,1);h.buffers.depth.setTest(!0);h.setScissorTest(!1);for(var d,e,x=0,t=u.length;x<t;x++){var p=u[x],y=p.shadow;if(void 0===y)console.warn("THREE.WebGLShadowMap:",p,"has no shadow.");else{var O=y.camera,E=y.matrix;l.setFromMatrixPosition(p.matrixWorld);
13600 O.position.copy(l);q.copy(y.mapSize);q.min(n);if(p&&p.isPointLight){d=6;e=!0;var S=q.x,F=q.y;w[0].set(2*S,F,S,F);w[1].set(0,F,S,F);w[2].set(3*S,F,S,F);w[3].set(S,F,S,F);w[4].set(3*S,0,S,F);w[5].set(S,0,S,F);q.x*=4;q.y*=2;E.makeTranslation(-l.x,-l.y,-l.z)}else d=1,e=!1,r.setFromMatrixPosition(p.target.matrixWorld),O.lookAt(r),O.updateMatrixWorld(),O.matrixWorldInverse.getInverse(O.matrixWorld),E.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),E.multiply(O.projectionMatrix),E.multiply(O.matrixWorldInverse);
13601 null===y.map&&(y.map=new Db(q.x,q.y,{minFilter:1003,magFilter:1003,format:1023}),y.map.texture.name=p.name+".shadowMap",O.updateProjectionMatrix());y.isSpotLightShadow&&y.update(p);a.setRenderTarget(y.map);a.clear();for(p=0;p<d;p++)e&&(r.copy(O.position),r.add(v[p]),O.up.copy(G[p]),O.lookAt(r),O.updateMatrixWorld(),O.matrixWorldInverse.getInverse(O.matrixWorld),h.viewport(w[p])),m.multiplyMatrices(O.projectionMatrix,O.matrixWorldInverse),k.setFromMatrix(m),f(b,c,O,e)}}d=a.getClearColor();e=a.getClearAlpha();
13602 a.setClearColor(d,e);R.needsUpdate=!1}}}function hb(a,b){this.origin=void 0!==a?a:new p;this.direction=void 0!==b?b:new p}function bb(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._order=d||bb.DefaultOrder}function Rd(){this.mask=1}function B(){Object.defineProperty(this,"id",{value:Lf++});this.uuid=Y.generateUUID();this.name="";this.type="Object3D";this.parent=null;this.children=[];this.up=B.DefaultUp.clone();var a=new p,b=new bb,c=new qa,d=new p(1,1,1);b.onChange(function(){c.setFromEuler(b,
13603 !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 J},normalMatrix:{value:new Ka}});this.matrix=new J;this.matrixWorld=new J;this.matrixAutoUpdate=B.DefaultMatrixAutoUpdate;this.matrixWorldNeedsUpdate=!1;this.layers=new Rd;this.visible=!0;this.receiveShadow=this.castShadow=!1;this.frustumCulled=!0;this.renderOrder=
13604 0;this.userData={};this.onBeforeRender=function(){};this.onAfterRender=function(){}}function Hb(a,b){this.start=void 0!==a?a:new p;this.end=void 0!==b?b:new p}function Ua(a,b,c){this.a=void 0!==a?a:new p;this.b=void 0!==b?b:new p;this.c=void 0!==c?c:new p}function Va(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?e:new H;this.vertexColors=Array.isArray(e)?e:[];this.materialIndex=void 0!==f?f:0}function Na(a){Z.call(this);
13605 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=!1;this.setValues(a)}function L(a,b,c){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
13606 this.uuid=Y.generateUUID();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 rc(a,b){L.call(this,new Int8Array(a),b)}function sc(a,b){L.call(this,new Uint8Array(a),b)}function tc(a,b){L.call(this,new Uint8ClampedArray(a),b)}function uc(a,b){L.call(this,new Int16Array(a),b)}function ib(a,b){L.call(this,new Uint16Array(a),b)}function vc(a,b){L.call(this,
13607 new Int32Array(a),b)}function jb(a,b){L.call(this,new Uint32Array(a),b)}function C(a,b){L.call(this,new Float32Array(a),b)}function wc(a,b){L.call(this,new Float64Array(a),b)}function Ke(){this.indices=[];this.vertices=[];this.normals=[];this.colors=[];this.uvs=[];this.uvs2=[];this.groups=[];this.morphTargets={};this.skinWeights=[];this.skinIndices=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.uvsNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.verticesNeedUpdate=
13608 !1}function Sd(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 M(){Object.defineProperty(this,"id",{value:Td++});this.uuid=Y.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=
13609 this.colorsNeedUpdate=this.normalsNeedUpdate=this.uvsNeedUpdate=this.verticesNeedUpdate=this.elementsNeedUpdate=!1}function I(){Object.defineProperty(this,"id",{value:Td++});this.uuid=Y.generateUUID();this.name="";this.type="BufferGeometry";this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.drawRange={start:0,count:Infinity}}function Ca(a,b){B.call(this);this.type="Mesh";this.geometry=void 0!==a?a:new I;this.material=void 0!==b?
13610 b:new Na({color:16777215*Math.random()});this.drawMode=0;this.updateMorphTargets()}function Ib(a,b,c,d,e,f){M.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};this.fromBufferGeometry(new kb(a,b,c,d,e,f));this.mergeVertices()}function kb(a,b,c,d,e,f){function g(a,b,c,d,e,f,g,l,S,E,F){var aa=f/S,R=g/E,ca=f/2,la=g/2,D=l/2;g=S+1;var C=E+1,B=f=0,P,K,W=new p;for(K=0;K<C;K++){var ba=K*R-la;for(P=0;P<g;P++)W[a]=(P*aa-ca)*d,W[b]=
13611 ba*e,W[c]=D,m.push(W.x,W.y,W.z),W[a]=0,W[b]=0,W[c]=0<l?1:-1,u.push(W.x,W.y,W.z),q.push(P/S),q.push(1-K/E),f+=1}for(K=0;K<E;K++)for(P=0;P<S;P++)a=n+P+g*(K+1),b=n+(P+1)+g*(K+1),c=n+(P+1)+g*K,k.push(n+P+g*K,a,c),k.push(a,b,c),B+=6;h.addGroup(r,B,F);r+=B;n+=f}I.call(this);this.type="BoxBufferGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};var h=this;d=Math.floor(d)||1;e=Math.floor(e)||1;f=Math.floor(f)||1;var k=[],m=[],u=[],q=[],n=0,r=0;g("z","y",
13612 "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 C(m,3));this.addAttribute("normal",new C(u,3));this.addAttribute("uv",new C(q,2))}function xc(a,b,c,d){M.call(this);this.type="PlaneGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};this.fromBufferGeometry(new lb(a,b,c,d));this.mergeVertices()}
13613 function lb(a,b,c,d){I.call(this);this.type="PlaneBufferGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};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,m=b/d,u=[],q=[],n=[],r=[];for(a=0;a<h;a++){var l=a*m-f;for(b=0;b<g;b++)q.push(b*k-e,-l,0),n.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,u.push(b+g*a,e,h),u.push(e,f,h);this.setIndex(u);this.addAttribute("position",new C(q,3));this.addAttribute("normal",
13614 new C(n,3));this.addAttribute("uv",new C(r,2))}function Oa(){B.call(this);this.type="Camera";this.matrixWorldInverse=new J;this.projectionMatrix=new J}function xa(a,b,c,d){Oa.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 Jb(a,b,c,d,e,f){Oa.call(this);this.type="OrthographicCamera";this.zoom=
13615 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 Mf(a){var b={};return{get:function(a){a.isInterleavedBufferAttribute&&(a=a.data);return b[a.uuid]},remove:function(c){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,g=f.array,h=f.dynamic?a.DYNAMIC_DRAW:a.STATIC_DRAW,
13616 k=a.createBuffer();a.bindBuffer(d,k);a.bufferData(d,g,h);f.onUploadCallback();h=a.FLOAT;g instanceof Float32Array?h=a.FLOAT:g instanceof Float64Array?console.warn("Unsupported data buffer format: Float64Array"):g instanceof Uint16Array?h=a.UNSIGNED_SHORT:g instanceof Int16Array?h=a.SHORT:g instanceof Uint32Array?h=a.UNSIGNED_INT:g instanceof Int32Array?h=a.INT:g instanceof Int8Array?h=a.BYTE:g instanceof Uint8Array&&(h=a.UNSIGNED_BYTE);b[e]={buffer:k,type:h,bytesPerElement:g.BYTES_PER_ELEMENT,version:f.version}}else e.version<
13617 c.version&&(f=c,g=f.array,k=f.updateRange,a.bindBuffer(d,e.buffer),!1===f.dynamic?a.bufferData(d,g,a.STATIC_DRAW):-1===k.count?a.bufferSubData(d,0,g):0===k.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."):(a.bufferSubData(d,k.offset*g.BYTES_PER_ELEMENT,g.subarray(k.offset,k.offset+k.count)),k.count=0),e.version=c.version)}}}function Nf(a,b){return a.renderOrder!==
13618 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-b.material.id:a.z!==b.z?a.z-b.z:a.id-b.id}function Of(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:a.id-b.id}function Pf(){var a=[],b=-1,c=[],d=-1;return{opaque:a,transparent:c,init:function(){d=b=-1},push:function(e,f,g,h,k){var m,u;g.transparent?(m=c,u=++d):(m=a,u=++b);(u=m[u])?(u.id=e.id,u.object=e,
13619 u.geometry=f,u.material=g,u.program=g.program,u.renderOrder=e.renderOrder,u.z=h,u.group=k):(u={id:e.id,object:e,geometry:f,material:g,program:g.program,renderOrder:e.renderOrder,z:h,group:k},m.push(u))},finish:function(){a.length=b+1;c.length=d+1},sort:function(){a.sort(Nf);c.sort(Of)}}}function Qf(){var a={};return{get:function(b,c){var d=b.id+","+c.id,e=a[d];void 0===e&&(e=new Pf,a[d]=e);return e},dispose:function(){a={}}}}function Rf(a,b,c){var d,e,f;this.setMode=function(a){d=a};this.setIndex=
13620 function(c){c.array instanceof Uint32Array&&b.get("OES_element_index_uint")?(e=a.UNSIGNED_INT,f=4):c.array instanceof Uint16Array?(e=a.UNSIGNED_SHORT,f=2):(e=a.UNSIGNED_BYTE,f=1)};this.render=function(b,h){a.drawElements(d,h,e,b*f);c.calls++;c.vertices+=h;d===a.TRIANGLES&&(c.faces+=h/3)};this.renderInstances=function(g,h,k){var m=b.get("ANGLE_instanced_arrays");null===m?console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):
13621 (m.drawElementsInstancedANGLE(d,k,e,h*f,g.maxInstancedCount),c.calls++,c.vertices+=k*g.maxInstancedCount,d===a.TRIANGLES&&(c.faces+=g.maxInstancedCount*k/3))}}function Sf(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)};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.");
13622 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)}}}function Tf(a,b,c){function d(a){a=a.target;var h=e[a.id];null!==h.index&&b.remove(h.index);for(var k in h.attributes)b.remove(h.attributes[k]);a.removeEventListener("dispose",d);delete e[a.id];if(k=f[a.id])b.remove(k),
13623 delete f[a.id];if(k=f[h.id])b.remove(k),delete f[h.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 I).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],a.ARRAY_BUFFER);c=c.morphAttributes;for(f in c)for(var d=
13624 c[f],e=0,u=d.length;e<u;e++)b.update(d[e],a.ARRAY_BUFFER)},getWireframeAttribute:function(c){var d=f[c.id];if(d)return d;var d=[],e=c.index,m=c.attributes;if(null!==e)for(var e=e.array,m=0,u=e.length;m<u;m+=3){var q=e[m+0],n=e[m+1],r=e[m+2];d.push(q,n,n,r,r,q)}else for(e=m.position.array,m=0,u=e.length/3-1;m<u;m+=3)q=m+0,n=m+1,r=m+2,d.push(q,n,n,r,r,q);d=new (65535<Sd(d)?jb:ib)(d,1);b.update(d,a.ELEMENT_ARRAY_BUFFER);return f[c.id]=d}}}function Uf(){var a={};return{get:function(b){if(void 0!==a[b.id])return a[b.id];
13625 var c;switch(b.type){case "DirectionalLight":c={direction:new p,color:new H,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new D};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 D};break;case "PointLight":c={position:new p,color:new H,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new D};break;case "HemisphereLight":c={direction:new p,skyColor:new H,
13626 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 Vf(a,b,c){var d={};return{update:function(a){var f=c.frame,g=a.geometry,h=b.get(a,g);d[h.id]!==f&&(g.isGeometry&&h.updateFromObject(a),b.update(h),d[h.id]=f);return h},clear:function(){d={}}}}function Wf(a){a=a.split("\n");for(var b=0;b<a.length;b++)a[b]=b+1+": "+a[b];return a.join("\n")}function Le(a,b,c){var d=a.createShader(b);a.shaderSource(d,c);a.compileShader(d);
13627 !1===a.getShaderParameter(d,a.COMPILE_STATUS)&&console.error("THREE.WebGLShader: Shader couldn't compile.");""!==a.getShaderInfoLog(d)&&console.warn("THREE.WebGLShader: gl.getShaderInfoLog()",b===a.VERTEX_SHADER?"vertex":"fragment",a.getShaderInfoLog(d),Wf(c));return d}function Me(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",
13628 "( value, 256.0 )"];case 3007:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw Error("unsupported encoding: "+a);}}function Ud(a,b){var c=Me(b);return"vec4 "+a+"( vec4 value ) { return "+c[0]+"ToLinear"+c[1]+"; }"}function Xf(a,b){var c=Me(b);return"vec4 "+a+"( vec4 value ) { return LinearTo"+c[0]+c[1]+"; }"}function Yf(a,b){var c;switch(b){case 1:c="Linear";break;case 2:c="Reinhard";break;case 3:c="Uncharted2";break;case 4:c="OptimizedCineon";break;default:throw Error("unsupported toneMapping: "+
13629 b);}return"vec3 "+a+"( vec3 color ) { return "+c+"ToneMapping( color ); }"}function Zf(a,b,c){a=a||{};return[a.derivatives||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":
13630 ""].filter(yc).join("\n")}function $f(a){var b=[],c;for(c in a){var d=a[c];!1!==d&&b.push("#define "+c+" "+d)}return b.join("\n")}function yc(a){return""!==a}function Ne(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 Vd(a){return a.replace(/^[ \t]*#include +<([\w\d.]+)>/gm,function(a,c){var d=U[c];
13631 if(void 0===d)throw Error("Can not resolve #include <"+c+">");return Vd(d)})}function Oe(a){return a.replace(/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,function(a,c,d,e){a="";for(c=parseInt(c);c<parseInt(d);c++)a+=e.replace(/\[ i \]/g,"[ "+c+" ]");return a})}function ag(a,b,c,d){var e=a.context,f=c.extensions,g=c.defines,h=c.__webglShader.vertexShader,k=c.__webglShader.fragmentShader,m="SHADOWMAP_TYPE_BASIC";1===d.shadowMapType?m="SHADOWMAP_TYPE_PCF":2===d.shadowMapType&&
13632 (m="SHADOWMAP_TYPE_PCF_SOFT");var u="ENVMAP_TYPE_CUBE",q="ENVMAP_MODE_REFLECTION",n="ENVMAP_BLENDING_MULTIPLY";if(d.envMap){switch(c.envMap.mapping){case 301:case 302:u="ENVMAP_TYPE_CUBE";break;case 306:case 307:u="ENVMAP_TYPE_CUBE_UV";break;case 303:case 304:u="ENVMAP_TYPE_EQUIREC";break;case 305:u="ENVMAP_TYPE_SPHERE"}switch(c.envMap.mapping){case 302:case 304:q="ENVMAP_MODE_REFRACTION"}switch(c.combine){case 0:n="ENVMAP_BLENDING_MULTIPLY";break;case 1:n="ENVMAP_BLENDING_MIX";break;case 2:n="ENVMAP_BLENDING_ADD"}}var r=
13633 0<a.gammaFactor?a.gammaFactor:1,f=Zf(f,d,a.extensions),l=$f(g),t=e.createProgram();c.isRawShaderMaterial?(g=[l,"\n"].filter(yc).join("\n"),m=[f,l,"\n"].filter(yc).join("\n")):(g=["precision "+d.precision+" float;","precision "+d.precision+" int;","#define SHADER_NAME "+c.__webglShader.name,l,d.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+r,"#define MAX_BONES "+d.maxBones,d.useFog&&d.fog?"#define USE_FOG":"",d.useFog&&d.fogExp?"#define FOG_EXP2":"",d.map?"#define USE_MAP":
13634 "",d.envMap?"#define USE_ENVMAP":"",d.envMap?"#define "+q:"",d.lightMap?"#define USE_LIGHTMAP":"",d.aoMap?"#define USE_AOMAP":"",d.emissiveMap?"#define USE_EMISSIVEMAP":"",d.bumpMap?"#define USE_BUMPMAP":"",d.normalMap?"#define USE_NORMALMAP":"",d.displacementMap&&d.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",d.specularMap?"#define USE_SPECULARMAP":"",d.roughnessMap?"#define USE_ROUGHNESSMAP":"",d.metalnessMap?"#define USE_METALNESSMAP":"",d.alphaMap?"#define USE_ALPHAMAP":"",d.vertexColors?
13635 "#define USE_COLOR":"",d.flatShading?"#define FLAT_SHADED":"",d.skinning?"#define USE_SKINNING":"",d.useVertexTexture?"#define BONE_TEXTURE":"",d.morphTargets?"#define USE_MORPHTARGETS":"",d.morphNormals&&!1===d.flatShading?"#define USE_MORPHNORMALS":"",d.doubleSided?"#define DOUBLE_SIDED":"",d.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+d.numClippingPlanes,d.shadowMapEnabled?"#define USE_SHADOWMAP":"",d.shadowMapEnabled?"#define "+m:"",d.sizeAttenuation?"#define USE_SIZEATTENUATION":
13636 "",d.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",d.logarithmicDepthBuffer&&a.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","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;",
13637 "\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\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;",
13638 "#endif","\n"].filter(yc).join("\n"),m=[f,"precision "+d.precision+" float;","precision "+d.precision+" int;","#define SHADER_NAME "+c.__webglShader.name,l,d.alphaTest?"#define ALPHATEST "+d.alphaTest:"","#define GAMMA_FACTOR "+r,d.useFog&&d.fog?"#define USE_FOG":"",d.useFog&&d.fogExp?"#define FOG_EXP2":"",d.map?"#define USE_MAP":"",d.envMap?"#define USE_ENVMAP":"",d.envMap?"#define "+u:"",d.envMap?"#define "+q:"",d.envMap?"#define "+n:"",d.lightMap?"#define USE_LIGHTMAP":"",d.aoMap?"#define USE_AOMAP":
13639 "",d.emissiveMap?"#define USE_EMISSIVEMAP":"",d.bumpMap?"#define USE_BUMPMAP":"",d.normalMap?"#define USE_NORMALMAP":"",d.specularMap?"#define USE_SPECULARMAP":"",d.roughnessMap?"#define USE_ROUGHNESSMAP":"",d.metalnessMap?"#define USE_METALNESSMAP":"",d.alphaMap?"#define USE_ALPHAMAP":"",d.vertexColors?"#define USE_COLOR":"",d.gradientMap?"#define USE_GRADIENTMAP":"",d.flatShading?"#define FLAT_SHADED":"",d.doubleSided?"#define DOUBLE_SIDED":"",d.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+
13640 d.numClippingPlanes,"#define UNION_CLIPPING_PLANES "+(d.numClippingPlanes-d.numClipIntersection),d.shadowMapEnabled?"#define USE_SHADOWMAP":"",d.shadowMapEnabled?"#define "+m:"",d.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",d.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",d.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",d.logarithmicDepthBuffer&&a.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",d.envMap&&a.extensions.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":
13641 "","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",0!==d.toneMapping?"#define TONE_MAPPING":"",0!==d.toneMapping?U.tonemapping_pars_fragment:"",0!==d.toneMapping?Yf("toneMapping",d.toneMapping):"",d.dithering?"#define DITHERING":"",d.outputEncoding||d.mapEncoding||d.envMapEncoding||d.emissiveMapEncoding?U.encodings_pars_fragment:"",d.mapEncoding?Ud("mapTexelToLinear",d.mapEncoding):"",d.envMapEncoding?Ud("envMapTexelToLinear",d.envMapEncoding):"",d.emissiveMapEncoding?Ud("emissiveMapTexelToLinear",
13642 d.emissiveMapEncoding):"",d.outputEncoding?Xf("linearToOutputTexel",d.outputEncoding):"",d.depthPacking?"#define DEPTH_PACKING "+c.depthPacking:"","\n"].filter(yc).join("\n"));h=Vd(h,d);h=Ne(h,d);k=Vd(k,d);k=Ne(k,d);c.isShaderMaterial||(h=Oe(h),k=Oe(k));k=m+k;h=Le(e,e.VERTEX_SHADER,g+h);k=Le(e,e.FRAGMENT_SHADER,k);e.attachShader(t,h);e.attachShader(t,k);void 0!==c.index0AttributeName?e.bindAttribLocation(t,0,c.index0AttributeName):!0===d.morphTargets&&e.bindAttribLocation(t,0,"position");e.linkProgram(t);
13643 d=e.getProgramInfoLog(t);u=e.getShaderInfoLog(h);q=e.getShaderInfoLog(k);r=n=!0;if(!1===e.getProgramParameter(t,e.LINK_STATUS))n=!1,console.error("THREE.WebGLProgram: shader error: ",e.getError(),"gl.VALIDATE_STATUS",e.getProgramParameter(t,e.VALIDATE_STATUS),"gl.getProgramInfoLog",d,u,q);else if(""!==d)console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",d);else if(""===u||""===q)r=!1;r&&(this.diagnostics={runnable:n,material:c,programLog:d,vertexShader:{log:u,prefix:g},fragmentShader:{log:q,
13644 prefix:m}});e.deleteShader(h);e.deleteShader(k);var p;this.getUniforms=function(){void 0===p&&(p=new fb(e,t,a));return p};var x;this.getAttributes=function(){if(void 0===x){for(var a={},b=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES),c=0;c<b;c++){var d=e.getActiveAttrib(t,c).name;a[d]=e.getAttribLocation(t,d)}x=a}return x};this.destroy=function(){e.deleteProgram(t);this.program=void 0};Object.defineProperties(this,{uniforms:{get:function(){console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms().");
13645 return this.getUniforms()}},attributes:{get:function(){console.warn("THREE.WebGLProgram: .attributes is now .getAttributes().");return this.getAttributes()}}});this.id=bg++;this.code=b;this.usedTimes=1;this.program=t;this.vertexShader=h;this.fragmentShader=k;return this}function cg(a,b){function c(a,b){var c;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=
13646 a.texture.encoding):c=3E3;3E3===c&&b&&(c=3007);return c}var d=[],e={MeshDepthMaterial:"depth",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"phong",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points"},f="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(" ");
13647 this.getParameters=function(d,f,k,m,u,q){var n=e[d.type],r;if(q.isSkinnedMesh)if(r=q.skeleton.bones,b.floatVertexTextures)r=1024;else{var l=Math.min(Math.floor((b.maxVertexUniforms-20)/4),r.length);l<r.length?(console.warn("THREE.WebGLRenderer: Skeleton has "+r.length+" bones. This GPU supports "+l+"."),r=0):r=l}else r=0;l=a.getPrecision();null!==d.precision&&(l=b.getMaxPrecision(d.precision),l!==d.precision&&console.warn("THREE.WebGLProgram.getParameters:",d.precision,"not supported, using",l,"instead."));
13648 var t=a.getRenderTarget();return{shaderID:n,precision:l,supportsVertexTextures:b.vertexTextures,outputEncoding:c(t?t.texture:null,a.gammaOutput),map:!!d.map,mapEncoding:c(d.map,a.gammaInput),envMap:!!d.envMap,envMapMode:d.envMap&&d.envMap.mapping,envMapEncoding:c(d.envMap,a.gammaInput),envMapCubeUV:!!d.envMap&&(306===d.envMap.mapping||307===d.envMap.mapping),lightMap:!!d.lightMap,aoMap:!!d.aoMap,emissiveMap:!!d.emissiveMap,emissiveMapEncoding:c(d.emissiveMap,a.gammaInput),bumpMap:!!d.bumpMap,normalMap:!!d.normalMap,
13649 displacementMap:!!d.displacementMap,roughnessMap:!!d.roughnessMap,metalnessMap:!!d.metalnessMap,specularMap:!!d.specularMap,alphaMap:!!d.alphaMap,gradientMap:!!d.gradientMap,combine:d.combine,vertexColors:d.vertexColors,fog:!!k,useFog:d.fog,fogExp:k&&k.isFogExp2,flatShading:1===d.shading,sizeAttenuation:d.sizeAttenuation,logarithmicDepthBuffer:b.logarithmicDepthBuffer,skinning:d.skinning&&0<r,maxBones:r,useVertexTexture:b.floatVertexTextures,morphTargets:d.morphTargets,morphNormals:d.morphNormals,
13650 maxMorphTargets:a.maxMorphTargets,maxMorphNormals:a.maxMorphNormals,numDirLights:f.directional.length,numPointLights:f.point.length,numSpotLights:f.spot.length,numRectAreaLights:f.rectArea.length,numHemiLights:f.hemi.length,numClippingPlanes:m,numClipIntersection:u,dithering:d.dithering,shadowMapEnabled:a.shadowMap.enabled&&q.receiveShadow&&0<f.shadows.length,shadowMapType:a.shadowMap.type,toneMapping:a.toneMapping,physicallyCorrectLights:a.physicallyCorrectLights,premultipliedAlpha:d.premultipliedAlpha,
13651 alphaTest:d.alphaTest,doubleSided:2===d.side,flipSided:1===d.side,depthPacking:void 0!==d.depthPacking?d.depthPacking:!1}};this.getProgramCode=function(a,b){var c=[];b.shaderID?c.push(b.shaderID):(c.push(a.fragmentShader),c.push(a.vertexShader));if(void 0!==a.defines)for(var d in a.defines)c.push(d),c.push(a.defines[d]);for(d=0;d<f.length;d++)c.push(b[f[d]]);return c.join()};this.acquireProgram=function(b,c,e){for(var f,u=0,q=d.length;u<q;u++){var n=d[u];if(n.code===e){f=n;++f.usedTimes;break}}void 0===
13652 f&&(f=new ag(a,e,b,c),d.push(f));return f};this.releaseProgram=function(a){if(0===--a.usedTimes){var b=d.indexOf(a);d[b]=d[d.length-1];d.pop();a.destroy()}};this.programs=d}function dg(a,b,c,d,e,f,g){function h(a,b){if(a.width>b||a.height>b){var c=b/Math.max(a.width,a.height),d=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");d.width=Math.floor(a.width*c);d.height=Math.floor(a.height*c);d.getContext("2d").drawImage(a,0,0,a.width,a.height,0,0,d.width,d.height);console.warn("THREE.WebGLRenderer: image is too big ("+
13653 a.width+"x"+a.height+"). Resized to "+d.width+"x"+d.height,a);return d}return a}function k(a){return Y.isPowerOfTwo(a.width)&&Y.isPowerOfTwo(a.height)}function m(b){return 1003===b||1004===b||1005===b?a.NEAREST:a.LINEAR}function u(b){b=b.target;b.removeEventListener("dispose",u);a:{var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube);else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d.remove(b)}g.textures--}function q(b){b=b.target;
13654 b.removeEventListener("dispose",q);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),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d.remove(b.texture);d.remove(b)}g.textures--}function n(b,
13655 m){var n=d.get(b);if(0<b.version&&n.__version!==b.version){var q=b.image;if(void 0===q)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",b);else if(!1===q.complete)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",b);else{void 0===n.__webglInit&&(n.__webglInit=!0,b.addEventListener("dispose",u),n.__webglTexture=a.createTexture(),g.textures++);c.activeTexture(a.TEXTURE0+m);c.bindTexture(a.TEXTURE_2D,n.__webglTexture);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,
13656 b.flipY);a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha);a.pixelStorei(a.UNPACK_ALIGNMENT,b.unpackAlignment);var l=h(b.image,e.maxTextureSize);if((1001!==b.wrapS||1001!==b.wrapT||1003!==b.minFilter&&1006!==b.minFilter)&&!1===k(l))if(q=l,q instanceof HTMLImageElement||q instanceof HTMLCanvasElement){var t=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");t.width=Y.nearestPowerOfTwo(q.width);t.height=Y.nearestPowerOfTwo(q.height);t.getContext("2d").drawImage(q,0,0,
13657 t.width,t.height);console.warn("THREE.WebGLRenderer: image is not power of two ("+q.width+"x"+q.height+"). Resized to "+t.width+"x"+t.height,q);l=t}else l=q;var q=k(l),t=f(b.format),z=f(b.type);r(a.TEXTURE_2D,b,q);var F=b.mipmaps;if(b.isDepthTexture){F=a.DEPTH_COMPONENT;if(1015===b.type){if(!p)throw Error("Float Depth Texture only supported in WebGL2.0");F=a.DEPTH_COMPONENT32F}else p&&(F=a.DEPTH_COMPONENT16);1026===b.format&&F===a.DEPTH_COMPONENT&&1012!==b.type&&1014!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),
13658 b.type=1012,z=f(b.type));1027===b.format&&(F=a.DEPTH_STENCIL,1020!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),b.type=1020,z=f(b.type)));c.texImage2D(a.TEXTURE_2D,0,F,l.width,l.height,0,t,z,null)}else if(b.isDataTexture)if(0<F.length&&q){for(var aa=0,R=F.length;aa<R;aa++)l=F[aa],c.texImage2D(a.TEXTURE_2D,aa,t,l.width,l.height,0,t,z,l.data);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,t,l.width,l.height,0,t,z,l.data);else if(b.isCompressedTexture)for(aa=
13659 0,R=F.length;aa<R;aa++)l=F[aa],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(t)?c.compressedTexImage2D(a.TEXTURE_2D,aa,t,l.width,l.height,0,l.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):c.texImage2D(a.TEXTURE_2D,aa,t,l.width,l.height,0,t,z,l.data);else if(0<F.length&&q){aa=0;for(R=F.length;aa<R;aa++)l=F[aa],c.texImage2D(a.TEXTURE_2D,aa,t,t,z,l);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,
13660 0,t,t,z,l);b.generateMipmaps&&q&&a.generateMipmap(a.TEXTURE_2D);n.__version=b.version;if(b.onUpdate)b.onUpdate(b);return}}c.activeTexture(a.TEXTURE0+m);c.bindTexture(a.TEXTURE_2D,n.__webglTexture)}function r(c,g,h){h?(a.texParameteri(c,a.TEXTURE_WRAP_S,f(g.wrapS)),a.texParameteri(c,a.TEXTURE_WRAP_T,f(g.wrapT)),a.texParameteri(c,a.TEXTURE_MAG_FILTER,f(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,f(g.minFilter))):(a.texParameteri(c,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(c,a.TEXTURE_WRAP_T,
13661 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,m(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,m(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"))||
13662 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,e.getMaxAnisotropy())),d.get(g).__currentAnisotropy=g.anisotropy)}function l(b,e,g,h){var k=f(e.texture.format),m=f(e.texture.type);c.texImage2D(h,0,k,e.width,e.height,0,k,m,null);a.bindFramebuffer(a.FRAMEBUFFER,b);a.framebufferTexture2D(a.FRAMEBUFFER,g,h,d.get(e.texture).__webglTexture,
13663 0);a.bindFramebuffer(a.FRAMEBUFFER,null)}function t(b,c){a.bindRenderbuffer(a.RENDERBUFFER,b);c.depthBuffer&&!c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_COMPONENT16,c.width,c.height),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,
13664 a.RGBA4,c.width,c.height);a.bindRenderbuffer(a.RENDERBUFFER,null)}var p="undefined"!==typeof WebGL2RenderingContext&&a instanceof WebGL2RenderingContext;this.setTexture2D=n;this.setTextureCube=function(b,m){var n=d.get(b);if(6===b.image.length)if(0<b.version&&n.__version!==b.version){n.__image__webglTextureCube||(b.addEventListener("dispose",u),n.__image__webglTextureCube=a.createTexture(),g.textures++);c.activeTexture(a.TEXTURE0+m);c.bindTexture(a.TEXTURE_CUBE_MAP,n.__image__webglTextureCube);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,
13665 b.flipY);for(var q=b&&b.isCompressedTexture,l=b.image[0]&&b.image[0].isDataTexture,t=[],z=0;6>z;z++)t[z]=q||l?l?b.image[z].image:b.image[z]:h(b.image[z],e.maxCubemapSize);var p=k(t[0]),y=f(b.format),R=f(b.type);r(a.TEXTURE_CUBE_MAP,b,p);for(z=0;6>z;z++)if(q)for(var ca,la=t[z].mipmaps,D=0,B=la.length;D<B;D++)ca=la[D],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(y)?c.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+z,D,y,ca.width,ca.height,0,ca.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):
13666 c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+z,D,y,ca.width,ca.height,0,y,R,ca.data);else l?c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+z,0,y,t[z].width,t[z].height,0,y,R,t[z].data):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+z,0,y,y,R,t[z]);b.generateMipmaps&&p&&a.generateMipmap(a.TEXTURE_CUBE_MAP);n.__version=b.version;if(b.onUpdate)b.onUpdate(b)}else c.activeTexture(a.TEXTURE0+m),c.bindTexture(a.TEXTURE_CUBE_MAP,n.__image__webglTextureCube)};this.setTextureCubeDynamic=function(b,e){c.activeTexture(a.TEXTURE0+
13667 e);c.bindTexture(a.TEXTURE_CUBE_MAP,d.get(b).__webglTexture)};this.setupRenderTarget=function(b){var e=d.get(b),f=d.get(b.texture);b.addEventListener("dispose",q);f.__webglTexture=a.createTexture();g.textures++;var h=!0===b.isWebGLRenderTargetCube,m=k(b);if(h){e.__webglFramebuffer=[];for(var u=0;6>u;u++)e.__webglFramebuffer[u]=a.createFramebuffer()}else e.__webglFramebuffer=a.createFramebuffer();if(h){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);r(a.TEXTURE_CUBE_MAP,b.texture,m);for(u=0;6>u;u++)l(e.__webglFramebuffer[u],
13668 b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+u);b.texture.generateMipmaps&&m&&a.generateMipmap(a.TEXTURE_CUBE_MAP);c.bindTexture(a.TEXTURE_CUBE_MAP,null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),r(a.TEXTURE_2D,b.texture,m),l(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),b.texture.generateMipmaps&&m&&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");
13669 if(b&&b.isWebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported!");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=
13670 !0);n(b.depthTexture,0);e=d.get(b.depthTexture).__webglTexture;if(1026===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,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(),t(e.__webglDepthbuffer[f],
13671 b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),t(e.__webglDepthbuffer,b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap=function(b){var e=b.texture;e.generateMipmaps&&k(b)&&1003!==e.minFilter&&1006!==e.minFilter&&(b=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 eg(){var a={};return{get:function(b){b=b.uuid;
13672 var c=a[b];void 0===c&&(c={},a[b]=c);return c},remove:function(b){delete a[b.uuid]},clear:function(){a={}}}}function fg(a,b,c){function d(b,c,d){var e=new Uint8Array(4),f=a.createTexture();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!==v[b]&&(a.enable(b),v[b]=!0)}function f(b){!1!==v[b]&&(a.disable(b),v[b]=!1)}function g(b,d,
13673 g,h,k,m,n,u){0!==b?e(a.BLEND):f(a.BLEND);if(b!==w||u!==ca)2===b?u?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,a.ONE,a.ONE,a.ONE)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.SRC_ALPHA,a.ONE)):3===b?u?(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)):4===b?u?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,
13674 a.SRC_COLOR,a.ZERO,a.SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.SRC_COLOR)):u?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,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)),w=b,ca=u;if(5===b){k=k||d;m=m||g;n=n||h;if(d!==O||k!==F)a.blendEquationSeparate(c(d),c(k)),O=d,F=k;if(g!==S||h!==E||m!==aa||n!==R)a.blendFuncSeparate(c(g),
13675 c(h),c(m),c(n)),S=g,E=h,aa=m,R=n}else R=aa=F=E=S=O=null}function h(b){la!==b&&(b?a.frontFace(a.CW):a.frontFace(a.CCW),la=b)}function k(b){0!==b?(e(a.CULL_FACE),b!==D&&(1===b?a.cullFace(a.BACK):2===b?a.cullFace(a.FRONT):a.cullFace(a.FRONT_AND_BACK))):f(a.CULL_FACE);D=b}function m(b,c,d){if(b){if(e(a.POLYGON_OFFSET_FILL),C!==c||P!==d)a.polygonOffset(c,d),C=c,P=d}else f(a.POLYGON_OFFSET_FILL)}function u(b){void 0===b&&(b=a.TEXTURE0+W-1);T!==b&&(a.activeTexture(b),T=b)}var q=new function(){var b=!1,c=
13676 new ga,d=null,e=new ga;return{setMask:function(c){d===c||b||(a.colorMask(c,c,c,c),d=c)},setLocked:function(a){b=a},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(0,0,0,1)}}},n=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);
13677 break;case 1:a.depthFunc(a.ALWAYS);break;case 2:a.depthFunc(a.LESS);break;case 3:a.depthFunc(a.LEQUAL);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,k=null,m=null,n=null,
13678 u=null;return{setTest:function(b){b?e(a.STENCIL_TEST):f(a.STENCIL_TEST)},setMask:function(d){c===d||b||(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(k!==b||m!==c||n!==d)a.stencilOp(b,c,d),k=b,m=c,n=d},setLocked:function(a){b=a},setClear:function(b){u!==b&&(a.clearStencil(b),u=b)},reset:function(){b=!1;u=n=m=k=h=g=d=c=null}}},l=a.getParameter(a.MAX_VERTEX_ATTRIBS),t=new Uint8Array(l),p=new Uint8Array(l),x=new Uint8Array(l),
13679 v={},G=null,w=null,O=null,S=null,E=null,F=null,aa=null,R=null,ca=!1,la=null,D=null,B=null,C=null,P=null,K=null,W=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS),l=parseFloat(/^WebGL\ ([0-9])/.exec(a.getParameter(a.VERSION))[1]),ba=1<=parseFloat(l),T=null,Q={},I=new ga,H=new ga,J={};J[a.TEXTURE_2D]=d(a.TEXTURE_2D,a.TEXTURE_2D,1);J[a.TEXTURE_CUBE_MAP]=d(a.TEXTURE_CUBE_MAP,a.TEXTURE_CUBE_MAP_POSITIVE_X,6);return{buffers:{color:q,depth:n,stencil:r},init:function(){q.setClear(0,0,0,1);n.setClear(1);r.setClear(0);
13680 e(a.DEPTH_TEST);n.setFunc(3);h(!1);k(1);e(a.CULL_FACE);e(a.BLEND);g(1)},initAttributes:function(){for(var a=0,b=t.length;a<b;a++)t[a]=0},enableAttribute:function(c){t[c]=1;0===p[c]&&(a.enableVertexAttribArray(c),p[c]=1);0!==x[c]&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,0),x[c]=0)},enableAttributeAndDivisor:function(c,d){t[c]=1;0===p[c]&&(a.enableVertexAttribArray(c),p[c]=1);x[c]!==d&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,d),x[c]=d)},disableUnusedAttributes:function(){for(var b=
13681 0,c=p.length;b!==c;++b)p[b]!==t[b]&&(a.disableVertexAttribArray(b),p[b]=0)},enable:e,disable:f,getCompressedTextureFormats:function(){if(null===G&&(G=[],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++)G.push(c[d]);return G},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,
13682 b.blendSrc,b.blendDst,b.blendEquationAlpha,b.blendSrcAlpha,b.blendDstAlpha,b.premultipliedAlpha):g(0);n.setFunc(b.depthFunc);n.setTest(b.depthTest);n.setMask(b.depthWrite);q.setMask(b.colorWrite);m(b.polygonOffset,b.polygonOffsetFactor,b.polygonOffsetUnits)},setFlipSided:h,setCullFace:k,setLineWidth:function(b){b!==B&&(ba&&a.lineWidth(b),B=b)},setPolygonOffset:m,getScissorTest:function(){return K},setScissorTest:function(b){(K=b)?e(a.SCISSOR_TEST):f(a.SCISSOR_TEST)},activeTexture:u,bindTexture:function(b,
13683 c){null===T&&u();var d=Q[T];void 0===d&&(d={type:void 0,texture:void 0},Q[T]=d);if(d.type!==b||d.texture!==c)a.bindTexture(b,c||J[b]),d.type=b,d.texture=c},compressedTexImage2D:function(){try{a.compressedTexImage2D.apply(a,arguments)}catch(b){console.error(b)}},texImage2D:function(){try{a.texImage2D.apply(a,arguments)}catch(b){console.error(b)}},scissor:function(b){!1===I.equals(b)&&(a.scissor(b.x,b.y,b.z,b.w),I.copy(b))},viewport:function(b){!1===H.equals(b)&&(a.viewport(b.x,b.y,b.z,b.w),H.copy(b))},
13684 reset:function(){for(var b=0;b<p.length;b++)1===p[b]&&(a.disableVertexAttribArray(b),p[b]=0);v={};T=G=null;Q={};D=la=w=null;q.reset();n.reset();r.reset()}}}function gg(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,
13685 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&&!!b.get("EXT_frag_depth");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),m=a.getParameter(a.MAX_CUBE_MAP_TEXTURE_SIZE),u=a.getParameter(a.MAX_VERTEX_ATTRIBS),q=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS),
13686 n=a.getParameter(a.MAX_VARYING_VECTORS),r=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS),l=0<h,t=!!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:m,maxAttributes:u,maxVertexUniforms:q,maxVaryings:n,maxFragmentUniforms:r,vertexTextures:l,
13687 floatFragmentTextures:t,floatVertexTextures:l&&t}}function hg(a){var b={};return{get:function(c){if(void 0!==b[c])return b[c];var d;switch(c){case "WEBGL_depth_texture":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")||a.getExtension("WEBKIT_EXT_texture_filter_anisotropic");
13688 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");break;default:d=a.getExtension(c)}null===d&&console.warn("THREE.WebGLRenderer: "+
13689 c+" extension not supported.");return b[c]=d}}}function ig(){function a(){m.value!==d&&(m.value=d,m.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=m.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+3]=h.constant}m.value=g;m.needsUpdate=!0}c.numPlanes=f;return g}var c=this,d=null,
13690 e=0,f=!1,g=!1,h=new wa,k=new Ka,m={value:null,needsUpdate:!1};this.uniform=m;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,l,t){if(!f||null===c||0===c.length||g&&!k)g?b(null):a();else{k=g?0:e;var p=4*k,x=l.clippingState||null;m.value=x;x=b(c,r,p,t);for(c=0;c!==p;++c)x[c]=d[c];l.clippingState=x;this.numIntersection=
13691 h?this.numPlanes:0;this.numPlanes+=k}}}function Xd(a){function b(){fa.init();fa.scissor(Q.copy(ha).multiplyScalar(ka));fa.viewport(Z.copy(zc).multiplyScalar(ka));fa.buffers.color.setClear(Ia.r,Ia.g,Ia.b,X,E)}function c(){T=M=null;ba="";W=-1;fa.reset()}function d(a){a.preventDefault();c();b();ia.clear();wa.clear()}function e(a){a=a.target;a.removeEventListener("dispose",e);f(a);ia.remove(a)}function f(a){var b=ia.get(a).program;a.program=void 0;void 0!==b&&ya.releaseProgram(b)}function g(a,b,c){a.render(function(a){C.renderBufferImmediate(a,
13692 b,c)})}function h(a,b){return Math.abs(b[0])-Math.abs(a[0])}function k(a,b,c){if(a.visible){if(a.layers.test(b.layers))if(a.isLight)aa.push(a);else if(a.isSprite)a.frustumCulled&&!ma.intersectsSprite(a)||D.push(a);else if(a.isLensFlare)B.push(a);else if(a.isImmediateRenderObject)c&&Qa.setFromMatrixPosition(a.matrixWorld).applyMatrix4(ld),R.push(a,null,a.material,Qa.z,null);else if(a.isMesh||a.isLine||a.isPoints)if(a.isSkinnedMesh&&a.skeleton.update(),!a.frustumCulled||ma.intersectsObject(a)){c&&Qa.setFromMatrixPosition(a.matrixWorld).applyMatrix4(ld);
13693 var d=wa.update(a),e=a.material;if(Array.isArray(e))for(var f=d.groups,g=0,h=f.length;g<h;g++){var m=f[g],n=e[m.materialIndex];n&&n.visible&&R.push(a,d,n,Qa.z,m)}else e.visible&&R.push(a,d,e,Qa.z,null)}a=a.children;g=0;for(h=a.length;g<h;g++)k(a[g],b,c)}}function m(a,b,c,d){for(var e=0,f=a.length;e<f;e++){var g=a[e],h=g.object,k=g.geometry,m=void 0===d?g.material:d,g=g.group;h.onBeforeRender(C,b,c,k,m,g);if(c.isArrayCamera&&c.enabled)for(var n=c.cameras,q=0,r=n.length;q<r;q++){var l=n[q],t=l.bounds;
13694 C.setViewport(t.x*N*ka,t.y*da*ka,t.z*N*ka,t.w*da*ka);C.setScissor(t.x*N*ka,t.y*da*ka,t.z*N*ka,t.w*da*ka);C.setScissorTest(!0);u(h,b,l,k,m,g)}else u(h,b,c,k,m,g);h.onAfterRender(C,b,c,k,m,g)}}function u(a,b,c,d,e,f){a.modelViewMatrix.multiplyMatrices(c.matrixWorldInverse,a.matrixWorld);a.normalMatrix.getNormalMatrix(a.modelViewMatrix);a.isImmediateRenderObject?(fa.setMaterial(e),b=n(c,b.fog,e,a),ba="",g(a,b,e)):C.renderBufferDirect(c,b.fog,d,e,a,f)}function q(a,b,c){var d=ia.get(a);c=ya.getParameters(a,
13695 ea,b,Pa.numPlanes,Pa.numIntersection,c);var g=ya.getProgramCode(a,c),h=d.program,k=!0;if(void 0===h)a.addEventListener("dispose",e);else if(h.code!==g)f(a);else{if(void 0!==c.shaderID)return;k=!1}k&&(c.shaderID?(h=ab[c.shaderID],d.__webglShader={name:a.type,uniforms:Ha.clone(h.uniforms),vertexShader:h.vertexShader,fragmentShader:h.fragmentShader}):d.__webglShader={name:a.type,uniforms:a.uniforms,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader},a.__webglShader=d.__webglShader,h=ya.acquireProgram(a,
13696 c,g),d.program=h,a.program=h);c=h.getAttributes();if(a.morphTargets)for(g=a.numSupportedMorphTargets=0;g<C.maxMorphTargets;g++)0<=c["morphTarget"+g]&&a.numSupportedMorphTargets++;if(a.morphNormals)for(g=a.numSupportedMorphNormals=0;g<C.maxMorphNormals;g++)0<=c["morphNormal"+g]&&a.numSupportedMorphNormals++;c=d.__webglShader.uniforms;if(!a.isShaderMaterial&&!a.isRawShaderMaterial||!0===a.clipping)d.numClippingPlanes=Pa.numPlanes,d.numIntersection=Pa.numIntersection,c.clippingPlanes=Pa.uniform;d.fog=
13697 b;d.lightsHash=ea.hash;a.lights&&(c.ambientLightColor.value=ea.ambient,c.directionalLights.value=ea.directional,c.spotLights.value=ea.spot,c.rectAreaLights.value=ea.rectArea,c.pointLights.value=ea.point,c.hemisphereLights.value=ea.hemi,c.directionalShadowMap.value=ea.directionalShadowMap,c.directionalShadowMatrix.value=ea.directionalShadowMatrix,c.spotShadowMap.value=ea.spotShadowMap,c.spotShadowMatrix.value=ea.spotShadowMatrix,c.pointShadowMap.value=ea.pointShadowMap,c.pointShadowMatrix.value=ea.pointShadowMatrix);
13698 a=d.program.getUniforms();a=fb.seqWithValue(a.seq,c);d.uniformsList=a}function n(a,b,c,d){U=0;var e=ia.get(c);kd&&(Wd||a!==T)&&Pa.setState(c.clippingPlanes,c.clipIntersection,c.clipShadows,a,e,a===T&&c.id===W);!1===c.needsUpdate&&(void 0===e.program?c.needsUpdate=!0:c.fog&&e.fog!==b?c.needsUpdate=!0:c.lights&&e.lightsHash!==ea.hash?c.needsUpdate=!0:void 0===e.numClippingPlanes||e.numClippingPlanes===Pa.numPlanes&&e.numIntersection===Pa.numIntersection||(c.needsUpdate=!0));c.needsUpdate&&(q(c,b,d),
13699 c.needsUpdate=!1);var f=!1,g=!1,h=!1,k=e.program,m=k.getUniforms(),n=e.__webglShader.uniforms;k.id!==M&&(A.useProgram(k.program),M=k.id,h=g=f=!0);c.id!==W&&(W=c.id,g=!0);if(f||a!==T){m.setValue(A,"projectionMatrix",a.projectionMatrix);na.logarithmicDepthBuffer&&m.setValue(A,"logDepthBufFC",2/(Math.log(a.far+1)/Math.LN2));a!==T&&(T=a,h=g=!0);if(c.isShaderMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.envMap)f=m.map.cameraPosition,void 0!==f&&f.setValue(A,Qa.setFromMatrixPosition(a.matrixWorld));
13700 (c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial||c.isMeshStandardMaterial||c.isShaderMaterial||c.skinning)&&m.setValue(A,"viewMatrix",a.matrixWorldInverse);m.setValue(A,"toneMappingExposure",C.toneMappingExposure);m.setValue(A,"toneMappingWhitePoint",C.toneMappingWhitePoint)}if(c.skinning&&(m.setOptional(A,d,"bindMatrix"),m.setOptional(A,d,"bindMatrixInverse"),a=d.skeleton))if(f=a.bones,na.floatVertexTextures){if(void 0===a.boneTexture){var f=Math.sqrt(4*f.length),f=Y.nextPowerOfTwo(Math.ceil(f)),
13701 f=Math.max(f,4),u=new Float32Array(f*f*4);u.set(a.boneMatrices);var t=new eb(u,f,f,1023,1015);a.boneMatrices=u;a.boneTexture=t;a.boneTextureSize=f}m.setValue(A,"boneTexture",a.boneTexture);m.setValue(A,"boneTextureSize",a.boneTextureSize)}else m.setOptional(A,a,"boneMatrices");if(g){c.lights&&(g=h,n.ambientLightColor.needsUpdate=g,n.directionalLights.needsUpdate=g,n.pointLights.needsUpdate=g,n.spotLights.needsUpdate=g,n.rectAreaLights.needsUpdate=g,n.hemisphereLights.needsUpdate=g);b&&c.fog&&(n.fogColor.value=
13702 b.color,b.isFog?(n.fogNear.value=b.near,n.fogFar.value=b.far):b.isFogExp2&&(n.fogDensity.value=b.density));if(c.isMeshBasicMaterial||c.isMeshLambertMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.isMeshNormalMaterial||c.isMeshDepthMaterial){n.opacity.value=c.opacity;n.diffuse.value=c.color;c.emissive&&n.emissive.value.copy(c.emissive).multiplyScalar(c.emissiveIntensity);n.map.value=c.map;n.specularMap.value=c.specularMap;n.alphaMap.value=c.alphaMap;c.lightMap&&(n.lightMap.value=c.lightMap,
13703 n.lightMapIntensity.value=c.lightMapIntensity);c.aoMap&&(n.aoMap.value=c.aoMap,n.aoMapIntensity.value=c.aoMapIntensity);var p;c.map?p=c.map:c.specularMap?p=c.specularMap:c.displacementMap?p=c.displacementMap:c.normalMap?p=c.normalMap:c.bumpMap?p=c.bumpMap:c.roughnessMap?p=c.roughnessMap:c.metalnessMap?p=c.metalnessMap:c.alphaMap?p=c.alphaMap:c.emissiveMap&&(p=c.emissiveMap);void 0!==p&&(p.isWebGLRenderTarget&&(p=p.texture),b=p.offset,p=p.repeat,n.offsetRepeat.value.set(b.x,b.y,p.x,p.y));n.envMap.value=
13704 c.envMap;n.flipEnvMap.value=c.envMap&&c.envMap.isCubeTexture?-1:1;n.reflectivity.value=c.reflectivity;n.refractionRatio.value=c.refractionRatio}c.isLineBasicMaterial?(n.diffuse.value=c.color,n.opacity.value=c.opacity):c.isLineDashedMaterial?(n.diffuse.value=c.color,n.opacity.value=c.opacity,n.dashSize.value=c.dashSize,n.totalSize.value=c.dashSize+c.gapSize,n.scale.value=c.scale):c.isPointsMaterial?(n.diffuse.value=c.color,n.opacity.value=c.opacity,n.size.value=c.size*ka,n.scale.value=.5*da,n.map.value=
13705 c.map,null!==c.map&&(p=c.map.offset,c=c.map.repeat,n.offsetRepeat.value.set(p.x,p.y,c.x,c.y))):c.isMeshLambertMaterial?c.emissiveMap&&(n.emissiveMap.value=c.emissiveMap):c.isMeshToonMaterial?(r(n,c),c.gradientMap&&(n.gradientMap.value=c.gradientMap)):c.isMeshPhongMaterial?r(n,c):c.isMeshPhysicalMaterial?(n.clearCoat.value=c.clearCoat,n.clearCoatRoughness.value=c.clearCoatRoughness,l(n,c)):c.isMeshStandardMaterial?l(n,c):c.isMeshDepthMaterial?c.displacementMap&&(n.displacementMap.value=c.displacementMap,
13706 n.displacementScale.value=c.displacementScale,n.displacementBias.value=c.displacementBias):c.isMeshNormalMaterial&&(c.bumpMap&&(n.bumpMap.value=c.bumpMap,n.bumpScale.value=c.bumpScale),c.normalMap&&(n.normalMap.value=c.normalMap,n.normalScale.value.copy(c.normalScale)),c.displacementMap&&(n.displacementMap.value=c.displacementMap,n.displacementScale.value=c.displacementScale,n.displacementBias.value=c.displacementBias));void 0!==n.ltcMat&&(n.ltcMat.value=V.LTC_MAT_TEXTURE);void 0!==n.ltcMag&&(n.ltcMag.value=
13707 V.LTC_MAG_TEXTURE);fb.upload(A,e.uniformsList,n,C)}m.setValue(A,"modelViewMatrix",d.modelViewMatrix);m.setValue(A,"normalMatrix",d.normalMatrix);m.setValue(A,"modelMatrix",d.matrixWorld);return k}function r(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&&
13708 (a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias)}function l(a,b){a.roughness.value=b.roughness;a.metalness.value=b.metalness;b.roughnessMap&&(a.roughnessMap.value=b.roughnessMap);b.metalnessMap&&(a.metalnessMap.value=b.metalnessMap);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));
13709 b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias);b.envMap&&(a.envMapIntensity.value=b.envMapIntensity)}function t(a,b){var c,d,e,f,g=0,h=0,k=0,m,n,u,q=b.matrixWorldInverse,l=0,r=0,t=0,z=0,p=0;c=0;for(d=a.length;c<d;c++)if(e=a[c],f=e.color,m=e.intensity,n=e.distance,u=e.shadow&&e.shadow.map?e.shadow.map.texture:null,e.isAmbientLight)g+=f.r*m,h+=f.g*m,k+=f.b*m;else if(e.isDirectionalLight){var v=
13710 Ba.get(e);v.color.copy(e.color).multiplyScalar(e.intensity);v.direction.setFromMatrixPosition(e.matrixWorld);Qa.setFromMatrixPosition(e.target.matrixWorld);v.direction.sub(Qa);v.direction.transformDirection(q);if(v.shadow=e.castShadow)f=e.shadow,v.shadowBias=f.bias,v.shadowRadius=f.radius,v.shadowMapSize=f.mapSize;ea.directionalShadowMap[l]=u;ea.directionalShadowMatrix[l]=e.shadow.matrix;ea.directional[l]=v;l++}else if(e.isSpotLight){v=Ba.get(e);v.position.setFromMatrixPosition(e.matrixWorld);v.position.applyMatrix4(q);
13711 v.color.copy(f).multiplyScalar(m);v.distance=n;v.direction.setFromMatrixPosition(e.matrixWorld);Qa.setFromMatrixPosition(e.target.matrixWorld);v.direction.sub(Qa);v.direction.transformDirection(q);v.coneCos=Math.cos(e.angle);v.penumbraCos=Math.cos(e.angle*(1-e.penumbra));v.decay=0===e.distance?0:e.decay;if(v.shadow=e.castShadow)f=e.shadow,v.shadowBias=f.bias,v.shadowRadius=f.radius,v.shadowMapSize=f.mapSize;ea.spotShadowMap[t]=u;ea.spotShadowMatrix[t]=e.shadow.matrix;ea.spot[t]=v;t++}else if(e.isRectAreaLight)v=
13712 Ba.get(e),v.color.copy(f).multiplyScalar(m/(e.width*e.height)),v.position.setFromMatrixPosition(e.matrixWorld),v.position.applyMatrix4(q),ra.identity(),qa.copy(e.matrixWorld),qa.premultiply(q),ra.extractRotation(qa),v.halfWidth.set(.5*e.width,0,0),v.halfHeight.set(0,.5*e.height,0),v.halfWidth.applyMatrix4(ra),v.halfHeight.applyMatrix4(ra),ea.rectArea[z]=v,z++;else if(e.isPointLight){v=Ba.get(e);v.position.setFromMatrixPosition(e.matrixWorld);v.position.applyMatrix4(q);v.color.copy(e.color).multiplyScalar(e.intensity);
13713 v.distance=e.distance;v.decay=0===e.distance?0:e.decay;if(v.shadow=e.castShadow)f=e.shadow,v.shadowBias=f.bias,v.shadowRadius=f.radius,v.shadowMapSize=f.mapSize;ea.pointShadowMap[r]=u;ea.pointShadowMatrix[r]=e.shadow.matrix;ea.point[r]=v;r++}else e.isHemisphereLight&&(v=Ba.get(e),v.direction.setFromMatrixPosition(e.matrixWorld),v.direction.transformDirection(q),v.direction.normalize(),v.skyColor.copy(e.color).multiplyScalar(m),v.groundColor.copy(e.groundColor).multiplyScalar(m),ea.hemi[p]=v,p++);
13714 ea.ambient[0]=g;ea.ambient[1]=h;ea.ambient[2]=k;ea.directional.length=l;ea.spot.length=t;ea.rectArea.length=z;ea.point.length=r;ea.hemi.length=p;ea.hash=l+","+r+","+t+","+z+","+p+","+ea.shadows.length}function y(a){var b;if(1E3===a)return A.REPEAT;if(1001===a)return A.CLAMP_TO_EDGE;if(1002===a)return A.MIRRORED_REPEAT;if(1003===a)return A.NEAREST;if(1004===a)return A.NEAREST_MIPMAP_NEAREST;if(1005===a)return A.NEAREST_MIPMAP_LINEAR;if(1006===a)return A.LINEAR;if(1007===a)return A.LINEAR_MIPMAP_NEAREST;
13715 if(1008===a)return A.LINEAR_MIPMAP_LINEAR;if(1009===a)return A.UNSIGNED_BYTE;if(1017===a)return A.UNSIGNED_SHORT_4_4_4_4;if(1018===a)return A.UNSIGNED_SHORT_5_5_5_1;if(1019===a)return A.UNSIGNED_SHORT_5_6_5;if(1010===a)return A.BYTE;if(1011===a)return A.SHORT;if(1012===a)return A.UNSIGNED_SHORT;if(1013===a)return A.INT;if(1014===a)return A.UNSIGNED_INT;if(1015===a)return A.FLOAT;if(1016===a&&(b=pa.get("OES_texture_half_float"),null!==b))return b.HALF_FLOAT_OES;if(1021===a)return A.ALPHA;if(1022===
13716 a)return A.RGB;if(1023===a)return A.RGBA;if(1024===a)return A.LUMINANCE;if(1025===a)return A.LUMINANCE_ALPHA;if(1026===a)return A.DEPTH_COMPONENT;if(1027===a)return A.DEPTH_STENCIL;if(100===a)return A.FUNC_ADD;if(101===a)return A.FUNC_SUBTRACT;if(102===a)return A.FUNC_REVERSE_SUBTRACT;if(200===a)return A.ZERO;if(201===a)return A.ONE;if(202===a)return A.SRC_COLOR;if(203===a)return A.ONE_MINUS_SRC_COLOR;if(204===a)return A.SRC_ALPHA;if(205===a)return A.ONE_MINUS_SRC_ALPHA;if(206===a)return A.DST_ALPHA;
13717 if(207===a)return A.ONE_MINUS_DST_ALPHA;if(208===a)return A.DST_COLOR;if(209===a)return A.ONE_MINUS_DST_COLOR;if(210===a)return A.SRC_ALPHA_SATURATE;if(2001===a||2002===a||2003===a||2004===a)if(b=pa.get("WEBGL_compressed_texture_s3tc"),null!==b){if(2001===a)return b.COMPRESSED_RGB_S3TC_DXT1_EXT;if(2002===a)return b.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(2003===a)return b.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(2004===a)return b.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(2100===a||2101===a||2102===a||2103===a)if(b=pa.get("WEBGL_compressed_texture_pvrtc"),
13718 null!==b){if(2100===a)return b.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(2101===a)return b.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(2102===a)return b.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(2103===a)return b.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(2151===a&&(b=pa.get("WEBGL_compressed_texture_etc1"),null!==b))return b.COMPRESSED_RGB_ETC1_WEBGL;if(103===a||104===a)if(b=pa.get("EXT_blend_minmax"),null!==b){if(103===a)return b.MIN_EXT;if(104===a)return b.MAX_EXT}return 1020===a&&(b=pa.get("WEBGL_depth_texture"),null!==b)?
13719 b.UNSIGNED_INT_24_8_WEBGL:0}console.log("THREE.WebGLRenderer","85");a=a||{};var x=void 0!==a.canvas?a.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),v=void 0!==a.context?a.context:null,G=void 0!==a.alpha?a.alpha:!1,w=void 0!==a.depth?a.depth:!0,O=void 0!==a.stencil?a.stencil:!0,S=void 0!==a.antialias?a.antialias:!1,E=void 0!==a.premultipliedAlpha?a.premultipliedAlpha:!0,F=void 0!==a.preserveDrawingBuffer?a.preserveDrawingBuffer:!1,aa=[],R=null,ca=new Float32Array(8),D=[],
13720 B=[];this.domElement=x;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 C=this,M=null,P=null,K=null,W=-1,ba="",T=null,Q=new ga,L=null,Z=new ga,U=0,Ia=new H(0),X=0,N=x.width,da=x.height,
13721 ka=1,ha=new ga(0,0,N,da),Pe=!1,zc=new ga(0,0,N,da),ma=new jd,Pa=new ig,kd=!1,Wd=!1,ld=new J,Qa=new p,qa=new J,ra=new J,ea={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],shadows:[]},va={geometries:0,textures:0},oa={frame:0,calls:0,vertices:0,faces:0,points:0};this.info={render:oa,memory:va,programs:null};var A;try{G={alpha:G,depth:w,stencil:O,
13722 antialias:S,premultipliedAlpha:E,preserveDrawingBuffer:F};A=v||x.getContext("webgl",G)||x.getContext("experimental-webgl",G);if(null===A){if(null!==x.getContext("webgl"))throw"Error creating WebGL context with your selected attributes.";throw"Error creating WebGL context.";}void 0===A.getShaderPrecisionFormat&&(A.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}});x.addEventListener("webglcontextlost",d,!1)}catch(jg){console.error("THREE.WebGLRenderer: "+jg)}var pa=new hg(A);
13723 pa.get("WEBGL_depth_texture");pa.get("OES_texture_float");pa.get("OES_texture_float_linear");pa.get("OES_texture_half_float");pa.get("OES_texture_half_float_linear");pa.get("OES_standard_derivatives");pa.get("ANGLE_instanced_arrays");pa.get("OES_element_index_uint")&&(I.MaxIndex=4294967296);var na=new gg(A,pa,a),fa=new fg(A,pa,y),ia=new eg,sa=new dg(A,pa,fa,ia,na,y,va),Aa=new Mf(A),Da=new Tf(A,Aa,va),wa=new Vf(A,Da,oa),ya=new cg(this,na),Ba=new Uf,Ga=new Qf;this.info.programs=ya.programs;var Ka=new Sf(A,
13724 pa,oa),La=new Rf(A,pa,oa),Fa,za,ta,ua;b();this.context=A;this.capabilities=na;this.extensions=pa;this.properties=ia;this.state=fa;var Ja=new Je(this,ea,wa,na);this.shadowMap=Ja;var Ma=new Jf(this,D),Oa=new If(this,B);this.getContext=function(){return A};this.getContextAttributes=function(){return A.getContextAttributes()};this.forceContextLoss=function(){var a=pa.get("WEBGL_lose_context");a&&a.loseContext()};this.getMaxAnisotropy=function(){return na.getMaxAnisotropy()};this.getPrecision=function(){return na.precision};
13725 this.getPixelRatio=function(){return ka};this.setPixelRatio=function(a){void 0!==a&&(ka=a,this.setSize(zc.z,zc.w,!1))};this.getSize=function(){return{width:N,height:da}};this.setSize=function(a,b,c){N=a;da=b;x.width=a*ka;x.height=b*ka;!1!==c&&(x.style.width=a+"px",x.style.height=b+"px");this.setViewport(0,0,a,b)};this.setViewport=function(a,b,c,d){fa.viewport(zc.set(a,b,c,d))};this.setScissor=function(a,b,c,d){fa.scissor(ha.set(a,b,c,d))};this.setScissorTest=function(a){fa.setScissorTest(Pe=a)};this.getClearColor=
13726 function(){return Ia};this.setClearColor=function(a,b){Ia.set(a);X=void 0!==b?b:1;fa.buffers.color.setClear(Ia.r,Ia.g,Ia.b,X,E)};this.getClearAlpha=function(){return X};this.setClearAlpha=function(a){X=a;fa.buffers.color.setClear(Ia.r,Ia.g,Ia.b,X,E)};this.clear=function(a,b,c){var d=0;if(void 0===a||a)d|=A.COLOR_BUFFER_BIT;if(void 0===b||b)d|=A.DEPTH_BUFFER_BIT;if(void 0===c||c)d|=A.STENCIL_BUFFER_BIT;A.clear(d)};this.clearColor=function(){this.clear(!0,!1,!1)};this.clearDepth=function(){this.clear(!1,
13727 !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.resetGLState=c;this.dispose=function(){x.removeEventListener("webglcontextlost",d,!1);Ga.dispose()};this.renderBufferImmediate=function(a,b,c){fa.initAttributes();var d=ia.get(a);a.hasPositions&&!d.position&&(d.position=A.createBuffer());a.hasNormals&&!d.normal&&(d.normal=A.createBuffer());a.hasUvs&&!d.uv&&(d.uv=A.createBuffer());a.hasColors&&!d.color&&(d.color=
13728 A.createBuffer());b=b.getAttributes();a.hasPositions&&(A.bindBuffer(A.ARRAY_BUFFER,d.position),A.bufferData(A.ARRAY_BUFFER,a.positionArray,A.DYNAMIC_DRAW),fa.enableAttribute(b.position),A.vertexAttribPointer(b.position,3,A.FLOAT,!1,0,0));if(a.hasNormals){A.bindBuffer(A.ARRAY_BUFFER,d.normal);if(!c.isMeshPhongMaterial&&!c.isMeshStandardMaterial&&!c.isMeshNormalMaterial&&1===c.shading)for(var e=0,f=3*a.count;e<f;e+=9){var g=a.normalArray,h=(g[e+0]+g[e+3]+g[e+6])/3,k=(g[e+1]+g[e+4]+g[e+7])/3,m=(g[e+
13729 2]+g[e+5]+g[e+8])/3;g[e+0]=h;g[e+1]=k;g[e+2]=m;g[e+3]=h;g[e+4]=k;g[e+5]=m;g[e+6]=h;g[e+7]=k;g[e+8]=m}A.bufferData(A.ARRAY_BUFFER,a.normalArray,A.DYNAMIC_DRAW);fa.enableAttribute(b.normal);A.vertexAttribPointer(b.normal,3,A.FLOAT,!1,0,0)}a.hasUvs&&c.map&&(A.bindBuffer(A.ARRAY_BUFFER,d.uv),A.bufferData(A.ARRAY_BUFFER,a.uvArray,A.DYNAMIC_DRAW),fa.enableAttribute(b.uv),A.vertexAttribPointer(Aa.uv,2,A.FLOAT,!1,0,0));a.hasColors&&0!==c.vertexColors&&(A.bindBuffer(A.ARRAY_BUFFER,d.color),A.bufferData(A.ARRAY_BUFFER,
13730 a.colorArray,A.DYNAMIC_DRAW),fa.enableAttribute(b.color),A.vertexAttribPointer(b.color,3,A.FLOAT,!1,0,0));fa.disableUnusedAttributes();A.drawArrays(A.TRIANGLES,0,a.count);a.count=0};this.renderBufferDirect=function(a,b,c,d,e,f){fa.setMaterial(d);var g=n(a,b,d,e);a=c.id+"_"+g.id+"_"+(!0===d.wireframe);var k=!1;a!==ba&&(ba=a,k=!0);b=e.morphTargetInfluences;if(void 0!==b){var m=[];a=0;for(var u=b.length;a<u;a++)k=b[a],m.push([k,a]);m.sort(h);8<m.length&&(m.length=8);var q=c.morphAttributes;a=0;for(u=
13731 m.length;a<u;a++)k=m[a],ca[a]=k[0],0!==k[0]?(b=k[1],!0===d.morphTargets&&q.position&&c.addAttribute("morphTarget"+a,q.position[b]),!0===d.morphNormals&&q.normal&&c.addAttribute("morphNormal"+a,q.normal[b])):(!0===d.morphTargets&&c.removeAttribute("morphTarget"+a),!0===d.morphNormals&&c.removeAttribute("morphNormal"+a));a=m.length;for(b=ca.length;a<b;a++)ca[a]=0;g.getUniforms().setValue(A,"morphTargetInfluences",ca);k=!0}b=c.index;u=c.attributes.position;m=1;!0===d.wireframe&&(b=Da.getWireframeAttribute(c),
13732 m=2);a=Ka;null!==b&&(a=La,a.setIndex(b));if(k){k=void 0;if(c&&c.isInstancedBufferGeometry&&null===pa.get("ANGLE_instanced_arrays"))console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");else{void 0===k&&(k=0);fa.initAttributes();var q=c.attributes,g=g.getAttributes(),l=d.defaultAttributeValues,r;for(r in g){var t=g[r];if(0<=t){var v=q[r];if(void 0!==v){var z=v.normalized,p=v.itemSize,w=Aa.get(v),
13733 x=w.buffer,y=w.type,w=w.bytesPerElement;if(v.isInterleavedBufferAttribute){var G=v.data,O=G.stride,v=v.offset;G&&G.isInstancedInterleavedBuffer?(fa.enableAttributeAndDivisor(t,G.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=G.meshPerAttribute*G.count)):fa.enableAttribute(t);A.bindBuffer(A.ARRAY_BUFFER,x);A.vertexAttribPointer(t,p,y,z,O*w,(k*O+v)*w)}else v.isInstancedBufferAttribute?(fa.enableAttributeAndDivisor(t,v.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=
13734 v.meshPerAttribute*v.count)):fa.enableAttribute(t),A.bindBuffer(A.ARRAY_BUFFER,x),A.vertexAttribPointer(t,p,y,z,0,k*p*w)}else if(void 0!==l&&(z=l[r],void 0!==z))switch(z.length){case 2:A.vertexAttrib2fv(t,z);break;case 3:A.vertexAttrib3fv(t,z);break;case 4:A.vertexAttrib4fv(t,z);break;default:A.vertexAttrib1fv(t,z)}}}fa.disableUnusedAttributes()}null!==b&&A.bindBuffer(A.ELEMENT_ARRAY_BUFFER,Aa.get(b).buffer)}r=0;null!==b?r=b.count:void 0!==u&&(r=u.count);u=c.drawRange.start*m;k=null!==f?f.start*m:
13735 0;b=Math.max(u,k);f=Math.max(0,Math.min(r,u+c.drawRange.count*m,k+(null!==f?f.count*m:Infinity))-1-b+1);if(0!==f){if(e.isMesh)if(!0===d.wireframe)fa.setLineWidth(d.wireframeLinewidth*(null===P?ka:1)),a.setMode(A.LINES);else switch(e.drawMode){case 0:a.setMode(A.TRIANGLES);break;case 1:a.setMode(A.TRIANGLE_STRIP);break;case 2:a.setMode(A.TRIANGLE_FAN)}else e.isLine?(d=d.linewidth,void 0===d&&(d=1),fa.setLineWidth(d*(null===P?ka:1)),e.isLineSegments?a.setMode(A.LINES):e.isLineLoop?a.setMode(A.LINE_LOOP):
13736 a.setMode(A.LINE_STRIP)):e.isPoints&&a.setMode(A.POINTS);c&&c.isInstancedBufferGeometry?0<c.maxInstancedCount&&a.renderInstances(c,b,f):a.render(b,f)}};this.compile=function(a,b){aa=[];a.traverse(function(a){a.isLight&&aa.push(a)});t(aa,b);a.traverse(function(b){if(b.material)if(Array.isArray(b.material))for(var c=0;c<b.material.length;c++)q(b.material[c],a.fog,b);else q(b.material,a.fog,b)})};this.render=function(a,b,c,d){if(void 0!==b&&!0!==b.isCamera)console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");
13737 else{ba="";W=-1;T=null;!0===a.autoUpdate&&a.updateMatrixWorld();b.onBeforeRender(C);null===b.parent&&b.updateMatrixWorld();b.matrixWorldInverse.getInverse(b.matrixWorld);ld.multiplyMatrices(b.projectionMatrix,b.matrixWorldInverse);ma.setFromMatrix(ld);aa.length=0;D.length=0;B.length=0;Wd=this.localClippingEnabled;kd=Pa.init(this.clippingPlanes,Wd,b);R=Ga.get(a,b);R.init();k(a,b,C.sortObjects);R.finish();!0===C.sortObjects&&R.sort();kd&&Pa.beginShadows();for(var e=aa,f=0,g=0,h=e.length;g<h;g++){var n=
13738 e[g];n.castShadow&&(ea.shadows[f]=n,f++)}ea.shadows.length=f;Ja.render(a,b);t(aa,b);kd&&Pa.endShadows();oa.frame++;oa.calls=0;oa.vertices=0;oa.faces=0;oa.points=0;void 0===c&&(c=null);this.setRenderTarget(c);e=a.background;null===e?fa.buffers.color.setClear(Ia.r,Ia.g,Ia.b,X,E):e&&e.isColor&&(fa.buffers.color.setClear(e.r,e.g,e.b,1,E),d=!0);(this.autoClear||d)&&this.clear(this.autoClearColor,this.autoClearDepth,this.autoClearStencil);e&&e.isCubeTexture?(void 0===ta&&(ta=new xa,ua=new Ca(new kb(5,5,
13739 5),new Ea({uniforms:ab.cube.uniforms,vertexShader:ab.cube.vertexShader,fragmentShader:ab.cube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1}))),ta.projectionMatrix.copy(b.projectionMatrix),ta.matrixWorld.extractRotation(b.matrixWorld),ta.matrixWorldInverse.getInverse(ta.matrixWorld),ua.material.uniforms.tCube.value=e,ua.modelViewMatrix.multiplyMatrices(ta.matrixWorldInverse,ua.matrixWorld),wa.update(ua),C.renderBufferDirect(ta,null,ua.geometry,ua.material,ua,null)):e&&e.isTexture&&(void 0===
13740 Fa&&(Fa=new Jb(-1,1,1,-1,0,1),za=new Ca(new lb(2,2),new Na({depthTest:!1,depthWrite:!1,fog:!1}))),za.material.map=e,wa.update(za),C.renderBufferDirect(Fa,null,za.geometry,za.material,za,null));d=R.opaque;e=R.transparent;a.overrideMaterial?(f=a.overrideMaterial,d.length&&m(d,a,b,f),e.length&&m(e,a,b,f)):(d.length&&m(d,a,b),e.length&&m(e,a,b));Ma.render(a,b);Oa.render(a,b,Z);c&&sa.updateRenderTargetMipmap(c);fa.buffers.depth.setTest(!0);fa.buffers.depth.setMask(!0);fa.buffers.color.setMask(!0);b.isArrayCamera&&
13741 b.enabled&&C.setScissorTest(!1);b.onAfterRender(C)}};this.setFaceCulling=function(a,b){fa.setCullFace(a);fa.setFlipSided(0===b)};this.allocTextureUnit=function(){var a=U;a>=na.maxTextures&&console.warn("WebGLRenderer: trying to use "+a+" texture units while this GPU supports only "+na.maxTextures);U+=1;return a};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."),
13742 a=!0),b=b.texture);sa.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);sa.setTexture2D(b,c)}}();this.setTextureCube=function(){var a=!1;return function(b,c){b&&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)&&
13743 6===b.image.length?sa.setTextureCube(b,c):sa.setTextureCubeDynamic(b,c)}}();this.getRenderTarget=function(){return P};this.setRenderTarget=function(a){(P=a)&&void 0===ia.get(a).__webglFramebuffer&&sa.setupRenderTarget(a);var b=a&&a.isWebGLRenderTargetCube,c;a?(c=ia.get(a),c=b?c.__webglFramebuffer[a.activeCubeFace]:c.__webglFramebuffer,Q.copy(a.scissor),L=a.scissorTest,Z.copy(a.viewport)):(c=null,Q.copy(ha).multiplyScalar(ka),L=Pe,Z.copy(zc).multiplyScalar(ka));K!==c&&(A.bindFramebuffer(A.FRAMEBUFFER,
13744 c),K=c);fa.scissor(Q);fa.setScissorTest(L);fa.viewport(Z);b&&(b=ia.get(a.texture),A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,b.__webglTexture,a.activeMipMapLevel))};this.readRenderTargetPixels=function(a,b,c,d,e,f){if(!1===(a&&a.isWebGLRenderTarget))console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");else{var g=ia.get(a).__webglFramebuffer;if(g){var h=!1;g!==K&&(A.bindFramebuffer(A.FRAMEBUFFER,
13745 g),h=!0);try{var k=a.texture,m=k.format,n=k.type;1023!==m&&y(m)!==A.getParameter(A.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===n||y(n)===A.getParameter(A.IMPLEMENTATION_COLOR_READ_TYPE)||1015===n&&(pa.get("OES_texture_float")||pa.get("WEBGL_color_buffer_float"))||1016===n&&pa.get("EXT_color_buffer_half_float")?A.checkFramebufferStatus(A.FRAMEBUFFER)===A.FRAMEBUFFER_COMPLETE?0<=b&&
13746 b<=a.width-d&&0<=c&&c<=a.height-e&&A.readPixels(b,c,d,e,y(m),y(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&&A.bindFramebuffer(A.FRAMEBUFFER,K)}}}}}function Kb(a,b){this.name="";this.color=new H(a);this.density=void 0!==b?b:2.5E-4}function Lb(a,b,c){this.name="";this.color=
13747 new H(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function md(){B.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function Yd(a,b,c,d,e){B.call(this);this.lensFlares=[];this.positionScreen=new p;this.customUpdateCallback=void 0;void 0!==a&&this.add(a,b,c,d,e)}function cb(a){Z.call(this);this.type="SpriteMaterial";this.color=new H(16777215);this.map=null;this.rotation=0;this.lights=this.fog=!1;this.setValues(a)}function Ac(a){B.call(this);
13748 this.type="Sprite";this.material=void 0!==a?a:new cb}function Bc(){B.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function Cc(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{console.warn("THREE.Skeleton boneInverses is the wrong length.");this.boneInverses=[];for(var c=0,d=this.bones.length;c<d;c++)this.boneInverses.push(new J)}}
13749 function nd(){B.call(this);this.type="Bone"}function od(a,b){Ca.call(this,a,b);this.type="SkinnedMesh";this.bindMode="attached";this.bindMatrix=new J;this.bindMatrixInverse=new J;var c=this.initBones(),c=new Cc(c);this.bind(c,this.matrixWorld);this.normalizeSkinWeights()}function ha(a){Z.call(this);this.type="LineBasicMaterial";this.color=new H(16777215);this.linewidth=1;this.linejoin=this.linecap="round";this.lights=!1;this.setValues(a)}function ya(a,b,c){if(1===c)return console.warn("THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead."),
13750 new da(a,b);B.call(this);this.type="Line";this.geometry=void 0!==a?a:new I;this.material=void 0!==b?b:new ha({color:16777215*Math.random()})}function da(a,b){ya.call(this,a,b);this.type="LineSegments"}function pd(a,b){ya.call(this,a,b);this.type="LineLoop"}function La(a){Z.call(this);this.type="PointsMaterial";this.color=new H(16777215);this.map=null;this.size=1;this.sizeAttenuation=!0;this.lights=!1;this.setValues(a)}function Mb(a,b){B.call(this);this.type="Points";this.geometry=void 0!==a?a:new I;
13751 this.material=void 0!==b?b:new La({color:16777215*Math.random()})}function Dc(){B.call(this);this.type="Group"}function qd(a,b,c,d,e,f,g,h,k){function m(){requestAnimationFrame(m);a.readyState>=a.HAVE_CURRENT_DATA&&(u.needsUpdate=!0)}X.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1;var u=this;m()}function Nb(a,b,c,d,e,f,g,h,k,m,u,q){X.call(this,null,f,g,h,k,m,d,e,u,q);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1}function rd(a,b,c,d,e,f,g,h,k){X.call(this,a,
13752 b,c,d,e,f,g,h,k);this.needsUpdate=!0}function Ec(a,b,c,d,e,f,g,h,k,m){m=void 0!==m?m:1026;if(1026!==m&&1027!==m)throw Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===c&&1026===m&&(c=1012);void 0===c&&1027===m&&(c=1020);X.call(this,null,d,e,f,g,h,m,c,k);this.image={width:a,height:b};this.magFilter=void 0!==g?g:1003;this.minFilter=void 0!==h?h:1003;this.generateMipmaps=this.flipY=!1}function Ob(a){I.call(this);this.type="WireframeGeometry";var b=[],
13753 c,d,e,f,g=[0,0],h={},k,m,u=["a","b","c"];if(a&&a.isGeometry){var q=a.faces;c=0;for(e=q.length;c<e;c++){var n=q[c];for(d=0;3>d;d++)k=n[u[d]],m=n[u[(d+1)%3]],g[0]=Math.min(k,m),g[1]=Math.max(k,m),k=g[0]+","+g[1],void 0===h[k]&&(h[k]={index1:g[0],index2:g[1]})}for(k in h)c=h[k],u=a.vertices[c.index1],b.push(u.x,u.y,u.z),u=a.vertices[c.index2],b.push(u.x,u.y,u.z)}else if(a&&a.isBufferGeometry){var r,u=new p;if(null!==a.index){q=a.attributes.position;n=a.index;r=a.groups;0===r.length&&(r=[{start:0,count:n.count,
13754 materialIndex:0}]);a=0;for(f=r.length;a<f;++a)for(c=r[a],d=c.start,e=c.count,c=d,e=d+e;c<e;c+=3)for(d=0;3>d;d++)k=n.getX(c+d),m=n.getX(c+(d+1)%3),g[0]=Math.min(k,m),g[1]=Math.max(k,m),k=g[0]+","+g[1],void 0===h[k]&&(h[k]={index1:g[0],index2:g[1]});for(k in h)c=h[k],u.fromBufferAttribute(q,c.index1),b.push(u.x,u.y,u.z),u.fromBufferAttribute(q,c.index2),b.push(u.x,u.y,u.z)}else for(q=a.attributes.position,c=0,e=q.count/3;c<e;c++)for(d=0;3>d;d++)h=3*c+d,u.fromBufferAttribute(q,h),b.push(u.x,u.y,u.z),
13755 h=3*c+(d+1)%3,u.fromBufferAttribute(q,h),b.push(u.x,u.y,u.z)}this.addAttribute("position",new C(b,3))}function Fc(a,b,c){M.call(this);this.type="ParametricGeometry";this.parameters={func:a,slices:b,stacks:c};this.fromBufferGeometry(new Pb(a,b,c));this.mergeVertices()}function Pb(a,b,c){I.call(this);this.type="ParametricBufferGeometry";this.parameters={func:a,slices:b,stacks:c};var d=[],e=[],f=[],g=[],h=new p,k=new p,m=new p,u=new p,q=new p,n,r,l=b+1;for(n=0;n<=c;n++){var t=n/c;for(r=0;r<=b;r++){var y=
13756 r/b,k=a(y,t,k);e.push(k.x,k.y,k.z);0<=y-1E-5?(m=a(y-1E-5,t,m),u.subVectors(k,m)):(m=a(y+1E-5,t,m),u.subVectors(m,k));0<=t-1E-5?(m=a(y,t-1E-5,m),q.subVectors(k,m)):(m=a(y,t+1E-5,m),q.subVectors(m,k));h.crossVectors(u,q).normalize();f.push(h.x,h.y,h.z);g.push(y,t)}}for(n=0;n<c;n++)for(r=0;r<b;r++)a=n*l+r+1,h=(n+1)*l+r+1,k=(n+1)*l+r,d.push(n*l+r,a,k),d.push(a,h,k);this.setIndex(d);this.addAttribute("position",new C(e,3));this.addAttribute("normal",new C(f,3));this.addAttribute("uv",new C(g,2))}function Gc(a,
13757 b,c,d){M.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};this.fromBufferGeometry(new ia(a,b,c,d));this.mergeVertices()}function ia(a,b,c,d){function e(a){h.push(a.x,a.y,a.z)}function f(b,c){var d=3*b;c.x=a[d+0];c.y=a[d+1];c.z=a[d+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)}I.call(this);this.type="PolyhedronBufferGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};c=c||1;var h=[],k=[];(function(a){for(var c=
13758 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=c,l=d,y=g,x=Math.pow(2,a),v=[],G,w;for(G=0;G<=x;G++){v[G]=[];var O=k.clone().lerp(y,G/x),S=l.clone().lerp(y,G/x),E=x-G;for(w=0;w<=E;w++)v[G][w]=0===w&&G===x?O:O.clone().lerp(S,w/E)}for(G=0;G<x;G++)for(w=0;w<2*(x-G)-1;w++)k=Math.floor(w/2),0===w%2?(e(v[G][k+1]),e(v[G+1][k]),e(v[G][k])):(e(v[G][k+1]),e(v[G+1][k+1]),e(v[G+1][k]))}})(d||0);(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+
13759 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 D,f=new D,l=new D,y=0,x=0;y<h.length;y+=9,x+=6){a.set(h[y+0],h[y+1],h[y+2]);b.set(h[y+3],h[y+4],h[y+5]);c.set(h[y+6],h[y+7],h[y+8]);e.set(k[x+0],k[x+1]);f.set(k[x+2],k[x+3]);l.set(k[x+4],k[x+5]);d.copy(a).add(b).add(c).divideScalar(3);
13760 var v=Math.atan2(d.z,-d.x);g(e,x+0,a,v);g(f,x+2,b,v);g(l,x+4,c,v)}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 C(h,3));this.addAttribute("normal",new C(h.slice(),3));this.addAttribute("uv",new C(k,2));this.normalizeNormals()}function Hc(a,b){M.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Qb(a,b));
13761 this.mergeVertices()}function Qb(a,b){ia.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 Ic(a,b){M.call(this);this.type="OctahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new mb(a,b));this.mergeVertices()}function mb(a,b){ia.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";
13762 this.parameters={radius:a,detail:b}}function Jc(a,b){M.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Rb(a,b));this.mergeVertices()}function Rb(a,b){var c=(1+Math.sqrt(5))/2;ia.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,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";
13763 this.parameters={radius:a,detail:b}}function Kc(a,b){M.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Sb(a,b));this.mergeVertices()}function Sb(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;ia.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,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,
13764 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 Lc(a,b,c,d,e,f){M.call(this);this.type="TubeGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};void 0!==f&&console.warn("THREE.TubeGeometry: taper has been removed.");a=new Tb(a,b,c,d,e);this.tangents=a.tangents;
13765 this.normals=a.normals;this.binormals=a.binormals;this.fromBufferGeometry(a);this.mergeVertices()}function Tb(a,b,c,d,e){function f(e){var f=a.getPointAt(e/b),m=g.normals[e];e=g.binormals[e];for(q=0;q<=d;q++){var u=q/d*Math.PI*2,t=Math.sin(u),u=-Math.cos(u);k.x=u*m.x+t*e.x;k.y=u*m.y+t*e.y;k.z=u*m.z+t*e.z;k.normalize();l.push(k.x,k.y,k.z);h.x=f.x+c*k.x;h.y=f.y+c*k.y;h.z=f.z+c*k.z;n.push(h.x,h.y,h.z)}}I.call(this);this.type="TubeBufferGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,
13766 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,m=new D,u,q,n=[],l=[],z=[],t=[];for(u=0;u<b;u++)f(u);f(!1===e?b:0);for(u=0;u<=b;u++)for(q=0;q<=d;q++)m.x=u/b,m.y=q/d,z.push(m.x,m.y);(function(){for(q=1;q<=b;q++)for(u=1;u<=d;u++){var a=(d+1)*q+(u-1),c=(d+1)*q+u,e=(d+1)*(q-1)+u;t.push((d+1)*(q-1)+(u-1),a,e);t.push(a,c,e)}})();this.setIndex(t);this.addAttribute("position",new C(n,3));
13767 this.addAttribute("normal",new C(l,3));this.addAttribute("uv",new C(z,2))}function Mc(a,b,c,d,e,f,g){M.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.");this.fromBufferGeometry(new Ub(a,b,c,d,e,f));this.mergeVertices()}function Ub(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)*
13768 .5*Math.cos(a);e.y=d*(2+c)*f*.5;e.z=d*Math.sin(b)*.5}I.call(this);this.type="TorusKnotBufferGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};a=a||100;b=b||40;c=Math.floor(c)||64;d=Math.floor(d)||8;e=e||2;f=f||3;var h=[],k=[],m=[],u=[],q,n,l=new p,z=new p,t=new p,y=new p,x=new p,v=new p,G=new p;for(q=0;q<=c;++q)for(n=q/c*e*Math.PI*2,g(n,e,f,a,t),g(n+.01,e,f,a,y),v.subVectors(y,t),G.addVectors(y,t),x.crossVectors(v,G),G.crossVectors(x,v),x.normalize(),G.normalize(),
13769 n=0;n<=d;++n){var w=n/d*Math.PI*2,O=-b*Math.cos(w),w=b*Math.sin(w);l.x=t.x+(O*G.x+w*x.x);l.y=t.y+(O*G.y+w*x.y);l.z=t.z+(O*G.z+w*x.z);k.push(l.x,l.y,l.z);z.subVectors(l,t).normalize();m.push(z.x,z.y,z.z);u.push(q/c);u.push(n/d)}for(n=1;n<=c;n++)for(q=1;q<=d;q++)a=(d+1)*n+(q-1),b=(d+1)*n+q,e=(d+1)*(n-1)+q,h.push((d+1)*(n-1)+(q-1),a,e),h.push(a,b,e);this.setIndex(h);this.addAttribute("position",new C(k,3));this.addAttribute("normal",new C(m,3));this.addAttribute("uv",new C(u,2))}function Nc(a,b,c,d,
13770 e){M.call(this);this.type="TorusGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};this.fromBufferGeometry(new Vb(a,b,c,d,e));this.mergeVertices()}function Vb(a,b,c,d,e){I.call(this);this.type="TorusBufferGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};a=a||100;b=b||40;c=Math.floor(c)||8;d=Math.floor(d)||6;e=e||2*Math.PI;var f=[],g=[],h=[],k=[],m=new p,u=new p,q=new p,n,l;for(n=0;n<=c;n++)for(l=0;l<=d;l++){var z=l/d*e,t=n/c*Math.PI*
13771 2;u.x=(a+b*Math.cos(t))*Math.cos(z);u.y=(a+b*Math.cos(t))*Math.sin(z);u.z=b*Math.sin(t);g.push(u.x,u.y,u.z);m.x=a*Math.cos(z);m.y=a*Math.sin(z);q.subVectors(u,m).normalize();h.push(q.x,q.y,q.z);k.push(l/d);k.push(n/c)}for(n=1;n<=c;n++)for(l=1;l<=d;l++)a=(d+1)*(n-1)+l-1,b=(d+1)*(n-1)+l,e=(d+1)*n+l,f.push((d+1)*n+l-1,a,e),f.push(a,b,e);this.setIndex(f);this.addAttribute("position",new C(g,3));this.addAttribute("normal",new C(h,3));this.addAttribute("uv",new C(k,2))}function db(a,b){M.call(this);this.type=
13772 "ExtrudeGeometry";this.parameters={shapes:a,options:b};this.fromBufferGeometry(new Fa(a,b));this.mergeVertices()}function Fa(a,b){"undefined"!==typeof a&&(I.call(this),this.type="ExtrudeBufferGeometry",a=Array.isArray(a)?a:[a],this.addShapeList(a,b),this.computeVertexNormals())}function Oc(a,b){M.call(this);this.type="TextGeometry";this.parameters={text:a,parameters:b};this.fromBufferGeometry(new Wb(a,b));this.mergeVertices()}function Wb(a,b){b=b||{};var c=b.font;if(!1===(c&&c.isFont))return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),
13773 new M;c=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);Fa.call(this,c,b);this.type="TextBufferGeometry"}function Pc(a,b,c,d,e,f,g){M.call(this);this.type="SphereGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};this.fromBufferGeometry(new nb(a,b,c,d,e,f,g));this.mergeVertices()}
13774 function nb(a,b,c,d,e,f,g){I.call(this);this.type="SphereBufferGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};a=a||50;b=Math.max(3,Math.floor(b)||8);c=Math.max(2,Math.floor(c)||6);d=void 0!==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,m,u=0,q=[],n=new p,l=new p,z=[],t=[],y=[],x=[];for(m=0;m<=c;m++){var v=[],G=m/c;for(k=0;k<=b;k++){var w=k/b;n.x=-a*Math.cos(d+w*e)*Math.sin(f+G*g);n.y=a*Math.cos(f+
13775 G*g);n.z=a*Math.sin(d+w*e)*Math.sin(f+G*g);t.push(n.x,n.y,n.z);l.set(n.x,n.y,n.z).normalize();y.push(l.x,l.y,l.z);x.push(w,1-G);v.push(u++)}q.push(v)}for(m=0;m<c;m++)for(k=0;k<b;k++)a=q[m][k+1],d=q[m][k],e=q[m+1][k],g=q[m+1][k+1],(0!==m||0<f)&&z.push(a,d,g),(m!==c-1||h<Math.PI)&&z.push(d,e,g);this.setIndex(z);this.addAttribute("position",new C(t,3));this.addAttribute("normal",new C(y,3));this.addAttribute("uv",new C(x,2))}function Qc(a,b,c,d,e,f){M.call(this);this.type="RingGeometry";this.parameters=
13776 {innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};this.fromBufferGeometry(new Xb(a,b,c,d,e,f));this.mergeVertices()}function Xb(a,b,c,d,e,f){I.call(this);this.type="RingBufferGeometry";this.parameters={innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};a=a||20;b=b||50;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=[],m=[],u=a,q=(b-a)/d,n=new p,l=new D,z,t;for(z=
13777 0;z<=d;z++){for(t=0;t<=c;t++)a=e+t/c*f,n.x=u*Math.cos(a),n.y=u*Math.sin(a),h.push(n.x,n.y,n.z),k.push(0,0,1),l.x=(n.x/b+1)/2,l.y=(n.y/b+1)/2,m.push(l.x,l.y);u+=q}for(z=0;z<d;z++)for(b=z*(c+1),t=0;t<c;t++)a=t+b,e=a+c+1,f=a+c+2,u=a+1,g.push(a,e,u),g.push(e,f,u);this.setIndex(g);this.addAttribute("position",new C(h,3));this.addAttribute("normal",new C(k,3));this.addAttribute("uv",new C(m,2))}function Rc(a,b,c,d){M.call(this);this.type="LatheGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};
13778 this.fromBufferGeometry(new Yb(a,b,c,d));this.mergeVertices()}function Yb(a,b,c,d){I.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=Y.clamp(d,0,2*Math.PI);var e=[],f=[],g=[],h=1/b,k=new p,m=new D,u,q;for(u=0;u<=b;u++){q=c+u*h*d;var n=Math.sin(q),l=Math.cos(q);for(q=0;q<=a.length-1;q++)k.x=a[q].x*n,k.y=a[q].y,k.z=a[q].x*l,f.push(k.x,k.y,k.z),m.x=u/b,m.y=q/(a.length-1),g.push(m.x,m.y)}for(u=0;u<b;u++)for(q=
13779 0;q<a.length-1;q++)c=q+u*a.length,h=c+a.length,k=c+a.length+1,m=c+1,e.push(c,h,m),e.push(h,k,m);this.setIndex(e);this.addAttribute("position",new C(f,3));this.addAttribute("uv",new C(g,2));this.computeVertexNormals();if(d===2*Math.PI)for(d=this.attributes.normal.array,e=new p,f=new p,g=new p,c=b*a.length*3,q=u=0;u<a.length;u++,q+=3)e.x=d[q+0],e.y=d[q+1],e.z=d[q+2],f.x=d[c+q+0],f.y=d[c+q+1],f.z=d[c+q+2],g.addVectors(e,f).normalize(),d[q+0]=d[c+q+0]=g.x,d[q+1]=d[c+q+1]=g.y,d[q+2]=d[c+q+2]=g.z}function Zb(a,
13780 b){M.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 $b(a,b));this.mergeVertices()}function $b(a,b){function c(a){var c,h,m=e.length/3;a=a.extractPoints(b);var l=a.shape,t=a.holes;if(!1===za.isClockWise(l))for(l=l.reverse(),a=0,c=t.length;a<c;a++)h=t[a],!0===za.isClockWise(h)&&(t[a]=h.reverse());var p=za.triangulateShape(l,t);
13781 a=0;for(c=t.length;a<c;a++)h=t[a],l=l.concat(h);a=0;for(c=l.length;a<c;a++)h=l[a],e.push(h.x,h.y,0),f.push(0,0,1),g.push(h.x,h.y);a=0;for(c=p.length;a<c;a++)l=p[a],d.push(l[0]+m,l[1]+m,l[2]+m),k+=3}I.call(this);this.type="ShapeBufferGeometry";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 m=0;m<a.length;m++)c(a[m]),this.addGroup(h,k,m),h+=k,k=0;this.setIndex(d);this.addAttribute("position",new C(e,3));this.addAttribute("normal",
13782 new C(f,3));this.addAttribute("uv",new C(g,2))}function ac(a,b){I.call(this);this.type="EdgesGeometry";this.parameters={thresholdAngle:b};var c=[],d=Math.cos(Y.DEG2RAD*(void 0!==b?b:1)),e=[0,0],f={},g,h,k=["a","b","c"],m;a.isBufferGeometry?(m=new M,m.fromBufferGeometry(a)):m=a.clone();m.mergeVertices();m.computeFaceNormals();var u=m.vertices;m=m.faces;for(var l=0,n=m.length;l<n;l++)for(var r=m[l],p=0;3>p;p++)g=r[k[p]],h=r[k[(p+1)%3]],e[0]=Math.min(g,h),e[1]=Math.max(g,h),g=e[0]+","+e[1],void 0===
13783 f[g]?f[g]={index1:e[0],index2:e[1],face1:l,face2:void 0}:f[g].face2=l;for(g in f)if(e=f[g],void 0===e.face2||m[e.face1].normal.dot(m[e.face2].normal)<=d)k=u[e.index1],c.push(k.x,k.y,k.z),k=u[e.index2],c.push(k.x,k.y,k.z);this.addAttribute("position",new C(c,3))}function ob(a,b,c,d,e,f,g,h){M.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 Wa(a,b,c,d,e,
13784 f,g,h));this.mergeVertices()}function Wa(a,b,c,d,e,f,g,h){function k(c){var e,f,k,t=new D,E=new p,F=0,aa=!0===c?a:b,R=!0===c?1:-1;f=z;for(e=1;e<=d;e++)l.push(0,y*R,0),n.push(0,R,0),r.push(.5,.5),z++;k=z;for(e=0;e<=d;e++){var C=e/d*h+g,B=Math.cos(C),C=Math.sin(C);E.x=aa*C;E.y=y*R;E.z=aa*B;l.push(E.x,E.y,E.z);n.push(0,R,0);t.x=.5*B+.5;t.y=.5*C*R+.5;r.push(t.x,t.y);z++}for(e=0;e<d;e++)t=f+e,E=k+e,!0===c?u.push(E,E+1,t):u.push(E+1,E,t),F+=3;m.addGroup(x,F,!0===c?1:2);x+=F}I.call(this);this.type="CylinderBufferGeometry";
13785 this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};var m=this;a=void 0!==a?a:20;b=void 0!==b?b:20;c=void 0!==c?c:100;d=Math.floor(d)||8;e=Math.floor(e)||1;f=void 0!==f?f:!1;g=void 0!==g?g:0;h=void 0!==h?h:2*Math.PI;var u=[],l=[],n=[],r=[],z=0,t=[],y=c/2,x=0;(function(){var f,k,w=new p,O=new p,S=0,E=(b-a)/c;for(k=0;k<=e;k++){var F=[],aa=k/e,C=aa*(b-a)+a;for(f=0;f<=d;f++){var D=f/d,B=D*h+g,I=Math.sin(B),B=Math.cos(B);O.x=C*
13786 I;O.y=-aa*c+y;O.z=C*B;l.push(O.x,O.y,O.z);w.set(I,E,B).normalize();n.push(w.x,w.y,w.z);r.push(D,1-aa);F.push(z++)}t.push(F)}for(f=0;f<d;f++)for(k=0;k<e;k++)w=t[k+1][f],O=t[k+1][f+1],E=t[k][f+1],u.push(t[k][f],w,E),u.push(w,O,E),S+=6;m.addGroup(x,S,0);x+=S})();!1===f&&(0<a&&k(!0),0<b&&k(!1));this.setIndex(u);this.addAttribute("position",new C(l,3));this.addAttribute("normal",new C(n,3));this.addAttribute("uv",new C(r,2))}function Sc(a,b,c,d,e,f,g){ob.call(this,0,a,b,c,d,e,f,g);this.type="ConeGeometry";
13787 this.parameters={radius:a,height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Tc(a,b,c,d,e,f,g){Wa.call(this,0,a,b,c,d,e,f,g);this.type="ConeBufferGeometry";this.parameters={radius:a,height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Uc(a,b,c,d){M.call(this);this.type="CircleGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};this.fromBufferGeometry(new bc(a,b,c,d));this.mergeVertices()}function bc(a,
13788 b,c,d){I.call(this);this.type="CircleBufferGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};a=a||50;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,m,u=new p,l=new D;f.push(0,0,0);g.push(0,0,1);h.push(.5,.5);m=0;for(k=3;m<=b;m++,k+=3){var n=c+m/b*d;u.x=a*Math.cos(n);u.y=a*Math.sin(n);f.push(u.x,u.y,u.z);g.push(0,0,1);l.x=(f[k]/a+1)/2;l.y=(f[k+1]/a+1)/2;h.push(l.x,l.y)}for(k=1;k<=b;k++)e.push(k,k+1,0);this.setIndex(e);this.addAttribute("position",
13789 new C(f,3));this.addAttribute("normal",new C(g,3));this.addAttribute("uv",new C(h,2))}function cc(a){Ea.call(this,{uniforms:Ha.merge([V.lights,{opacity:{value:1}}]),vertexShader:U.shadow_vert,fragmentShader:U.shadow_frag});this.transparent=this.lights=!0;Object.defineProperties(this,{opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(a){this.uniforms.opacity.value=a}}});this.setValues(a)}function dc(a){Ea.call(this,a);this.type="RawShaderMaterial"}function Ra(a){Z.call(this);
13790 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 D(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=this.alphaMap=this.metalnessMap=this.roughnessMap=null;
13791 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 pb(a){Ra.call(this);this.defines={PHYSICAL:""};this.type="MeshPhysicalMaterial";this.reflectivity=.5;this.clearCoatRoughness=this.clearCoat=0;this.setValues(a)}function ta(a){Z.call(this);this.type="MeshPhongMaterial";this.color=new H(16777215);this.specular=new H(1118481);this.shininess=
13792 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 D(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=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap=
13793 "round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function qb(a){ta.call(this);this.defines={TOON:""};this.type="MeshToonMaterial";this.gradientMap=null;this.setValues(a)}function rb(a){Z.call(this,a);this.type="MeshNormalMaterial";this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new D(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.skinning=
13794 this.lights=this.fog=!1;this.setValues(a)}function sb(a){Z.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=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=
13795 this.morphTargets=this.skinning=!1;this.setValues(a)}function tb(a){Z.call(this);this.type="LineDashedMaterial";this.color=new H(16777215);this.scale=this.linewidth=1;this.dashSize=3;this.gapSize=1;this.lights=!1;this.setValues(a)}function Zd(a,b,c){var d=this,e=!1,f=0,g=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,f,g);if(f===
13796 g&&(e=!1,void 0!==d.onLoad))d.onLoad()};this.itemError=function(a){if(void 0!==d.onError)d.onError(a)}}function ua(a){this.manager=void 0!==a?a:Aa}function Qe(a){this.manager=void 0!==a?a:Aa;this._parser=null}function $d(a){this.manager=void 0!==a?a:Aa;this._parser=null}function Vc(a){this.manager=void 0!==a?a:Aa}function ae(a){this.manager=void 0!==a?a:Aa}function sd(a){this.manager=void 0!==a?a:Aa}function ma(a,b){B.call(this);this.type="Light";this.color=new H(a);this.intensity=void 0!==b?b:1;
13797 this.receiveShadow=void 0}function td(a,b,c){ma.call(this,a,c);this.type="HemisphereLight";this.castShadow=void 0;this.position.copy(B.DefaultUp);this.updateMatrix();this.groundColor=new H(b)}function ub(a){this.camera=a;this.bias=0;this.radius=1;this.mapSize=new D(512,512);this.map=null;this.matrix=new J}function ud(){ub.call(this,new xa(50,1,.5,500))}function vd(a,b,c,d,e,f){ma.call(this,a,b);this.type="SpotLight";this.position.copy(B.DefaultUp);this.updateMatrix();this.target=new B;Object.defineProperty(this,
13798 "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 ud}function wd(a,b,c,d){ma.call(this,a,b);this.type="PointLight";Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(a){this.intensity=a/(4*Math.PI)}});this.distance=void 0!==c?c:0;this.decay=void 0!==d?d:1;this.shadow=new ub(new xa(90,
13799 1,.5,500))}function xd(){ub.call(this,new Jb(-5,5,5,-5,.5,500))}function yd(a,b){ma.call(this,a,b);this.type="DirectionalLight";this.position.copy(B.DefaultUp);this.updateMatrix();this.target=new B;this.shadow=new xd}function zd(a,b){ma.call(this,a,b);this.type="AmbientLight";this.castShadow=void 0}function Ad(a,b,c,d){ma.call(this,a,b);this.type="RectAreaLight";this.position.set(0,1,0);this.updateMatrix();this.width=void 0!==c?c:10;this.height=void 0!==d?d:10}function Da(a,b,c,d){this.parameterPositions=
13800 a;this._cachedIndex=0;this.resultBuffer=void 0!==d?d:new b.constructor(c);this.sampleValues=b;this.valueSize=c}function Bd(a,b,c,d){Da.call(this,a,b,c,d);this._offsetNext=this._weightNext=this._offsetPrev=this._weightPrev=-0}function Wc(a,b,c,d){Da.call(this,a,b,c,d)}function Cd(a,b,c,d){Da.call(this,a,b,c,d)}function vb(a,b,c,d){if(void 0===a)throw Error("track name is undefined");if(void 0===b||0===b.length)throw Error("no keyframes in track named "+a);this.name=a;this.times=va.convertArray(b,this.TimeBufferType);
13801 this.values=va.convertArray(c,this.ValueBufferType);this.setInterpolation(d||this.DefaultInterpolation);this.validate();this.optimize()}function ec(a,b,c,d){vb.call(this,a,b,c,d)}function Dd(a,b,c,d){Da.call(this,a,b,c,d)}function Xc(a,b,c,d){vb.call(this,a,b,c,d)}function fc(a,b,c,d){vb.call(this,a,b,c,d)}function Ed(a,b,c,d){vb.call(this,a,b,c,d)}function Fd(a,b,c){vb.call(this,a,b,c)}function Gd(a,b,c,d){vb.call(this,a,b,c,d)}function wb(a,b,c,d){vb.apply(this,arguments)}function Ba(a,b,c){this.name=
13802 a;this.tracks=c;this.duration=void 0!==b?b:-1;this.uuid=Y.generateUUID();0>this.duration&&this.resetDuration();this.optimize()}function Hd(a){this.manager=void 0!==a?a:Aa;this.textures={}}function be(a){this.manager=void 0!==a?a:Aa}function gc(){this.onLoadStart=function(){};this.onLoadProgress=function(){};this.onLoadComplete=function(){}}function ce(a){"boolean"===typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),a=void 0);this.manager=void 0!==
13803 a?a:Aa;this.withCredentials=!1}function Re(a){this.manager=void 0!==a?a:Aa;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 xb(a,b,c,d){var e=1-a;return e*e*b+2*(1-a)*a*c+a*a*d}function yb(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 na(){this.arcLengthDivisions=200}function Sa(a,b){this.arcLengthDivisions=200;this.v1=a;this.v2=b}function Yc(){this.arcLengthDivisions=200;this.curves=
13804 [];this.autoClose=!1}function Xa(a,b,c,d,e,f,g,h){this.arcLengthDivisions=200;this.aX=a;this.aY=b;this.xRadius=c;this.yRadius=d;this.aStartAngle=e;this.aEndAngle=f;this.aClockwise=g;this.aRotation=h||0}function zb(a){this.arcLengthDivisions=200;this.points=void 0===a?[]:a}function hc(a,b,c,d){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2=c;this.v3=d}function ic(a,b,c){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2=c}function Zc(a){Yc.call(this);this.currentPoint=new D;a&&this.fromPoints(a)}
13805 function Ab(){Zc.apply(this,arguments);this.holes=[]}function de(){this.subPaths=[];this.currentPath=null}function ee(a){this.data=a}function Te(a){this.manager=void 0!==a?a:Aa}function fe(a){this.manager=void 0!==a?a:Aa}function Ue(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new xa;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new xa;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=!1}function Id(a,b,c){B.call(this);this.type="CubeCamera";
13806 var d=new xa(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new p(1,0,0));this.add(d);var e=new xa(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new p(-1,0,0));this.add(e);var f=new xa(90,1,a,b);f.up.set(0,0,1);f.lookAt(new p(0,1,0));this.add(f);var g=new xa(90,1,a,b);g.up.set(0,0,-1);g.lookAt(new p(0,-1,0));this.add(g);var h=new xa(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new p(0,0,1));this.add(h);var k=new xa(90,1,a,b);k.up.set(0,-1,0);k.lookAt(new p(0,0,-1));this.add(k);this.renderTarget=new Eb(c,c,{format:1022,magFilter:1006,
13807 minFilter:1006});this.renderTarget.texture.name="CubeCamera";this.updateCubeMap=function(a,b){null===this.parent&&this.updateMatrixWorld();var c=this.renderTarget,n=c.texture.generateMipmaps;c.texture.generateMipmaps=!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=n;c.activeCubeFace=5;a.render(b,k,c);a.setRenderTarget(null)}}function ge(a){xa.call(this);
13808 this.enabled=!1;this.cameras=a||[]}function he(){B.call(this);this.type="AudioListener";this.context=ie.getContext();this.gain=this.context.createGain();this.gain.connect(this.context.destination);this.filter=null}function jc(a){B.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.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";
13809 this.filters=[]}function je(a){jc.call(this,a);this.panner=this.context.createPanner();this.panner.connect(this.gain)}function ke(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 le(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=
13810 new a(4*c);this._mixBufferRegion=b;this.referenceCount=this.useCount=this.cumulativeWeight=0}function Ve(a,b,c){c=c||oa.parseTrackName(b);this._targetGroup=a;this._bindings=a.subscribe_(b,c)}function oa(a,b,c){this.path=b;this.parsedPath=c||oa.parseTrackName(b);this.node=oa.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function We(a){this.uuid=Y.generateUUID();this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var b={};this._indicesByUUID=b;for(var c=0,d=arguments.length;c!==
13811 d;++c)b[arguments[c].uuid]=c;this._paths=[];this._parsedPaths=[];this._bindings=[];this._bindingsIndicesByPath={};var e=this;this.stats={objects:{get total(){return e._objects.length},get inUse(){return this.total-e.nCachedObjects_}},get bindingsPerObject(){return e._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=
13812 d}this._interpolantSettings=d;this._interpolants=c;this._propertyBindings=Array(b);this._weightInterpolant=this._timeScaleInterpolant=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();
13813 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."),a=b);this.value=a}function me(){I.call(this);this.type="InstancedBufferGeometry";this.maxInstancedCount=void 0}function ne(a,b,c,d){this.uuid=Y.generateUUID();this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0===d}function kc(a,b){this.uuid=Y.generateUUID();this.array=a;this.stride=b;this.count=void 0!==a?a.length/b:0;this.dynamic=!1;this.updateRange=
13814 {offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function oe(a,b,c){kc.call(this,a,b);this.meshPerAttribute=c||1}function pe(a,b,c){L.call(this,a,b);this.meshPerAttribute=c||1}function Ze(a,b,c,d){this.ray=new hb(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}}})}
13815 function $e(a,b){return a.distance-b.distance}function qe(a,b,c,d){if(!1!==a.visible&&(a.raycast(b,c),!0===d)){a=a.children;d=0;for(var e=a.length;d<e;d++)qe(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 ra(a,
13816 b){Ca.call(this,a,b);this.animationsMap={};this.animationsList=[];var c=this.geometry.morphTargets.length;this.createAnimation("__default",0,c-1,c/1);this.setAnimationWeight("__default",1)}function $c(a){B.call(this);this.material=a;this.render=function(a){}}function ad(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c: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 I;b=new C(6*b,3);c.addAttribute("position",
13817 b);da.call(this,c,new ha({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function lc(a){B.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;a=new I;for(var 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],c=0,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 C(b,3));b=new ha({fog:!1});this.cone=new da(a,b);this.add(this.cone);
13818 this.update()}function mc(a){this.bones=this.getBoneList(a);for(var b=new I,c=[],d=[],e=new H(0,0,1),f=new H(0,1,0),g=0;g<this.bones.length;g++){var h=this.bones[g];h.parent&&h.parent.isBone&&(c.push(0,0,0),c.push(0,0,0),d.push(e.r,e.g,e.b),d.push(f.r,f.g,f.b))}b.addAttribute("position",new C(c,3));b.addAttribute("color",new C(d,3));c=new ha({vertexColors:2,depthTest:!1,depthWrite:!1,transparent:!0});da.call(this,b,c);this.root=a;this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.update()}function nc(a,
13819 b){this.light=a;this.light.updateMatrixWorld();var c=new nb(b,4,2),d=new Na({wireframe:!0,fog:!1});d.color.copy(this.light.color);Ca.call(this,c,d);this.matrix=this.light.matrixWorld;this.matrixAutoUpdate=!1}function oc(a){B.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;a=new ha({color:a.color});var b=new I;b.addAttribute("position",new L(new Float32Array(15),3));this.add(new ya(b,a));this.update()}function pc(a,b){B.call(this);this.light=
13820 a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;var c=new mb(b);c.rotateY(.5*Math.PI);var d=new Na({vertexColors:2,wireframe:!0}),e=c.getAttribute("position"),e=new Float32Array(3*e.count);c.addAttribute("color",new L(e,3));this.add(new Ca(c,d));this.update()}function bd(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,m=0,u=-g;k<=b;k++,u+=f){a.push(-g,0,u,g,0,u);a.push(u,0,-g,u,0,g);
13821 var l=k===e?c:d;l.toArray(h,m);m+=3;l.toArray(h,m);m+=3;l.toArray(h,m);m+=3;l.toArray(h,m);m+=3}b=new I;b.addAttribute("position",new C(a,3));b.addAttribute("color",new C(h,3));c=new ha({vertexColors:2});da.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,m,u,l,n;for(u=0;u<=b;u++)m=u/b*2*Math.PI,k=Math.sin(m)*a,m=Math.cos(m)*a,g.push(0,0,0),g.push(k,0,m),n=u&1?e:f,h.push(n.r,n.g,n.b),h.push(n.r,n.g,n.b);
13822 for(u=0;u<=c;u++)for(n=u&1?e:f,l=a-a/c*u,b=0;b<d;b++)m=b/d*2*Math.PI,k=Math.sin(m)*l,m=Math.cos(m)*l,g.push(k,0,m),h.push(n.r,n.g,n.b),m=(b+1)/d*2*Math.PI,k=Math.sin(m)*l,m=Math.cos(m)*l,g.push(k,0,m),h.push(n.r,n.g,n.b);a=new I;a.addAttribute("position",new C(g,3));a.addAttribute("color",new C(h,3));g=new ha({vertexColors:2});da.call(this,a,g)}function cd(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:
13823 console.warn("THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.");c=new I;b=new C(6*b,3);c.addAttribute("position",b);da.call(this,c,new ha({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function qc(a,b){B.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;void 0===b&&(b=1);var c=new I;c.addAttribute("position",new C([-b,b,0,b,b,0,b,-b,0,-b,-b,0,-b,b,0],3));var d=new ha({fog:!1});
13824 this.add(new ya(c,d));c=new I;c.addAttribute("position",new C([0,0,0,0,0,1],3));this.add(new ya(c,d));this.update()}function dd(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 I,e=new ha({color:16777215,vertexColors:1}),f=[],g=[],h={},k=new H(16755200),m=new H(16711680),u=new H(43775),l=new H(16777215),n=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",
13825 k);b("f4","f3",k);b("f3","f1",k);b("n1","f1",k);b("n2","f2",k);b("n3","f3",k);b("n4","f4",k);b("p","n1",m);b("p","n2",m);b("p","n3",m);b("p","n4",m);b("u1","u2",u);b("u2","u3",u);b("u3","u1",u);b("c","t",l);b("p","c",n);b("cn1","cn2",n);b("cn3","cn4",n);b("cf1","cf2",n);b("cf3","cf4",n);d.addAttribute("position",new C(f,3));d.addAttribute("color",new C(g,3));da.call(this,d,e);this.camera=a;this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix();this.matrix=a.matrixWorld;this.matrixAutoUpdate=
13826 !1;this.pointMap=h;this.update()}function Bb(a,b){this.object=a;void 0===b&&(b=16776960);var c=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]),d=new Float32Array(24),e=new I;e.setIndex(new L(c,1));e.addAttribute("position",new L(d,3));da.call(this,e,new ha({color:b}));this.matrixAutoUpdate=!1;this.update()}function Cb(a,b,c,d,e,f){B.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 I,Ld.addAttribute("position",new C([0,
13827 0,0,0,1,0],3)),re=new Wa(0,.5,1,5,1),re.translate(0,-.5,0));this.position.copy(b);this.line=new ya(Ld,new ha({color:d}));this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new Ca(re,new Na({color:d}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);this.setDirection(a);this.setLength(c,e,f)}function Md(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 I;a.addAttribute("position",new C(b,3));a.addAttribute("color",new C([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));b=new ha({vertexColors:2});
13828 da.call(this,a,b)}function se(){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,m,u){e=((f-e)/k-(g-e)/(k+m)+(g-f)/m)*m;h=((g-f)/m-(h-f)/(m+u)+(h-g)/u)*m;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 Ja(a){this.arcLengthDivisions=200;this.points=a||[];this.closed=!1}function ed(a,b,c,d){this.arcLengthDivisions=200;this.v0=a;this.v1=
13829 b;this.v2=c;this.v3=d}function fd(a,b,c){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2=c}function gd(a,b){this.arcLengthDivisions=200;this.v1=a;this.v2=b}function Nd(a,b,c,d,e,f){Xa.call(this,a,b,c,c,d,e,f)}function df(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");Ja.call(this,a);this.type="catmullrom";this.closed=!0}function ef(a){console.warn("THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");Ja.call(this,
13830 a);this.type="catmullrom"}function te(a){console.warn("THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.");Ja.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});void 0===Function.prototype.name&&Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1]}});
13831 void 0===Object.assign&&function(){Object.assign=function(a){if(void 0===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(sa.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)},
13832 hasEventListener:function(a,b){if(void 0===this._listeners)return!1;var c=this._listeners;return void 0!==c[a]&&-1!==c[a].indexOf(b)},removeEventListener:function(a,b){if(void 0!==this._listeners){var c=this._listeners[a];if(void 0!==c){var d=c.indexOf(b);-1!==d&&c.splice(d,1)}}},dispatchEvent:function(a){if(void 0!==this._listeners){var b=this._listeners[a.type];if(void 0!==b){a.target=this;var c=[],d,e=b.length;for(d=0;d<e;d++)c[d]=b[d];for(d=0;d<e;d++)c[d].call(this,a)}}}});var Y={DEG2RAD:Math.PI/
13833 180,RAD2DEG:180/Math.PI,generateUUID:function(){var a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),b=Array(36),c=0,d;return function(){for(var e=0;36>e;e++)8===e||13===e||18===e||23===e?b[e]="-":14===e?b[e]="4":(2>=c&&(c=33554432+16777216*Math.random()|0),d=c&15,c>>=4,b[e]=a[19===e?d&3|8:d]);return b.join("")}}(),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-
13834 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,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*Y.DEG2RAD},radToDeg:function(a){return a*Y.RAD2DEG},
13835 isPowerOfTwo:function(a){return 0===(a&a-1)&&0!==a},nearestPowerOfTwo:function(a){return Math.pow(2,Math.round(Math.log(a)/Math.LN2))},nextPowerOfTwo:function(a){a--;a|=a>>1;a|=a>>2;a|=a>>4;a|=a>>8;a|=a>>16;a++;return a}};Object.defineProperties(D.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(D.prototype,{isVector2:!0,set:function(a,b){this.x=a;this.y=b;return this},setScalar:function(a){this.y=
13836 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;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,
13837 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},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."),
13838 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;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)},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=
13839 Math.max(this.x,a.x);this.y=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 D,b=new D;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.multiplyScalar(Math.max(a,Math.min(b,c))/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);
13840 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)},lengthManhattan:function(){return Math.abs(this.x)+
13841 Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length())},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},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=
13842 (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);
13843 return this},rotateAround:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=this.x-a.x,f=this.y-a.y;this.x=e*c-f*d+a.x;this.y=e*d+f*c+a.y;return this}});var jf=0;X.DEFAULT_IMAGE=void 0;X.DEFAULT_MAPPING=300;Object.defineProperty(X.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(X.prototype,sa.prototype,{constructor:X,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);
13844 this.mapping=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.generateMipmaps=a.generateMipmaps;this.premultiplyAlpha=a.premultiplyAlpha;this.flipY=a.flipY;this.unpackAlignment=a.unpackAlignment;this.encoding=a.encoding;return this},toJSON:function(a){if(void 0!==a.textures[this.uuid])return a.textures[this.uuid];var b={metadata:{version:4.5,
13845 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],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var c=this.image;void 0===c.uuid&&(c.uuid=Y.generateUUID());if(void 0===a.images[c.uuid]){var d=a.images,e=c.uuid,f=c.uuid,g;void 0!==c.toDataURL?g=c:(g=document.createElementNS("http://www.w3.org/1999/xhtml",
13846 "canvas"),g.width=c.width,g.height=c.height,g.getContext("2d").drawImage(c,0,0,c.width,c.height));g=2048<g.width||2048<g.height?g.toDataURL("image/jpeg",.6):g.toDataURL("image/png");d[e]={uuid:f,url:g}}b.image=c.uuid}return a.textures[this.uuid]=b},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(a){if(300===this.mapping){a.multiply(this.repeat);a.add(this.offset);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=
13847 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)%2)?Math.ceil(a.y)-a.y:a.y-Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}});Object.assign(ga.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},
13848 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;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,
13849 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."),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},
13850 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,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*=
13851 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]*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/
13852 b);return this},setAxisAngleFromRotationMatrix:function(a){var b,c,d;a=a.elements;var e=a[0];d=a[4];var f=a[8],g=a[1],h=a[5],k=a[9];c=a[2];b=a[6];var m=a[10];if(.01>Math.abs(d-g)&&.01>Math.abs(f-c)&&.01>Math.abs(k-b)){if(.1>Math.abs(d+g)&&.1>Math.abs(f+c)&&.1>Math.abs(k+b)&&.1>Math.abs(e+h+m-3))return this.set(1,0,0,0),this;a=Math.PI;e=(e+1)/2;h=(h+1)/2;m=(m+1)/2;d=(d+g)/4;f=(f+c)/4;k=(k+b)/4;e>h&&e>m?.01>e?(b=0,d=c=.707106781):(b=Math.sqrt(e),c=d/b,d=f/b):h>m?.01>h?(b=.707106781,c=0,d=.707106781):
13853 (c=Math.sqrt(h),b=d/c,d=k/c):.01>m?(c=b=.707106781,d=0):(d=Math.sqrt(m),b=f/d,c=k/d);this.set(b,c,d,a);return this}a=Math.sqrt((b-k)*(b-k)+(f-c)*(f-c)+(g-d)*(g-d));.001>Math.abs(a)&&(a=1);this.x=(b-k)/a;this.y=(f-c)/a;this.z=(g-d)/a;this.w=Math.acos((e+h+m-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,
13854 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,this.w));return this},clampScalar:function(){var a=new ga,b=new ga;return function(c,d){a.set(c,c,c,c);b.set(d,d,d,d);return this.clamp(a,b)}}(),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},
13855 ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);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},
13856 negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;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)},lengthManhattan: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())},
13857 setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(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=
13858 []);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,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(Db.prototype,sa.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,
13859 0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=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"})}});Eb.prototype=Object.create(Db.prototype);Eb.prototype.constructor=Eb;Eb.prototype.isWebGLRenderTargetCube=!0;Object.assign(qa,{slerp:function(a,b,
13860 c,d){return c.copy(a).slerp(b,d)},slerpFlat:function(a,b,c,d,e,f,g){var h=c[d+0],k=c[d+1],m=c[d+2];c=c[d+3];d=e[f+0];var u=e[f+1],l=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==u||m!==l){f=1-g;var n=h*d+k*u+m*l+c*e,r=0<=n?1:-1,p=1-n*n;p>Number.EPSILON&&(p=Math.sqrt(p),n=Math.atan2(p,n*r),f=Math.sin(f*n)/p,g=Math.sin(g*n)/p);r*=g;h=h*f+d*r;k=k*f+u*r;m=m*f+l*r;c=c*f+e*r;f===1-g&&(g=1/Math.sqrt(h*h+k*k+m*m+c*c),h*=g,k*=g,m*=g,c*=g)}a[b]=h;a[b+1]=k;a[b+2]=m;a[b+3]=c}});Object.defineProperties(qa.prototype,{x:{get:function(){return this._x},
13861 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(qa.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,
13862 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(!1===(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,f=a.order,g=Math.cos,h=Math.sin,k=g(c/2),m=g(d/2),g=g(e/2),c=h(c/2),d=h(d/2),e=h(e/2);"XYZ"===f?(this._x=c*m*g+k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g-c*d*e):"YXZ"===f?(this._x=c*m*g+
13863 k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g+c*d*e):"ZXY"===f?(this._x=c*m*g-k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g-c*d*e):"ZYX"===f?(this._x=c*m*g-k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g+c*d*e):"YZX"===f?(this._x=c*m*g+k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g-c*d*e):"XZY"===f&&(this._x=c*m*g-k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g+c*d*e);if(!1!==b)this.onChangeCallback();return this},setFromAxisAngle:function(a,
13864 b){var c=b/2,d=Math.sin(c);this._x=a.x*d;this._y=a.y*d;this._z=a.z*d;this._w=Math.cos(c);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],m=c+f+b;0<m?(c=.5/Math.sqrt(m+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=
13865 .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*=
13866 -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},
13867 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,f=a._w,g=b._x,h=b._y,k=b._z,m=b._w;this._x=c*m+f*g+d*k-e*h;this._y=d*m+f*h+e*g-c*k;this._z=e*m+f*k+c*h-d*g;this._w=f*m-c*g-d*h-e*k;this.onChangeCallback();
13868 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;var h=Math.sqrt(1-g*g);if(.001>Math.abs(h))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 k=Math.atan2(h,g),g=Math.sin((1-b)*k)/h,h=Math.sin(b*
13869 k)/h;this._w=f*g+this._w*h;this._x=c*g+this._x*h;this._y=d*g+this._y*h;this._z=e*g+this._z*h;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=
13870 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;
13871 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},
13872 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=
13873 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 qa;return function(b){!1===(b&&b.isEuler)&&console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");
13874 return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a=new qa;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;this.x=a[0]*b+a[4]*c+a[8]*d+a[12];this.y=a[1]*b+a[5]*c+a[9]*d+a[13];this.z=a[2]*b+a[6]*c+a[10]*d+a[14];
13875 return this.divideScalar(a[3]*b+a[7]*c+a[11]*d+a[15])},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,m=a*d+e*c-f*b,b=-e*b-f*c-g*d;this.x=h*a+b*-e+k*-g-m*-f;this.y=k*a+b*-f+m*-e-h*-g;this.z=m*a+b*-g+h*-f-k*-e;return this},project:function(){var a=new J;return function(b){a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyMatrix4(a)}}(),unproject:function(){var a=new J;return function(b){a.multiplyMatrices(b.matrixWorld,
13876 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=
13877 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.multiplyScalar(Math.max(a,Math.min(b,c))/c)},floor:function(){this.x=Math.floor(this.x);
13878 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=-this.x;
13879 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)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*
13880 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){if(void 0!==b)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(a,b);var c=this.x,d=this.y,e=this.z;this.x=d*a.z-e*a.y;this.y=e*a.x-c*a.z;this.z=c*a.y-d*a.x;return this},crossVectors:function(a,b){var c=a.x,d=a.y,e=a.z,f=b.x,g=b.y,h=b.z;this.x=d*h-e*g;this.y=
13881 e*f-c*h;this.z=c*g-d*f;return this},projectOnVector:function(a){var b=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(Y.clamp(a,-1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},
13882 distanceToSquared:function(a){var b=this.x-a.x,c=this.y-a.y;a=this.z-a.z;return b*b+c*c+a*a},distanceToManhattan: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){return this.setFromMatrixColumn(a,
13883 3)},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=[]);void 0===b&&(b=0);a[b]=
13884 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(J.prototype,{isMatrix4:!0,set:function(a,b,c,d,e,f,g,h,k,m,u,l,n,r,p,t){var y=this.elements;y[0]=a;y[4]=b;y[8]=c;y[12]=d;y[1]=e;y[5]=f;y[9]=g;y[13]=h;y[2]=k;y[6]=m;y[10]=u;y[14]=l;y[3]=n;y[7]=r;y[11]=p;y[15]=t;return this},identity:function(){this.set(1,
13885 0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this},clone:function(){return(new J).fromArray(this.elements)},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);
13886 b.setFromMatrixColumn(this,1);c.setFromMatrixColumn(this,2);return this},makeBasis:function(a,b,c){this.set(a.x,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}}(),
13887 makeRotationFromEuler:function(a){!1===(a&&a.isEuler)&&console.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");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){a=f*h;var k=f*e,m=c*h,u=c*e;b[0]=g*h;b[4]=-g*e;b[8]=d;b[1]=k+m*d;b[5]=a-u*d;b[9]=-c*g;b[2]=u-a*d;b[6]=m+k*d;b[10]=f*g}else"YXZ"===a.order?(a=g*h,k=g*e,m=d*h,u=d*e,b[0]=a+u*c,b[4]=m*c-k,b[8]=
13888 f*d,b[1]=f*e,b[5]=f*h,b[9]=-c,b[2]=k*c-m,b[6]=u+a*c,b[10]=f*g):"ZXY"===a.order?(a=g*h,k=g*e,m=d*h,u=d*e,b[0]=a-u*c,b[4]=-f*e,b[8]=m+k*c,b[1]=k+m*c,b[5]=f*h,b[9]=u-a*c,b[2]=-f*d,b[6]=c,b[10]=f*g):"ZYX"===a.order?(a=f*h,k=f*e,m=c*h,u=c*e,b[0]=g*h,b[4]=m*d-k,b[8]=a*d+u,b[1]=g*e,b[5]=u*d+a,b[9]=k*d-m,b[2]=-d,b[6]=c*g,b[10]=f*g):"YZX"===a.order?(a=f*g,k=f*d,m=c*g,u=c*d,b[0]=g*h,b[4]=u-a*e,b[8]=m*e+k,b[1]=e,b[5]=f*h,b[9]=-c*h,b[2]=-d*h,b[6]=k*e+m,b[10]=a-u*e):"XZY"===a.order&&(a=f*g,k=f*d,m=c*g,u=c*d,b[0]=
13889 g*h,b[4]=-e,b[8]=d*h,b[1]=a*e+u,b[5]=f*h,b[9]=k*e-m,b[2]=m*e-k,b[6]=c*h,b[10]=u*e+a);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=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 m=c*h,c=c*k,u=d*h,d=d*k,e=e*k,g=f*g,h=f*h,f=f*k;b[0]=1-(u+e);b[4]=m-f;b[8]=c+h;b[1]=m+f;b[5]=1-(a+e);b[9]=d-g;b[2]=c-h;b[6]=d+g;b[10]=1-(a+u);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,
13890 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()&&(c.z+=1E-4,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)):
13891 this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements,e=this.elements,f=c[0],g=c[4],h=c[8],k=c[12],m=c[1],u=c[5],l=c[9],n=c[13],r=c[2],p=c[6],t=c[10],y=c[14],x=c[3],v=c[7],G=c[11],c=c[15],w=d[0],O=d[4],S=d[8],E=d[12],F=d[1],C=d[5],R=d[9],D=d[13],B=d[2],I=d[6],H=d[10],J=d[14],P=d[3],K=d[7],W=d[11],d=d[15];e[0]=f*w+g*F+h*B+k*P;e[4]=f*O+g*C+h*I+k*K;e[8]=f*S+g*R+h*H+k*W;e[12]=f*E+g*D+h*J+k*d;e[1]=m*w+u*
13892 F+l*B+n*P;e[5]=m*O+u*C+l*I+n*K;e[9]=m*S+u*R+l*H+n*W;e[13]=m*E+u*D+l*J+n*d;e[2]=r*w+p*F+t*B+y*P;e[6]=r*O+p*C+t*I+y*K;e[10]=r*S+p*R+t*H+y*W;e[14]=r*E+p*D+t*J+y*d;e[3]=x*w+v*F+G*B+c*P;e[7]=x*O+v*C+G*I+c*K;e[11]=x*S+v*R+G*H+c*W;e[15]=x*E+v*D+G*J+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=
13893 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=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],m=a[2],u=a[6],l=a[10],n=a[14];return a[3]*(+e*h*u-d*k*u-e*g*l+c*k*l+d*g*n-c*h*n)+a[7]*(+b*h*n-b*k*l+e*f*l-d*f*n+d*k*m-e*h*m)+a[11]*(+b*k*u-b*g*n-e*f*u+c*f*n+e*g*m-c*k*m)+a[15]*(-d*g*m-b*h*u+b*g*l+d*f*u-c*f*l+c*h*m)},transpose:function(){var a=this.elements,b;b=a[1];a[1]=a[4];a[4]=
13894 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=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,e=d[0],f=d[1],g=d[2],h=d[3],k=d[4],m=d[5],l=d[6],q=d[7],n=d[8],r=d[9],p=d[10],t=d[11],y=d[12],x=d[13],v=d[14],d=d[15],G=r*v*q-x*p*q+x*l*t-m*v*t-r*l*d+m*p*d,w=y*p*q-n*v*q-y*l*t+k*v*t+n*l*d-k*p*d,O=n*x*q-y*r*q+y*m*t-
13895 k*x*t-n*m*d+k*r*d,S=y*r*l-n*x*l-y*m*p+k*x*p+n*m*v-k*r*v,E=e*G+f*w+g*O+h*S;if(0===E){if(!0===b)throw Error("THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0");console.warn("THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0");return this.identity()}E=1/E;c[0]=G*E;c[1]=(x*p*h-r*v*h-x*g*t+f*v*t+r*g*d-f*p*d)*E;c[2]=(m*v*h-x*l*h+x*g*q-f*v*q-m*g*d+f*l*d)*E;c[3]=(r*l*h-m*p*h-r*g*q+f*p*q+m*g*t-f*l*t)*E;c[4]=w*E;c[5]=(n*v*h-y*p*h+y*g*t-e*v*t-n*g*d+e*p*d)*E;c[6]=(y*l*h-k*v*h-
13896 y*g*q+e*v*q+k*g*d-e*l*d)*E;c[7]=(k*p*h-n*l*h+n*g*q-e*p*q-k*g*t+e*l*t)*E;c[8]=O*E;c[9]=(y*r*h-n*x*h-y*f*t+e*x*t+n*f*d-e*r*d)*E;c[10]=(k*x*h-y*m*h+y*f*q-e*x*q-k*f*d+e*m*d)*E;c[11]=(n*m*h-k*r*h-n*f*q+e*r*q+k*f*t-e*m*t)*E;c[12]=S*E;c[13]=(n*x*g-y*r*g+y*f*p-e*x*p-n*f*v+e*r*v)*E;c[14]=(y*m*g-k*x*g-y*f*l+e*x*l+k*f*v-e*m*v)*E;c[15]=(k*r*g-n*m*g+n*f*l-e*r*l-k*f*p+e*m*p)*E;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]*=
13897 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],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,
13898 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=Math.cos(b),d=Math.sin(b),e=1-c,f=a.x,g=a.y,h=a.z,k=e*f,m=e*g;this.set(k*f+c,k*g-d*h,k*h+d*g,0,k*g+d*h,m*g+c,m*h-d*f,0,k*h-d*g,m*h+d*f,e*h*h+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},
13899 compose:function(a,b,c){this.makeRotationFromQuaternion(b);this.scale(c);this.setPosition(a);return this},decompose:function(){var a=new p,b=new J;return function(c,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,m=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]*=
13900 m;b.elements[9]*=m;b.elements[10]*=m;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.");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,
13901 b,c,d,e,f){var g=this.elements,h=1/(b-a),k=1/(c-d),m=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*m;g[14]=-((f+e)*m);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b=this.elements;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;
13902 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}});eb.prototype=Object.create(X.prototype);eb.prototype.constructor=eb;eb.prototype.isDataTexture=!0;Za.prototype=Object.create(X.prototype);Za.prototype.constructor=Za;Za.prototype.isCubeTexture=!0;Object.defineProperty(Za.prototype,"images",{get:function(){return this.image},set:function(a){this.image=
13903 a}});var De=new X,Ee=new Za,ye=[],Ae=[],Ce=new Float32Array(16),Be=new Float32Array(9);Ie.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 Qd=/([\w\d_]+)(\])?(\[|\.)?/g;fb.prototype.setValue=function(a,b,c){b=this.map[b];void 0!==b&&b.setValue(a,c,this.renderer)};fb.prototype.setOptional=function(a,b,c){b=b[c];void 0!==b&&this.setValue(a,c,b)};fb.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!==
13904 h.needsUpdate&&g.setValue(a,h.value,d)}};fb.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 kg={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,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,
13905 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,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,
13906 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,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,
13907 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,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,
13908 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,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,
13909 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&&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=
13910 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=Y.euclideanModulo(b,1);c=Y.clamp(c,0,1);d=Y.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/
13911 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,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=
13912 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,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)+
13913 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=kg[a],void 0!==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,
13914 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);var c=0<b?1/b:1;this.r=Math.pow(a.r,c);this.g=Math.pow(a.g,c);this.b=Math.pow(a.b,c);return this},convertGammaToLinear:function(){var a=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*
13915 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):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)+")"},
13916 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+=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},
13917 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=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 V={common:{diffuse:{value:new H(15658734)},
13918 opacity:{value:1},map:{value:null},offsetRepeat:{value:new ga(0,0,1,1)},specularMap:{value:null},alphaMap:{value:null},envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},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 D(1,1)}},displacementmap:{displacementMap:{value:null},
13919 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},fogFar:{value:2E3},fogColor:{value:new H(16777215)}},lights:{ambientLightColor:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},
13920 spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],
13921 properties:{color:{},position:{},width:{},height:{}}}},points:{diffuse:{value:new H(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},offsetRepeat:{value:new ga(0,0,1,1)}}},Ha={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():
13922 Array.isArray(e)?b[c][d]=e.slice():b[c][d]=e}}return b}},U={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",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",
13923 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 * transpose( 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",
13924 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 = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\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",
13925 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",
13926 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",
13927 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 transpose( const in mat3 v ) {\n\tmat3 tmp;\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\n\treturn tmp;\n}\n",
13928 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",
13929 defaultnormal_vertex:"#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\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 += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n",
13930 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",
13931 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, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * 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",
13932 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",
13933 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",
13934 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",
13935 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",
13936 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",
13937 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};\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 = saturate( reflectVec.y * 0.5 + 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",
13938 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};\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_BlinnPhong( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in BlinnPhongMaterial 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 = BlinnExponentToGGXRoughness( material.specularShininess );\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_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_Direct_RectArea\t\tRE_Direct_RectArea_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n",
13939 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",
13940 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",
13941 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 ] ) : 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",
13942 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\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n",
13943 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\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n",map_particle_pars_fragment:"#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n",
13944 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",
13945 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",
13946 normal_flip:"#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n",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 ) * flipNormal;\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",
13947 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 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\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",
13948 packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 1.0 - 2.0 * rgb.xyz;\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",
13949 premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n",project_vertex:"#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\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",
13950 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\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\treturn (\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\treturn (\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\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\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 ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\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",
13951 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",
13952 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",
13953 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 ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n",
13954 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",
13955 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\tskinned = bindMatrixInverse * skinned;\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",
13956 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:"#define saturate(a) clamp( a, 0.0, 1.0 )\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",
13957 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 vec4 offsetRepeat;\n#endif\n",
13958 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 = uv * offsetRepeat.zw + offsetRepeat.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",
13959 uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n",
13960 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}\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",
13961 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#include <begin_vertex>\n\t#include <displacementmap_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}\n",
13962 distanceRGBA_frag:"uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n",distanceRGBA_vert:"varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition;\n}\n",
13963 equirect_frag:"uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 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",
13964 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",
13965 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",
13966 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 <normal_flip>\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",
13967 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",
13968 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 <normal_flip>\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",
13969 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",
13970 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_flip>\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",
13971 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 <displacementmap_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\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",
13972 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 <specularmap_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\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",
13973 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 <specularmap_pars_fragment>\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 <displacementmap_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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
13974 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_flip>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n",
13975 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 <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_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",
13976 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",
13977 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",
13978 shadow_frag:"uniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n",shadow_vert:"#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}\n"},ab={basic:{uniforms:Ha.merge([V.common,
13979 V.aomap,V.lightmap,V.fog]),vertexShader:U.meshbasic_vert,fragmentShader:U.meshbasic_frag},lambert:{uniforms:Ha.merge([V.common,V.aomap,V.lightmap,V.emissivemap,V.fog,V.lights,{emissive:{value:new H(0)}}]),vertexShader:U.meshlambert_vert,fragmentShader:U.meshlambert_frag},phong:{uniforms:Ha.merge([V.common,V.aomap,V.lightmap,V.emissivemap,V.bumpmap,V.normalmap,V.displacementmap,V.gradientmap,V.fog,V.lights,{emissive:{value:new H(0)},specular:{value:new H(1118481)},shininess:{value:30}}]),vertexShader:U.meshphong_vert,
13980 fragmentShader:U.meshphong_frag},standard:{uniforms:Ha.merge([V.common,V.aomap,V.lightmap,V.emissivemap,V.bumpmap,V.normalmap,V.displacementmap,V.roughnessmap,V.metalnessmap,V.fog,V.lights,{emissive:{value:new H(0)},roughness:{value:.5},metalness:{value:.5},envMapIntensity:{value:1}}]),vertexShader:U.meshphysical_vert,fragmentShader:U.meshphysical_frag},points:{uniforms:Ha.merge([V.points,V.fog]),vertexShader:U.points_vert,fragmentShader:U.points_frag},dashed:{uniforms:Ha.merge([V.common,V.fog,{scale:{value:1},
13981 dashSize:{value:1},totalSize:{value:2}}]),vertexShader:U.linedashed_vert,fragmentShader:U.linedashed_frag},depth:{uniforms:Ha.merge([V.common,V.displacementmap]),vertexShader:U.depth_vert,fragmentShader:U.depth_frag},normal:{uniforms:Ha.merge([V.common,V.bumpmap,V.normalmap,V.displacementmap,{opacity:{value:1}}]),vertexShader:U.normal_vert,fragmentShader:U.normal_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:U.cube_vert,fragmentShader:U.cube_frag},equirect:{uniforms:{tEquirect:{value:null},
13982 tFlip:{value:-1}},vertexShader:U.equirect_vert,fragmentShader:U.equirect_frag},distanceRGBA:{uniforms:{lightPos:{value:new p}},vertexShader:U.distanceRGBA_vert,fragmentShader:U.distanceRGBA_frag}};ab.physical={uniforms:Ha.merge([ab.standard.uniforms,{clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:U.meshphysical_vert,fragmentShader:U.meshphysical_frag};Object.assign(id.prototype,{set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromPoints:function(a){this.makeEmpty();
13983 for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new D;return function(b,c){var d=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(d);this.max.copy(b).add(d);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||
13984 this.max.y<this.min.y},getCenter:function(a){a=a||new D;return this.isEmpty()?a.set(0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=a||new D;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<
13985 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<=this.max.y},getParameter:function(a,b){return(b||new D).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 D).copy(a).clamp(this.min,this.max)},
13986 distanceToPoint:function(){var a=new D;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);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)}});var Kf=0;Object.assign(Z.prototype,sa.prototype,{isMaterial:!0,setValues:function(a){if(void 0!==
13987 a)for(var b in a){var c=a[b];if(void 0===c)console.warn("THREE.Material: '"+b+"' parameter is undefined.");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=void 0===a;c&&(a={textures:{},images:{}});var d={metadata:{version:4.5,type:"Material",
13988 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());this.specular&&this.specular.isColor&&(d.specular=this.specular.getHex());void 0!==this.shininess&&(d.shininess=this.shininess);void 0!==this.clearCoat&&(d.clearCoat=
13989 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&&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,
13990 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);this.metalnessMap&&this.metalnessMap.isTexture&&(d.metalnessMap=this.metalnessMap.toJSON(a).uuid);this.emissiveMap&&this.emissiveMap.isTexture&&(d.emissiveMap=this.emissiveMap.toJSON(a).uuid);
13991 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&&(d.size=this.size);void 0!==this.sizeAttenuation&&(d.sizeAttenuation=this.sizeAttenuation);1!==this.blending&&(d.blending=this.blending);2!==this.shading&&(d.shading=this.shading);0!==this.side&&
13992 (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.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);
13993 "round"!==this.wireframeLinecap&&(d.wireframeLinecap=this.wireframeLinecap);"round"!==this.wireframeLinejoin&&(d.wireframeLinejoin=this.wireframeLinejoin);d.skinning=this.skinning;d.morphTargets=this.morphTargets;d.dithering=this.dithering;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;this.lights=a.lights;this.blending=a.blending;this.side=a.side;
13994 this.shading=a.shading;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=a.precision;this.polygonOffset=a.polygonOffset;this.polygonOffsetFactor=
13995 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.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]=a[d].clone();this.clippingPlanes=b;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Ea.prototype=Object.create(Z.prototype);
13996 Ea.prototype.constructor=Ea;Ea.prototype.isShaderMaterial=!0;Ea.prototype.copy=function(a){Z.prototype.copy.call(this,a);this.fragmentShader=a.fragmentShader;this.vertexShader=a.vertexShader;this.uniforms=Ha.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};Ea.prototype.toJSON=
13997 function(a){a=Z.prototype.toJSON.call(this,a);a.uniforms=this.uniforms;a.vertexShader=this.vertexShader;a.fragmentShader=this.fragmentShader;return a};$a.prototype=Object.create(Z.prototype);$a.prototype.constructor=$a;$a.prototype.isMeshDepthMaterial=!0;$a.prototype.copy=function(a){Z.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=
13998 a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;return this};Object.assign(Ta.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 m=a[h],l=a[h+1],q=a[h+2];m<b&&(b=m);l<c&&(c=l);q<d&&(d=q);m>e&&(e=m);l>f&&(f=l);q>g&&(g=q)}this.min.set(b,c,d);this.max.set(e,
13999 f,g);return this},setFromBufferAttribute:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.count;h<k;h++){var m=a.getX(h),l=a.getY(h),q=a.getZ(h);m<b&&(b=m);l<c&&(c=l);q<d&&(d=q);m>e&&(e=m);l>f&&(f=l);q>g&&(g=q)}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){var d=a.copy(c).multiplyScalar(.5);
14000 this.min.copy(b).sub(d);this.max.copy(b).add(d);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=
14001 a||new p;return this.isEmpty()?a.set(0,0,0):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(){var a=new p;return function(b){var c=this;b.updateMatrixWorld(!0);
14002 b.traverse(function(b){var e,f;e=b.geometry;if(void 0!==e)if(e.isGeometry){var g=e.vertices;e=0;for(f=g.length;e<f;e++)a.copy(g[e]),a.applyMatrix4(b.matrixWorld),c.expandByPoint(a)}else if(e.isBufferGeometry&&(g=e.attributes.position,void 0!==g))for(e=0,f=g.count;e<f;e++)a.fromBufferAttribute(g,e).applyMatrix4(b.matrixWorld),c.expandByPoint(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<=
14003 a.min.x&&a.max.x<=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,
14004 a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){var b,c;0<a.normal.x?(b=a.normal.x*this.min.x,c=a.normal.x*this.max.x):(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,
14005 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 Ga;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=
14006 [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);
14007 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(Ga.prototype,{set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a=new Ta;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).getCenter(d);for(var e=0,f=0,g=b.length;f<g;f++)e=Math.max(e,
14008 d.distanceToSquared(b[f]));this.radius=Math.sqrt(e);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)<=
14009 b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(this.center.dot(a.normal)-a.constant)<=this.radius},clampPoint:function(a,b){var c=this.center.distanceToSquared(a),d=b||new p;d.copy(a);c>this.radius*this.radius&&(d.sub(this.center).normalize(),d.multiplyScalar(this.radius).add(this.center));return d},getBoundingBox:function(a){a=a||new Ta;a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a);
14010 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(Ka.prototype,{isMatrix3:!0,set:function(a,b,c,d,e,f,g,h,k){var m=this.elements;m[0]=a;m[1]=d;m[2]=g;m[3]=b;m[4]=e;m[5]=h;m[6]=c;m[7]=f;m[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)},copy:function(a){var b=
14011 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,a)},premultiply:function(a){return this.multiplyMatrices(a,
14012 this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements,e=this.elements,f=c[0],g=c[3],h=c[6],k=c[1],m=c[4],l=c[7],q=c[2],n=c[5],c=c[8],r=d[0],p=d[3],t=d[6],y=d[1],x=d[4],v=d[7],G=d[2],w=d[5],d=d[8];e[0]=f*r+g*y+h*G;e[3]=f*p+g*x+h*w;e[6]=f*t+g*v+h*d;e[1]=k*r+m*y+l*G;e[4]=k*p+m*x+l*w;e[7]=k*t+m*v+l*d;e[2]=q*r+n*y+c*G;e[5]=q*p+n*x+c*w;e[8]=q*t+n*v+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[3]*=a;b[6]*=a;b[1]*=a;b[4]*=a;b[7]*=a;b[2]*=a;b[5]*=a;b[8]*=a;return this},
14013 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,d=this.elements,e=c[0],f=c[1],g=c[2],h=c[3],k=c[4],m=c[5],l=c[6],q=c[7],c=c[8],n=c*k-m*q,r=m*l-c*h,p=q*h-k*l,t=e*n+f*r+g*p;if(0===t){if(!0===b)throw Error("THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0");
14014 console.warn("THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0");return this.identity()}t=1/t;d[0]=n*t;d[1]=(g*q-c*f)*t;d[2]=(m*f-g*k)*t;d[3]=r*t;d[4]=(c*e-g*l)*t;d[5]=(g*h-m*e)*t;d[6]=p*t;d[7]=(f*l-q*e)*t;d[8]=(k*e-f*h)*t;return this},transpose:function(){var a,b=this.elements;a=b[1];b[1]=b[3];b[3]=a;a=b[2];b[2]=b[6];b[6]=a;a=b[5];b[5]=b[7];b[7]=a;return this},getNormalMatrix:function(a){return this.setFromMatrix4(a).getInverse(this).transpose()},transposeIntoArray:function(a){var b=
14015 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},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=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]=
14016 c[8];return a}});Object.assign(wa.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=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)},
14017 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)+this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a,b){return this.orthoPoint(a,b).sub(a).negate()},orthoPoint:function(a,
14018 b){var c=this.distanceToPoint(a);return(b||new p).copy(this.normal).multiplyScalar(c)},intersectLine:function(){var a=new p;return function(b,c){var d=c||new p,e=b.delta(a),f=this.normal.dot(e);if(0===f){if(0===this.distanceToPoint(b.start))return d.copy(b.start)}else return f=-(b.start.dot(this.normal)+this.constant)/f,0>f||1<f?void 0:d.copy(e).multiplyScalar(f).add(b.start)}}(),intersectsLine:function(a){var b=this.distanceToPoint(a.start);a=this.distanceToPoint(a.end);return 0>b&&0<a||0>a&&0<b},
14019 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 Ka;return function(c,d){var e=this.coplanarPoint(a).applyMatrix4(c),f=d||b.getNormalMatrix(c),f=this.normal.applyMatrix3(f).normalize();this.constant=-e.dot(f);return this}}(),translate:function(a){this.constant-=a.dot(this.normal);return this},equals:function(a){return a.normal.equals(this.normal)&&
14020 a.constant===this.constant}});Object.assign(jd.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,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],m=c[7],l=c[8],q=c[9],n=c[10],r=c[11],p=c[12],t=c[13],
14021 y=c[14],c=c[15];b[0].setComponents(f-a,m-g,r-l,c-p).normalize();b[1].setComponents(f+a,m+g,r+l,c+p).normalize();b[2].setComponents(f+d,m+h,r+q,c+t).normalize();b[3].setComponents(f-d,m-h,r-q,c-t).normalize();b[4].setComponents(f-e,m-k,r-n,c-y).normalize();b[5].setComponents(f+e,m+k,r+n,c+y).normalize();return this},intersectsObject:function(){var a=new Ga;return function(b){var c=b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),
14022 intersectsSprite:function(){var a=new Ga;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=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?
14023 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}});Object.assign(hb.prototype,{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);
14024 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,b){var c=b||new p;c.subVectors(a,this.origin);var d=c.dot(this.direction);return 0>d?c.copy(this.origin):c.copy(this.direction).multiplyScalar(d).add(this.origin)},
14025 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=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);
14026 var h=.5*d.distanceTo(e),k=-this.direction.dot(b),m=c.dot(this.direction),l=-c.dot(b),q=c.lengthSq(),n=Math.abs(1-k*k),r;0<n?(d=k*l-m,e=k*m-l,r=h*n,0<=d?e>=-r?e<=r?(h=1/n,d*=h,e*=h,k=d*(d+k*e+2*m)+e*(k*d+e+2*l)+q):(e=h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+q):(e=-h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+q):e<=-r?(d=Math.max(0,-(-k*h+m)),e=0<d?-h:Math.min(Math.max(-h,-l),h),k=-d*d+e*(e+2*l)+q):e<=r?(d=0,e=Math.min(Math.max(-h,-l),h),k=e*(e+2*l)+q):(d=Math.max(0,-(k*h+m)),e=0<d?h:Math.min(Math.max(-h,
14027 -l),h),k=-d*d+e*(e+2*l)+q)):(e=0<k?-h:h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+q);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,f=b.radius*b.radius;if(e>f)return null;f=Math.sqrt(f-e);e=d-f;d+=f;return 0>e&&0>d?null:0>e?this.at(d,c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<=
14028 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){var c=this.distanceToPlane(a);return null===c?null:this.at(c,b)},intersectsPlane:function(a){var b=a.distanceToPoint(this.origin);return 0===b||0>a.normal.dot(this.direction)*b?!0:!1},intersectBox:function(a,b){var c,d,e,f,g;d=1/this.direction.x;f=1/this.direction.y;g=1/this.direction.z;
14029 var h=this.origin;0<=d?(c=(a.min.x-h.x)*d,d*=a.max.x-h.x):(c=(a.max.x-h.x)*d,d*=a.min.x-h.x);0<=f?(e=(a.min.y-h.y)*f,f*=a.max.y-h.y):(e=(a.max.y-h.y)*f,f*=a.min.y-h.y);if(c>f||e>d)return null;if(e>c||c!==c)c=e;if(f<d||d!==d)d=f;0<=g?(e=(a.min.z-h.z)*g,g*=a.max.z-h.z):(e=(a.max.z-h.z)*g,g*=a.min.z-h.z);if(c>g||e>d)return null;if(e>c||c!==c)c=e;if(g<d||d!==d)d=g;return 0>d?null:this.at(0<=c?c:d,b)},intersectsBox:function(){var a=new p;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a=
14030 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;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.direction.add(this.origin).applyMatrix4(a);this.origin.applyMatrix4(a);
14031 this.direction.sub(this.origin);this.direction.normalize();return this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}});bb.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" ");bb.DefaultOrder="XYZ";Object.defineProperties(bb.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=
14032 a;this.onChangeCallback()}},order:{get:function(){return this._order},set:function(a){this._order=a;this.onChangeCallback()}}});Object.assign(bb.prototype,{isEuler:!0,set:function(a,b,c,d){this._x=a;this._y=b;this._z=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,
14033 b,c){var d=Y.clamp,e=a.elements;a=e[0];var f=e[4],g=e[8],h=e[1],k=e[5],m=e[9],l=e[2],q=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(-m,e),this._z=Math.atan2(-f,a)):(this._x=Math.atan2(q,k),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(m,-1,1)),.99999>Math.abs(m)?(this._y=Math.atan2(g,e),this._z=Math.atan2(h,k)):(this._y=Math.atan2(-l,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(q,-1,1)),.99999>Math.abs(q)?(this._y=Math.atan2(-l,e),this._z=
14034 Math.atan2(-f,k)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(l,-1,1)),.99999>Math.abs(l)?(this._x=Math.atan2(q,e),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-f,k))):"YZX"===b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-m,k),this._y=Math.atan2(-l,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(q,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-m,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+
14035 b);this._order=b;if(!1!==c)this.onChangeCallback();return this},setFromQuaternion:function(){var a=new J;return function(b,c,d){a.makeRotationFromQuaternion(b);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 qa;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=
14036 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===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(Rd.prototype,{set:function(a){this.mask=1<<a|0},enable:function(a){this.mask=
14037 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)}});var Lf=0;B.DefaultUp=new p(0,1,0);B.DefaultMatrixAutoUpdate=!0;Object.assign(B.prototype,sa.prototype,{isObject3D:!0,applyMatrix:function(a){this.matrix.multiplyMatrices(a,this.matrix);this.matrix.decompose(this.position,this.quaternion,this.scale)},setRotationFromAxisAngle:function(a,b){this.quaternion.setFromAxisAngle(a,b)},setRotationFromEuler:function(a){this.quaternion.setFromEuler(a,
14038 !0)},setRotationFromMatrix:function(a){this.quaternion.setFromRotationMatrix(a)},setRotationFromQuaternion:function(a){this.quaternion.copy(a)},rotateOnAxis:function(){var a=new qa;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.multiply(a);return this}}(),rotateX:function(){var a=new p(1,0,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateY:function(){var a=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,
14039 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,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)},
14040 worldToLocal:function(){var a=new J;return function(b){return b.applyMatrix4(a.getInverse(this.matrixWorld))}}(),lookAt:function(){var a=new J;return function(b){this.isCamera?a.lookAt(this.position,b,this.up):a.lookAt(b,this.position,this.up);this.quaternion.setFromRotationMatrix(a)}}(),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;
14041 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]);b=this.children.indexOf(a);-1!==b&&(a.parent=null,a.dispatchEvent({type:"removed"}),this.children.splice(b,1))},getObjectById:function(a){return this.getObjectByProperty("id",a)},getObjectByName:function(a){return this.getObjectByProperty("name",
14042 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);return a.setFromMatrixPosition(this.matrixWorld)},getWorldQuaternion:function(){var a=new p,b=new p;return function(c){c=c||new qa;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,c,b);return c}}(),getWorldRotation:function(){var a=new qa;return function(b){b=
14043 b||new bb;this.getWorldQuaternion(a);return b.setFromQuaternion(a,this.rotation.order,!1)}}(),getWorldScale:function(){var a=new p,b=new qa;return function(c){c=c||new p;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,b,c);return c}}(),getWorldDirection:function(){var a=new qa;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)},
14044 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,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,
14045 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=[],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var d=void 0===a||""===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;""!==
14046 this.name&&(f.name=this.name);"{}"!==JSON.stringify(this.userData)&&(f.userData=this.userData);!0===this.castShadow&&(f.castShadow=!0);!0===this.receiveShadow&&(f.receiveShadow=!0);!1===this.visible&&(f.visible=!1);f.matrix=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,
14047 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&&(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);
14048 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;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(var c=0;c<a.children.length;c++)this.add(a.children[c].clone());
14049 return this}});Object.assign(Hb.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);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)},
14050 at:function(a,b){var c=b||new p;return this.delta(c).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new p,b=new p;return function(c,d){a.subVectors(c,this.start);b.subVectors(this.end,this.start);var e=b.dot(b),e=b.dot(a)/e;d&&(e=Y.clamp(e,0,1));return e}}(),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);
14051 return this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)}});Object.assign(Ua,{normal:function(){var a=new p;return function(b,c,d,e){e=e||new p;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 m=
14052 d*k-e*e;h=h||new p;if(0===m)return h.set(-2,-1,-1);m=1/m;k=(k*f-e*g)*m;d=(d*g-e*f)*m;return h.set(1-k-d,d,k)}}(),containsPoint:function(){var a=new p;return function(b,c,d,e){b=Ua.barycoordFromPoint(b,c,d,e,a);return 0<=b.x&&0<=b.y&&1>=b.x+b.y}}()});Object.assign(Ua.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)},
14053 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,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 Ua.normal(this.a,this.b,this.c,a)},plane:function(a){return(a||new wa).setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return Ua.barycoordFromPoint(a,
14054 this.a,this.b,this.c,b)},containsPoint:function(a){return Ua.containsPoint(a,this.a,this.b,this.c)},closestPointToPoint:function(){var a=new wa,b=[new Hb,new Hb,new Hb],c=new p,d=new p;return function(e,f){var g=f||new p,h=Infinity;a.setFromCoplanarPoints(this.a,this.b,this.c);a.projectPoint(e,c);if(!0===this.containsPoint(c))g.copy(c);else{b[0].set(this.a,this.b);b[1].set(this.b,this.c);b[2].set(this.c,this.a);for(var k=0;k<b.length;k++){b[k].closestPointToPoint(c,!0,d);var m=c.distanceToSquared(d);
14055 m<h&&(h=m,g.copy(d))}}return g}}(),equals:function(a){return a.a.equals(this.a)&&a.b.equals(this.b)&&a.c.equals(this.c)}});Object.assign(Va.prototype,{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]=
14056 a.vertexColors[b].clone();return this}});Na.prototype=Object.create(Z.prototype);Na.prototype.constructor=Na;Na.prototype.isMeshBasicMaterial=!0;Na.prototype.copy=function(a){Z.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=a.reflectivity;
14057 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};Object.defineProperty(L.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(L.prototype,{isBufferAttribute:!0,setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
14058 this.count=void 0!==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=
14059 this.array,c=0,d=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",
14060 d),f=new D);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 ga);b[c++]=f.x;b[c++]=f.y;
14061 b[c++]=f.z;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+
14062 3]},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,
14063 this.itemSize)).copy(this)}});rc.prototype=Object.create(L.prototype);rc.prototype.constructor=rc;sc.prototype=Object.create(L.prototype);sc.prototype.constructor=sc;tc.prototype=Object.create(L.prototype);tc.prototype.constructor=tc;uc.prototype=Object.create(L.prototype);uc.prototype.constructor=uc;ib.prototype=Object.create(L.prototype);ib.prototype.constructor=ib;vc.prototype=Object.create(L.prototype);vc.prototype.constructor=vc;jb.prototype=Object.create(L.prototype);jb.prototype.constructor=
14064 jb;C.prototype=Object.create(L.prototype);C.prototype.constructor=C;wc.prototype=Object.create(L.prototype);wc.prototype.constructor=wc;Object.assign(Ke.prototype,{computeGroups:function(a){var b,c=[],d=void 0;a=a.faces;for(var e=0;e<a.length;e++){var f=a[e];f.materialIndex!==d&&(d=f.materialIndex,void 0!==b&&(b.count=3*e-b.start,c.push(b)),b={start:3*e,materialIndex:d})}void 0!==b&&(b.count=3*e-b.start,c.push(b));this.groups=c},fromGeometry:function(a){var b=a.faces,c=a.vertices,d=a.faceVertexUvs,
14065 e=d[0]&&0<d[0].length,f=d[1]&&0<d[1].length,g=a.morphTargets,h=g.length,k;if(0<h){k=[];for(var m=0;m<h;m++)k[m]=[];this.morphTargets.position=k}var l=a.morphNormals,q=l.length,n;if(0<q){n=[];for(m=0;m<q;m++)n[m]=[];this.morphTargets.normal=n}for(var r=a.skinIndices,p=a.skinWeights,t=r.length===c.length,y=p.length===c.length,m=0;m<b.length;m++){var x=b[m];this.vertices.push(c[x.a],c[x.b],c[x.c]);var v=x.vertexNormals;3===v.length?this.normals.push(v[0],v[1],v[2]):(v=x.normal,this.normals.push(v,v,
14066 v));v=x.vertexColors;3===v.length?this.colors.push(v[0],v[1],v[2]):(v=x.color,this.colors.push(v,v,v));!0===e&&(v=d[0][m],void 0!==v?this.uvs.push(v[0],v[1],v[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ",m),this.uvs.push(new D,new D,new D)));!0===f&&(v=d[1][m],void 0!==v?this.uvs2.push(v[0],v[1],v[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ",m),this.uvs2.push(new D,new D,new D)));for(v=0;v<h;v++){var G=g[v].vertices;k[v].push(G[x.a],
14067 G[x.b],G[x.c])}for(v=0;v<q;v++)G=l[v].vertexNormals[m],n[v].push(G.a,G.b,G.c);t&&this.skinIndices.push(r[x.a],r[x.b],r[x.c]);y&&this.skinWeights.push(p[x.a],p[x.b],p[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 Td=0;Object.assign(M.prototype,sa.prototype,{isGeometry:!0,applyMatrix:function(a){for(var b=
14068 (new Ka).getNormalMatrix(a),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 J;return function(b){a.makeRotationX(b);
14069 this.applyMatrix(a);return this}}(),rotateY:function(){var a=new J;return function(b){a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new J;return function(b){a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a=new J;return function(b,c,d){a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=new J;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new B;return function(b){a.lookAt(b);
14070 a.updateMatrix();this.applyMatrix(a.matrix)}}(),fromBufferGeometry:function(a){function b(a,b,d,e){var f=void 0!==g?[l[a].clone(),l[b].clone(),l[d].clone()]:[],r=void 0!==h?[c.colors[a].clone(),c.colors[b].clone(),c.colors[d].clone()]:[];e=new Va(a,b,d,f,r,e);c.faces.push(e);void 0!==k&&c.faceVertexUvs[0].push([q[a].clone(),q[b].clone(),q[d].clone()]);void 0!==m&&c.faceVertexUvs[1].push([n[a].clone(),n[b].clone(),n[d].clone()])}var c=this,d=null!==a.index?a.index.array:void 0,e=a.attributes,f=e.position.array,
14071 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,m=void 0!==e.uv2?e.uv2.array:void 0;void 0!==m&&(this.faceVertexUvs[1]=[]);for(var l=[],q=[],n=[],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&&l.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&&q.push(new D(k[r],k[r+1])),void 0!==m&&n.push(new D(m[r],m[r+1]));var z=a.groups;if(0<z.length)for(e=0;e<z.length;e++)for(var f=
14072 z[e],t=f.start,y=f.count,r=t,t=t+y;r<t;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,
14073 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 J;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===
14074 a&&(a=!0);var b,c,d;d=Array(this.vertices.length);b=0;for(c=this.vertices.length;b<c;b++)d[b]=new p;if(a){var e,f,g,h=new p,k=new p;a=0;for(b=this.faces.length;a<b;a++)c=this.faces[a],e=this.vertices[c.a],f=this.vertices[c.b],g=this.vertices[c.c],h.subVectors(g,f),k.subVectors(e,f),h.cross(k),d[c.a].add(h),d[c.b].add(h),d[c.c].add(h)}else for(this.computeFaceNormals(),a=0,b=this.faces.length;a<b;a++)c=this.faces[a],d[c.a].add(c.normal),d[c.b].add(c.normal),d[c.c].add(c.normal);b=0;for(c=this.vertices.length;b<
14075 c;b++)d[b].normalize();a=0;for(b=this.faces.length;a<b;a++)c=this.faces[a],e=c.vertexNormals,3===e.length?(e[0].copy(d[c.a]),e[1].copy(d[c.b]),e[2].copy(d[c.c])):(e[0]=d[c.a].clone(),e[1]=d[c.b].clone(),e[2]=d[c.c].clone());0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeFlatVertexNormals:function(){var a,b,c;this.computeFaceNormals();a=0;for(b=this.faces.length;a<b;a++){c=this.faces[a];var d=c.vertexNormals;3===d.length?(d[0].copy(c.normal),d[1].copy(c.normal),d[2].copy(c.normal)):(d[0]=
14076 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,c,d,e;c=0;for(d=this.faces.length;c<d;c++)for(e=this.faces[c],e.__originalFaceNormal?e.__originalFaceNormal.copy(e.normal):e.__originalFaceNormal=e.normal.clone(),e.__originalVertexNormals||(e.__originalVertexNormals=[]),a=0,b=e.vertexNormals.length;a<b;a++)e.__originalVertexNormals[a]?e.__originalVertexNormals[a].copy(e.vertexNormals[a]):e.__originalVertexNormals[a]=
14077 e.vertexNormals[a].clone();var f=new M;f.faces=this.faces;a=0;for(b=this.morphTargets.length;a<b;a++){if(!this.morphNormals[a]){this.morphNormals[a]={};this.morphNormals[a].faceNormals=[];this.morphNormals[a].vertexNormals=[];e=this.morphNormals[a].faceNormals;var g=this.morphNormals[a].vertexNormals,h,k;c=0;for(d=this.faces.length;c<d;c++)h=new p,k={a:new p,b:new p,c:new p},e.push(h),g.push(k)}g=this.morphNormals[a];f.vertices=this.morphTargets[a].vertices;f.computeFaceNormals();f.computeVertexNormals();
14078 c=0;for(d=this.faces.length;c<d;c++)e=this.faces[c],h=g.faceNormals[c],k=g.vertexNormals[c],h.copy(e.normal),k.a.copy(e.vertexNormals[0]),k.b.copy(e.vertexNormals[1]),k.c.copy(e.vertexNormals[2])}c=0;for(d=this.faces.length;c<d;c++)e=this.faces[c],e.normal=e.__originalFaceNormal,e.vertexNormals=e.__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===
14079 this.boundingBox&&(this.boundingBox=new Ta);this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new Ga);this.boundingSphere.setFromPoints(this.vertices)},merge:function(a,b,c){if(!1===(a&&a.isGeometry))console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",a);else{var d,e=this.vertices.length,f=this.vertices,g=a.vertices,h=this.faces,k=a.faces,m=this.faceVertexUvs[0],l=a.faceVertexUvs[0],q=this.colors,
14080 n=a.colors;void 0===c&&(c=0);void 0!==b&&(d=(new Ka).getNormalMatrix(b));a=0;for(var r=g.length;a<r;a++){var p=g[a].clone();void 0!==b&&p.applyMatrix4(b);f.push(p)}a=0;for(r=n.length;a<r;a++)q.push(n[a].clone());a=0;for(r=k.length;a<r;a++){var g=k[a],t=g.vertexNormals,n=g.vertexColors,q=new Va(g.a+e,g.b+e,g.c+e);q.normal.copy(g.normal);void 0!==d&&q.normal.applyMatrix3(d).normalize();b=0;for(f=t.length;b<f;b++)p=t[b].clone(),void 0!==d&&p.applyMatrix3(d).normalize(),q.vertexNormals.push(p);q.color.copy(g.color);
14081 b=0;for(f=n.length;b<f;b++)p=n[b],q.vertexColors.push(p.clone());q.materialIndex=g.materialIndex+c;h.push(q)}a=0;for(r=l.length;a<r;a++)if(c=l[a],d=[],void 0!==c){b=0;for(f=c.length;b<f;b++)d.push(c[b].clone());m.push(d)}}},mergeMesh:function(a){!1===(a&&a.isMesh)?console.error("THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.",a):(a.matrixAutoUpdate&&a.updateMatrix(),this.merge(a.geometry,a.matrix))},mergeVertices:function(){var a={},b=[],c=[],d,e=Math.pow(10,4),f,g;f=0;for(g=this.vertices.length;f<
14082 g;f++)d=this.vertices[f],d=Math.round(d.x*e)+"_"+Math.round(d.y*e)+"_"+Math.round(d.z*e),void 0===a[d]?(a[d]=f,b.push(this.vertices[f]),c[f]=b.length-1):c[f]=c[a[d]];a=[];f=0;for(g=this.faces.length;f<g;f++)for(e=this.faces[f],e.a=c[e.a],e.b=c[e.b],e.c=c[e.c],e=[e.a,e.b,e.c],d=0;3>d;d++)if(e[d]===e[(d+1)%3]){a.push(f);break}for(f=a.length-1;0<=f;f--)for(e=a[f],this.faces.splice(e,1),c=0,g=this.faceVertexUvs.length;c<g;c++)this.faceVertexUvs[c].splice(e,1);f=this.vertices.length-b.length;this.vertices=
14083 b;return f},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);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()+
14084 a.z.toString();if(void 0!==m[b])return m[b];m[b]=k.length/3;k.push(a.x,a.y,a.z);return m[b]}function c(a){var b=a.r.toString()+a.g.toString()+a.b.toString();if(void 0!==q[b])return q[b];q[b]=l.length;l.push(a.getHex());return q[b]}function d(a){var b=a.x.toString()+a.y.toString();if(void 0!==r[b])return r[b];r[b]=n.length/2;n.push(a.x,a.y);return r[b]}var e={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!==
14085 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=[],m={},l=[],q={},n=[],r={};for(g=0;g<this.faces.length;g++){var p=this.faces[g],t=void 0!==this.faceVertexUvs[0][g],y=0<p.normal.length(),x=0<p.vertexNormals.length,v=1!==p.color.r||1!==p.color.g||1!==p.color.b,G=0<p.vertexColors.length,w=0,w=a(w,0,0),w=a(w,1,!0),w=a(w,2,!1),w=a(w,3,t),w=a(w,4,y),w=a(w,5,x),w=a(w,6,
14086 v),w=a(w,7,G);h.push(w);h.push(p.a,p.b,p.c);h.push(p.materialIndex);t&&(t=this.faceVertexUvs[0][g],h.push(d(t[0]),d(t[1]),d(t[2])));y&&h.push(b(p.normal));x&&(y=p.vertexNormals,h.push(b(y[0]),b(y[1]),b(y[2])));v&&h.push(c(p.color));G&&(p=p.vertexColors,h.push(c(p[0]),c(p[1]),c(p[2])))}e.data={};e.data.vertices=f;e.data.normals=k;0<l.length&&(e.data.colors=l);0<n.length&&(e.data.uvs=[n]);e.data.faces=h;return e},clone:function(){return(new M).copy(this)},copy:function(a){var b,c,d,e,f,g;this.vertices=
14087 [];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;d=a.vertices;b=0;for(c=d.length;b<c;b++)this.vertices.push(d[b].clone());d=a.colors;b=0;for(c=d.length;b<c;b++)this.colors.push(d[b].clone());d=a.faces;b=0;for(c=d.length;b<c;b++)this.faces.push(d[b].clone());b=0;for(c=a.faceVertexUvs.length;b<c;b++){var h=a.faceVertexUvs[b];void 0===
14088 this.faceVertexUvs[b]&&(this.faceVertexUvs[b]=[]);d=0;for(e=h.length;d<e;d++){var k=h[d],m=[];f=0;for(g=k.length;f<g;f++)m.push(k[f].clone());this.faceVertexUvs[b].push(m)}}f=a.morphTargets;b=0;for(c=f.length;b<c;b++){g={};g.name=f[b].name;if(void 0!==f[b].vertices)for(g.vertices=[],d=0,e=f[b].vertices.length;d<e;d++)g.vertices.push(f[b].vertices[d].clone());if(void 0!==f[b].normals)for(g.normals=[],d=0,e=f[b].normals.length;d<e;d++)g.normals.push(f[b].normals[d].clone());this.morphTargets.push(g)}f=
14089 a.morphNormals;b=0;for(c=f.length;b<c;b++){g={};if(void 0!==f[b].vertexNormals)for(g.vertexNormals=[],d=0,e=f[b].vertexNormals.length;d<e;d++)h=f[b].vertexNormals[d],k={},k.a=h.a.clone(),k.b=h.b.clone(),k.c=h.c.clone(),g.vertexNormals.push(k);if(void 0!==f[b].faceNormals)for(g.faceNormals=[],d=0,e=f[b].faceNormals.length;d<e;d++)g.faceNormals.push(f[b].faceNormals[d].clone());this.morphNormals.push(g)}d=a.skinWeights;b=0;for(c=d.length;b<c;b++)this.skinWeights.push(d[b].clone());d=a.skinIndices;b=
14090 0;for(c=d.length;b<c;b++)this.skinIndices.push(d[b].clone());d=a.lineDistances;b=0;for(c=d.length;b<c;b++)this.lineDistances.push(d[b]);b=a.boundingBox;null!==b&&(this.boundingBox=b.clone());b=a.boundingSphere;null!==b&&(this.boundingSphere=b.clone());this.elementsNeedUpdate=a.elementsNeedUpdate;this.verticesNeedUpdate=a.verticesNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.normalsNeedUpdate=a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.lineDistancesNeedUpdate=a.lineDistancesNeedUpdate;
14091 this.groupsNeedUpdate=a.groupsNeedUpdate;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});I.MaxIndex=65535;Object.assign(I.prototype,sa.prototype,{isBufferGeometry:!0,getIndex:function(){return this.index},setIndex:function(a){Array.isArray(a)?this.index=new (65535<Sd(a)?jb:ib)(a,1):this.index=a},addAttribute:function(a,b,c){if(!1===(b&&b.isBufferAttribute)&&!1===(b&&b.isInterleavedBufferAttribute))console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),
14092 this.addAttribute(a,new L(b,c));else if("index"===a)console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),this.setIndex(b);else return this.attributes[a]=b,this},getAttribute:function(a){return this.attributes[a]},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=
14093 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 Ka).getNormalMatrix(a).applyToBufferAttribute(b),b.needsUpdate=!0);null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();return this},rotateX:function(){var a=new J;return function(b){a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a=new J;return function(b){a.makeRotationY(b);
14094 this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new J;return function(b){a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a=new J;return function(b,c,d){a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=new J;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new B;return function(b){a.lookAt(b);a.updateMatrix();this.applyMatrix(a.matrix)}}(),center:function(){this.computeBoundingBox();
14095 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 C(3*b.vertices.length,3);var c=new C(3*b.colors.length,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 C(b.lineDistances.length,1),this.addAttribute("lineDistance",a.copyArray(b.lineDistances)));null!==b.boundingSphere&&
14096 (this.boundingSphere=b.boundingSphere.clone());null!==b.boundingBox&&(this.boundingBox=b.boundingBox.clone())}else a.isMesh&&b&&b.isGeometry&&this.fromGeometry(b);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;
14097 c.groupsNeedUpdate=b.groupsNeedUpdate;b.verticesNeedUpdate=!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),
14098 c.needsUpdate=!0),b.colorsNeedUpdate=!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 Ke).fromGeometry(a);return this.fromDirectGeometry(a.__directGeometry)},
14099 fromDirectGeometry:function(a){var b=new Float32Array(3*a.vertices.length);this.addAttribute("position",(new L(b,3)).copyVector3sArray(a.vertices));0<a.normals.length&&(b=new Float32Array(3*a.normals.length),this.addAttribute("normal",(new L(b,3)).copyVector3sArray(a.normals)));0<a.colors.length&&(b=new Float32Array(3*a.colors.length),this.addAttribute("color",(new L(b,3)).copyColorsArray(a.colors)));0<a.uvs.length&&(b=new Float32Array(2*a.uvs.length),this.addAttribute("uv",(new L(b,2)).copyVector2sArray(a.uvs)));
14100 0<a.uvs2.length&&(b=new Float32Array(2*a.uvs2.length),this.addAttribute("uv2",(new L(b,2)).copyVector2sArray(a.uvs2)));0<a.indices.length&&(b=new (65535<Sd(a.indices)?Uint32Array:Uint16Array)(3*a.indices.length),this.setIndex((new L(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 C(3*g.length,3);b.push(h.copyVector3sArray(g))}this.morphAttributes[c]=b}0<a.skinIndices.length&&(c=new C(4*
14101 a.skinIndices.length,4),this.addAttribute("skinIndex",c.copyVector4sArray(a.skinIndices)));0<a.skinWeights.length&&(c=new C(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 Ta);var a=this.attributes.position;void 0!==a?this.boundingBox.setFromBufferAttribute(a):
14102 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 Ta,b=new p;return function(){null===this.boundingSphere&&(this.boundingSphere=new Ga);var c=this.attributes.position;if(c){var d=this.boundingSphere.center;a.setFromBufferAttribute(c);
14103 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;
14104 if(void 0===b.normal)this.addAttribute("normal",new L(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,k,m,l=new p,q=new p,n=new p,r=new p,z=new p;if(a){a=a.array;0===c.length&&this.addGroup(0,a.length);for(var t=0,y=c.length;t<y;++t)for(f=c[t],g=f.start,h=f.count,f=g,g+=h;f<g;f+=3)h=3*a[f+0],k=3*a[f+1],m=3*a[f+2],l.fromArray(d,h),q.fromArray(d,k),n.fromArray(d,m),r.subVectors(n,q),z.subVectors(l,q),r.cross(z),e[h]+=r.x,e[h+1]+=r.y,
14105 e[h+2]+=r.z,e[k]+=r.x,e[k+1]+=r.y,e[k+2]+=r.z,e[m]+=r.x,e[m+1]+=r.y,e[m+2]+=r.z}else for(f=0,g=d.length;f<g;f+=9)l.fromArray(d,f),q.fromArray(d,f+3),n.fromArray(d,f+6),r.subVectors(n,q),z.subVectors(l,q),r.cross(z),e[f]=r.x,e[f+1]=r.y,e[f+2]=r.z,e[f+3]=r.x,e[f+4]=r.y,e[f+5]=r.z,e[f+6]=r.x,e[f+7]=r.y,e[f+8]=r.z;this.normalizeNormals();b.normal.needsUpdate=!0}},merge:function(a,b){if(!1===(a&&a.isBufferGeometry))console.error("THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.",
14106 a);else{void 0===b&&(b=0);var c=this.attributes,d;for(d in c)if(void 0!==a.attributes[d])for(var e=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}},normalizeNormals:function(){for(var a=this.attributes.normal,b,c,d,e,f=0,g=a.count;f<g;f++)b=a.getX(f),c=a.getY(f),d=a.getZ(f),e=1/Math.sqrt(b*b+c*c+d*d),a.setXYZ(f,b*e,c*e,d*e)},toNonIndexed:function(){if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed."),
14107 this;var a=new I,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,m=0,l=b.length;m<l;m++){h=b[m]*e;for(var q=0;q<e;q++)g[k++]=f[h++]}a.addAttribute(d,new L(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,c;for(c in b)void 0!==b[c]&&
14108 (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(),
14109 radius:c.radius});return a},clone:function(){return(new I).copy(this)},copy:function(a){var b,c,d;this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.name=a.name;c=a.index;null!==c&&this.setIndex(c.clone());c=a.attributes;for(b in c)this.addAttribute(b,c[b].clone());var e=a.morphAttributes;for(b in e){var f=[],g=e[b];c=0;for(d=g.length;c<d;c++)f.push(g[c].clone());this.morphAttributes[b]=f}b=a.groups;c=0;for(d=b.length;c<d;c++)e=
14110 b[c],this.addGroup(e.start,e.count,e.materialIndex);b=a.boundingBox;null!==b&&(this.boundingBox=b.clone());b=a.boundingSphere;null!==b&&(this.boundingSphere=b.clone());this.drawRange.start=a.drawRange.start;this.drawRange.count=a.drawRange.count;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Ca.prototype=Object.assign(Object.create(B.prototype),{constructor:Ca,isMesh:!0,setDrawMode:function(a){this.drawMode=a},copy:function(a){B.prototype.copy.call(this,a);this.drawMode=a.drawMode;
14111 return this},updateMorphTargets:function(){var a=this.geometry.morphTargets;if(void 0!==a&&0<a.length){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(var b=0,c=a.length;b<c;b++)this.morphTargetInfluences.push(0),this.morphTargetDictionary[a[b].name]=b}},raycast:function(){function a(a,b,c,d,e,f,g){Ua.barycoordFromPoint(a,b,c,d,t);e.multiplyScalar(t.x);f.multiplyScalar(t.y);g.multiplyScalar(t.z);e.add(f).add(g);return e.clone()}function b(a,b,c,d,e,f,g){var h=a.material;if(null===
14112 (1===h.side?c.intersectTriangle(f,e,d,!0,g):c.intersectTriangle(d,e,f,2!==h.side,g)))return null;x.copy(g);x.applyMatrix4(a.matrixWorld);c=b.ray.origin.distanceTo(x);return c<b.near||c>b.far?null:{distance:c,point:x.clone(),object:a}}function c(c,d,e,f,m,l,u,q){g.fromBufferAttribute(f,l);h.fromBufferAttribute(f,u);k.fromBufferAttribute(f,q);if(c=b(c,d,e,g,h,k,y))m&&(n.fromBufferAttribute(m,l),r.fromBufferAttribute(m,u),z.fromBufferAttribute(m,q),c.uv=a(y,g,h,k,n,r,z)),c.face=new Va(l,u,q,Ua.normal(g,
14113 h,k)),c.faceIndex=l;return c}var d=new J,e=new hb,f=new Ga,g=new p,h=new p,k=new p,m=new p,l=new p,q=new p,n=new D,r=new D,z=new D,t=new p,y=new p,x=new p;return function(p,t){var w=this.geometry,x=this.material,C=this.matrixWorld;if(void 0!==x&&(null===w.boundingSphere&&w.computeBoundingSphere(),f.copy(w.boundingSphere),f.applyMatrix4(C),!1!==p.ray.intersectsSphere(f)&&(d.getInverse(C),e.copy(p.ray).applyMatrix4(d),null===w.boundingBox||!1!==e.intersectsBox(w.boundingBox)))){var E;if(w.isBufferGeometry){var F,
14114 D,x=w.index,B=w.attributes.position,C=w.attributes.uv,ca,I;if(null!==x)for(ca=0,I=x.count;ca<I;ca+=3){if(w=x.getX(ca),F=x.getX(ca+1),D=x.getX(ca+2),E=c(this,p,e,B,C,w,F,D))E.faceIndex=Math.floor(ca/3),t.push(E)}else for(ca=0,I=B.count;ca<I;ca+=3)if(w=ca,F=ca+1,D=ca+2,E=c(this,p,e,B,C,w,F,D))E.index=w,t.push(E)}else if(w.isGeometry){var H,C=Array.isArray(x);ca=w.vertices;I=w.faces;F=w.faceVertexUvs[0];0<F.length&&(B=F);for(var J=0,M=I.length;J<M;J++){var P=I[J];E=C?x[P.materialIndex]:x;if(void 0!==
14115 E){F=ca[P.a];D=ca[P.b];H=ca[P.c];if(!0===E.morphTargets){E=w.morphTargets;var K=this.morphTargetInfluences;g.set(0,0,0);h.set(0,0,0);k.set(0,0,0);for(var W=0,ba=E.length;W<ba;W++){var T=K[W];if(0!==T){var Q=E[W].vertices;g.addScaledVector(m.subVectors(Q[P.a],F),T);h.addScaledVector(l.subVectors(Q[P.b],D),T);k.addScaledVector(q.subVectors(Q[P.c],H),T)}}g.add(F);h.add(D);k.add(H);F=g;D=h;H=k}if(E=b(this,p,e,F,D,H,y))B&&B[J]&&(K=B[J],n.copy(K[0]),r.copy(K[1]),z.copy(K[2]),E.uv=a(y,F,D,H,n,r,z)),E.face=
14116 P,E.faceIndex=J,t.push(E)}}}}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});Ib.prototype=Object.create(M.prototype);Ib.prototype.constructor=Ib;kb.prototype=Object.create(I.prototype);kb.prototype.constructor=kb;xc.prototype=Object.create(M.prototype);xc.prototype.constructor=xc;lb.prototype=Object.create(I.prototype);lb.prototype.constructor=lb;Oa.prototype=Object.assign(Object.create(B.prototype),{constructor:Oa,isCamera:!0,copy:function(a){B.prototype.copy.call(this,
14117 a);this.matrixWorldInverse.copy(a.matrixWorldInverse);this.projectionMatrix.copy(a.projectionMatrix);return this},getWorldDirection:function(){var a=new qa;return function(b){b=b||new p;this.getWorldQuaternion(a);return b.set(0,0,-1).applyQuaternion(a)}}(),clone:function(){return(new this.constructor).copy(this)}});xa.prototype=Object.assign(Object.create(Oa.prototype),{constructor:xa,isPerspectiveCamera:!0,copy:function(a){Oa.prototype.copy.call(this,a);this.fov=a.fov;this.zoom=a.zoom;this.near=
14118 a.near;this.far=a.far;this.focus=a.focus;this.aspect=a.aspect;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*Y.RAD2DEG*Math.atan(a);this.updateProjectionMatrix()},getFocalLength:function(){var a=Math.tan(.5*Y.DEG2RAD*this.fov);return.5*this.getFilmHeight()/a},getEffectiveFOV:function(){return 2*Y.RAD2DEG*Math.atan(Math.tan(.5*Y.DEG2RAD*this.fov)/this.zoom)},
14119 getFilmWidth:function(){return this.filmGauge*Math.min(this.aspect,1)},getFilmHeight:function(){return this.filmGauge/Math.max(this.aspect,1)},setViewOffset:function(a,b,c,d,e,f){this.aspect=a/b;this.view={fullWidth:a,fullHeight:b,offsetX:c,offsetY:d,width:e,height:f};this.updateProjectionMatrix()},clearViewOffset:function(){this.view=null;this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=this.near,b=a*Math.tan(.5*Y.DEG2RAD*this.fov)/this.zoom,c=2*b,d=this.aspect*c,e=-.5*d,f=
14120 this.view;if(null!==f)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=B.prototype.toJSON.call(this,a);a.object.fov=this.fov;a.object.zoom=this.zoom;a.object.near=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=
14121 this.filmGauge;a.object.filmOffset=this.filmOffset;return a}});Jb.prototype=Object.assign(Object.create(Oa.prototype),{constructor:Jb,isOrthographicCamera:!0,copy:function(a){Oa.prototype.copy.call(this,a);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){this.view={fullWidth:a,fullHeight:b,offsetX:c,offsetY:d,width:e,height:f};
14122 this.updateProjectionMatrix()},clearViewOffset:function(){this.view=null;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)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)/this.view.height,
14123 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=B.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}});var bg=0;Kb.prototype.isFogExp2=!0;
14124 Kb.prototype.clone=function(){return new Kb(this.color.getHex(),this.density)};Kb.prototype.toJSON=function(a){return{type:"FogExp2",color:this.color.getHex(),density:this.density}};Lb.prototype.isFog=!0;Lb.prototype.clone=function(){return new Lb(this.color.getHex(),this.near,this.far)};Lb.prototype.toJSON=function(a){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}};md.prototype=Object.assign(Object.create(B.prototype),{constructor:md,copy:function(a,b){B.prototype.copy.call(this,
14125 a,b);null!==a.background&&(this.background=a.background.clone());null!==a.fog&&(this.fog=a.fog.clone());null!==a.overrideMaterial&&(this.overrideMaterial=a.overrideMaterial.clone());this.autoUpdate=a.autoUpdate;this.matrixAutoUpdate=a.matrixAutoUpdate;return this},toJSON:function(a){var b=B.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}});Yd.prototype=Object.assign(Object.create(B.prototype),
14126 {constructor:Yd,isLensFlare:!0,copy:function(a){B.prototype.copy.call(this,a);this.positionScreen.copy(a.positionScreen);this.customUpdateCallback=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,
14127 opacity:f,color:e,blending:d})},updateLensFlares:function(){var a,b=this.lensFlares.length,c,d=2*-this.positionScreen.x,e=2*-this.positionScreen.y;for(a=0;a<b;a++)c=this.lensFlares[a],c.x=this.positionScreen.x+d*c.distance,c.y=this.positionScreen.y+e*c.distance,c.wantedRotation=c.x*Math.PI*.25,c.rotation+=.25*(c.wantedRotation-c.rotation)}});cb.prototype=Object.create(Z.prototype);cb.prototype.constructor=cb;cb.prototype.isSpriteMaterial=!0;cb.prototype.copy=function(a){Z.prototype.copy.call(this,
14128 a);this.color.copy(a.color);this.map=a.map;this.rotation=a.rotation;return this};Ac.prototype=Object.assign(Object.create(B.prototype),{constructor:Ac,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)}});
14129 Bc.prototype=Object.assign(Object.create(B.prototype),{constructor:Bc,copy:function(a){B.prototype.copy.call(this,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-
14130 1].object},raycast:function(){var a=new p;return function(b,c){a.setFromMatrixPosition(this.matrixWorld);var d=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;
14131 for(;e<f;e++)d[e].object.visible=!1}}}(),toJSON:function(a){a=B.prototype.toJSON.call(this,a);a.object.levels=[];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(Cc.prototype,{calculateInverses:function(){this.boneInverses=[];for(var a=0,b=this.bones.length;a<b;a++){var c=new J;this.bones[a]&&c.getInverse(this.bones[a].matrixWorld);this.boneInverses.push(c)}},pose:function(){var a,b,c;b=0;for(c=this.bones.length;b<
14132 c;b++)(a=this.bones[b])&&a.matrixWorld.getInverse(this.boneInverses[b]);b=0;for(c=this.bones.length;b<c;b++)if(a=this.bones[b])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 J,b=new J;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:
14133 b,d[g]),a.toArray(e,16*g);void 0!==f&&(f.needsUpdate=!0)}}(),clone:function(){return new Cc(this.bones,this.boneInverses)}});nd.prototype=Object.assign(Object.create(B.prototype),{constructor:nd,isBone:!0});od.prototype=Object.assign(Object.create(Ca.prototype),{constructor:od,isSkinnedMesh:!0,initBones:function(){var a=[],b,c,d,e;if(this.geometry&&void 0!==this.geometry.bones){d=0;for(e=this.geometry.bones.length;d<e;d++)c=this.geometry.bones[d],b=new nd,a.push(b),b.name=c.name,b.position.fromArray(c.pos),
14134 b.quaternion.fromArray(c.rotq),void 0!==c.scl&&b.scale.fromArray(c.scl);d=0;for(e=this.geometry.bones.length;d<e;d++)c=this.geometry.bones[d],-1!==c.parent&&null!==c.parent&&void 0!==a[c.parent]?a[c.parent].add(a[d]):this.add(a[d])}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,
14135 b;if(this.geometry&&this.geometry.isGeometry)for(b=0;b<this.geometry.skinWeights.length;b++){var c=this.geometry.skinWeights[b];a=1/c.lengthManhattan();Infinity!==a?c.multiplyScalar(a):c.set(1,0,0,0)}else if(this.geometry&&this.geometry.isBufferGeometry){var c=new ga,d=this.geometry.attributes.skinWeight;for(b=0;b<d.count;b++)c.x=d.getX(b),c.y=d.getY(b),c.z=d.getZ(b),c.w=d.getW(b),a=1/c.lengthManhattan(),Infinity!==a?c.multiplyScalar(a):c.set(1,0,0,0),d.setXYZW(b,c.x,c.y,c.z,c.w)}},updateMatrixWorld:function(a){Ca.prototype.updateMatrixWorld.call(this,
14136 a);"attached"===this.bindMode?this.bindMatrixInverse.getInverse(this.matrixWorld):"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)}});ha.prototype=Object.create(Z.prototype);ha.prototype.constructor=ha;ha.prototype.isLineBasicMaterial=!0;ha.prototype.copy=function(a){Z.prototype.copy.call(this,a);this.color.copy(a.color);
14137 this.linewidth=a.linewidth;this.linecap=a.linecap;this.linejoin=a.linejoin;return this};ya.prototype=Object.assign(Object.create(B.prototype),{constructor:ya,isLine:!0,raycast:function(){var a=new J,b=new hb,c=new Ga;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,m=new p,h=new p,
14138 l=new p,q=this&&this.isLineSegments?2:1;if(g.isBufferGeometry){var n=g.index,r=g.attributes.position.array;if(null!==n)for(var n=n.array,g=0,z=n.length-1;g<z;g+=q){var t=n[g+1];k.fromArray(r,3*n[g]);m.fromArray(r,3*t);t=b.distanceSqToSegment(k,m,l,h);t>f||(l.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(l),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else for(g=0,z=r.length/3-1;g<z;g+=q)k.fromArray(r,
14139 3*g),m.fromArray(r,3*g+3),t=b.distanceSqToSegment(k,m,l,h),t>f||(l.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(l),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else if(g.isGeometry)for(k=g.vertices,m=k.length,g=0;g<m-1;g+=q)t=b.distanceSqToSegment(k[g],k[g+1],l,h),t>f||(l.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(l),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),
14140 index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});da.prototype=Object.assign(Object.create(ya.prototype),{constructor:da,isLineSegments:!0});pd.prototype=Object.assign(Object.create(ya.prototype),{constructor:pd,isLineLoop:!0});La.prototype=Object.create(Z.prototype);La.prototype.constructor=La;La.prototype.isPointsMaterial=!0;La.prototype.copy=function(a){Z.prototype.copy.call(this,a);this.color.copy(a.color);
14141 this.map=a.map;this.size=a.size;this.sizeAttenuation=a.sizeAttenuation;return this};Mb.prototype=Object.assign(Object.create(B.prototype),{constructor:Mb,isPoints:!0,raycast:function(){var a=new J,b=new hb,c=new Ga;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a);if(f<l){var h=b.closestPointToPoint(a);h.applyMatrix4(k);var m=d.ray.origin.distanceTo(h);m<d.near||m>d.far||e.push({distance:m,distanceToRay:Math.sqrt(f),point:h.clone(),index:c,face:null,object:g})}}var g=this,h=this.geometry,
14142 k=this.matrixWorld,m=d.params.Points.threshold;null===h.boundingSphere&&h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k);c.radius+=m;if(!1!==d.ray.intersectsSphere(c)){a.getInverse(k);b.copy(d.ray).applyMatrix4(a);var m=m/((this.scale.x+this.scale.y+this.scale.z)/3),l=m*m,m=new p;if(h.isBufferGeometry){var q=h.index,h=h.attributes.position.array;if(null!==q)for(var n=q.array,q=0,r=n.length;q<r;q++){var z=n[q];m.fromArray(h,3*z);f(m,z)}else for(q=0,n=h.length/3;q<n;q++)m.fromArray(h,
14143 3*q),f(m,q)}else for(m=h.vertices,q=0,n=m.length;q<n;q++)f(m[q],q)}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});Dc.prototype=Object.assign(Object.create(B.prototype),{constructor:Dc});qd.prototype=Object.create(X.prototype);qd.prototype.constructor=qd;Nb.prototype=Object.create(X.prototype);Nb.prototype.constructor=Nb;Nb.prototype.isCompressedTexture=!0;rd.prototype=Object.create(X.prototype);rd.prototype.constructor=rd;Ec.prototype=Object.create(X.prototype);
14144 Ec.prototype.constructor=Ec;Ec.prototype.isDepthTexture=!0;Ob.prototype=Object.create(I.prototype);Ob.prototype.constructor=Ob;Fc.prototype=Object.create(M.prototype);Fc.prototype.constructor=Fc;Pb.prototype=Object.create(I.prototype);Pb.prototype.constructor=Pb;Gc.prototype=Object.create(M.prototype);Gc.prototype.constructor=Gc;ia.prototype=Object.create(I.prototype);ia.prototype.constructor=ia;Hc.prototype=Object.create(M.prototype);Hc.prototype.constructor=Hc;Qb.prototype=Object.create(ia.prototype);
14145 Qb.prototype.constructor=Qb;Ic.prototype=Object.create(M.prototype);Ic.prototype.constructor=Ic;mb.prototype=Object.create(ia.prototype);mb.prototype.constructor=mb;Jc.prototype=Object.create(M.prototype);Jc.prototype.constructor=Jc;Rb.prototype=Object.create(ia.prototype);Rb.prototype.constructor=Rb;Kc.prototype=Object.create(M.prototype);Kc.prototype.constructor=Kc;Sb.prototype=Object.create(ia.prototype);Sb.prototype.constructor=Sb;Lc.prototype=Object.create(M.prototype);Lc.prototype.constructor=
14146 Lc;Tb.prototype=Object.create(I.prototype);Tb.prototype.constructor=Tb;Mc.prototype=Object.create(M.prototype);Mc.prototype.constructor=Mc;Ub.prototype=Object.create(I.prototype);Ub.prototype.constructor=Ub;Nc.prototype=Object.create(M.prototype);Nc.prototype.constructor=Nc;Vb.prototype=Object.create(I.prototype);Vb.prototype.constructor=Vb;var za={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=
14147 a.length;if(3>c)return null;var d=[],e=[],f=[],g,h,k;if(0<za.area(a))for(h=0;h<c;h++)e[h]=h;else for(h=0;h<c;h++)e[h]=c-1-h;var m=2*c;for(h=c-1;2<c;){if(0>=m--){console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()");break}g=h;c<=g&&(g=0);h=g+1;c<=h&&(h=0);k=h+1;c<=k&&(k=0);var l;a:{var q,n,r,p,t,y,x,v;q=a[e[g]].x;n=a[e[g]].y;r=a[e[h]].x;p=a[e[h]].y;t=a[e[k]].x;y=a[e[k]].y;if(0>=(r-q)*(y-n)-(p-n)*(t-q))l=!1;else{var G,w,O,C,E,F,D,B,I,H;G=t-r;w=y-p;O=q-t;C=n-y;E=r-q;F=p-n;
14148 for(l=0;l<c;l++)if(x=a[e[l]].x,v=a[e[l]].y,!(x===q&&v===n||x===r&&v===p||x===t&&v===y)&&(D=x-q,B=v-n,I=x-r,H=v-p,x-=t,v-=y,I=G*H-w*I,D=E*B-F*D,B=O*v-C*x,I>=-Number.EPSILON&&B>=-Number.EPSILON&&D>=-Number.EPSILON)){l=!1;break a}l=!0}}if(l){d.push([a[e[g]],a[e[h]],a[e[k]]]);f.push([e[g],e[h],e[k]]);g=h;for(k=h+1;k<c;g++,k++)e[g]=e[k];c--;m=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<=
14149 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,m=e.y-c.y,l=a.x-c.x,n=a.y-c.y,q=h*k-g*m,u=h*l-g*n;if(Math.abs(q)>Number.EPSILON){if(0<q){if(0>u||u>q)return[];k=m*l-k*n;if(0>k||k>q)return[]}else{if(0<u||u<q)return[];k=m*l-k*n;if(0<k||k<q)return[]}if(0===k)return!f||0!==u&&u!==q?[a]:[];if(k===q)return!f||0!==u&&u!==q?[b]:[];if(0===u)return[c];if(u===q)return[e];f=k/q;return[{x:a.x+f*g,y:a.y+f*h}]}if(0!==u||m*l!==
14150 k*n)return[];h=0===g&&0===h;k=0===k&&0===m;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,m=e,c=e.x):(b=e,q=e.x,m=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,m=e,c=e.y):(b=e,q=e.y,m=c,c=c.y));return k<=q?a<q?[]:a===q?f?[]:[b]:a<=c?[b,h]:[b,m]:k>c?[]:k===c?f?[]:[g]:a<=c?[g,h]:[g,m]}function f(a,b,c,d){var e=b.x-a.x,f=b.y-a.y;b=c.x-a.x;
14151 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,m,l,q={};k=a.concat();g=0;for(h=b.length;g<h;g++)Array.prototype.push.apply(k,b[g]);g=0;for(h=k.length;g<h;g++)l=k[g].x+":"+k[g].y,void 0!==q[l]&&console.warn("THREE.ShapeUtils: Duplicate point",l,g),q[l]=g;g=function(a,b){function c(a,b){var d=h.length-1,e=a-1;0>e&&(e=d);var g=a+1;g>d&&(g=0);d=f(h[a],h[e],h[g],k[b]);if(!d)return!1;d=k.length-
14152 1;e=b-1;0>e&&(e=d);g=b+1;g>d&&(g=0);return(d=f(k[b],k[e],k[g],h[a]))?!0:!1}function d(a,b){var c,f;for(c=0;c<h.length;c++)if(f=c+1,f%=h.length,f=e(a,b,h[c],h[f],!0),0<f.length)return!0;return!1}function g(a,c){var d,f,h,k;for(d=0;d<m.length;d++)for(f=b[m[d]],h=0;h<f.length;h++)if(k=h+1,k%=f.length,k=e(a,c,f[h],f[k],!0),0<k.length)return!0;return!1}var h=a.concat(),k,m=[],l,n,q,u,p,C=[],D,B,I,H=0;for(l=b.length;H<l;H++)m.push(H);D=0;for(var J=2*m.length;0<m.length;){J--;if(0>J){console.log("Infinite Loop! Holes left:"+
14153 m.length+", Probably Hole outside Shape!");break}for(n=D;n<h.length;n++){q=h[n];l=-1;for(H=0;H<m.length;H++)if(u=m[H],p=q.x+":"+q.y+":"+u,void 0===C[p]){k=b[u];for(B=0;B<k.length;B++)if(u=k[B],c(n,B)&&!d(q,u)&&!g(q,u)){l=B;m.splice(H,1);D=h.slice(0,n+1);u=h.slice(n);B=k.slice(l);I=k.slice(0,l+1);h=D.concat(B).concat(I).concat(u);D=n;break}if(0<=l)break;C[p]=!0}if(0<=l)break}}return h}(a,b);var n=za.triangulate(g,!1);g=0;for(h=n.length;g<h;g++)for(m=n[g],k=0;3>k;k++)l=m[k].x+":"+m[k].y,l=q[l],void 0!==
14154 l&&(m[k]=l);return n.concat()},isClockWise:function(a){return 0>za.area(a)}};db.prototype=Object.create(M.prototype);db.prototype.constructor=db;Fa.prototype=Object.create(I.prototype);Fa.prototype.constructor=Fa;Fa.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}};Fa.prototype.addShapeList=
14155 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",new C(b.arrays.position,3));this.addAttribute("uv",new C(b.arrays.uv,2))};Fa.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,e,f;e=a.x-b.x;f=a.y-b.y;d=c.x-a.x;var g=c.y-a.y,h=e*e+f*f;if(Math.abs(e*g-f*d)>Number.EPSILON){var k=
14156 Math.sqrt(h),m=Math.sqrt(d*d+g*g),h=b.x-f/k;b=b.y+e/k;g=((c.x-g/m-h)*g-(c.y+d/m-b)*d)/(e*g-f*d);d=h+e*g-a.x;e=b+f*g-a.y;f=d*d+e*e;if(2>=f)return new D(d,e);f=Math.sqrt(f/2)}else a=!1,e>Number.EPSILON?d>Number.EPSILON&&(a=!0):e<-Number.EPSILON?d<-Number.EPSILON&&(a=!0):Math.sign(f)===Math.sign(g)&&(a=!0),a?(d=-f,f=Math.sqrt(h)):(d=e,e=f,f=Math.sqrt(h/2));return new D(d/f,e/f)}function e(a,b){var c,d;for(N=a.length;0<=--N;){c=N;d=N-1;0>d&&(d=a.length-1);var e,f=G+2*y;for(e=0;e<f;e++){var g=da*e,m=da*
14157 (e+1),n=b+d+g,q=b+d+m,m=b+c+m;h(b+c+g);h(n);h(m);h(n);h(q);h(m);g=l.length/3;g=E.generateSideWallUV(Z,l,g-6,g-3,g-2,g-1);k(g[0]);k(g[1]);k(g[3]);k(g[1]);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=l.length/3;a=E.generateTopUV(Z,l,a-3,a-2,a-1);k(a[0]);k(a[1]);k(a[2])}function h(a){q.push(l.length/3);l.push(r[3*a+0]);l.push(r[3*a+1]);l.push(r[3*a+2])}function k(a){n.push(a.x);n.push(a.y)}var m=b.arrays?b.arrays:this.getArrays(),l=m.position,q=
14158 m.index,n=m.uv,r=[],m=void 0!==b.amount?b.amount:100,z=void 0!==b.bevelThickness?b.bevelThickness:6,t=void 0!==b.bevelSize?b.bevelSize:z-2,y=void 0!==b.bevelSegments?b.bevelSegments:3,x=void 0!==b.bevelEnabled?b.bevelEnabled:!0,v=void 0!==b.curveSegments?b.curveSegments:12,G=void 0!==b.steps?b.steps:1,w=b.extrudePath,B,I=!1,E=void 0!==b.UVGenerator?b.UVGenerator:db.WorldUVGenerator,F,H,R,J;w&&(B=w.getSpacedPoints(G),I=!0,x=!1,F=void 0!==b.frames?b.frames:w.computeFrenetFrames(G,!1),H=new p,R=new p,
14159 J=new p);x||(t=z=y=0);var M,L,V,Z=this,w=a.extractPoints(v),v=w.shape,P=w.holes;if(w=!za.isClockWise(v)){v=v.reverse();L=0;for(V=P.length;L<V;L++)M=P[L],za.isClockWise(M)&&(P[L]=M.reverse());w=!1}var K=za.triangulateShape(v,P),W=v;L=0;for(V=P.length;L<V;L++)M=P[L],v=v.concat(M);var ba,T,Q,Y,U,da=v.length,X,ga=K.length,w=[],N=0;Q=W.length;ba=Q-1;for(T=N+1;N<Q;N++,ba++,T++)ba===Q&&(ba=0),T===Q&&(T=0),w[N]=d(W[N],W[ba],W[T]);var ia=[],ka,ha=w.concat();L=0;for(V=P.length;L<V;L++){M=P[L];ka=[];N=0;Q=M.length;
14160 ba=Q-1;for(T=N+1;N<Q;N++,ba++,T++)ba===Q&&(ba=0),T===Q&&(T=0),ka[N]=d(M[N],M[ba],M[T]);ia.push(ka);ha=ha.concat(ka)}for(ba=0;ba<y;ba++){Q=ba/y;Y=z*Math.cos(Q*Math.PI/2);T=t*Math.sin(Q*Math.PI/2);N=0;for(Q=W.length;N<Q;N++)U=c(W[N],w[N],T),f(U.x,U.y,-Y);L=0;for(V=P.length;L<V;L++)for(M=P[L],ka=ia[L],N=0,Q=M.length;N<Q;N++)U=c(M[N],ka[N],T),f(U.x,U.y,-Y)}T=t;for(N=0;N<da;N++)U=x?c(v[N],ha[N],T):v[N],I?(R.copy(F.normals[0]).multiplyScalar(U.x),H.copy(F.binormals[0]).multiplyScalar(U.y),J.copy(B[0]).add(R).add(H),
14161 f(J.x,J.y,J.z)):f(U.x,U.y,0);for(Q=1;Q<=G;Q++)for(N=0;N<da;N++)U=x?c(v[N],ha[N],T):v[N],I?(R.copy(F.normals[Q]).multiplyScalar(U.x),H.copy(F.binormals[Q]).multiplyScalar(U.y),J.copy(B[Q]).add(R).add(H),f(J.x,J.y,J.z)):f(U.x,U.y,m/G*Q);for(ba=y-1;0<=ba;ba--){Q=ba/y;Y=z*Math.cos(Q*Math.PI/2);T=t*Math.sin(Q*Math.PI/2);N=0;for(Q=W.length;N<Q;N++)U=c(W[N],w[N],T),f(U.x,U.y,m+Y);L=0;for(V=P.length;L<V;L++)for(M=P[L],ka=ia[L],N=0,Q=M.length;N<Q;N++)U=c(M[N],ka[N],T),I?f(U.x,U.y+B[G-1].y,B[G-1].x+Y):f(U.x,
14162 U.y,m+Y)}(function(){var a=l.length/3;if(x){var c=0*da;for(N=0;N<ga;N++)X=K[N],g(X[2]+c,X[1]+c,X[0]+c);c=da*(G+2*y);for(N=0;N<ga;N++)X=K[N],g(X[0]+c,X[1]+c,X[2]+c)}else{for(N=0;N<ga;N++)X=K[N],g(X[2],X[1],X[0]);for(N=0;N<ga;N++)X=K[N],g(X[0]+da*G,X[1]+da*G,X[2]+da*G)}Z.addGroup(a,l.length/3-a,void 0!==b.material?b.material:0)})();(function(){var a=l.length/3,c=0;e(W,c);c+=W.length;L=0;for(V=P.length;L<V;L++)M=P[L],e(M,c),c+=M.length;Z.addGroup(a,l.length/3-a,void 0!==b.extrudeMaterial?b.extrudeMaterial:
14163 1)})();b.arrays||(this.setIndex(q),this.addAttribute("position",new C(l,3)),this.addAttribute("uv",new C(b.arrays.uv,2)))};db.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 D(b[3*c],b[3*c+1]),new D(a,d),new D(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 m=b[3*e],l=b[3*e+1];e=b[3*e+2];var q=b[3*f],n=b[3*f+1];b=b[3*f+2];return.01>Math.abs(g-k)?[new D(a,1-c),new D(h,
14164 1-d),new D(m,1-e),new D(q,1-b)]:[new D(g,1-c),new D(k,1-d),new D(l,1-e),new D(n,1-b)]}};Oc.prototype=Object.create(M.prototype);Oc.prototype.constructor=Oc;Wb.prototype=Object.create(Fa.prototype);Wb.prototype.constructor=Wb;Pc.prototype=Object.create(M.prototype);Pc.prototype.constructor=Pc;nb.prototype=Object.create(I.prototype);nb.prototype.constructor=nb;Qc.prototype=Object.create(M.prototype);Qc.prototype.constructor=Qc;Xb.prototype=Object.create(I.prototype);Xb.prototype.constructor=Xb;Rc.prototype=
14165 Object.create(M.prototype);Rc.prototype.constructor=Rc;Yb.prototype=Object.create(I.prototype);Yb.prototype.constructor=Yb;Zb.prototype=Object.create(M.prototype);Zb.prototype.constructor=Zb;$b.prototype=Object.create(I.prototype);$b.prototype.constructor=$b;ac.prototype=Object.create(I.prototype);ac.prototype.constructor=ac;ob.prototype=Object.create(M.prototype);ob.prototype.constructor=ob;Wa.prototype=Object.create(I.prototype);Wa.prototype.constructor=Wa;Sc.prototype=Object.create(ob.prototype);
14166 Sc.prototype.constructor=Sc;Tc.prototype=Object.create(Wa.prototype);Tc.prototype.constructor=Tc;Uc.prototype=Object.create(M.prototype);Uc.prototype.constructor=Uc;bc.prototype=Object.create(I.prototype);bc.prototype.constructor=bc;var Ma=Object.freeze({WireframeGeometry:Ob,ParametricGeometry:Fc,ParametricBufferGeometry:Pb,TetrahedronGeometry:Hc,TetrahedronBufferGeometry:Qb,OctahedronGeometry:Ic,OctahedronBufferGeometry:mb,IcosahedronGeometry:Jc,IcosahedronBufferGeometry:Rb,DodecahedronGeometry:Kc,
14167 DodecahedronBufferGeometry:Sb,PolyhedronGeometry:Gc,PolyhedronBufferGeometry:ia,TubeGeometry:Lc,TubeBufferGeometry:Tb,TorusKnotGeometry:Mc,TorusKnotBufferGeometry:Ub,TorusGeometry:Nc,TorusBufferGeometry:Vb,TextGeometry:Oc,TextBufferGeometry:Wb,SphereGeometry:Pc,SphereBufferGeometry:nb,RingGeometry:Qc,RingBufferGeometry:Xb,PlaneGeometry:xc,PlaneBufferGeometry:lb,LatheGeometry:Rc,LatheBufferGeometry:Yb,ShapeGeometry:Zb,ShapeBufferGeometry:$b,ExtrudeGeometry:db,ExtrudeBufferGeometry:Fa,EdgesGeometry:ac,
14168 ConeGeometry:Sc,ConeBufferGeometry:Tc,CylinderGeometry:ob,CylinderBufferGeometry:Wa,CircleGeometry:Uc,CircleBufferGeometry:bc,BoxGeometry:Ib,BoxBufferGeometry:kb});cc.prototype=Object.create(Ea.prototype);cc.prototype.constructor=cc;cc.prototype.isShadowMaterial=!0;dc.prototype=Object.create(Ea.prototype);dc.prototype.constructor=dc;dc.prototype.isRawShaderMaterial=!0;Ra.prototype=Object.create(Z.prototype);Ra.prototype.constructor=Ra;Ra.prototype.isMeshStandardMaterial=!0;Ra.prototype.copy=function(a){Z.prototype.copy.call(this,
14169 a);this.defines={STANDARD:""};this.color.copy(a.color);this.roughness=a.roughness;this.metalness=a.metalness;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;
14170 this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.roughnessMap=a.roughnessMap;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=
14171 a.morphNormals;return this};pb.prototype=Object.create(Ra.prototype);pb.prototype.constructor=pb;pb.prototype.isMeshPhysicalMaterial=!0;pb.prototype.copy=function(a){Ra.prototype.copy.call(this,a);this.defines={PHYSICAL:""};this.reflectivity=a.reflectivity;this.clearCoat=a.clearCoat;this.clearCoatRoughness=a.clearCoatRoughness;return this};ta.prototype=Object.create(Z.prototype);ta.prototype.constructor=ta;ta.prototype.isMeshPhongMaterial=!0;ta.prototype.copy=function(a){Z.prototype.copy.call(this,
14172 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=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=
14173 a.displacementScale;this.displacementBias=a.displacementBias;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};qb.prototype=
14174 Object.create(ta.prototype);qb.prototype.constructor=qb;qb.prototype.isMeshToonMaterial=!0;qb.prototype.copy=function(a){ta.prototype.copy.call(this,a);this.gradientMap=a.gradientMap;return this};rb.prototype=Object.create(Z.prototype);rb.prototype.constructor=rb;rb.prototype.isMeshNormalMaterial=!0;rb.prototype.copy=function(a){Z.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;
14175 this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};sb.prototype=Object.create(Z.prototype);sb.prototype.constructor=sb;sb.prototype.isMeshLambertMaterial=!0;sb.prototype.copy=function(a){Z.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=
14176 a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=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;
14177 this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};tb.prototype=Object.create(Z.prototype);tb.prototype.constructor=tb;tb.prototype.isLineDashedMaterial=!0;tb.prototype.copy=function(a){Z.prototype.copy.call(this,a);this.color.copy(a.color);this.linewidth=a.linewidth;this.scale=a.scale;this.dashSize=a.dashSize;this.gapSize=a.gapSize;return this};var lg=Object.freeze({ShadowMaterial:cc,SpriteMaterial:cb,RawShaderMaterial:dc,ShaderMaterial:Ea,PointsMaterial:La,
14178 MeshPhysicalMaterial:pb,MeshStandardMaterial:Ra,MeshPhongMaterial:ta,MeshToonMaterial:qb,MeshNormalMaterial:rb,MeshLambertMaterial:sb,MeshDepthMaterial:$a,MeshBasicMaterial:Na,LineDashedMaterial:tb,LineBasicMaterial:ha,Material:Z}),hd={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={}}},Aa=new Zd;Object.assign(ua.prototype,{load:function(a,b,
14179 c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);var e=this,f=hd.get(a);if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;var g=a.match(/^data:(.*?)(;base64)?,(.*)$/);if(g){var h=g[1],k=!!g[2],g=g[3],g=window.decodeURIComponent(g);k&&(g=window.atob(g));try{var m,l=(this.responseType||"").toLowerCase();switch(l){case "arraybuffer":case "blob":m=new ArrayBuffer(g.length);for(var q=new Uint8Array(m),k=0;k<g.length;k++)q[k]=g.charCodeAt(k);
14180 "blob"===l&&(m=new Blob([m],{type:h}));break;case "document":m=(new DOMParser).parseFromString(g,h);break;case "json":m=JSON.parse(g);break;default:m=g}window.setTimeout(function(){b&&b(m);e.manager.itemEnd(a)},0)}catch(p){window.setTimeout(function(){d&&d(p);e.manager.itemEnd(a);e.manager.itemError(a)},0)}}else{var n=new XMLHttpRequest;n.open("GET",a,!0);n.addEventListener("load",function(c){var f=c.target.response;hd.add(a,f);200===this.status?(b&&b(f),e.manager.itemEnd(a)):0===this.status?(console.warn("THREE.FileLoader: HTTP Status 0 received."),
14181 b&&b(f),e.manager.itemEnd(a)):(d&&d(c),e.manager.itemEnd(a),e.manager.itemError(a))},!1);void 0!==c&&n.addEventListener("progress",function(a){c(a)},!1);n.addEventListener("error",function(b){d&&d(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,
14182 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=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){k.load(a[e],function(a){a=f._parser(a,!0);g[e]={width:a.width,height:a.height,
14183 format:a.format,mipmaps:a.mipmaps};m+=1;6===m&&(1===a.mipmapCount&&(h.minFilter=1006),h.format=a.format,h.needsUpdate=!0,b&&b(h))},c,d)}var f=this,g=[],h=new Nb;h.image=g;var k=new ua(this.manager);k.setPath(this.path);k.setResponseType("arraybuffer");if(Array.isArray(a))for(var m=0,l=0,q=a.length;l<q;++l)e(l);else k.load(a,function(a){a=f._parser(a,!0);if(a.isCubemap)for(var c=a.mipmaps.length/a.mipmapCount,d=0;d<c;d++){g[d]={mipmaps:[]};for(var e=0;e<a.mipmapCount;e++)g[d].mipmaps.push(a.mipmaps[d*
14184 a.mipmapCount+e]),g[d].format=a.format,g[d].width=a.width,g[d].height=a.height}else h.image.width=a.width,h.image.height=a.height,h.mipmaps=a.mipmaps;1===a.mipmapCount&&(h.minFilter=1006);h.format=a.format;h.needsUpdate=!0;b&&b(h)},c,d);return h},setPath:function(a){this.path=a;return this}});Object.assign($d.prototype,{load:function(a,b,c,d){var e=this,f=new eb,g=new ua(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!==
14185 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!==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(Vc.prototype,
14186 {load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);var e=this,f=hd.get(a);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(){hd.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&&
14187 (c.crossOrigin=this.crossOrigin);e.manager.itemStart(a);c.src=a;return c},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(ae.prototype,{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 Za,g=new Vc(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=
14188 a;return this},setPath:function(a){this.path=a;return this}});Object.assign(sd.prototype,{load:function(a,b,c,d){var e=new Vc(this.manager);e.setCrossOrigin(this.crossOrigin);e.setPath(this.path);var f=new X;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}});ma.prototype=Object.assign(Object.create(B.prototype),
14189 {constructor:ma,isLight:!0,copy:function(a){B.prototype.copy.call(this,a);this.color.copy(a.color);this.intensity=a.intensity;return this},toJSON:function(a){a=B.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!==
14190 this.penumbra&&(a.object.penumbra=this.penumbra);void 0!==this.shadow&&(a.object.shadow=this.shadow.toJSON());return a}});td.prototype=Object.assign(Object.create(ma.prototype),{constructor:td,isHemisphereLight:!0,copy:function(a){ma.prototype.copy.call(this,a);this.groundColor.copy(a.groundColor);return this}});Object.assign(ub.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)},
14191 toJSON:function(){var a={};0!==this.bias&&(a.bias=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}});ud.prototype=Object.assign(Object.create(ub.prototype),{constructor:ud,isSpotLightShadow:!0,update:function(a){var b=this.camera,c=2*Y.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=
14192 c,b.aspect=d,b.far=a,b.updateProjectionMatrix()}});vd.prototype=Object.assign(Object.create(ma.prototype),{constructor:vd,isSpotLight:!0,copy:function(a){ma.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}});wd.prototype=Object.assign(Object.create(ma.prototype),{constructor:wd,isPointLight:!0,copy:function(a){ma.prototype.copy.call(this,a);this.distance=a.distance;
14193 this.decay=a.decay;this.shadow=a.shadow.clone();return this}});xd.prototype=Object.assign(Object.create(ub.prototype),{constructor:xd});yd.prototype=Object.assign(Object.create(ma.prototype),{constructor:yd,isDirectionalLight:!0,copy:function(a){ma.prototype.copy.call(this,a);this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});zd.prototype=Object.assign(Object.create(ma.prototype),{constructor:zd,isAmbientLight:!0});Ad.prototype=Object.assign(Object.create(ma.prototype),{constructor:Ad,
14194 isRectAreaLight:!0,copy:function(a){ma.prototype.copy.call(this,a);this.width=a.width;this.height=a.height;return this},toJSON:function(a){a=ma.prototype.toJSON.call(this,a);a.object.width=this.width;a.object.height=this.height;return a}});var va={arraySlice:function(a,b,c){return va.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)},
14195 isTypedArray:function(a){return ArrayBuffer.isView(a)&&!(a instanceof 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=
14196 f[d],void 0!==g&&(b.push(f.time),c.push.apply(c,g)),f=a[e++];while(void 0!==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(Da.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-
14197 1,a,e)}if(c===f)break;e=d;d=b[++c];if(a<d)break b}d=b.length;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,
14198 e,a,d)},settings:null,DefaultSettings_:{},getSettings_:function(){return this.settings||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(a,b,c,d){throw Error("call to abstract method");},intervalChanged_:function(a,b,c){}});Object.assign(Da.prototype,{beforeStart_:Da.prototype.copySampleValue_,afterEnd_:Da.prototype.copySampleValue_});Bd.prototype=Object.assign(Object.create(Da.prototype),
14199 {constructor:Bd,DefaultSettings_:{endingStart:2400,endingEnd:2400},intervalChanged_:function(a,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=
14200 a/(h-c);this._offsetPrev=e*d;this._offsetNext=f*d},interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g,k=this._offsetPrev,m=this._offsetNext,l=this._weightPrev,q=this._weightNext,n=(c-b)/(d-b);c=n*n;d=c*n;b=-l*d+2*l*c-l*n;l=(1+l)*d+(-1.5-2*l)*c+(-.5+l)*n+1;n=(-1-q)*d+(1.5+q)*c+.5*n;q=q*d-q*c;for(c=0;c!==g;++c)e[c]=b*f[k+c]+l*f[h+c]+n*f[a+c]+q*f[m+c];return e}});Wc.prototype=Object.assign(Object.create(Da.prototype),{constructor:Wc,interpolate_:function(a,
14201 b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g;b=(c-b)/(d-b);c=1-b;for(d=0;d!==g;++d)e[d]=f[h+d]*c+f[a+d]*b;return e}});Cd.prototype=Object.assign(Object.create(Da.prototype),{constructor:Cd,interpolate_:function(a,b,c,d){return this.copySampleValue_(a-1)}});var Ya;Ya={TimeBufferType:Float32Array,ValueBufferType:Float32Array,DefaultInterpolation:2301,InterpolantFactoryMethodDiscrete:function(a){return new Cd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodLinear:function(a){return new Wc(this.times,
14202 this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:function(a){return new Bd(this.times,this.values,this.getValueSize(),a)},setInterpolation:function(a){var b;switch(a){case 2300: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);
14203 else throw Error(b);console.warn(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=
14204 0,d=b.length;c!==d;++c)b[c]*=a;return this},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),d=this.getValueSize(),this.times=va.arraySlice(c,e,f),this.values=va.arraySlice(this.values,e*d,f*d);return this},validate:function(){var a=!0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("invalid value size in track",this),a=!1);var c=this.times,b=this.values,d=c.length;0===d&&(console.error("track is empty",
14205 this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("time is not a valid number",this,f,g);a=!1;break}if(null!==e&&e>g){console.error("out of order keys",this,f,g,e);a=!1;break}e=g}if(void 0!==b&&va.isTypedArray(b))for(f=0,c=b.length;f!==c;++f)if(d=b[f],isNaN(d)){console.error("value is not a valid number",this,f,d);a=!1;break}return a},optimize:function(){for(var a=this.times,b=this.values,c=this.getValueSize(),d=2302===this.getInterpolation(),e=1,
14206 f=a.length-1,g=1;g<f;++g){var h=!1,k=a[g];if(k!==a[g+1]&&(1!==g||k!==k[0]))if(d)h=!0;else for(var m=g*c,l=m-c,q=m+c,k=0;k!==c;++k){var n=b[m+k];if(n!==b[l+k]||n!==b[q+k]){h=!0;break}}if(h){if(g!==e)for(a[e]=a[g],h=g*c,m=e*c,k=0;k!==c;++k)b[m+k]=b[h+k];++e}}if(0<f){a[e]=a[f];h=f*c;m=e*c;for(k=0;k!==c;++k)b[m+k]=b[h+k];++e}e!==a.length&&(this.times=va.arraySlice(a,0,e),this.values=va.arraySlice(b,0,e*c));return this}};ec.prototype=Object.assign(Object.create(Ya),{constructor:ec,ValueTypeName:"vector"});
14207 Dd.prototype=Object.assign(Object.create(Da.prototype),{constructor:Dd,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)qa.slerpFlat(e,0,f,a-g,f,a,b);return e}});Xc.prototype=Object.assign(Object.create(Ya),{constructor:Xc,ValueTypeName:"quaternion",DefaultInterpolation:2301,InterpolantFactoryMethodLinear:function(a){return new Dd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:void 0});
14208 fc.prototype=Object.assign(Object.create(Ya),{constructor:fc,ValueTypeName:"number"});Ed.prototype=Object.assign(Object.create(Ya),{constructor:Ed,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Fd.prototype=Object.assign(Object.create(Ya),{constructor:Fd,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});
14209 Gd.prototype=Object.assign(Object.create(Ya),{constructor:Gd,ValueTypeName:"color"});wb.prototype=Ya;Ya.constructor=wb;Object.assign(wb,{parse:function(a){if(void 0===a.type)throw Error("track type undefined, can not parse");var b=wb._getTrackTypeForValueTypeName(a.type);if(void 0===a.times){var c=[],d=[];va.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,a.interpolation)},toJSON:function(a){var b=a.constructor;if(void 0!==b.toJSON)b=
14210 b.toJSON(a);else{var b={name:a.name,times:va.convertArray(a.times,Array),values:va.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 fc;case "vector":case "vector2":case "vector3":case "vector4":return ec;case "color":return Gd;case "quaternion":return Xc;case "bool":case "boolean":return Fd;
14211 case "string":return Ed}throw Error("Unsupported typeName: "+a);}});Object.assign(Ba,{parse:function(a){for(var b=[],c=a.tracks,d=1/(a.fps||1),e=0,f=c.length;e!==f;++e)b.push(wb.parse(c[e]).scale(d));return new Ba(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(wb.toJSON(c[d]));return a},CreateFromMorphTargetSequence:function(a,b,c,d){for(var e=b.length,f=[],g=0;g<e;g++){var h=[],k=[];h.push((g+e-1)%
14212 e,g,(g+1)%e);k.push(0,1,0);var m=va.getKeyframeOrder(h),h=va.sortedArray(h,1,m),k=va.sortedArray(k,1,m);d||0!==h[0]||(h.push(e),k.push(k[0]));f.push((new fc(".morphTargetInfluences["+b[g].name+"]",h,k)).scale(1/c))}return new Ba(a,-1,f)},findByName:function(a,b){var c=a;Array.isArray(a)||(c=a.geometry&&a.geometry.animations||a.animations);for(var d=0;d<c.length;d++)if(c[d].name===b)return c[d];return null},CreateClipsFromMorphTargetSequences:function(a,b,c){for(var d={},e=/^([\w-]*?)([\d]+)$/,f=0,
14213 g=a.length;f<g;f++){var h=a[f],k=h.name.match(e);if(k&&1<k.length){var m=k[1];(k=d[m])||(d[m]=k=[]);k.push(h)}}a=[];for(m in d)a.push(Ba.CreateFromMorphTargetSequence(m,d[m],b,c));return a},parseAnimation:function(a,b){if(!a)return console.error(" no animation in JSONLoader data"),null;for(var c=function(a,b,c,d,e){if(0!==c.length){var f=[],g=[];va.flattenJSON(c,f,g,d);0!==f.length&&e.push(new a(b,f,g))}},d=[],e=a.name||"default",f=a.length||-1,g=a.fps||30,h=a.hierarchy||[],k=0;k<h.length;k++){var m=
14214 h[k].keys;if(m&&0!==m.length)if(m[0].morphTargets){for(var f={},l=0;l<m.length;l++)if(m[l].morphTargets)for(var q=0;q<m[l].morphTargets.length;q++)f[m[l].morphTargets[q]]=-1;for(var n in f){for(var p=[],z=[],q=0;q!==m[l].morphTargets.length;++q){var t=m[l];p.push(t.time);z.push(t.morphTarget===n?1:0)}d.push(new fc(".morphTargetInfluence["+n+"]",p,z))}f=f.length*(g||1)}else l=".bones["+b[k].name+"]",c(ec,l+".position",m,"pos",d),c(Xc,l+".quaternion",m,"rot",d),c(ec,l+".scale",m,"scl",d)}return 0===
14215 d.length?null:new Ba(e,f,d)}});Object.assign(Ba.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(Hd.prototype,{load:function(a,b,c,d){var e=this,f=new ua(e.manager);f.setResponseType("json");
14216 f.load(a,function(a){b(e.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 lg[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);void 0!==a.emissive&&d.emissive.setHex(a.emissive);void 0!==
14217 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!==a.fog&&(d.fog=a.fog);void 0!==a.shading&&(d.shading=a.shading);
14218 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!==a.wireframeLinewidth&&(d.wireframeLinewidth=a.wireframeLinewidth);void 0!==
14219 a.wireframeLinecap&&(d.wireframeLinecap=a.wireframeLinecap);void 0!==a.wireframeLinejoin&&(d.wireframeLinejoin=a.wireframeLinejoin);void 0!==a.skinning&&(d.skinning=a.skinning);void 0!==a.morphTargets&&(d.morphTargets=a.morphTargets);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=
14220 a.bumpScale);void 0!==a.normalMap&&(d.normalMap=b(a.normalMap));if(void 0!==a.normalScale){var e=a.normalScale;!1===Array.isArray(e)&&(e=[e,e]);d.normalScale=(new D).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));
14221 void 0!==a.emissiveMap&&(d.emissiveMap=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);
14222 void 0!==a.gradientMap&&(d.gradientMap=b(a.gradientMap));return d}});Object.assign(be.prototype,{load:function(a,b,c,d){var e=this,f=new ua(e.manager);f.setResponseType("json");f.load(a,function(a){b(e.parse(a))},c,d)},parse:function(a){var b=new I,c=a.data.index;void 0!==c&&(c=new ff[c.type](c.array),b.setIndex(new L(c,1)));var d=a.data.attributes,e;for(e in d){var f=d[e],c=new ff[f.type](f.array);b.addAttribute(e,new L(c,f.itemSize,f.normalized))}e=a.data.groups||a.data.drawcalls||a.data.offsets;
14223 if(void 0!==e)for(c=0,d=e.length;c!==d;++c)f=e[c],b.addGroup(f.start,f.count,f.materialIndex);a=a.data.boundingSphere;void 0!==a&&(e=new p,void 0!==a.center&&e.fromArray(a.center),b.boundingSphere=new Ga(e,a.radius));return b}});var ff={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};gc.Handlers={handlers:[],add:function(a,b){this.handlers.push(a,
14224 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(gc.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},
14225 b=new H,c=new sd,d=new Hd;return function(e,f,g){function h(a,b,d,e,h){a=f+a;var m=gc.Handlers.get(a);null!==m?a=m.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=Y.generateUUID();k[b]=a;return b}var k={},m={uuid:Y.generateUUID(),
14226 type:"MeshLambertMaterial"},l;for(l in e){var q=e[l];switch(l){case "DbgColor":case "DbgIndex":case "opticalDensity":case "illumination":break;case "DbgName":m.name=q;break;case "blending":m.blending=a[q];break;case "colorAmbient":case "mapAmbient":console.warn("THREE.Loader.createMaterial:",l,"is no longer supported.");break;case "colorDiffuse":m.color=b.fromArray(q).getHex();break;case "colorSpecular":m.specular=b.fromArray(q).getHex();break;case "colorEmissive":m.emissive=b.fromArray(q).getHex();
14227 break;case "specularCoef":m.shininess=q;break;case "shading":"basic"===q.toLowerCase()&&(m.type="MeshBasicMaterial");"phong"===q.toLowerCase()&&(m.type="MeshPhongMaterial");"standard"===q.toLowerCase()&&(m.type="MeshStandardMaterial");break;case "mapDiffuse":m.map=h(q,e.mapDiffuseRepeat,e.mapDiffuseOffset,e.mapDiffuseWrap,e.mapDiffuseAnisotropy);break;case "mapDiffuseRepeat":case "mapDiffuseOffset":case "mapDiffuseWrap":case "mapDiffuseAnisotropy":break;case "mapEmissive":m.emissiveMap=h(q,e.mapEmissiveRepeat,
14228 e.mapEmissiveOffset,e.mapEmissiveWrap,e.mapEmissiveAnisotropy);break;case "mapEmissiveRepeat":case "mapEmissiveOffset":case "mapEmissiveWrap":case "mapEmissiveAnisotropy":break;case "mapLight":m.lightMap=h(q,e.mapLightRepeat,e.mapLightOffset,e.mapLightWrap,e.mapLightAnisotropy);break;case "mapLightRepeat":case "mapLightOffset":case "mapLightWrap":case "mapLightAnisotropy":break;case "mapAO":m.aoMap=h(q,e.mapAORepeat,e.mapAOOffset,e.mapAOWrap,e.mapAOAnisotropy);break;case "mapAORepeat":case "mapAOOffset":case "mapAOWrap":case "mapAOAnisotropy":break;
14229 case "mapBump":m.bumpMap=h(q,e.mapBumpRepeat,e.mapBumpOffset,e.mapBumpWrap,e.mapBumpAnisotropy);break;case "mapBumpScale":m.bumpScale=q;break;case "mapBumpRepeat":case "mapBumpOffset":case "mapBumpWrap":case "mapBumpAnisotropy":break;case "mapNormal":m.normalMap=h(q,e.mapNormalRepeat,e.mapNormalOffset,e.mapNormalWrap,e.mapNormalAnisotropy);break;case "mapNormalFactor":m.normalScale=[q,q];break;case "mapNormalRepeat":case "mapNormalOffset":case "mapNormalWrap":case "mapNormalAnisotropy":break;case "mapSpecular":m.specularMap=
14230 h(q,e.mapSpecularRepeat,e.mapSpecularOffset,e.mapSpecularWrap,e.mapSpecularAnisotropy);break;case "mapSpecularRepeat":case "mapSpecularOffset":case "mapSpecularWrap":case "mapSpecularAnisotropy":break;case "mapMetalness":m.metalnessMap=h(q,e.mapMetalnessRepeat,e.mapMetalnessOffset,e.mapMetalnessWrap,e.mapMetalnessAnisotropy);break;case "mapMetalnessRepeat":case "mapMetalnessOffset":case "mapMetalnessWrap":case "mapMetalnessAnisotropy":break;case "mapRoughness":m.roughnessMap=h(q,e.mapRoughnessRepeat,
14231 e.mapRoughnessOffset,e.mapRoughnessWrap,e.mapRoughnessAnisotropy);break;case "mapRoughnessRepeat":case "mapRoughnessOffset":case "mapRoughnessWrap":case "mapRoughnessAnisotropy":break;case "mapAlpha":m.alphaMap=h(q,e.mapAlphaRepeat,e.mapAlphaOffset,e.mapAlphaWrap,e.mapAlphaAnisotropy);break;case "mapAlphaRepeat":case "mapAlphaOffset":case "mapAlphaWrap":case "mapAlphaAnisotropy":break;case "flipSided":m.side=1;break;case "doubleSided":m.side=2;break;case "transparency":console.warn("THREE.Loader.createMaterial: transparency has been renamed to opacity");
14232 m.opacity=q;break;case "depthTest":case "depthWrite":case "colorWrite":case "opacity":case "reflectivity":case "transparent":case "visible":case "wireframe":m[l]=q;break;case "vertexColors":!0===q&&(m.vertexColors=2);"face"===q&&(m.vertexColors=1);break;default:console.error("THREE.Loader.createMaterial: Unsupported",l,q)}}"MeshBasicMaterial"===m.type&&delete m.emissive;"MeshPhongMaterial"!==m.type&&delete m.specular;1>m.opacity&&(m.transparent=!0);d.setTextures(k);return d.parse(m)}}()});Object.assign(ce.prototype,
14233 {load:function(a,b,c,d){var e=this,f=this.texturePath&&"string"===typeof this.texturePath?this.texturePath:gc.prototype.extractUrlBase(a),g=new ua(this.manager);g.setResponseType("json");g.setWithCredentials(this.withCredentials);g.load(a,function(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+
14234 " should be loaded with THREE.SceneLoader instead.");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 M,d=a,e,f,g,h,k,m,l,q,n,r,z,t,y,x,v=d.faces;n=d.vertices;var G=d.normals,w=d.colors;m=d.scale;var B=0;if(void 0!==d.uvs){for(e=0;e<d.uvs.length;e++)d.uvs[e].length&&B++;for(e=0;e<B;e++)c.faceVertexUvs[e]=[]}h=0;for(k=n.length;h<k;)e=
14235 new p,e.x=n[h++]*m,e.y=n[h++]*m,e.z=n[h++]*m,c.vertices.push(e);h=0;for(k=v.length;h<k;)if(n=v[h++],r=n&1,g=n&2,e=n&8,l=n&16,z=n&32,m=n&64,n&=128,r){r=new Va;r.a=v[h];r.b=v[h+1];r.c=v[h+3];t=new Va;t.a=v[h+1];t.b=v[h+2];t.c=v[h+3];h+=4;g&&(g=v[h++],r.materialIndex=g,t.materialIndex=g);g=c.faces.length;if(e)for(e=0;e<B;e++)for(y=d.uvs[e],c.faceVertexUvs[e][g]=[],c.faceVertexUvs[e][g+1]=[],f=0;4>f;f++)q=v[h++],x=y[2*q],q=y[2*q+1],x=new D(x,q),2!==f&&c.faceVertexUvs[e][g].push(x),0!==f&&c.faceVertexUvs[e][g+
14236 1].push(x);l&&(l=3*v[h++],r.normal.set(G[l++],G[l++],G[l]),t.normal.copy(r.normal));if(z)for(e=0;4>e;e++)l=3*v[h++],z=new p(G[l++],G[l++],G[l]),2!==e&&r.vertexNormals.push(z),0!==e&&t.vertexNormals.push(z);m&&(m=v[h++],m=w[m],r.color.setHex(m),t.color.setHex(m));if(n)for(e=0;4>e;e++)m=v[h++],m=w[m],2!==e&&r.vertexColors.push(new H(m)),0!==e&&t.vertexColors.push(new H(m));c.faces.push(r);c.faces.push(t)}else{r=new Va;r.a=v[h++];r.b=v[h++];r.c=v[h++];g&&(g=v[h++],r.materialIndex=g);g=c.faces.length;
14237 if(e)for(e=0;e<B;e++)for(y=d.uvs[e],c.faceVertexUvs[e][g]=[],f=0;3>f;f++)q=v[h++],x=y[2*q],q=y[2*q+1],x=new D(x,q),c.faceVertexUvs[e][g].push(x);l&&(l=3*v[h++],r.normal.set(G[l++],G[l++],G[l]));if(z)for(e=0;3>e;e++)l=3*v[h++],z=new p(G[l++],G[l++],G[l]),r.vertexNormals.push(z);m&&(m=v[h++],r.color.setHex(w[m]));if(n)for(e=0;3>e;e++)m=v[h++],r.vertexColors.push(new H(w[m]));c.faces.push(r)}d=a;h=void 0!==d.influencesPerVertex?d.influencesPerVertex:2;if(d.skinWeights)for(k=0,v=d.skinWeights.length;k<
14238 v;k+=h)c.skinWeights.push(new ga(d.skinWeights[k],1<h?d.skinWeights[k+1]:0,2<h?d.skinWeights[k+2]:0,3<h?d.skinWeights[k+3]:0));if(d.skinIndices)for(k=0,v=d.skinIndices.length;k<v;k+=h)c.skinIndices.push(new ga(d.skinIndices[k],1<h?d.skinIndices[k+1]:0,2<h?d.skinIndices[k+2]:0,3<h?d.skinIndices[k+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+
14239 "), skinIndices ("+c.skinIndices.length+"), and skinWeights ("+c.skinWeights.length+") should match.");k=a;v=k.scale;if(void 0!==k.morphTargets)for(d=0,h=k.morphTargets.length;d<h;d++)for(c.morphTargets[d]={},c.morphTargets[d].name=k.morphTargets[d].name,c.morphTargets[d].vertices=[],G=c.morphTargets[d].vertices,w=k.morphTargets[d].vertices,B=0,n=w.length;B<n;B+=3)m=new p,m.x=w[B]*v,m.y=w[B+1]*v,m.z=w[B+2]*v,G.push(m);if(void 0!==k.morphColors&&0<k.morphColors.length)for(console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.'),
14240 v=c.faces,k=k.morphColors[0].colors,d=0,h=v.length;d<h;d++)v[d].color.fromArray(k,3*d);k=a;d=[];h=[];void 0!==k.animation&&h.push(k.animation);void 0!==k.animations&&(k.animations.length?h=h.concat(k.animations):h.push(k.animations));for(k=0;k<h.length;k++)(v=Ba.parseAnimation(h[k],c.bones))&&d.push(v);c.morphTargets&&(h=Ba.CreateClipsFromMorphTargetSequences(c.morphTargets,10),d=d.concat(h));0<d.length&&(c.animations=d);c.computeFaceNormals();c.computeBoundingSphere();if(void 0===a.materials||0===
14241 a.materials.length)return{geometry:c};d=gc.prototype.initMaterials(a.materials,b,this.crossOrigin);return{geometry:c,materials:d}}}()});Object.assign(Re.prototype,{load:function(a,b,c,d){""===this.texturePath&&(this.texturePath=a.substring(0,a.lastIndexOf("/")+1));var e=this;(new ua(e.manager)).load(a,function(c){var g=null;try{g=JSON.parse(c)}catch(h){void 0!==d&&d(h);console.error("THREE:ObjectLoader: Can't parse "+a+".",h.message);return}c=g.metadata;void 0===c||void 0===c.type||"geometry"===c.type.toLowerCase()?
14242 console.error("THREE.ObjectLoader: Can't load "+a+". Use THREE.JSONLoader instead."):e.parse(g,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&&
14243 0!==a.images.length||void 0===b||b(e);return e},parseGeometries:function(a){var b={};if(void 0!==a)for(var c=new ce,d=new be,e=0,f=a.length;e<f;e++){var g,h=a[e];switch(h.type){case "PlaneGeometry":case "PlaneBufferGeometry":g=new Ma[h.type](h.width,h.height,h.widthSegments,h.heightSegments);break;case "BoxGeometry":case "BoxBufferGeometry":case "CubeGeometry":g=new Ma[h.type](h.width,h.height,h.depth,h.widthSegments,h.heightSegments,h.depthSegments);break;case "CircleGeometry":case "CircleBufferGeometry":g=
14244 new Ma[h.type](h.radius,h.segments,h.thetaStart,h.thetaLength);break;case "CylinderGeometry":case "CylinderBufferGeometry":g=new Ma[h.type](h.radiusTop,h.radiusBottom,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "ConeGeometry":case "ConeBufferGeometry":g=new Ma[h.type](h.radius,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "SphereGeometry":case "SphereBufferGeometry":g=new Ma[h.type](h.radius,h.widthSegments,
14245 h.heightSegments,h.phiStart,h.phiLength,h.thetaStart,h.thetaLength);break;case "DodecahedronGeometry":case "IcosahedronGeometry":case "OctahedronGeometry":case "TetrahedronGeometry":g=new Ma[h.type](h.radius,h.detail);break;case "RingGeometry":case "RingBufferGeometry":g=new Ma[h.type](h.innerRadius,h.outerRadius,h.thetaSegments,h.phiSegments,h.thetaStart,h.thetaLength);break;case "TorusGeometry":case "TorusBufferGeometry":g=new Ma[h.type](h.radius,h.tube,h.radialSegments,h.tubularSegments,h.arc);
14246 break;case "TorusKnotGeometry":case "TorusKnotBufferGeometry":g=new Ma[h.type](h.radius,h.tube,h.tubularSegments,h.radialSegments,h.p,h.q);break;case "LatheGeometry":case "LatheBufferGeometry":g=new Ma[h.type](h.points,h.segments,h.phiStart,h.phiLength);break;case "BufferGeometry":g=d.parse(h);break;case "Geometry":g=c.parse(h,this.texturePath).geometry;break;default:console.warn('THREE.ObjectLoader: Unsupported geometry type "'+h.type+'"');continue}g.uuid=h.uuid;void 0!==h.name&&(g.name=h.name);
14247 b[h.uuid]=g}return b},parseMaterials:function(a,b){var c={};if(void 0!==a){var d=new Hd;d.setTextures(b);for(var e=0,f=a.length;e<f;e++){var g=a[e];if("MultiMaterial"===g.type){for(var h=[],k=0;k<g.materials.length;k++)h.push(d.parse(g.materials[k]));c[g.uuid]=h}else c[g.uuid]=d.parse(g)}}return c},parseAnimations:function(a){for(var b=[],c=0;c<a.length;c++){var d=Ba.parse(a[c]);b.push(d)}return b},parseImages:function(a,b){function c(a){d.manager.itemStart(a);return g.load(a,function(){d.manager.itemEnd(a)},
14248 void 0,function(){d.manager.itemEnd(a);d.manager.itemError(a)})}var d=this,e={};if(void 0!==a&&0<a.length){var f=new Zd(b),g=new Vc(f);g.setCrossOrigin(this.crossOrigin);for(var f=0,h=a.length;f<h;f++){var k=a[f],l=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(k.url)?k.url:d.texturePath+k.url;e[k.uuid]=c(l)}}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!==
14249 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 X(b[g.image]);h.needsUpdate=!0;h.uuid=g.uuid;void 0!==g.name&&(h.name=g.name);void 0!==g.mapping&&(h.mapping=c(g.mapping,mg));void 0!==g.offset&&h.offset.fromArray(g.offset);void 0!==g.repeat&&h.repeat.fromArray(g.repeat);void 0!==g.wrap&&(h.wrapS=c(g.wrap[0],gf),h.wrapT=c(g.wrap[1],
14250 gf));void 0!==g.minFilter&&(h.minFilter=c(g.minFilter,hf));void 0!==g.magFilter&&(h.magFilter=c(g.magFilter,hf));void 0!==g.anisotropy&&(h.anisotropy=g.anisotropy);void 0!==g.flipY&&(h.flipY=g.flipY);d[g.uuid]=h}return d},parseObject:function(){var a=new J;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",
14251 f);b.push(d[f])}return b}void 0===d[a]&&console.warn("THREE.ObjectLoader: Undefined material",a);return d[a]}}var g;switch(b.type){case "Scene":g=new md;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 Lb(b.fog.color,b.fog.near,b.fog.far):"FogExp2"===b.fog.type&&(g.fog=new Kb(b.fog.color,b.fog.density)));break;case "PerspectiveCamera":g=new xa(b.fov,b.aspect,b.near,b.far);void 0!==b.focus&&(g.focus=b.focus);void 0!==
14252 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=Object.assign({},b.view));break;case "OrthographicCamera":g=new Jb(b.left,b.right,b.top,b.bottom,b.near,b.far);break;case "AmbientLight":g=new zd(b.color,b.intensity);break;case "DirectionalLight":g=new yd(b.color,b.intensity);break;case "PointLight":g=new wd(b.color,b.intensity,b.distance,b.decay);break;case "RectAreaLight":g=new Ad(b.color,b.intensity,
14253 b.width,b.height);break;case "SpotLight":g=new vd(b.color,b.intensity,b.distance,b.angle,b.penumbra,b.decay);break;case "HemisphereLight":g=new td(b.color,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 od(g,h):new Ca(g,h);break;case "LOD":g=new Bc;break;case "Line":g=new ya(e(b.geometry),f(b.material),b.mode);break;case "LineLoop":g=
14254 new pd(e(b.geometry),f(b.material));break;case "LineSegments":g=new da(e(b.geometry),f(b.material));break;case "PointCloud":case "Points":g=new Mb(e(b.geometry),f(b.material));break;case "Sprite":g=new Ac(f(b.material));break;case "Group":g=new Dc;break;default:g=new B}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),
14255 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);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!==
14256 b.visible&&(g.visible=b.visible);void 0!==b.userData&&(g.userData=b.userData);if(void 0!==b.children)for(var k in b.children)g.add(this.parseObject(b.children[k],c,d));if("LOD"===b.type)for(b=b.levels,h=0;h<b.length;h++){var l=b[h];k=g.getObjectByProperty("uuid",l.object);void 0!==k&&g.addLevel(k,l.distance)}return g}}()});var mg={UVMapping:300,CubeReflectionMapping:301,CubeRefractionMapping:302,EquirectangularReflectionMapping:303,EquirectangularRefractionMapping:304,SphericalReflectionMapping:305,
14257 CubeUVReflectionMapping:306,CubeUVRefractionMapping:307},gf={RepeatWrapping:1E3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002},hf={NearestFilter:1003,NearestMipMapNearestFilter:1004,NearestMipMapLinearFilter:1005,LinearFilter:1006,LinearMipMapNearestFilter:1007,LinearMipMapLinearFilter:1008};Object.assign(na.prototype,{getPoint:function(){console.warn("THREE.Curve: .getPoint() not implemented.");return null},getPointAt:function(a){a=this.getUtoTmapping(a);return this.getPoint(a)},getPoints:function(a){void 0===
14258 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/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,d=this.getPoint(0),e,f=0;b.push(0);for(e=1;e<=a;e++)c=
14259 this.getPoint(e/a),f+=c.distanceTo(d),b.push(f),d=c;return this.cacheArcLengths=b},updateArcLengths:function(){this.needsUpdate=!0;this.getLengths()},getUtoTmapping:function(a,b){var c=this.getLengths(),d,e=c.length,f;f=b?b:a*c[e-1];for(var g=0,h=e-1,k;g<=h;)if(d=Math.floor(g+(h-g)/2),k=c[d]-f,0>k)g=d+1;else if(0<k)h=d-1;else{h=d;break}d=h;if(c[d]===f)return d/(e-1);g=c[d];return(d+(f-g)/(c[d+1]-g))/(e-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()},
14260 getTangentAt:function(a){a=this.getUtoTmapping(a);return this.getTangent(a)},computeFrenetFrames:function(a,b){var c=new p,d=[],e=[],f=[],g=new p,h=new J,k,l;for(k=0;k<=a;k++)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 u=Math.abs(d[0].y),q=Math.abs(d[0].z);l<=k&&(k=l,c.set(1,0,0));u<=k&&(k=u,c.set(0,1,0));q<=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]=
14261 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(Y.clamp(d[k-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(Y.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}}});Sa.prototype=Object.create(na.prototype);
14262 Sa.prototype.constructor=Sa;Sa.prototype.isLineCurve=!0;Sa.prototype.getPoint=function(a){if(1===a)return this.v2.clone();var b=this.v2.clone().sub(this.v1);b.multiplyScalar(a).add(this.v1);return b};Sa.prototype.getPointAt=function(a){return this.getPoint(a)};Sa.prototype.getTangent=function(a){return this.v2.clone().sub(this.v1).normalize()};Yc.prototype=Object.assign(Object.create(na.prototype),{constructor:Yc,add:function(a){this.curves.push(a)},closePath:function(){var a=this.curves[0].getPoint(0),
14263 b=this.curves[this.curves.length-1].getPoint(1);a.equals(b)||this.curves.push(new Sa(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=!0;this.cacheLengths=null;this.getCurveLengths()},getCurveLengths:function(){if(this.cacheLengths&&
14264 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=e[d],f=f.getPoints(f&&f.isEllipseCurve?2*a:f&&f.isLineCurve?1:f&&f.isSplineCurve?a*f.points.length:
14265 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},createPointsGeometry:function(a){a=this.getPoints(a);return this.createGeometry(a)},createSpacedPointsGeometry:function(a){a=this.getSpacedPoints(a);return this.createGeometry(a)},createGeometry:function(a){for(var b=new M,c=0,d=a.length;c<d;c++){var e=a[c];b.vertices.push(new p(e.x,e.y,e.z||0))}return b}});Xa.prototype=Object.create(na.prototype);Xa.prototype.constructor=
14266 Xa;Xa.prototype.isEllipseCurve=!0;Xa.prototype.getPoint=function(a){for(var b=2*Math.PI,c=this.aEndAngle-this.aStartAngle,d=Math.abs(c)<Number.EPSILON;0>c;)c+=b;for(;c>b;)c-=b;c<Number.EPSILON&&(c=d?0:b);!0!==this.aClockwise||d||(c=c===b?-b:c-b);b=this.aStartAngle+a*c;a=this.aX+this.xRadius*Math.cos(b);var e=this.aY+this.yRadius*Math.sin(b);0!==this.aRotation&&(b=Math.cos(this.aRotation),c=Math.sin(this.aRotation),d=a-this.aX,e-=this.aY,a=d*b-e*c+this.aX,e=d*c+e*b+this.aY);return new D(a,e)};zb.prototype=
14267 Object.create(na.prototype);zb.prototype.constructor=zb;zb.prototype.isSplineCurve=!0;zb.prototype.getPoint=function(a){var b=this.points,c=(b.length-1)*a;a=Math.floor(c);var c=c-a,d=b[0===a?a:a-1],e=b[a],f=b[a>b.length-2?b.length-1:a+1],b=b[a>b.length-3?b.length-1:a+2];return new D(Se(c,d.x,e.x,f.x,b.x),Se(c,d.y,e.y,f.y,b.y))};hc.prototype=Object.create(na.prototype);hc.prototype.constructor=hc;hc.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2,e=this.v3;return new D(yb(a,b.x,c.x,
14268 d.x,e.x),yb(a,b.y,c.y,d.y,e.y))};ic.prototype=Object.create(na.prototype);ic.prototype.constructor=ic;ic.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2;return new D(xb(a,b.x,c.x,d.x),xb(a,b.y,c.y,d.y))};var ue=Object.assign(Object.create(Yc.prototype),{fromPoints: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 Sa(this.currentPoint.clone(),new D(a,b));
14269 this.curves.push(c);this.currentPoint.set(a,b)},quadraticCurveTo:function(a,b,c,d){a=new ic(this.currentPoint.clone(),new D(a,b),new D(c,d));this.curves.push(a);this.currentPoint.set(c,d)},bezierCurveTo:function(a,b,c,d,e,f){a=new hc(this.currentPoint.clone(),new D(a,b),new D(c,d),new D(e,f));this.curves.push(a);this.currentPoint.set(e,f)},splineThru:function(a){var b=[this.currentPoint.clone()].concat(a),b=new zb(b);this.curves.push(b);this.currentPoint.copy(a[a.length-1])},arc:function(a,b,c,d,
14270 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,e,f,g,h){a=new Xa(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)}});Zc.prototype=ue;ue.constructor=Zc;Ab.prototype=
14271 Object.assign(Object.create(ue),{constructor:Ab,getPointsHoles:function(a){for(var b=[],c=0,d=this.holes.length;c<d;c++)b[c]=this.holes[c].getPoints(a);return b},extractAllPoints:function(a){return{shape:this.getPoints(a),holes:this.getPointsHoles(a)}},extractPoints:function(a){return this.extractAllPoints(a)}});Object.assign(de.prototype,{moveTo:function(a,b){this.currentPath=new Zc;this.subPaths.push(this.currentPath);this.currentPath.moveTo(a,b)},lineTo:function(a,b){this.currentPath.lineTo(a,
14272 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,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 Ab;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,
14273 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<=a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=za.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);var g,h,k,l=[];if(1===f.length)return h=f[0],k=new Ab,k.curves=h.curves,l.push(k),l;var p=!e(f[0].getPoints()),p=a?!p:p;k=[];var q=[],n=[],r=0,z;q[r]=void 0;n[r]=[];for(var t=0,y=f.length;t<y;t++)h=f[t],z=h.getPoints(),
14274 g=e(z),(g=a?!g:g)?(!p&&q[r]&&r++,q[r]={s:new Ab,p:z},q[r].s.curves=h.curves,p&&r++,n[r]=[]):n[r].push({h:h,p:z[0]});if(!q[0])return c(f);if(1<q.length){t=!1;h=[];e=0;for(f=q.length;e<f;e++)k[e]=[];e=0;for(f=q.length;e<f;e++)for(g=n[e],p=0;p<g.length;p++){r=g[p];z=!0;for(y=0;y<q.length;y++)d(r.p,q[y].p)&&(e!==y&&h.push({froms:e,tos:y,hole:p}),z?(z=!1,k[y].push(r)):t=!0);z&&k[e].push(r)}0<h.length&&(t||(n=k))}t=0;for(e=q.length;t<e;t++)for(k=q[t].s,l.push(k),h=n[t],f=0,g=h.length;f<g;f++)k.holes.push(h[f].h);
14275 return l}});Object.assign(ee.prototype,{isFont:!0,generateShapes:function(a,b,c){void 0===b&&(b=100);void 0===c&&(c=4);var d=this.data;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 p;p=e;var q=g,n=h;if(l=d.glyphs[l]||d.glyphs["?"]){var r=new de,z=[],t,y,x,v,B,w,C,D;if(l.o)for(var E=l._cachedOutline||(l._cachedOutline=l.o.split(" ")),F=0,I=E.length;F<I;)switch(E[F++]){case "m":t=
14276 E[F++]*p+q;y=E[F++]*p+n;r.moveTo(t,y);break;case "l":t=E[F++]*p+q;y=E[F++]*p+n;r.lineTo(t,y);break;case "q":t=E[F++]*p+q;y=E[F++]*p+n;B=E[F++]*p+q;w=E[F++]*p+n;r.quadraticCurveTo(B,w,t,y);if(v=z[z.length-1]){x=v.x;v=v.y;for(var H=1;H<=c;H++){var J=H/c;xb(J,x,B,t);xb(J,v,w,y)}}break;case "b":if(t=E[F++]*p+q,y=E[F++]*p+n,B=E[F++]*p+q,w=E[F++]*p+n,C=E[F++]*p+q,D=E[F++]*p+n,r.bezierCurveTo(B,w,C,D,t,y),v=z[z.length-1])for(x=v.x,v=v.y,H=1;H<=c;H++)J=H/c,yb(J,x,B,C,t),yb(J,v,w,D,y)}p={offsetX:l.ha*p,path:r}}else p=
14277 void 0;g+=p.offsetX;b.push(p.path)}}c=[];d=0;for(a=b.length;d<a;d++)Array.prototype.push.apply(c,b[d].toShapes());return c}});Object.assign(Te.prototype,{load:function(a,b,c,d){var e=this;(new ua(this.manager)).load(a,function(a){var c;try{c=JSON.parse(a)}catch(d){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 ee(a)}});var Od,ie={getContext:function(){void 0===
14278 Od&&(Od=new (window.AudioContext||window.webkitAudioContext));return Od},setContext:function(a){Od=a}};Object.assign(fe.prototype,{load:function(a,b,c,d){var e=new ua(this.manager);e.setResponseType("arraybuffer");e.load(a,function(a){ie.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 J,l=new J;return function(p){if(a!==this||b!==p.focus||c!==p.fov||d!==p.aspect*this.aspect||e!==p.near||f!==p.far||g!==p.zoom||h!==this.eyeSep){a=
14279 this;b=p.focus;c=p.fov;d=p.aspect*this.aspect;e=p.near;f=p.far;g=p.zoom;var q=p.projectionMatrix.clone();h=this.eyeSep/2;var n=h*e/b,r=e*Math.tan(Y.DEG2RAD*c*.5)/g,z,t;l.elements[12]=-h;k.elements[12]=h;z=-r*d+n;t=r*d+n;q.elements[0]=2*e/(t-z);q.elements[8]=(t+z)/(t-z);this.cameraL.projectionMatrix.copy(q);z=-r*d-n;t=r*d-n;q.elements[0]=2*e/(t-z);q.elements[8]=(t+z)/(t-z);this.cameraR.projectionMatrix.copy(q)}this.cameraL.matrixWorld.copy(p.matrixWorld).multiply(l);this.cameraR.matrixWorld.copy(p.matrixWorld).multiply(k)}}()});
14280 Id.prototype=Object.create(B.prototype);Id.prototype.constructor=Id;ge.prototype=Object.assign(Object.create(xa.prototype),{constructor:ge,isArrayCamera:!0});he.prototype=Object.assign(Object.create(B.prototype),{constructor:he,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!==
14281 this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):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 qa,c=new p,d=new p;return function(e){B.prototype.updateMatrixWorld.call(this,e);e=this.context.listener;var f=
14282 this.up;this.matrixWorld.decompose(a,b,c);d.set(0,0,-1).applyQuaternion(b);e.positionX?(e.positionX.setValueAtTime(a.x,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,
14283 this.context.currentTime),e.upZ.setValueAtTime(f.z,this.context.currentTime)):(e.setPosition(a.x,a.y,a.z),e.setOrientation(d.x,d.y,d.z,f.x,f.y,f.z))}}()});jc.prototype=Object.assign(Object.create(B.prototype),{constructor:jc,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===
14284 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.");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);a.start(0,this.startTime);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.");
14285 else return this.source.stop(),this.startTime=this.context.currentTime,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.startTime=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());
14286 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]},
14287 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."),
14288 !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}});je.prototype=Object.assign(Object.create(jc.prototype),{constructor:je,getOutput:function(){return this.panner},getRefDistance:function(){return this.panner.refDistance},setRefDistance:function(a){this.panner.refDistance=
14289 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){B.prototype.updateMatrixWorld.call(this,b);a.setFromMatrixPosition(this.matrixWorld);this.panner.setPosition(a.x,
14290 a.y,a.z)}}()});Object.assign(ke.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(le.prototype,{accumulate:function(a,b){var c=this.buffer,d=this.valueSize,e=a*d+d,f=this.cumulativeWeight;if(0===f){for(f=0;f!==d;++f)c[e+f]=c[f];f=b}else f+=b,this._mixBufferRegion(c,e,0,b/f,d);this.cumulativeWeight=f},apply:function(a){var b=
14291 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=
14292 0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d){qa.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_,
14293 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(oa,{Composite:Ve,create:function(a,b,c){return a&&a.isAnimationObjectGroup?new oa.Composite(a,b,c):new oa(a,b,c)},parseTrackName:function(){var a=new RegExp("^"+/((?:[\w-]+[\/:])*)/.source+/([\w-\.]+)?/.source+/(?:\.([\w-]+)(?:\[(.+)\])?)?/.source+/\.([\w-]+)(?:\[(.+)\])?/.source+"$"),b=["material","materials","bones"];return function(c){var d=
14294 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: "+c);return d}}(),findNode:function(a,b){if(!b||
14295 ""===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 g=a[c];if(g.name===b||g.uuid===b||(g=d(g.children)))return g}return null};if(c=d(a.children))return c}return null}});Object.assign(oa.prototype,{_getValue_unavailable:function(){},_setValue_unavailable:function(){},BindingType:{Direct:0,
14296 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.node[this.propertyName]=a[b]},function(a,b){this.node[this.propertyName]=a[b];
14297 this.targetObject.needsUpdate=!0},function(a,b){this.node[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=!0}],[function(a,b){this.resolvedProperty[this.propertyIndex]=
14298 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}]],getValue:function(a,b){this.bind();this.getValue(a,b)},setValue:function(a,
14299 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=oa.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(" can not bind to material as node does not have a material",this);return}if(!a.material.materials){console.error(" can not bind to material.materials as node.material does not have a materials array",
14300 this);return}a=a.material.materials;break;case "bones":if(!a.skeleton){console.error(" 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(" can not bind to objectName of node, undefined",this);return}a=a[c]}if(void 0!==f){if(void 0===a[f]){console.error(" 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(" trying to update property for track: "+
14301 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=a);c=this.BindingType.Direct;if(void 0!==e){if("morphTargetInfluences"===d){if(!a.geometry){console.error(" can not bind to morphTargetInfluences becasuse node does not have a geometry",this);return}if(!a.geometry.morphTargets){console.error(" can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets",
14302 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,this.resolvedProperty=f):this.propertyName=d;this.getValue=this.GetterByBindingType[c];this.setValue=this.SetterByBindingTypeAndVersioning[c][b]}}else console.error(" trying to update node for track: "+
14303 this.path+" but it wasn't found.")},unbind:function(){this.node=null;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}});Object.assign(oa.prototype,{_getValue_unbound:oa.prototype.getValue,_setValue_unbound:oa.prototype.setValue});Object.assign(We.prototype,{isAnimationObjectGroup:!0,add:function(a){for(var b=this._objects,c=b.length,d=this.nCachedObjects_,e=this._indicesByUUID,f=this._paths,g=this._parsedPaths,h=this._bindings,k=h.length,l=0,p=arguments.length;l!==p;++l){var q=
14304 arguments[l],n=q.uuid,r=e[n];if(void 0===r){r=c++;e[n]=r;b.push(q);for(var n=0,z=k;n!==z;++n)h[n].push(new oa(q,f[n],g[n]))}else if(r<d){var t=--d,z=b[t];e[z.uuid]=r;b[r]=z;e[n]=t;b[t]=q;n=0;for(z=k;n!==z;++n){var y=h[n],x=y[r];y[r]=y[t];void 0===x&&(x=new oa(q,f[n],g[n]));y[t]=x}}else void 0!==b[r]&&console.error("Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes...")}this.nCachedObjects_=d},remove:function(a){for(var b=this._objects,
14305 c=this.nCachedObjects_,d=this._indicesByUUID,e=this._bindings,f=e.length,g=0,h=arguments.length;g!==h;++g){var k=arguments[g],l=k.uuid,p=d[l];if(void 0!==p&&p>=c){var q=c++,n=b[q];d[n.uuid]=p;b[p]=n;d[l]=q;b[q]=k;k=0;for(l=f;k!==l;++k){var n=e[k],r=n[p];n[p]=n[q];n[q]=r}}}this.nCachedObjects_=c},uncache:function(a){for(var b=this._objects,c=b.length,d=this.nCachedObjects_,e=this._indicesByUUID,f=this._bindings,g=f.length,h=0,k=arguments.length;h!==k;++h){var l=arguments[h].uuid,p=e[l];if(void 0!==
14306 p)if(delete e[l],p<d){var l=--d,q=b[l],n=--c,r=b[n];e[q.uuid]=p;b[p]=q;e[r.uuid]=l;b[l]=r;b.pop();q=0;for(r=g;q!==r;++q){var z=f[q],t=z[n];z[p]=z[l];z[l]=t;z.pop()}}else for(n=--c,r=b[n],e[r.uuid]=p,b[p]=r,b.pop(),q=0,r=g;q!==r;++q)z=f[q],z[p]=z[n],z.pop()}this.nCachedObjects_=d},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]=
14307 d;f.push(a);g.push(b);e.push(l);c=k;for(d=h.length;c!==d;++c)l[c]=new oa(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=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=
14308 !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)},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?
14309 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);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=
14310 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},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,
14311 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=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||
14312 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;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],
14313 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],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===
14314 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;-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?
14315 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=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,
14316 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,sa.prototype,{_bindAction:function(a,b){var c=a._localRoot||this._root,d=a._clip.tracks,e=d.length,f=a._propertyBindings,g=a._interpolants,h=c.uuid,k=this._bindingsByRootAndName,l=k[h];void 0===l&&(l={},k[h]=l);for(k=0;k!==e;++k){var p=d[k],q=p.name,n=l[q];if(void 0===
14317 n){n=f[k];if(void 0!==n){null===n._cacheIndex&&(++n.referenceCount,this._addInactiveBinding(n,h,q));continue}n=new le(oa.create(c,q,b&&b._propertyBindings[k].binding.parsedPath),p.ValueTypeName,p.getValueSize());++n.referenceCount;this._addInactiveBinding(n,h,q)}f[k]=n;g[k].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,
14318 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,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=
14319 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},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},
14320 _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);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;
14321 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;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=
14322 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]=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;
14323 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=--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 Wc(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer),
14324 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;b[c]=e},_controlInterpolantsResultBuffer:new Float32Array(1),clipAction:function(a,b){var c=b||this._root,d=c.uuid,e="string"===typeof a?Ba.findByName(c,a):a,c=null!==e?e.uuid:a,f=this._actionsByClip[c],g=null;if(void 0!==f){g=f.actionByRoot[d];if(void 0!==g)return g;g=f.knownActions[0];null===
14325 e&&(e=g._clip)}if(null===e)return null;e=new Xe(this,e,b);this._bindAction(e,g);this._addInactiveAction(e,c,d);return e},existingAction:function(a,b){var c=b||this._root,d=c.uuid,c="string"===typeof a?Ba.findByName(c,a):a,c=this._actionsByClip[c?c.uuid:a];return void 0!==c?c.actionByRoot[d]||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=
14326 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;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=
14327 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=this._actionsByClip,c;for(c in b){var d=b[c].actionByRoot[a];void 0!==d&&(this._deactivateAction(d),this._removeInactiveAction(d))}c=this._bindingsByRootAndName[a];if(void 0!==c)for(var e in c)a=c[e],a.restoreOriginalState(),this._removeInactiveBinding(a)},uncacheAction:function(a,b){var c=this.existingAction(a,
14328 b);null!==c&&(this._deactivateAction(c),this._removeInactiveAction(c))}});Jd.prototype.clone=function(){return new Jd(void 0===this.value.clone?this.value:this.value.clone())};me.prototype=Object.assign(Object.create(I.prototype),{constructor:me,isInstancedBufferGeometry:!0,addGroup:function(a,b,c){this.groups.push({start:a,count:b,materialIndex:c})},copy:function(a){var b=a.index;null!==b&&this.setIndex(b.clone());var b=a.attributes,c;for(c in b)this.addAttribute(c,b[c].clone());a=a.groups;c=0;for(b=
14329 a.length;c<b;c++){var d=a[c];this.addGroup(d.start,d.count,d.materialIndex)}return this}});Object.defineProperties(ne.prototype,{count:{get:function(){return this.data.count}},array:{get:function(){return this.data.array}}});Object.assign(ne.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*this.data.stride+this.offset+1]=b;return this},setZ:function(a,b){this.data.array[a*this.data.stride+
14330 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+3]},setXY:function(a,b,c){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+
14331 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(kc.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(kc.prototype,{isInterleavedBuffer:!0,setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
14332 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+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=
14333 a;return this}});oe.prototype=Object.assign(Object.create(kc.prototype),{constructor:oe,isInstancedInterleavedBuffer:!0,copy:function(a){kc.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});pe.prototype=Object.assign(Object.create(L.prototype),{constructor:pe,isInstancedBufferAttribute:!0,copy:function(a){L.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,
14334 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)):console.error("THREE.Raycaster: Unsupported camera type.")},intersectObject:function(a,b){var c=[];qe(a,this,c,b);c.sort($e);return c},intersectObjects:function(a,
14335 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++)qe(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=0;this.running=!0},stop:function(){this.getElapsedTime();this.running=!1},getElapsedTime:function(){this.getDelta();return this.elapsedTime},getDelta:function(){var a=
14336 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)},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-
14337 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(Y.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)},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*
14338 a.x+a.z*a.z);this.theta=Math.atan2(a.x,a.z);this.y=a.y;return this}});ra.prototype=Object.create(Ca.prototype);ra.prototype.constructor=ra;ra.prototype.createAnimation=function(a,b,c,d){b={start:b,end:c,length:c-b+1,fps:d,duration:(c-b)/d,lastFrame:0,currentFrame:0,active:!1,time:0,direction:1,weight:1,directionBackwards:!1,mirroredLoop:!1};this.animationsMap[a]=b;this.animationsList.push(b)};ra.prototype.autoCreateAnimations=function(a){for(var b=/([a-z]+)_?(\d+)/i,c,d={},e=this.geometry,f=0,g=e.morphTargets.length;f<
14339 g;f++){var h=e.morphTargets[f].name.match(b);if(h&&1<h.length){var k=h[1];d[k]||(d[k]={start:Infinity,end:-Infinity});h=d[k];f<h.start&&(h.start=f);f>h.end&&(h.end=f);c||(c=k)}}for(k in d)h=d[k],this.createAnimation(k,h.start,h.end,a);this.firstAnimation=c};ra.prototype.setAnimationDirectionForward=function(a){if(a=this.animationsMap[a])a.direction=1,a.directionBackwards=!1};ra.prototype.setAnimationDirectionBackward=function(a){if(a=this.animationsMap[a])a.direction=-1,a.directionBackwards=!0};ra.prototype.setAnimationFPS=
14340 function(a,b){var c=this.animationsMap[a];c&&(c.fps=b,c.duration=(c.end-c.start)/c.fps)};ra.prototype.setAnimationDuration=function(a,b){var c=this.animationsMap[a];c&&(c.duration=b,c.fps=(c.end-c.start)/c.duration)};ra.prototype.setAnimationWeight=function(a,b){var c=this.animationsMap[a];c&&(c.weight=b)};ra.prototype.setAnimationTime=function(a,b){var c=this.animationsMap[a];c&&(c.time=b)};ra.prototype.getAnimationTime=function(a){var b=0;if(a=this.animationsMap[a])b=a.time;return b};ra.prototype.getAnimationDuration=
14341 function(a){var b=-1;if(a=this.animationsMap[a])b=a.duration;return b};ra.prototype.playAnimation=function(a){var b=this.animationsMap[a];b?(b.time=0,b.active=!0):console.warn("THREE.MorphBlendMesh: animation["+a+"] undefined in .playAnimation()")};ra.prototype.stopAnimation=function(a){if(a=this.animationsMap[a])a.active=!1};ra.prototype.update=function(a){for(var b=0,c=this.animationsList.length;b<c;b++){var d=this.animationsList[b];if(d.active){var e=d.duration/d.length;d.time+=d.direction*a;if(d.mirroredLoop){if(d.time>
14342 d.duration||0>d.time)d.direction*=-1,d.time>d.duration&&(d.time=d.duration,d.directionBackwards=!0),0>d.time&&(d.time=0,d.directionBackwards=!1)}else d.time%=d.duration,0>d.time&&(d.time+=d.duration);var f=d.start+Y.clamp(Math.floor(d.time/e),0,d.length-1),g=d.weight;f!==d.currentFrame&&(this.morphTargetInfluences[d.lastFrame]=0,this.morphTargetInfluences[d.currentFrame]=1*g,this.morphTargetInfluences[f]=0,d.lastFrame=d.currentFrame,d.currentFrame=f);e=d.time%e/e;d.directionBackwards&&(e=1-e);d.currentFrame!==
14343 d.lastFrame?(this.morphTargetInfluences[d.currentFrame]=e*g,this.morphTargetInfluences[d.lastFrame]=(1-e)*g):this.morphTargetInfluences[d.currentFrame]=g}}};$c.prototype=Object.create(B.prototype);$c.prototype.constructor=$c;$c.prototype.isImmediateRenderObject=!0;ad.prototype=Object.create(da.prototype);ad.prototype.constructor=ad;ad.prototype.update=function(){var a=new p,b=new p,c=new Ka;return function(){var d=["a","b","c"];this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);
14344 var e=this.object.matrixWorld,f=this.geometry.attributes.position,g=this.object.geometry;if(g&&g.isGeometry)for(var h=g.vertices,k=g.faces,l=g=0,p=k.length;l<p;l++)for(var q=k[l],n=0,r=q.vertexNormals.length;n<r;n++){var z=q.vertexNormals[n];a.copy(h[q[d[n]]]).applyMatrix4(e);b.copy(z).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);f.setXYZ(g,a.x,a.y,a.z);g+=1;f.setXYZ(g,b.x,b.y,b.z);g+=1}else if(g&&g.isBufferGeometry)for(d=g.attributes.position,h=g.attributes.normal,n=g=0,r=d.count;n<
14345 r;n++)a.set(d.getX(n),d.getY(n),d.getZ(n)).applyMatrix4(e),b.set(h.getX(n),h.getY(n),h.getZ(n)),b.applyMatrix3(c).normalize().multiplyScalar(this.size).add(a),f.setXYZ(g,a.x,a.y,a.z),g+=1,f.setXYZ(g,b.x,b.y,b.z),g+=1;f.needsUpdate=!0}}();lc.prototype=Object.create(B.prototype);lc.prototype.constructor=lc;lc.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()};lc.prototype.update=function(){var a=new p,b=new p;return function(){var c=this.light.distance?this.light.distance:
14346 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));this.cone.material.color.copy(this.light.color)}}();mc.prototype=Object.create(da.prototype);mc.prototype.constructor=mc;mc.prototype.getBoneList=function(a){var b=[];a&&a.isBone&&b.push(a);for(var c=0;c<a.children.length;c++)b.push.apply(b,this.getBoneList(a.children[c]));return b};mc.prototype.update=function(){var a=
14347 new p,b=new J,c=new J;return function(){var d=this.geometry,e=d.getAttribute("position");c.getInverse(this.root.matrixWorld);for(var f=0,g=0;f<this.bones.length;f++){var h=this.bones[f];h.parent&&h.parent.isBone&&(b.multiplyMatrices(c,h.matrixWorld),a.setFromMatrixPosition(b),e.setXYZ(g,a.x,a.y,a.z),b.multiplyMatrices(c,h.parent.matrixWorld),a.setFromMatrixPosition(b),e.setXYZ(g+1,a.x,a.y,a.z),g+=2)}d.getAttribute("position").needsUpdate=!0}}();nc.prototype=Object.create(Ca.prototype);nc.prototype.constructor=
14348 nc;nc.prototype.dispose=function(){this.geometry.dispose();this.material.dispose()};nc.prototype.update=function(){this.material.color.copy(this.light.color)};oc.prototype=Object.create(B.prototype);oc.prototype.constructor=oc;oc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};oc.prototype.update=function(){var a=this.children[0];a.material.color.copy(this.light.color);var b=.5*this.light.width,c=.5*this.light.height,a=a.geometry.attributes.position,
14349 d=a.array;d[0]=b;d[1]=-c;d[2]=0;d[3]=b;d[4]=c;d[5]=0;d[6]=-b;d[7]=c;d[8]=0;d[9]=-b;d[10]=-c;d[11]=0;d[12]=b;d[13]=-c;d[14]=0;a.needsUpdate=!0};pc.prototype=Object.create(B.prototype);pc.prototype.constructor=pc;pc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};pc.prototype.update=function(){var a=new p,b=new H,c=new H;return function(){var d=this.children[0],e=d.geometry.getAttribute("color");b.copy(this.light.color);c.copy(this.light.groundColor);
14350 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)}d.lookAt(a.setFromMatrixPosition(this.light.matrixWorld).negate());e.needsUpdate=!0}}();bd.prototype=Object.create(da.prototype);bd.prototype.constructor=bd;Kd.prototype=Object.create(da.prototype);Kd.prototype.constructor=Kd;cd.prototype=Object.create(da.prototype);cd.prototype.constructor=cd;cd.prototype.update=function(){var a=new p,b=new p,c=new Ka;return function(){this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);
14351 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 p=f[k],q=p.normal;a.copy(g[p.a]).add(g[p.b]).add(g[p.c]).divideScalar(3).applyMatrix4(d);b.copy(q).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);e.setXYZ(h,a.x,a.y,a.z);h+=1;e.setXYZ(h,b.x,b.y,b.z);h+=1}e.needsUpdate=!0}}();qc.prototype=Object.create(B.prototype);qc.prototype.constructor=qc;qc.prototype.dispose=function(){var a=this.children[0],
14352 b=this.children[1];a.geometry.dispose();a.material.dispose();b.geometry.dispose();b.material.dispose()};qc.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,a);var d=this.children[0],e=this.children[1];d.lookAt(c);d.material.color.copy(this.light.color);e.lookAt(c);e.scale.z=c.length()}}();dd.prototype=Object.create(da.prototype);dd.prototype.constructor=dd;
14353 dd.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"),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 Oa;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",
14354 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",0,1,-1);b.getAttribute("position").needsUpdate=!0}}();Bb.prototype=Object.create(da.prototype);Bb.prototype.constructor=Bb;Bb.prototype.update=function(){var a=new Ta;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,
14355 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]=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()}}}();Bb.prototype.setFromObject=function(a){this.object=a;this.update();return this};var Ld,re;Cb.prototype=Object.create(B.prototype);Cb.prototype.constructor=Cb;Cb.prototype.setDirection=function(){var a=
14356 new p,b;return function(c){.99999<c.y?this.quaternion.set(0,0,0,1):-.99999>c.y?this.quaternion.set(1,0,0,0):(a.set(c.z,0,-c.x).normalize(),b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a,b))}}();Cb.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()};Cb.prototype.setColor=function(a){this.line.material.color.copy(a);this.cone.material.color.copy(a)};
14357 Md.prototype=Object.create(da.prototype);Md.prototype.constructor=Md;var Pd=new p,ve=new se,we=new se,xe=new se;Ja.prototype=Object.create(na.prototype);Ja.prototype.constructor=Ja;Ja.prototype.getPoint=function(a){var b=this.points,c=b.length;2>c&&console.log("duh, you need at least 2 points");a*=c-(this.closed?0:1);var d=Math.floor(a);a-=d;this.closed?d+=0<d?0:(Math.floor(Math.abs(d)/b.length)+1)*b.length:0===a&&d===c-1&&(d=c-2,a=1);var e,f,g;this.closed||0<d?e=b[(d-1)%c]:(Pd.subVectors(b[0],b[1]).add(b[0]),
14358 e=Pd);f=b[d%c];g=b[(d+1)%c];this.closed||d+2<c?b=b[(d+2)%c]:(Pd.subVectors(b[c-1],b[c-2]).add(b[c-1]),b=Pd);if(void 0===this.type||"centripetal"===this.type||"chordal"===this.type){var h="chordal"===this.type?.5:.25,c=Math.pow(e.distanceToSquared(f),h),d=Math.pow(f.distanceToSquared(g),h),h=Math.pow(g.distanceToSquared(b),h);1E-4>d&&(d=1);1E-4>c&&(c=d);1E-4>h&&(h=d);ve.initNonuniformCatmullRom(e.x,f.x,g.x,b.x,c,d,h);we.initNonuniformCatmullRom(e.y,f.y,g.y,b.y,c,d,h);xe.initNonuniformCatmullRom(e.z,
14359 f.z,g.z,b.z,c,d,h)}else"catmullrom"===this.type&&(c=void 0!==this.tension?this.tension:.5,ve.initCatmullRom(e.x,f.x,g.x,b.x,c),we.initCatmullRom(e.y,f.y,g.y,b.y,c),xe.initCatmullRom(e.z,f.z,g.z,b.z,c));return new p(ve.calc(a),we.calc(a),xe.calc(a))};ed.prototype=Object.create(na.prototype);ed.prototype.constructor=ed;ed.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2,e=this.v3;return new p(yb(a,b.x,c.x,d.x,e.x),yb(a,b.y,c.y,d.y,e.y),yb(a,b.z,c.z,d.z,e.z))};fd.prototype=Object.create(na.prototype);
14360 fd.prototype.constructor=fd;fd.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2;return new p(xb(a,b.x,c.x,d.x),xb(a,b.y,c.y,d.y),xb(a,b.z,c.z,d.z))};gd.prototype=Object.create(na.prototype);gd.prototype.constructor=gd;gd.prototype.getPoint=function(a){if(1===a)return this.v2.clone();var b=new p;b.subVectors(this.v2,this.v1);b.multiplyScalar(a);b.add(this.v1);return b};Nd.prototype=Object.create(Xa.prototype);Nd.prototype.constructor=Nd;na.create=function(a,b){console.log("THREE.Curve.create() has been deprecated");
14361 a.prototype=Object.create(na.prototype);a.prototype.constructor=a;a.prototype.getPoint=b;return a};df.prototype=Object.create(Ja.prototype);ef.prototype=Object.create(Ja.prototype);te.prototype=Object.create(Ja.prototype);Object.assign(te.prototype,{initFromArray:function(a){console.error("THREE.Spline: .initFromArray() has been removed.")},getControlPointsArray:function(a){console.error("THREE.Spline: .getControlPointsArray() has been removed.")},reparametrizeByArcLength:function(a){console.error("THREE.Spline: .reparametrizeByArcLength() has been removed.")}});
14362 bd.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")};Object.assign(id.prototype,{center:function(a){console.warn("THREE.Box2: .center() has been renamed to .getCenter().");return this.getCenter(a)},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().");
14363 return this.intersectsBox(a)},size:function(a){console.warn("THREE.Box2: .size() has been renamed to .getSize().");return this.getSize(a)}});Object.assign(Ta.prototype,{center:function(a){console.warn("THREE.Box3: .center() has been renamed to .getCenter().");return this.getCenter(a)},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().");
14364 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)}});Hb.prototype.center=function(a){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");return this.getCenter(a)};Y.random16=function(){console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead.");
14365 return Math.random()};Object.assign(Ka.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(a){console.warn("THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.");
14366 return this.applyToVector3Array(a)},applyToBuffer:function(a,b,c){console.warn("THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");return this.applyToBufferAttribute(a)},applyToVector3Array:function(a,b,c){console.error("THREE.Matrix3: .applyToVector3Array() has been removed.")}});Object.assign(J.prototype,{extractPosition:function(a){console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().");return this.copyPosition(a)},
14367 flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},getPosition:function(){var a;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().");
14368 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.");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(a){console.warn("THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.");
14369 return this.applyToVector3Array(a)},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.");return a.applyMatrix4(this)},translate:function(){console.error("THREE.Matrix4: .translate() has been removed.")},rotateX:function(){console.error("THREE.Matrix4: .rotateX() has been removed.")},
14370 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,b,c){console.warn("THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");return this.applyToBufferAttribute(a)},applyToVector3Array:function(a,b,c){console.error("THREE.Matrix4: .applyToVector3Array() has been removed.")},
14371 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)}});wa.prototype.isIntersectionLine=function(a){console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().");return this.intersectsLine(a)};qa.prototype.multiplyVector3=function(a){console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.");
14372 return a.applyQuaternion(this)};Object.assign(hb.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)},isIntersectionSphere:function(a){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)}});
14373 Object.assign(Ab.prototype,{extrude:function(a){console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.");return new db(this,a)},makeGeometry:function(a){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");return new Zb(this,a)}});Object.assign(D.prototype,{fromAttribute:function(a,b,c){console.error("THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)}});Object.assign(p.prototype,
14374 {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)},getScaleFromMatrix:function(a){console.warn("THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().");
14375 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,b,c){console.error("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,
14376 b,c)}});Object.assign(ga.prototype,{fromAttribute:function(a,b,c){console.error("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)}});M.prototype.computeTangents=function(){console.warn("THREE.Geometry: .computeTangents() has been removed.")};Object.assign(B.prototype,{getChildByName:function(a){console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().");return this.getObjectByName(a)},renderDepth:function(){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.")},
14377 translate:function(a,b){console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.");return this.translateOnAxis(b,a)}});Object.defineProperties(B.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.");this.rotation.order=a}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},
14378 set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}});Object.defineProperties(Bc.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Object.defineProperty(Cc.prototype,"useVertexTexture",{get:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")},set:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")}});
14379 Object.defineProperty(na.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}});xa.prototype.setLens=function(a,b){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup.");void 0!==b&&(this.filmGauge=b);this.setFocalLength(a)};
14380 Object.defineProperties(ma.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.");
14381 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.");
14382 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.");
14383 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(L.prototype,{length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead.");return this.array.length}}});Object.assign(I.prototype,{addIndex:function(a){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().");this.setIndex(a)},addDrawCall:function(a,
14384 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.")}});
14385 Object.defineProperties(I.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.");
14386 return this}}});Object.defineProperties(Z.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}}});Object.defineProperties(ta.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")}}});
14387 Object.defineProperties(Ea.prototype,{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");return this.extensions.derivatives},set:function(a){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=a}}});Object.assign(Xd.prototype,{getCurrentRenderTarget:function(){console.warn("THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().");return this.getRenderTarget()},
14388 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' ).");return this.extensions.get("OES_texture_half_float")},supportsStandardDerivatives:function(){console.warn("THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( 'OES_standard_derivatives' ).");
14389 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")},supportsCompressedTexturePVRTC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( 'WEBGL_compressed_texture_pvrtc' ).");return this.extensions.get("WEBGL_compressed_texture_pvrtc")},
14390 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.");return this.capabilities.vertexTextures},supportsInstancedArrays:function(){console.warn("THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( 'ANGLE_instanced_arrays' ).");
14391 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.")},addPostPlugin:function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},updateShadowMap:function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")}});
14392 Object.defineProperties(Xd.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.");this.shadowMap.type=a}},shadowMapCullFace:{get:function(){return this.shadowMap.cullFace},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.");
14393 this.shadowMap.cullFace=a}}});Object.defineProperties(Je.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(Db.prototype,{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.");
14394 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.");return this.texture.magFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");this.texture.magFilter=
14395 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.");return this.texture.anisotropy},set:function(a){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");this.texture.anisotropy=
14396 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},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.");
14397 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.");this.texture.type=a}},generateMipmaps:{get:function(){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");return this.texture.generateMipmaps},
14398 set:function(a){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");this.texture.generateMipmaps=a}}});jc.prototype.load=function(a){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");var b=this;(new fe).load(a,function(a){b.setBuffer(a)});return this};ke.prototype.getData=function(){console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData().");return this.getFrequencyData()};l.WebGLRenderTargetCube=Eb;l.WebGLRenderTarget=
14399 Db;l.WebGLRenderer=Xd;l.ShaderLib=ab;l.UniformsLib=V;l.UniformsUtils=Ha;l.ShaderChunk=U;l.FogExp2=Kb;l.Fog=Lb;l.Scene=md;l.LensFlare=Yd;l.Sprite=Ac;l.LOD=Bc;l.SkinnedMesh=od;l.Skeleton=Cc;l.Bone=nd;l.Mesh=Ca;l.LineSegments=da;l.LineLoop=pd;l.Line=ya;l.Points=Mb;l.Group=Dc;l.VideoTexture=qd;l.DataTexture=eb;l.CompressedTexture=Nb;l.CubeTexture=Za;l.CanvasTexture=rd;l.DepthTexture=Ec;l.Texture=X;l.CompressedTextureLoader=Qe;l.DataTextureLoader=$d;l.CubeTextureLoader=ae;l.TextureLoader=sd;l.ObjectLoader=
14400 Re;l.MaterialLoader=Hd;l.BufferGeometryLoader=be;l.DefaultLoadingManager=Aa;l.LoadingManager=Zd;l.JSONLoader=ce;l.ImageLoader=Vc;l.FontLoader=Te;l.FileLoader=ua;l.Loader=gc;l.Cache=hd;l.AudioLoader=fe;l.SpotLightShadow=ud;l.SpotLight=vd;l.PointLight=wd;l.RectAreaLight=Ad;l.HemisphereLight=td;l.DirectionalLightShadow=xd;l.DirectionalLight=yd;l.AmbientLight=zd;l.LightShadow=ub;l.Light=ma;l.StereoCamera=Ue;l.PerspectiveCamera=xa;l.OrthographicCamera=Jb;l.CubeCamera=Id;l.ArrayCamera=ge;l.Camera=Oa;l.AudioListener=
14401 he;l.PositionalAudio=je;l.AudioContext=ie;l.AudioAnalyser=ke;l.Audio=jc;l.VectorKeyframeTrack=ec;l.StringKeyframeTrack=Ed;l.QuaternionKeyframeTrack=Xc;l.NumberKeyframeTrack=fc;l.ColorKeyframeTrack=Gd;l.BooleanKeyframeTrack=Fd;l.PropertyMixer=le;l.PropertyBinding=oa;l.KeyframeTrack=wb;l.AnimationUtils=va;l.AnimationObjectGroup=We;l.AnimationMixer=Ye;l.AnimationClip=Ba;l.Uniform=Jd;l.InstancedBufferGeometry=me;l.BufferGeometry=I;l.GeometryIdCount=function(){return Td++};l.Geometry=M;l.InterleavedBufferAttribute=
14402 ne;l.InstancedInterleavedBuffer=oe;l.InterleavedBuffer=kc;l.InstancedBufferAttribute=pe;l.Face3=Va;l.Object3D=B;l.Raycaster=Ze;l.Layers=Rd;l.EventDispatcher=sa;l.Clock=af;l.QuaternionLinearInterpolant=Dd;l.LinearInterpolant=Wc;l.DiscreteInterpolant=Cd;l.CubicInterpolant=Bd;l.Interpolant=Da;l.Triangle=Ua;l.Math=Y;l.Spherical=bf;l.Cylindrical=cf;l.Plane=wa;l.Frustum=jd;l.Sphere=Ga;l.Ray=hb;l.Matrix4=J;l.Matrix3=Ka;l.Box3=Ta;l.Box2=id;l.Line3=Hb;l.Euler=bb;l.Vector4=ga;l.Vector3=p;l.Vector2=D;l.Quaternion=
14403 qa;l.Color=H;l.MorphBlendMesh=ra;l.ImmediateRenderObject=$c;l.VertexNormalsHelper=ad;l.SpotLightHelper=lc;l.SkeletonHelper=mc;l.PointLightHelper=nc;l.RectAreaLightHelper=oc;l.HemisphereLightHelper=pc;l.GridHelper=bd;l.PolarGridHelper=Kd;l.FaceNormalsHelper=cd;l.DirectionalLightHelper=qc;l.CameraHelper=dd;l.BoxHelper=Bb;l.ArrowHelper=Cb;l.AxisHelper=Md;l.CatmullRomCurve3=Ja;l.CubicBezierCurve3=ed;l.QuadraticBezierCurve3=fd;l.LineCurve3=gd;l.ArcCurve=Nd;l.EllipseCurve=Xa;l.SplineCurve=zb;l.CubicBezierCurve=
14404 hc;l.QuadraticBezierCurve=ic;l.LineCurve=Sa;l.Shape=Ab;l.Path=Zc;l.ShapePath=de;l.Font=ee;l.CurvePath=Yc;l.Curve=na;l.ShapeUtils=za;l.SceneUtils={createMultiMaterialObject:function(a,b){for(var c=new Dc,d=0,e=b.length;d<e;d++)c.add(new Ca(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){var d=new J;d.getInverse(c.matrixWorld);a.applyMatrix(d);b.remove(a);c.add(a)}};l.WireframeGeometry=Ob;l.ParametricGeometry=Fc;l.ParametricBufferGeometry=
14405 Pb;l.TetrahedronGeometry=Hc;l.TetrahedronBufferGeometry=Qb;l.OctahedronGeometry=Ic;l.OctahedronBufferGeometry=mb;l.IcosahedronGeometry=Jc;l.IcosahedronBufferGeometry=Rb;l.DodecahedronGeometry=Kc;l.DodecahedronBufferGeometry=Sb;l.PolyhedronGeometry=Gc;l.PolyhedronBufferGeometry=ia;l.TubeGeometry=Lc;l.TubeBufferGeometry=Tb;l.TorusKnotGeometry=Mc;l.TorusKnotBufferGeometry=Ub;l.TorusGeometry=Nc;l.TorusBufferGeometry=Vb;l.TextGeometry=Oc;l.TextBufferGeometry=Wb;l.SphereGeometry=Pc;l.SphereBufferGeometry=
14406 nb;l.RingGeometry=Qc;l.RingBufferGeometry=Xb;l.PlaneGeometry=xc;l.PlaneBufferGeometry=lb;l.LatheGeometry=Rc;l.LatheBufferGeometry=Yb;l.ShapeGeometry=Zb;l.ShapeBufferGeometry=$b;l.ExtrudeGeometry=db;l.ExtrudeBufferGeometry=Fa;l.EdgesGeometry=ac;l.ConeGeometry=Sc;l.ConeBufferGeometry=Tc;l.CylinderGeometry=ob;l.CylinderBufferGeometry=Wa;l.CircleGeometry=Uc;l.CircleBufferGeometry=bc;l.BoxGeometry=Ib;l.BoxBufferGeometry=kb;l.ShadowMaterial=cc;l.SpriteMaterial=cb;l.RawShaderMaterial=dc;l.ShaderMaterial=
14407 Ea;l.PointsMaterial=La;l.MeshPhysicalMaterial=pb;l.MeshStandardMaterial=Ra;l.MeshPhongMaterial=ta;l.MeshToonMaterial=qb;l.MeshNormalMaterial=rb;l.MeshLambertMaterial=sb;l.MeshDepthMaterial=$a;l.MeshBasicMaterial=Na;l.LineDashedMaterial=tb;l.LineBasicMaterial=ha;l.Material=Z;l.Float64BufferAttribute=wc;l.Float32BufferAttribute=C;l.Uint32BufferAttribute=jb;l.Int32BufferAttribute=vc;l.Uint16BufferAttribute=ib;l.Int16BufferAttribute=uc;l.Uint8ClampedBufferAttribute=tc;l.Uint8BufferAttribute=sc;l.Int8BufferAttribute=
14408 rc;l.BufferAttribute=L;l.REVISION="85";l.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2};l.CullFaceNone=0;l.CullFaceBack=1;l.CullFaceFront=2;l.CullFaceFrontBack=3;l.FrontFaceDirectionCW=0;l.FrontFaceDirectionCCW=1;l.BasicShadowMap=0;l.PCFShadowMap=1;l.PCFSoftShadowMap=2;l.FrontSide=0;l.BackSide=1;l.DoubleSide=2;l.FlatShading=1;l.SmoothShading=2;l.NoColors=0;l.FaceColors=1;l.VertexColors=2;l.NoBlending=0;l.NormalBlending=1;l.AdditiveBlending=2;l.SubtractiveBlending=3;l.MultiplyBlending=4;l.CustomBlending=5;l.AddEquation=
14409 100;l.SubtractEquation=101;l.ReverseSubtractEquation=102;l.MinEquation=103;l.MaxEquation=104;l.ZeroFactor=200;l.OneFactor=201;l.SrcColorFactor=202;l.OneMinusSrcColorFactor=203;l.SrcAlphaFactor=204;l.OneMinusSrcAlphaFactor=205;l.DstAlphaFactor=206;l.OneMinusDstAlphaFactor=207;l.DstColorFactor=208;l.OneMinusDstColorFactor=209;l.SrcAlphaSaturateFactor=210;l.NeverDepth=0;l.AlwaysDepth=1;l.LessDepth=2;l.LessEqualDepth=3;l.EqualDepth=4;l.GreaterEqualDepth=5;l.GreaterDepth=6;l.NotEqualDepth=7;l.MultiplyOperation=
14410 0;l.MixOperation=1;l.AddOperation=2;l.NoToneMapping=0;l.LinearToneMapping=1;l.ReinhardToneMapping=2;l.Uncharted2ToneMapping=3;l.CineonToneMapping=4;l.UVMapping=300;l.CubeReflectionMapping=301;l.CubeRefractionMapping=302;l.EquirectangularReflectionMapping=303;l.EquirectangularRefractionMapping=304;l.SphericalReflectionMapping=305;l.CubeUVReflectionMapping=306;l.CubeUVRefractionMapping=307;l.RepeatWrapping=1E3;l.ClampToEdgeWrapping=1001;l.MirroredRepeatWrapping=1002;l.NearestFilter=1003;l.NearestMipMapNearestFilter=
14411 1004;l.NearestMipMapLinearFilter=1005;l.LinearFilter=1006;l.LinearMipMapNearestFilter=1007;l.LinearMipMapLinearFilter=1008;l.UnsignedByteType=1009;l.ByteType=1010;l.ShortType=1011;l.UnsignedShortType=1012;l.IntType=1013;l.UnsignedIntType=1014;l.FloatType=1015;l.HalfFloatType=1016;l.UnsignedShort4444Type=1017;l.UnsignedShort5551Type=1018;l.UnsignedShort565Type=1019;l.UnsignedInt248Type=1020;l.AlphaFormat=1021;l.RGBFormat=1022;l.RGBAFormat=1023;l.LuminanceFormat=1024;l.LuminanceAlphaFormat=1025;l.RGBEFormat=
14412 1023;l.DepthFormat=1026;l.DepthStencilFormat=1027;l.RGB_S3TC_DXT1_Format=2001;l.RGBA_S3TC_DXT1_Format=2002;l.RGBA_S3TC_DXT3_Format=2003;l.RGBA_S3TC_DXT5_Format=2004;l.RGB_PVRTC_4BPPV1_Format=2100;l.RGB_PVRTC_2BPPV1_Format=2101;l.RGBA_PVRTC_4BPPV1_Format=2102;l.RGBA_PVRTC_2BPPV1_Format=2103;l.RGB_ETC1_Format=2151;l.LoopOnce=2200;l.LoopRepeat=2201;l.LoopPingPong=2202;l.InterpolateDiscrete=2300;l.InterpolateLinear=2301;l.InterpolateSmooth=2302;l.ZeroCurvatureEnding=2400;l.ZeroSlopeEnding=2401;l.WrapAroundEnding=
14413 2402;l.TrianglesDrawMode=0;l.TriangleStripDrawMode=1;l.TriangleFanDrawMode=2;l.LinearEncoding=3E3;l.sRGBEncoding=3001;l.GammaEncoding=3007;l.RGBEEncoding=3002;l.LogLuvEncoding=3003;l.RGBM7Encoding=3004;l.RGBM16Encoding=3005;l.RGBDEncoding=3006;l.BasicDepthPacking=3200;l.RGBADepthPacking=3201;l.CubeGeometry=Ib;l.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 Va(a,b,c,e,f,g)};l.LineStrip=0;l.LinePieces=1;l.MeshFaceMaterial=
14414 function(a){console.warn("THREE.MeshFaceMaterial has been removed. Use an Array instead.");return a};l.MultiMaterial=function(a){void 0===a&&(a=[]);console.warn("THREE.MultiMaterial has been removed. Use an Array instead.");a.isMultiMaterial=!0;a.materials=a;a.clone=function(){return a.slice()};return a};l.PointCloud=function(a,b){console.warn("THREE.PointCloud has been renamed to THREE.Points.");return new Mb(a,b)};l.Particle=function(a){console.warn("THREE.Particle has been renamed to THREE.Sprite.");
14415 return new Ac(a)};l.ParticleSystem=function(a,b){console.warn("THREE.ParticleSystem has been renamed to THREE.Points.");return new Mb(a,b)};l.PointCloudMaterial=function(a){console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.");return new La(a)};l.ParticleBasicMaterial=function(a){console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.");return new La(a)};l.ParticleSystemMaterial=function(a){console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.");
14416 return new La(a)};l.Vertex=function(a,b,c){console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead.");return new p(a,b,c)};l.DynamicBufferAttribute=function(a,b){console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.");return(new L(a,b)).setDynamic(!0)};l.Int8Attribute=function(a,b){console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.");return new rc(a,b)};l.Uint8Attribute=
14417 function(a,b){console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.");return new sc(a,b)};l.Uint8ClampedAttribute=function(a,b){console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.");return new tc(a,b)};l.Int16Attribute=function(a,b){console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.");return new uc(a,b)};l.Uint16Attribute=function(a,b){console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.");
14418 return new ib(a,b)};l.Int32Attribute=function(a,b){console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.");return new vc(a,b)};l.Uint32Attribute=function(a,b){console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.");return new jb(a,b)};l.Float32Attribute=function(a,b){console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.");return new C(a,b)};l.Float64Attribute=
14419 function(a,b){console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.");return new wc(a,b)};l.ClosedSplineCurve3=df;l.SplineCurve3=ef;l.Spline=te;l.BoundingBoxHelper=function(a,b){console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.");return new Bb(a,b)};l.EdgesHelper=function(a,b){console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.");return new da(new ac(a.geometry),new ha({color:void 0!==
14420 b?b:16777215}))};l.WireframeHelper=function(a,b){console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.");return new da(new Ob(a.geometry),new ha({color:void 0!==b?b:16777215}))};l.XHRLoader=function(a){console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader.");return new ua(a)};l.BinaryTextureLoader=function(a){console.warn("THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.");return new $d(a)};l.GeometryUtils={merge:function(a,b,
14421 c){console.warn("THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.");var d;b.isMesh&&(b.matrixAutoUpdate&&b.updateMatrix(),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()}};l.ImageUtils={crossOrigin:void 0,loadTexture:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");
14422 var e=new sd;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.");var e=new ae;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.")}};
14423 l.Projector=function(){console.error("THREE.Projector has been moved to /examples/js/renderers/Projector.js.");this.projectVector=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().")}};l.CanvasRenderer=function(){console.error("THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js");
14424 this.domElement=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");this.clear=function(){};this.render=function(){};this.setClearColor=function(){};this.setSize=function(){}};Object.defineProperty(l,"__esModule",{value:!0})});
14426 },{}],177:[function(require,module,exports){
14429 module.exports = TinyQueue;
14431 function TinyQueue(data, compare) {
14432 if (!(this instanceof TinyQueue)) return new TinyQueue(data, compare);
14434 this.data = data || [];
14435 this.length = this.data.length;
14436 this.compare = compare || defaultCompare;
14438 if (this.length > 0) {
14439 for (var i = (this.length >> 1); i >= 0; i--) this._down(i);
14443 function defaultCompare(a, b) {
14444 return a < b ? -1 : a > b ? 1 : 0;
14447 TinyQueue.prototype = {
14449 push: function (item) {
14450 this.data.push(item);
14452 this._up(this.length - 1);
14456 if (this.length === 0) return undefined;
14457 var top = this.data[0];
14459 if (this.length > 0) {
14460 this.data[0] = this.data[this.length];
14467 peek: function () {
14468 return this.data[0];
14471 _up: function (pos) {
14472 var data = this.data;
14473 var compare = this.compare;
14474 var item = data[pos];
14477 var parent = (pos - 1) >> 1;
14478 var current = data[parent];
14479 if (compare(item, current) >= 0) break;
14480 data[pos] = current;
14487 _down: function (pos) {
14488 var data = this.data;
14489 var compare = this.compare;
14490 var len = this.length;
14491 var halfLen = len >> 1;
14492 var item = data[pos];
14494 while (pos < halfLen) {
14495 var left = (pos << 1) + 1;
14496 var right = left + 1;
14497 var best = data[left];
14499 if (right < len && compare(data[right], best) < 0) {
14501 best = data[right];
14503 if (compare(best, item) >= 0) break;
14513 },{}],178:[function(require,module,exports){
14514 // Underscore.js 1.8.3
14515 // http://underscorejs.org
14516 // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
14517 // Underscore may be freely distributed under the MIT license.
14524 // Establish the root object, `window` in the browser, or `exports` on the server.
14527 // Save the previous value of the `_` variable.
14528 var previousUnderscore = root._;
14530 // Save bytes in the minified (but not gzipped) version:
14531 var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
14533 // Create quick reference variables for speed access to core prototypes.
14535 push = ArrayProto.push,
14536 slice = ArrayProto.slice,
14537 toString = ObjProto.toString,
14538 hasOwnProperty = ObjProto.hasOwnProperty;
14540 // All **ECMAScript 5** native function implementations that we hope to use
14541 // are declared here.
14543 nativeIsArray = Array.isArray,
14544 nativeKeys = Object.keys,
14545 nativeBind = FuncProto.bind,
14546 nativeCreate = Object.create;
14548 // Naked function reference for surrogate-prototype-swapping.
14549 var Ctor = function(){};
14551 // Create a safe reference to the Underscore object for use below.
14552 var _ = function(obj) {
14553 if (obj instanceof _) return obj;
14554 if (!(this instanceof _)) return new _(obj);
14555 this._wrapped = obj;
14558 // Export the Underscore object for **Node.js**, with
14559 // backwards-compatibility for the old `require()` API. If we're in
14560 // the browser, add `_` as a global object.
14561 if (typeof exports !== 'undefined') {
14562 if (typeof module !== 'undefined' && module.exports) {
14563 exports = module.exports = _;
14570 // Current version.
14571 _.VERSION = '1.8.3';
14573 // Internal function that returns an efficient (for current engines) version
14574 // of the passed-in callback, to be repeatedly applied in other Underscore
14576 var optimizeCb = function(func, context, argCount) {
14577 if (context === void 0) return func;
14578 switch (argCount == null ? 3 : argCount) {
14579 case 1: return function(value) {
14580 return func.call(context, value);
14582 case 2: return function(value, other) {
14583 return func.call(context, value, other);
14585 case 3: return function(value, index, collection) {
14586 return func.call(context, value, index, collection);
14588 case 4: return function(accumulator, value, index, collection) {
14589 return func.call(context, accumulator, value, index, collection);
14592 return function() {
14593 return func.apply(context, arguments);
14597 // A mostly-internal function to generate callbacks that can be applied
14598 // to each element in a collection, returning the desired result — either
14599 // identity, an arbitrary callback, a property matcher, or a property accessor.
14600 var cb = function(value, context, argCount) {
14601 if (value == null) return _.identity;
14602 if (_.isFunction(value)) return optimizeCb(value, context, argCount);
14603 if (_.isObject(value)) return _.matcher(value);
14604 return _.property(value);
14606 _.iteratee = function(value, context) {
14607 return cb(value, context, Infinity);
14610 // An internal function for creating assigner functions.
14611 var createAssigner = function(keysFunc, undefinedOnly) {
14612 return function(obj) {
14613 var length = arguments.length;
14614 if (length < 2 || obj == null) return obj;
14615 for (var index = 1; index < length; index++) {
14616 var source = arguments[index],
14617 keys = keysFunc(source),
14619 for (var i = 0; i < l; i++) {
14621 if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
14628 // An internal function for creating a new object that inherits from another.
14629 var baseCreate = function(prototype) {
14630 if (!_.isObject(prototype)) return {};
14631 if (nativeCreate) return nativeCreate(prototype);
14632 Ctor.prototype = prototype;
14633 var result = new Ctor;
14634 Ctor.prototype = null;
14638 var property = function(key) {
14639 return function(obj) {
14640 return obj == null ? void 0 : obj[key];
14644 // Helper for collection methods to determine whether a collection
14645 // should be iterated as an array or as an object
14646 // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
14647 // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
14648 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
14649 var getLength = property('length');
14650 var isArrayLike = function(collection) {
14651 var length = getLength(collection);
14652 return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
14655 // Collection Functions
14656 // --------------------
14658 // The cornerstone, an `each` implementation, aka `forEach`.
14659 // Handles raw objects in addition to array-likes. Treats all
14660 // sparse array-likes as if they were dense.
14661 _.each = _.forEach = function(obj, iteratee, context) {
14662 iteratee = optimizeCb(iteratee, context);
14664 if (isArrayLike(obj)) {
14665 for (i = 0, length = obj.length; i < length; i++) {
14666 iteratee(obj[i], i, obj);
14669 var keys = _.keys(obj);
14670 for (i = 0, length = keys.length; i < length; i++) {
14671 iteratee(obj[keys[i]], keys[i], obj);
14677 // Return the results of applying the iteratee to each element.
14678 _.map = _.collect = function(obj, iteratee, context) {
14679 iteratee = cb(iteratee, context);
14680 var keys = !isArrayLike(obj) && _.keys(obj),
14681 length = (keys || obj).length,
14682 results = Array(length);
14683 for (var index = 0; index < length; index++) {
14684 var currentKey = keys ? keys[index] : index;
14685 results[index] = iteratee(obj[currentKey], currentKey, obj);
14690 // Create a reducing function iterating left or right.
14691 function createReduce(dir) {
14692 // Optimized iterator function as using arguments.length
14693 // in the main function will deoptimize the, see #1991.
14694 function iterator(obj, iteratee, memo, keys, index, length) {
14695 for (; index >= 0 && index < length; index += dir) {
14696 var currentKey = keys ? keys[index] : index;
14697 memo = iteratee(memo, obj[currentKey], currentKey, obj);
14702 return function(obj, iteratee, memo, context) {
14703 iteratee = optimizeCb(iteratee, context, 4);
14704 var keys = !isArrayLike(obj) && _.keys(obj),
14705 length = (keys || obj).length,
14706 index = dir > 0 ? 0 : length - 1;
14707 // Determine the initial value if none is provided.
14708 if (arguments.length < 3) {
14709 memo = obj[keys ? keys[index] : index];
14712 return iterator(obj, iteratee, memo, keys, index, length);
14716 // **Reduce** builds up a single result from a list of values, aka `inject`,
14718 _.reduce = _.foldl = _.inject = createReduce(1);
14720 // The right-associative version of reduce, also known as `foldr`.
14721 _.reduceRight = _.foldr = createReduce(-1);
14723 // Return the first value which passes a truth test. Aliased as `detect`.
14724 _.find = _.detect = function(obj, predicate, context) {
14726 if (isArrayLike(obj)) {
14727 key = _.findIndex(obj, predicate, context);
14729 key = _.findKey(obj, predicate, context);
14731 if (key !== void 0 && key !== -1) return obj[key];
14734 // Return all the elements that pass a truth test.
14735 // Aliased as `select`.
14736 _.filter = _.select = function(obj, predicate, context) {
14738 predicate = cb(predicate, context);
14739 _.each(obj, function(value, index, list) {
14740 if (predicate(value, index, list)) results.push(value);
14745 // Return all the elements for which a truth test fails.
14746 _.reject = function(obj, predicate, context) {
14747 return _.filter(obj, _.negate(cb(predicate)), context);
14750 // Determine whether all of the elements match a truth test.
14751 // Aliased as `all`.
14752 _.every = _.all = function(obj, predicate, context) {
14753 predicate = cb(predicate, context);
14754 var keys = !isArrayLike(obj) && _.keys(obj),
14755 length = (keys || obj).length;
14756 for (var index = 0; index < length; index++) {
14757 var currentKey = keys ? keys[index] : index;
14758 if (!predicate(obj[currentKey], currentKey, obj)) return false;
14763 // Determine if at least one element in the object matches a truth test.
14764 // Aliased as `any`.
14765 _.some = _.any = function(obj, predicate, context) {
14766 predicate = cb(predicate, context);
14767 var keys = !isArrayLike(obj) && _.keys(obj),
14768 length = (keys || obj).length;
14769 for (var index = 0; index < length; index++) {
14770 var currentKey = keys ? keys[index] : index;
14771 if (predicate(obj[currentKey], currentKey, obj)) return true;
14776 // Determine if the array or object contains a given item (using `===`).
14777 // Aliased as `includes` and `include`.
14778 _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
14779 if (!isArrayLike(obj)) obj = _.values(obj);
14780 if (typeof fromIndex != 'number' || guard) fromIndex = 0;
14781 return _.indexOf(obj, item, fromIndex) >= 0;
14784 // Invoke a method (with arguments) on every item in a collection.
14785 _.invoke = function(obj, method) {
14786 var args = slice.call(arguments, 2);
14787 var isFunc = _.isFunction(method);
14788 return _.map(obj, function(value) {
14789 var func = isFunc ? method : value[method];
14790 return func == null ? func : func.apply(value, args);
14794 // Convenience version of a common use case of `map`: fetching a property.
14795 _.pluck = function(obj, key) {
14796 return _.map(obj, _.property(key));
14799 // Convenience version of a common use case of `filter`: selecting only objects
14800 // containing specific `key:value` pairs.
14801 _.where = function(obj, attrs) {
14802 return _.filter(obj, _.matcher(attrs));
14805 // Convenience version of a common use case of `find`: getting the first object
14806 // containing specific `key:value` pairs.
14807 _.findWhere = function(obj, attrs) {
14808 return _.find(obj, _.matcher(attrs));
14811 // Return the maximum element (or element-based computation).
14812 _.max = function(obj, iteratee, context) {
14813 var result = -Infinity, lastComputed = -Infinity,
14815 if (iteratee == null && obj != null) {
14816 obj = isArrayLike(obj) ? obj : _.values(obj);
14817 for (var i = 0, length = obj.length; i < length; i++) {
14819 if (value > result) {
14824 iteratee = cb(iteratee, context);
14825 _.each(obj, function(value, index, list) {
14826 computed = iteratee(value, index, list);
14827 if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
14829 lastComputed = computed;
14836 // Return the minimum element (or element-based computation).
14837 _.min = function(obj, iteratee, context) {
14838 var result = Infinity, lastComputed = Infinity,
14840 if (iteratee == null && obj != null) {
14841 obj = isArrayLike(obj) ? obj : _.values(obj);
14842 for (var i = 0, length = obj.length; i < length; i++) {
14844 if (value < result) {
14849 iteratee = cb(iteratee, context);
14850 _.each(obj, function(value, index, list) {
14851 computed = iteratee(value, index, list);
14852 if (computed < lastComputed || computed === Infinity && result === Infinity) {
14854 lastComputed = computed;
14861 // Shuffle a collection, using the modern version of the
14862 // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
14863 _.shuffle = function(obj) {
14864 var set = isArrayLike(obj) ? obj : _.values(obj);
14865 var length = set.length;
14866 var shuffled = Array(length);
14867 for (var index = 0, rand; index < length; index++) {
14868 rand = _.random(0, index);
14869 if (rand !== index) shuffled[index] = shuffled[rand];
14870 shuffled[rand] = set[index];
14875 // Sample **n** random values from a collection.
14876 // If **n** is not specified, returns a single random element.
14877 // The internal `guard` argument allows it to work with `map`.
14878 _.sample = function(obj, n, guard) {
14879 if (n == null || guard) {
14880 if (!isArrayLike(obj)) obj = _.values(obj);
14881 return obj[_.random(obj.length - 1)];
14883 return _.shuffle(obj).slice(0, Math.max(0, n));
14886 // Sort the object's values by a criterion produced by an iteratee.
14887 _.sortBy = function(obj, iteratee, context) {
14888 iteratee = cb(iteratee, context);
14889 return _.pluck(_.map(obj, function(value, index, list) {
14893 criteria: iteratee(value, index, list)
14895 }).sort(function(left, right) {
14896 var a = left.criteria;
14897 var b = right.criteria;
14899 if (a > b || a === void 0) return 1;
14900 if (a < b || b === void 0) return -1;
14902 return left.index - right.index;
14906 // An internal function used for aggregate "group by" operations.
14907 var group = function(behavior) {
14908 return function(obj, iteratee, context) {
14910 iteratee = cb(iteratee, context);
14911 _.each(obj, function(value, index) {
14912 var key = iteratee(value, index, obj);
14913 behavior(result, value, key);
14919 // Groups the object's values by a criterion. Pass either a string attribute
14920 // to group by, or a function that returns the criterion.
14921 _.groupBy = group(function(result, value, key) {
14922 if (_.has(result, key)) result[key].push(value); else result[key] = [value];
14925 // Indexes the object's values by a criterion, similar to `groupBy`, but for
14926 // when you know that your index values will be unique.
14927 _.indexBy = group(function(result, value, key) {
14928 result[key] = value;
14931 // Counts instances of an object that group by a certain criterion. Pass
14932 // either a string attribute to count by, or a function that returns the
14934 _.countBy = group(function(result, value, key) {
14935 if (_.has(result, key)) result[key]++; else result[key] = 1;
14938 // Safely create a real, live array from anything iterable.
14939 _.toArray = function(obj) {
14940 if (!obj) return [];
14941 if (_.isArray(obj)) return slice.call(obj);
14942 if (isArrayLike(obj)) return _.map(obj, _.identity);
14943 return _.values(obj);
14946 // Return the number of elements in an object.
14947 _.size = function(obj) {
14948 if (obj == null) return 0;
14949 return isArrayLike(obj) ? obj.length : _.keys(obj).length;
14952 // Split a collection into two arrays: one whose elements all satisfy the given
14953 // predicate, and one whose elements all do not satisfy the predicate.
14954 _.partition = function(obj, predicate, context) {
14955 predicate = cb(predicate, context);
14956 var pass = [], fail = [];
14957 _.each(obj, function(value, key, obj) {
14958 (predicate(value, key, obj) ? pass : fail).push(value);
14960 return [pass, fail];
14966 // Get the first element of an array. Passing **n** will return the first N
14967 // values in the array. Aliased as `head` and `take`. The **guard** check
14968 // allows it to work with `_.map`.
14969 _.first = _.head = _.take = function(array, n, guard) {
14970 if (array == null) return void 0;
14971 if (n == null || guard) return array[0];
14972 return _.initial(array, array.length - n);
14975 // Returns everything but the last entry of the array. Especially useful on
14976 // the arguments object. Passing **n** will return all the values in
14977 // the array, excluding the last N.
14978 _.initial = function(array, n, guard) {
14979 return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
14982 // Get the last element of an array. Passing **n** will return the last N
14983 // values in the array.
14984 _.last = function(array, n, guard) {
14985 if (array == null) return void 0;
14986 if (n == null || guard) return array[array.length - 1];
14987 return _.rest(array, Math.max(0, array.length - n));
14990 // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
14991 // Especially useful on the arguments object. Passing an **n** will return
14992 // the rest N values in the array.
14993 _.rest = _.tail = _.drop = function(array, n, guard) {
14994 return slice.call(array, n == null || guard ? 1 : n);
14997 // Trim out all falsy values from an array.
14998 _.compact = function(array) {
14999 return _.filter(array, _.identity);
15002 // Internal implementation of a recursive `flatten` function.
15003 var flatten = function(input, shallow, strict, startIndex) {
15004 var output = [], idx = 0;
15005 for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
15006 var value = input[i];
15007 if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
15008 //flatten current level of array or arguments object
15009 if (!shallow) value = flatten(value, shallow, strict);
15010 var j = 0, len = value.length;
15011 output.length += len;
15013 output[idx++] = value[j++];
15015 } else if (!strict) {
15016 output[idx++] = value;
15022 // Flatten out an array, either recursively (by default), or just one level.
15023 _.flatten = function(array, shallow) {
15024 return flatten(array, shallow, false);
15027 // Return a version of the array that does not contain the specified value(s).
15028 _.without = function(array) {
15029 return _.difference(array, slice.call(arguments, 1));
15032 // Produce a duplicate-free version of the array. If the array has already
15033 // been sorted, you have the option of using a faster algorithm.
15034 // Aliased as `unique`.
15035 _.uniq = _.unique = function(array, isSorted, iteratee, context) {
15036 if (!_.isBoolean(isSorted)) {
15037 context = iteratee;
15038 iteratee = isSorted;
15041 if (iteratee != null) iteratee = cb(iteratee, context);
15044 for (var i = 0, length = getLength(array); i < length; i++) {
15045 var value = array[i],
15046 computed = iteratee ? iteratee(value, i, array) : value;
15048 if (!i || seen !== computed) result.push(value);
15050 } else if (iteratee) {
15051 if (!_.contains(seen, computed)) {
15052 seen.push(computed);
15053 result.push(value);
15055 } else if (!_.contains(result, value)) {
15056 result.push(value);
15062 // Produce an array that contains the union: each distinct element from all of
15063 // the passed-in arrays.
15064 _.union = function() {
15065 return _.uniq(flatten(arguments, true, true));
15068 // Produce an array that contains every item shared between all the
15069 // passed-in arrays.
15070 _.intersection = function(array) {
15072 var argsLength = arguments.length;
15073 for (var i = 0, length = getLength(array); i < length; i++) {
15074 var item = array[i];
15075 if (_.contains(result, item)) continue;
15076 for (var j = 1; j < argsLength; j++) {
15077 if (!_.contains(arguments[j], item)) break;
15079 if (j === argsLength) result.push(item);
15084 // Take the difference between one array and a number of other arrays.
15085 // Only the elements present in just the first array will remain.
15086 _.difference = function(array) {
15087 var rest = flatten(arguments, true, true, 1);
15088 return _.filter(array, function(value){
15089 return !_.contains(rest, value);
15093 // Zip together multiple lists into a single array -- elements that share
15094 // an index go together.
15095 _.zip = function() {
15096 return _.unzip(arguments);
15099 // Complement of _.zip. Unzip accepts an array of arrays and groups
15100 // each array's elements on shared indices
15101 _.unzip = function(array) {
15102 var length = array && _.max(array, getLength).length || 0;
15103 var result = Array(length);
15105 for (var index = 0; index < length; index++) {
15106 result[index] = _.pluck(array, index);
15111 // Converts lists into objects. Pass either a single array of `[key, value]`
15112 // pairs, or two parallel arrays of the same length -- one of keys, and one of
15113 // the corresponding values.
15114 _.object = function(list, values) {
15116 for (var i = 0, length = getLength(list); i < length; i++) {
15118 result[list[i]] = values[i];
15120 result[list[i][0]] = list[i][1];
15126 // Generator function to create the findIndex and findLastIndex functions
15127 function createPredicateIndexFinder(dir) {
15128 return function(array, predicate, context) {
15129 predicate = cb(predicate, context);
15130 var length = getLength(array);
15131 var index = dir > 0 ? 0 : length - 1;
15132 for (; index >= 0 && index < length; index += dir) {
15133 if (predicate(array[index], index, array)) return index;
15139 // Returns the first index on an array-like that passes a predicate test
15140 _.findIndex = createPredicateIndexFinder(1);
15141 _.findLastIndex = createPredicateIndexFinder(-1);
15143 // Use a comparator function to figure out the smallest index at which
15144 // an object should be inserted so as to maintain order. Uses binary search.
15145 _.sortedIndex = function(array, obj, iteratee, context) {
15146 iteratee = cb(iteratee, context, 1);
15147 var value = iteratee(obj);
15148 var low = 0, high = getLength(array);
15149 while (low < high) {
15150 var mid = Math.floor((low + high) / 2);
15151 if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
15156 // Generator function to create the indexOf and lastIndexOf functions
15157 function createIndexFinder(dir, predicateFind, sortedIndex) {
15158 return function(array, item, idx) {
15159 var i = 0, length = getLength(array);
15160 if (typeof idx == 'number') {
15162 i = idx >= 0 ? idx : Math.max(idx + length, i);
15164 length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
15166 } else if (sortedIndex && idx && length) {
15167 idx = sortedIndex(array, item);
15168 return array[idx] === item ? idx : -1;
15170 if (item !== item) {
15171 idx = predicateFind(slice.call(array, i, length), _.isNaN);
15172 return idx >= 0 ? idx + i : -1;
15174 for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
15175 if (array[idx] === item) return idx;
15181 // Return the position of the first occurrence of an item in an array,
15182 // or -1 if the item is not included in the array.
15183 // If the array is large and already in sort order, pass `true`
15184 // for **isSorted** to use binary search.
15185 _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
15186 _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
15188 // Generate an integer Array containing an arithmetic progression. A port of
15189 // the native Python `range()` function. See
15190 // [the Python documentation](http://docs.python.org/library/functions.html#range).
15191 _.range = function(start, stop, step) {
15192 if (stop == null) {
15198 var length = Math.max(Math.ceil((stop - start) / step), 0);
15199 var range = Array(length);
15201 for (var idx = 0; idx < length; idx++, start += step) {
15202 range[idx] = start;
15208 // Function (ahem) Functions
15209 // ------------------
15211 // Determines whether to execute a function as a constructor
15212 // or a normal function with the provided arguments
15213 var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
15214 if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
15215 var self = baseCreate(sourceFunc.prototype);
15216 var result = sourceFunc.apply(self, args);
15217 if (_.isObject(result)) return result;
15221 // Create a function bound to a given object (assigning `this`, and arguments,
15222 // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
15224 _.bind = function(func, context) {
15225 if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
15226 if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
15227 var args = slice.call(arguments, 2);
15228 var bound = function() {
15229 return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
15234 // Partially apply a function by creating a version that has had some of its
15235 // arguments pre-filled, without changing its dynamic `this` context. _ acts
15236 // as a placeholder, allowing any combination of arguments to be pre-filled.
15237 _.partial = function(func) {
15238 var boundArgs = slice.call(arguments, 1);
15239 var bound = function() {
15240 var position = 0, length = boundArgs.length;
15241 var args = Array(length);
15242 for (var i = 0; i < length; i++) {
15243 args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
15245 while (position < arguments.length) args.push(arguments[position++]);
15246 return executeBound(func, bound, this, this, args);
15251 // Bind a number of an object's methods to that object. Remaining arguments
15252 // are the method names to be bound. Useful for ensuring that all callbacks
15253 // defined on an object belong to it.
15254 _.bindAll = function(obj) {
15255 var i, length = arguments.length, key;
15256 if (length <= 1) throw new Error('bindAll must be passed function names');
15257 for (i = 1; i < length; i++) {
15258 key = arguments[i];
15259 obj[key] = _.bind(obj[key], obj);
15264 // Memoize an expensive function by storing its results.
15265 _.memoize = function(func, hasher) {
15266 var memoize = function(key) {
15267 var cache = memoize.cache;
15268 var address = '' + (hasher ? hasher.apply(this, arguments) : key);
15269 if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
15270 return cache[address];
15272 memoize.cache = {};
15276 // Delays a function for the given number of milliseconds, and then calls
15277 // it with the arguments supplied.
15278 _.delay = function(func, wait) {
15279 var args = slice.call(arguments, 2);
15280 return setTimeout(function(){
15281 return func.apply(null, args);
15285 // Defers a function, scheduling it to run after the current call stack has
15287 _.defer = _.partial(_.delay, _, 1);
15289 // Returns a function, that, when invoked, will only be triggered at most once
15290 // during a given window of time. Normally, the throttled function will run
15291 // as much as it can, without ever going more than once per `wait` duration;
15292 // but if you'd like to disable the execution on the leading edge, pass
15293 // `{leading: false}`. To disable execution on the trailing edge, ditto.
15294 _.throttle = function(func, wait, options) {
15295 var context, args, result;
15296 var timeout = null;
15298 if (!options) options = {};
15299 var later = function() {
15300 previous = options.leading === false ? 0 : _.now();
15302 result = func.apply(context, args);
15303 if (!timeout) context = args = null;
15305 return function() {
15307 if (!previous && options.leading === false) previous = now;
15308 var remaining = wait - (now - previous);
15311 if (remaining <= 0 || remaining > wait) {
15313 clearTimeout(timeout);
15317 result = func.apply(context, args);
15318 if (!timeout) context = args = null;
15319 } else if (!timeout && options.trailing !== false) {
15320 timeout = setTimeout(later, remaining);
15326 // Returns a function, that, as long as it continues to be invoked, will not
15327 // be triggered. The function will be called after it stops being called for
15328 // N milliseconds. If `immediate` is passed, trigger the function on the
15329 // leading edge, instead of the trailing.
15330 _.debounce = function(func, wait, immediate) {
15331 var timeout, args, context, timestamp, result;
15333 var later = function() {
15334 var last = _.now() - timestamp;
15336 if (last < wait && last >= 0) {
15337 timeout = setTimeout(later, wait - last);
15341 result = func.apply(context, args);
15342 if (!timeout) context = args = null;
15347 return function() {
15350 timestamp = _.now();
15351 var callNow = immediate && !timeout;
15352 if (!timeout) timeout = setTimeout(later, wait);
15354 result = func.apply(context, args);
15355 context = args = null;
15362 // Returns the first function passed as an argument to the second,
15363 // allowing you to adjust arguments, run code before and after, and
15364 // conditionally execute the original function.
15365 _.wrap = function(func, wrapper) {
15366 return _.partial(wrapper, func);
15369 // Returns a negated version of the passed-in predicate.
15370 _.negate = function(predicate) {
15371 return function() {
15372 return !predicate.apply(this, arguments);
15376 // Returns a function that is the composition of a list of functions, each
15377 // consuming the return value of the function that follows.
15378 _.compose = function() {
15379 var args = arguments;
15380 var start = args.length - 1;
15381 return function() {
15383 var result = args[start].apply(this, arguments);
15384 while (i--) result = args[i].call(this, result);
15389 // Returns a function that will only be executed on and after the Nth call.
15390 _.after = function(times, func) {
15391 return function() {
15393 return func.apply(this, arguments);
15398 // Returns a function that will only be executed up to (but not including) the Nth call.
15399 _.before = function(times, func) {
15401 return function() {
15403 memo = func.apply(this, arguments);
15405 if (times <= 1) func = null;
15410 // Returns a function that will be executed at most one time, no matter how
15411 // often you call it. Useful for lazy initialization.
15412 _.once = _.partial(_.before, 2);
15414 // Object Functions
15415 // ----------------
15417 // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
15418 var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
15419 var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
15420 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
15422 function collectNonEnumProps(obj, keys) {
15423 var nonEnumIdx = nonEnumerableProps.length;
15424 var constructor = obj.constructor;
15425 var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
15427 // Constructor is a special case.
15428 var prop = 'constructor';
15429 if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
15431 while (nonEnumIdx--) {
15432 prop = nonEnumerableProps[nonEnumIdx];
15433 if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
15439 // Retrieve the names of an object's own properties.
15440 // Delegates to **ECMAScript 5**'s native `Object.keys`
15441 _.keys = function(obj) {
15442 if (!_.isObject(obj)) return [];
15443 if (nativeKeys) return nativeKeys(obj);
15445 for (var key in obj) if (_.has(obj, key)) keys.push(key);
15447 if (hasEnumBug) collectNonEnumProps(obj, keys);
15451 // Retrieve all the property names of an object.
15452 _.allKeys = function(obj) {
15453 if (!_.isObject(obj)) return [];
15455 for (var key in obj) keys.push(key);
15457 if (hasEnumBug) collectNonEnumProps(obj, keys);
15461 // Retrieve the values of an object's properties.
15462 _.values = function(obj) {
15463 var keys = _.keys(obj);
15464 var length = keys.length;
15465 var values = Array(length);
15466 for (var i = 0; i < length; i++) {
15467 values[i] = obj[keys[i]];
15472 // Returns the results of applying the iteratee to each element of the object
15473 // In contrast to _.map it returns an object
15474 _.mapObject = function(obj, iteratee, context) {
15475 iteratee = cb(iteratee, context);
15476 var keys = _.keys(obj),
15477 length = keys.length,
15480 for (var index = 0; index < length; index++) {
15481 currentKey = keys[index];
15482 results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
15487 // Convert an object into a list of `[key, value]` pairs.
15488 _.pairs = function(obj) {
15489 var keys = _.keys(obj);
15490 var length = keys.length;
15491 var pairs = Array(length);
15492 for (var i = 0; i < length; i++) {
15493 pairs[i] = [keys[i], obj[keys[i]]];
15498 // Invert the keys and values of an object. The values must be serializable.
15499 _.invert = function(obj) {
15501 var keys = _.keys(obj);
15502 for (var i = 0, length = keys.length; i < length; i++) {
15503 result[obj[keys[i]]] = keys[i];
15508 // Return a sorted list of the function names available on the object.
15509 // Aliased as `methods`
15510 _.functions = _.methods = function(obj) {
15512 for (var key in obj) {
15513 if (_.isFunction(obj[key])) names.push(key);
15515 return names.sort();
15518 // Extend a given object with all the properties in passed-in object(s).
15519 _.extend = createAssigner(_.allKeys);
15521 // Assigns a given object with all the own properties in the passed-in object(s)
15522 // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
15523 _.extendOwn = _.assign = createAssigner(_.keys);
15525 // Returns the first key on an object that passes a predicate test
15526 _.findKey = function(obj, predicate, context) {
15527 predicate = cb(predicate, context);
15528 var keys = _.keys(obj), key;
15529 for (var i = 0, length = keys.length; i < length; i++) {
15531 if (predicate(obj[key], key, obj)) return key;
15535 // Return a copy of the object only containing the whitelisted properties.
15536 _.pick = function(object, oiteratee, context) {
15537 var result = {}, obj = object, iteratee, keys;
15538 if (obj == null) return result;
15539 if (_.isFunction(oiteratee)) {
15540 keys = _.allKeys(obj);
15541 iteratee = optimizeCb(oiteratee, context);
15543 keys = flatten(arguments, false, false, 1);
15544 iteratee = function(value, key, obj) { return key in obj; };
15547 for (var i = 0, length = keys.length; i < length; i++) {
15549 var value = obj[key];
15550 if (iteratee(value, key, obj)) result[key] = value;
15555 // Return a copy of the object without the blacklisted properties.
15556 _.omit = function(obj, iteratee, context) {
15557 if (_.isFunction(iteratee)) {
15558 iteratee = _.negate(iteratee);
15560 var keys = _.map(flatten(arguments, false, false, 1), String);
15561 iteratee = function(value, key) {
15562 return !_.contains(keys, key);
15565 return _.pick(obj, iteratee, context);
15568 // Fill in a given object with default properties.
15569 _.defaults = createAssigner(_.allKeys, true);
15571 // Creates an object that inherits from the given prototype object.
15572 // If additional properties are provided then they will be added to the
15574 _.create = function(prototype, props) {
15575 var result = baseCreate(prototype);
15576 if (props) _.extendOwn(result, props);
15580 // Create a (shallow-cloned) duplicate of an object.
15581 _.clone = function(obj) {
15582 if (!_.isObject(obj)) return obj;
15583 return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
15586 // Invokes interceptor with the obj, and then returns obj.
15587 // The primary purpose of this method is to "tap into" a method chain, in
15588 // order to perform operations on intermediate results within the chain.
15589 _.tap = function(obj, interceptor) {
15594 // Returns whether an object has a given set of `key:value` pairs.
15595 _.isMatch = function(object, attrs) {
15596 var keys = _.keys(attrs), length = keys.length;
15597 if (object == null) return !length;
15598 var obj = Object(object);
15599 for (var i = 0; i < length; i++) {
15601 if (attrs[key] !== obj[key] || !(key in obj)) return false;
15607 // Internal recursive comparison function for `isEqual`.
15608 var eq = function(a, b, aStack, bStack) {
15609 // Identical objects are equal. `0 === -0`, but they aren't identical.
15610 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
15611 if (a === b) return a !== 0 || 1 / a === 1 / b;
15612 // A strict comparison is necessary because `null == undefined`.
15613 if (a == null || b == null) return a === b;
15614 // Unwrap any wrapped objects.
15615 if (a instanceof _) a = a._wrapped;
15616 if (b instanceof _) b = b._wrapped;
15617 // Compare `[[Class]]` names.
15618 var className = toString.call(a);
15619 if (className !== toString.call(b)) return false;
15620 switch (className) {
15621 // Strings, numbers, regular expressions, dates, and booleans are compared by value.
15622 case '[object RegExp]':
15623 // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
15624 case '[object String]':
15625 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
15626 // equivalent to `new String("5")`.
15627 return '' + a === '' + b;
15628 case '[object Number]':
15629 // `NaN`s are equivalent, but non-reflexive.
15630 // Object(NaN) is equivalent to NaN
15631 if (+a !== +a) return +b !== +b;
15632 // An `egal` comparison is performed for other numeric values.
15633 return +a === 0 ? 1 / +a === 1 / b : +a === +b;
15634 case '[object Date]':
15635 case '[object Boolean]':
15636 // Coerce dates and booleans to numeric primitive values. Dates are compared by their
15637 // millisecond representations. Note that invalid dates with millisecond representations
15638 // of `NaN` are not equivalent.
15642 var areArrays = className === '[object Array]';
15644 if (typeof a != 'object' || typeof b != 'object') return false;
15646 // Objects with different constructors are not equivalent, but `Object`s or `Array`s
15647 // from different frames are.
15648 var aCtor = a.constructor, bCtor = b.constructor;
15649 if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
15650 _.isFunction(bCtor) && bCtor instanceof bCtor)
15651 && ('constructor' in a && 'constructor' in b)) {
15655 // Assume equality for cyclic structures. The algorithm for detecting cyclic
15656 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
15658 // Initializing stack of traversed objects.
15659 // It's done here since we only need them for objects and arrays comparison.
15660 aStack = aStack || [];
15661 bStack = bStack || [];
15662 var length = aStack.length;
15664 // Linear search. Performance is inversely proportional to the number of
15665 // unique nested structures.
15666 if (aStack[length] === a) return bStack[length] === b;
15669 // Add the first object to the stack of traversed objects.
15673 // Recursively compare objects and arrays.
15675 // Compare array lengths to determine if a deep comparison is necessary.
15677 if (length !== b.length) return false;
15678 // Deep compare the contents, ignoring non-numeric properties.
15680 if (!eq(a[length], b[length], aStack, bStack)) return false;
15683 // Deep compare objects.
15684 var keys = _.keys(a), key;
15685 length = keys.length;
15686 // Ensure that both objects contain the same number of properties before comparing deep equality.
15687 if (_.keys(b).length !== length) return false;
15689 // Deep compare each member
15690 key = keys[length];
15691 if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
15694 // Remove the first object from the stack of traversed objects.
15700 // Perform a deep comparison to check if two objects are equal.
15701 _.isEqual = function(a, b) {
15705 // Is a given array, string, or object empty?
15706 // An "empty" object has no enumerable own-properties.
15707 _.isEmpty = function(obj) {
15708 if (obj == null) return true;
15709 if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
15710 return _.keys(obj).length === 0;
15713 // Is a given value a DOM element?
15714 _.isElement = function(obj) {
15715 return !!(obj && obj.nodeType === 1);
15718 // Is a given value an array?
15719 // Delegates to ECMA5's native Array.isArray
15720 _.isArray = nativeIsArray || function(obj) {
15721 return toString.call(obj) === '[object Array]';
15724 // Is a given variable an object?
15725 _.isObject = function(obj) {
15726 var type = typeof obj;
15727 return type === 'function' || type === 'object' && !!obj;
15730 // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
15731 _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
15732 _['is' + name] = function(obj) {
15733 return toString.call(obj) === '[object ' + name + ']';
15737 // Define a fallback version of the method in browsers (ahem, IE < 9), where
15738 // there isn't any inspectable "Arguments" type.
15739 if (!_.isArguments(arguments)) {
15740 _.isArguments = function(obj) {
15741 return _.has(obj, 'callee');
15745 // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
15746 // IE 11 (#1621), and in Safari 8 (#1929).
15747 if (typeof /./ != 'function' && typeof Int8Array != 'object') {
15748 _.isFunction = function(obj) {
15749 return typeof obj == 'function' || false;
15753 // Is a given object a finite number?
15754 _.isFinite = function(obj) {
15755 return isFinite(obj) && !isNaN(parseFloat(obj));
15758 // Is the given value `NaN`? (NaN is the only number which does not equal itself).
15759 _.isNaN = function(obj) {
15760 return _.isNumber(obj) && obj !== +obj;
15763 // Is a given value a boolean?
15764 _.isBoolean = function(obj) {
15765 return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
15768 // Is a given value equal to null?
15769 _.isNull = function(obj) {
15770 return obj === null;
15773 // Is a given variable undefined?
15774 _.isUndefined = function(obj) {
15775 return obj === void 0;
15778 // Shortcut function for checking if an object has a given property directly
15779 // on itself (in other words, not on a prototype).
15780 _.has = function(obj, key) {
15781 return obj != null && hasOwnProperty.call(obj, key);
15784 // Utility Functions
15785 // -----------------
15787 // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
15788 // previous owner. Returns a reference to the Underscore object.
15789 _.noConflict = function() {
15790 root._ = previousUnderscore;
15794 // Keep the identity function around for default iteratees.
15795 _.identity = function(value) {
15799 // Predicate-generating functions. Often useful outside of Underscore.
15800 _.constant = function(value) {
15801 return function() {
15806 _.noop = function(){};
15808 _.property = property;
15810 // Generates a function for a given object that returns a given property.
15811 _.propertyOf = function(obj) {
15812 return obj == null ? function(){} : function(key) {
15817 // Returns a predicate for checking whether an object has a given set of
15818 // `key:value` pairs.
15819 _.matcher = _.matches = function(attrs) {
15820 attrs = _.extendOwn({}, attrs);
15821 return function(obj) {
15822 return _.isMatch(obj, attrs);
15826 // Run a function **n** times.
15827 _.times = function(n, iteratee, context) {
15828 var accum = Array(Math.max(0, n));
15829 iteratee = optimizeCb(iteratee, context, 1);
15830 for (var i = 0; i < n; i++) accum[i] = iteratee(i);
15834 // Return a random integer between min and max (inclusive).
15835 _.random = function(min, max) {
15840 return min + Math.floor(Math.random() * (max - min + 1));
15843 // A (possibly faster) way to get the current timestamp as an integer.
15844 _.now = Date.now || function() {
15845 return new Date().getTime();
15848 // List of HTML entities for escaping.
15857 var unescapeMap = _.invert(escapeMap);
15859 // Functions for escaping and unescaping strings to/from HTML interpolation.
15860 var createEscaper = function(map) {
15861 var escaper = function(match) {
15864 // Regexes for identifying a key that needs to be escaped
15865 var source = '(?:' + _.keys(map).join('|') + ')';
15866 var testRegexp = RegExp(source);
15867 var replaceRegexp = RegExp(source, 'g');
15868 return function(string) {
15869 string = string == null ? '' : '' + string;
15870 return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
15873 _.escape = createEscaper(escapeMap);
15874 _.unescape = createEscaper(unescapeMap);
15876 // If the value of the named `property` is a function then invoke it with the
15877 // `object` as context; otherwise, return it.
15878 _.result = function(object, property, fallback) {
15879 var value = object == null ? void 0 : object[property];
15880 if (value === void 0) {
15883 return _.isFunction(value) ? value.call(object) : value;
15886 // Generate a unique integer id (unique within the entire client session).
15887 // Useful for temporary DOM ids.
15889 _.uniqueId = function(prefix) {
15890 var id = ++idCounter + '';
15891 return prefix ? prefix + id : id;
15894 // By default, Underscore uses ERB-style template delimiters, change the
15895 // following template settings to use alternative delimiters.
15896 _.templateSettings = {
15897 evaluate : /<%([\s\S]+?)%>/g,
15898 interpolate : /<%=([\s\S]+?)%>/g,
15899 escape : /<%-([\s\S]+?)%>/g
15902 // When customizing `templateSettings`, if you don't want to define an
15903 // interpolation, evaluation or escaping regex, we need one that is
15904 // guaranteed not to match.
15905 var noMatch = /(.)^/;
15907 // Certain characters need to be escaped so that they can be put into a
15918 var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
15920 var escapeChar = function(match) {
15921 return '\\' + escapes[match];
15924 // JavaScript micro-templating, similar to John Resig's implementation.
15925 // Underscore templating handles arbitrary delimiters, preserves whitespace,
15926 // and correctly escapes quotes within interpolated code.
15927 // NB: `oldSettings` only exists for backwards compatibility.
15928 _.template = function(text, settings, oldSettings) {
15929 if (!settings && oldSettings) settings = oldSettings;
15930 settings = _.defaults({}, settings, _.templateSettings);
15932 // Combine delimiters into one regular expression via alternation.
15933 var matcher = RegExp([
15934 (settings.escape || noMatch).source,
15935 (settings.interpolate || noMatch).source,
15936 (settings.evaluate || noMatch).source
15937 ].join('|') + '|$', 'g');
15939 // Compile the template source, escaping string literals appropriately.
15941 var source = "__p+='";
15942 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
15943 source += text.slice(index, offset).replace(escaper, escapeChar);
15944 index = offset + match.length;
15947 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
15948 } else if (interpolate) {
15949 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
15950 } else if (evaluate) {
15951 source += "';\n" + evaluate + "\n__p+='";
15954 // Adobe VMs need the match returned to produce the correct offest.
15959 // If a variable is not specified, place data values in local scope.
15960 if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
15962 source = "var __t,__p='',__j=Array.prototype.join," +
15963 "print=function(){__p+=__j.call(arguments,'');};\n" +
15964 source + 'return __p;\n';
15967 var render = new Function(settings.variable || 'obj', '_', source);
15973 var template = function(data) {
15974 return render.call(this, data, _);
15977 // Provide the compiled source as a convenience for precompilation.
15978 var argument = settings.variable || 'obj';
15979 template.source = 'function(' + argument + '){\n' + source + '}';
15984 // Add a "chain" function. Start chaining a wrapped Underscore object.
15985 _.chain = function(obj) {
15986 var instance = _(obj);
15987 instance._chain = true;
15993 // If Underscore is called as a function, it returns a wrapped object that
15994 // can be used OO-style. This wrapper holds altered versions of all the
15995 // underscore functions. Wrapped objects may be chained.
15997 // Helper function to continue chaining intermediate results.
15998 var result = function(instance, obj) {
15999 return instance._chain ? _(obj).chain() : obj;
16002 // Add your own custom functions to the Underscore object.
16003 _.mixin = function(obj) {
16004 _.each(_.functions(obj), function(name) {
16005 var func = _[name] = obj[name];
16006 _.prototype[name] = function() {
16007 var args = [this._wrapped];
16008 push.apply(args, arguments);
16009 return result(this, func.apply(_, args));
16014 // Add all of the Underscore functions to the wrapper object.
16017 // Add all mutator Array functions to the wrapper.
16018 _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
16019 var method = ArrayProto[name];
16020 _.prototype[name] = function() {
16021 var obj = this._wrapped;
16022 method.apply(obj, arguments);
16023 if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
16024 return result(this, obj);
16028 // Add all accessor Array functions to the wrapper.
16029 _.each(['concat', 'join', 'slice'], function(name) {
16030 var method = ArrayProto[name];
16031 _.prototype[name] = function() {
16032 return result(this, method.apply(this._wrapped, arguments));
16036 // Extracts the result from a wrapped and chained object.
16037 _.prototype.value = function() {
16038 return this._wrapped;
16041 // Provide unwrapping proxy for some methods used in engine operations
16042 // such as arithmetic and JSON stringification.
16043 _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
16045 _.prototype.toString = function() {
16046 return '' + this._wrapped;
16049 // AMD registration happens at the end for compatibility with AMD loaders
16050 // that may not enforce next-turn semantics on modules. Even though general
16051 // practice for AMD registration is to be anonymous, underscore registers
16052 // as a named module because, like jQuery, it is a base library that is
16053 // popular enough to be bundled in a third party lib, but not be part of
16054 // an AMD load request. Those cases could generate an error when an
16055 // anonymous define() is called outside of a loader request.
16056 if (typeof define === 'function' && define.amd) {
16057 define('underscore', [], function() {
16063 },{}],179:[function(require,module,exports){
16064 var createElement = require("./vdom/create-element.js")
16066 module.exports = createElement
16068 },{"./vdom/create-element.js":185}],180:[function(require,module,exports){
16069 var diff = require("./vtree/diff.js")
16071 module.exports = diff
16073 },{"./vtree/diff.js":205}],181:[function(require,module,exports){
16074 var h = require("./virtual-hyperscript/index.js")
16078 },{"./virtual-hyperscript/index.js":192}],182:[function(require,module,exports){
16079 var diff = require("./diff.js")
16080 var patch = require("./patch.js")
16081 var h = require("./h.js")
16082 var create = require("./create-element.js")
16083 var VNode = require('./vnode/vnode.js')
16084 var VText = require('./vnode/vtext.js')
16095 },{"./create-element.js":179,"./diff.js":180,"./h.js":181,"./patch.js":183,"./vnode/vnode.js":201,"./vnode/vtext.js":203}],183:[function(require,module,exports){
16096 var patch = require("./vdom/patch.js")
16098 module.exports = patch
16100 },{"./vdom/patch.js":188}],184:[function(require,module,exports){
16101 var isObject = require("is-object")
16102 var isHook = require("../vnode/is-vhook.js")
16104 module.exports = applyProperties
16106 function applyProperties(node, props, previous) {
16107 for (var propName in props) {
16108 var propValue = props[propName]
16110 if (propValue === undefined) {
16111 removeProperty(node, propName, propValue, previous);
16112 } else if (isHook(propValue)) {
16113 removeProperty(node, propName, propValue, previous)
16114 if (propValue.hook) {
16115 propValue.hook(node,
16117 previous ? previous[propName] : undefined)
16120 if (isObject(propValue)) {
16121 patchObject(node, props, previous, propName, propValue);
16123 node[propName] = propValue
16129 function removeProperty(node, propName, propValue, previous) {
16131 var previousValue = previous[propName]
16133 if (!isHook(previousValue)) {
16134 if (propName === "attributes") {
16135 for (var attrName in previousValue) {
16136 node.removeAttribute(attrName)
16138 } else if (propName === "style") {
16139 for (var i in previousValue) {
16142 } else if (typeof previousValue === "string") {
16143 node[propName] = ""
16145 node[propName] = null
16147 } else if (previousValue.unhook) {
16148 previousValue.unhook(node, propName, propValue)
16153 function patchObject(node, props, previous, propName, propValue) {
16154 var previousValue = previous ? previous[propName] : undefined
16157 if (propName === "attributes") {
16158 for (var attrName in propValue) {
16159 var attrValue = propValue[attrName]
16161 if (attrValue === undefined) {
16162 node.removeAttribute(attrName)
16164 node.setAttribute(attrName, attrValue)
16171 if(previousValue && isObject(previousValue) &&
16172 getPrototype(previousValue) !== getPrototype(propValue)) {
16173 node[propName] = propValue
16177 if (!isObject(node[propName])) {
16178 node[propName] = {}
16181 var replacer = propName === "style" ? "" : undefined
16183 for (var k in propValue) {
16184 var value = propValue[k]
16185 node[propName][k] = (value === undefined) ? replacer : value
16189 function getPrototype(value) {
16190 if (Object.getPrototypeOf) {
16191 return Object.getPrototypeOf(value)
16192 } else if (value.__proto__) {
16193 return value.__proto__
16194 } else if (value.constructor) {
16195 return value.constructor.prototype
16199 },{"../vnode/is-vhook.js":196,"is-object":20}],185:[function(require,module,exports){
16200 var document = require("global/document")
16202 var applyProperties = require("./apply-properties")
16204 var isVNode = require("../vnode/is-vnode.js")
16205 var isVText = require("../vnode/is-vtext.js")
16206 var isWidget = require("../vnode/is-widget.js")
16207 var handleThunk = require("../vnode/handle-thunk.js")
16209 module.exports = createElement
16211 function createElement(vnode, opts) {
16212 var doc = opts ? opts.document || document : document
16213 var warn = opts ? opts.warn : null
16215 vnode = handleThunk(vnode).a
16217 if (isWidget(vnode)) {
16218 return vnode.init()
16219 } else if (isVText(vnode)) {
16220 return doc.createTextNode(vnode.text)
16221 } else if (!isVNode(vnode)) {
16223 warn("Item is not a valid virtual dom node", vnode)
16228 var node = (vnode.namespace === null) ?
16229 doc.createElement(vnode.tagName) :
16230 doc.createElementNS(vnode.namespace, vnode.tagName)
16232 var props = vnode.properties
16233 applyProperties(node, props)
16235 var children = vnode.children
16237 for (var i = 0; i < children.length; i++) {
16238 var childNode = createElement(children[i], opts)
16240 node.appendChild(childNode)
16247 },{"../vnode/handle-thunk.js":194,"../vnode/is-vnode.js":197,"../vnode/is-vtext.js":198,"../vnode/is-widget.js":199,"./apply-properties":184,"global/document":16}],186:[function(require,module,exports){
16248 // Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
16249 // We don't want to read all of the DOM nodes in the tree so we use
16250 // the in-order tree indexing to eliminate recursion down certain branches.
16251 // We only recurse into a DOM node if we know that it contains a child of
16256 module.exports = domIndex
16258 function domIndex(rootNode, tree, indices, nodes) {
16259 if (!indices || indices.length === 0) {
16262 indices.sort(ascending)
16263 return recurse(rootNode, tree, indices, nodes, 0)
16267 function recurse(rootNode, tree, indices, nodes, rootIndex) {
16268 nodes = nodes || {}
16272 if (indexInRange(indices, rootIndex, rootIndex)) {
16273 nodes[rootIndex] = rootNode
16276 var vChildren = tree.children
16280 var childNodes = rootNode.childNodes
16282 for (var i = 0; i < tree.children.length; i++) {
16285 var vChild = vChildren[i] || noChild
16286 var nextIndex = rootIndex + (vChild.count || 0)
16288 // skip recursion down the tree if there are no nodes down here
16289 if (indexInRange(indices, rootIndex, nextIndex)) {
16290 recurse(childNodes[i], vChild, indices, nodes, rootIndex)
16293 rootIndex = nextIndex
16301 // Binary search for an index in the interval [left, right]
16302 function indexInRange(indices, left, right) {
16303 if (indices.length === 0) {
16308 var maxIndex = indices.length - 1
16312 while (minIndex <= maxIndex) {
16313 currentIndex = ((maxIndex + minIndex) / 2) >> 0
16314 currentItem = indices[currentIndex]
16316 if (minIndex === maxIndex) {
16317 return currentItem >= left && currentItem <= right
16318 } else if (currentItem < left) {
16319 minIndex = currentIndex + 1
16320 } else if (currentItem > right) {
16321 maxIndex = currentIndex - 1
16330 function ascending(a, b) {
16331 return a > b ? 1 : -1
16334 },{}],187:[function(require,module,exports){
16335 var applyProperties = require("./apply-properties")
16337 var isWidget = require("../vnode/is-widget.js")
16338 var VPatch = require("../vnode/vpatch.js")
16340 var updateWidget = require("./update-widget")
16342 module.exports = applyPatch
16344 function applyPatch(vpatch, domNode, renderOptions) {
16345 var type = vpatch.type
16346 var vNode = vpatch.vNode
16347 var patch = vpatch.patch
16350 case VPatch.REMOVE:
16351 return removeNode(domNode, vNode)
16352 case VPatch.INSERT:
16353 return insertNode(domNode, patch, renderOptions)
16355 return stringPatch(domNode, vNode, patch, renderOptions)
16356 case VPatch.WIDGET:
16357 return widgetPatch(domNode, vNode, patch, renderOptions)
16359 return vNodePatch(domNode, vNode, patch, renderOptions)
16361 reorderChildren(domNode, patch)
16364 applyProperties(domNode, patch, vNode.properties)
16367 return replaceRoot(domNode,
16368 renderOptions.patch(domNode, patch, renderOptions))
16374 function removeNode(domNode, vNode) {
16375 var parentNode = domNode.parentNode
16378 parentNode.removeChild(domNode)
16381 destroyWidget(domNode, vNode);
16386 function insertNode(parentNode, vNode, renderOptions) {
16387 var newNode = renderOptions.render(vNode, renderOptions)
16390 parentNode.appendChild(newNode)
16396 function stringPatch(domNode, leftVNode, vText, renderOptions) {
16399 if (domNode.nodeType === 3) {
16400 domNode.replaceData(0, domNode.length, vText.text)
16403 var parentNode = domNode.parentNode
16404 newNode = renderOptions.render(vText, renderOptions)
16406 if (parentNode && newNode !== domNode) {
16407 parentNode.replaceChild(newNode, domNode)
16414 function widgetPatch(domNode, leftVNode, widget, renderOptions) {
16415 var updating = updateWidget(leftVNode, widget)
16419 newNode = widget.update(leftVNode, domNode) || domNode
16421 newNode = renderOptions.render(widget, renderOptions)
16424 var parentNode = domNode.parentNode
16426 if (parentNode && newNode !== domNode) {
16427 parentNode.replaceChild(newNode, domNode)
16431 destroyWidget(domNode, leftVNode)
16437 function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
16438 var parentNode = domNode.parentNode
16439 var newNode = renderOptions.render(vNode, renderOptions)
16441 if (parentNode && newNode !== domNode) {
16442 parentNode.replaceChild(newNode, domNode)
16448 function destroyWidget(domNode, w) {
16449 if (typeof w.destroy === "function" && isWidget(w)) {
16454 function reorderChildren(domNode, moves) {
16455 var childNodes = domNode.childNodes
16461 for (var i = 0; i < moves.removes.length; i++) {
16462 remove = moves.removes[i]
16463 node = childNodes[remove.from]
16465 keyMap[remove.key] = node
16467 domNode.removeChild(node)
16470 var length = childNodes.length
16471 for (var j = 0; j < moves.inserts.length; j++) {
16472 insert = moves.inserts[j]
16473 node = keyMap[insert.key]
16474 // this is the weirdest bug i've ever seen in webkit
16475 domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to])
16479 function replaceRoot(oldRoot, newRoot) {
16480 if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
16481 oldRoot.parentNode.replaceChild(newRoot, oldRoot)
16487 },{"../vnode/is-widget.js":199,"../vnode/vpatch.js":202,"./apply-properties":184,"./update-widget":189}],188:[function(require,module,exports){
16488 var document = require("global/document")
16489 var isArray = require("x-is-array")
16491 var render = require("./create-element")
16492 var domIndex = require("./dom-index")
16493 var patchOp = require("./patch-op")
16494 module.exports = patch
16496 function patch(rootNode, patches, renderOptions) {
16497 renderOptions = renderOptions || {}
16498 renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch
16499 ? renderOptions.patch
16501 renderOptions.render = renderOptions.render || render
16503 return renderOptions.patch(rootNode, patches, renderOptions)
16506 function patchRecursive(rootNode, patches, renderOptions) {
16507 var indices = patchIndices(patches)
16509 if (indices.length === 0) {
16513 var index = domIndex(rootNode, patches.a, indices)
16514 var ownerDocument = rootNode.ownerDocument
16516 if (!renderOptions.document && ownerDocument !== document) {
16517 renderOptions.document = ownerDocument
16520 for (var i = 0; i < indices.length; i++) {
16521 var nodeIndex = indices[i]
16522 rootNode = applyPatch(rootNode,
16524 patches[nodeIndex],
16531 function applyPatch(rootNode, domNode, patchList, renderOptions) {
16538 if (isArray(patchList)) {
16539 for (var i = 0; i < patchList.length; i++) {
16540 newNode = patchOp(patchList[i], domNode, renderOptions)
16542 if (domNode === rootNode) {
16547 newNode = patchOp(patchList, domNode, renderOptions)
16549 if (domNode === rootNode) {
16557 function patchIndices(patches) {
16560 for (var key in patches) {
16562 indices.push(Number(key))
16569 },{"./create-element":185,"./dom-index":186,"./patch-op":187,"global/document":16,"x-is-array":224}],189:[function(require,module,exports){
16570 var isWidget = require("../vnode/is-widget.js")
16572 module.exports = updateWidget
16574 function updateWidget(a, b) {
16575 if (isWidget(a) && isWidget(b)) {
16576 if ("name" in a && "name" in b) {
16577 return a.id === b.id
16579 return a.init === b.init
16586 },{"../vnode/is-widget.js":199}],190:[function(require,module,exports){
16589 var EvStore = require('ev-store');
16591 module.exports = EvHook;
16593 function EvHook(value) {
16594 if (!(this instanceof EvHook)) {
16595 return new EvHook(value);
16598 this.value = value;
16601 EvHook.prototype.hook = function (node, propertyName) {
16602 var es = EvStore(node);
16603 var propName = propertyName.substr(3);
16605 es[propName] = this.value;
16608 EvHook.prototype.unhook = function(node, propertyName) {
16609 var es = EvStore(node);
16610 var propName = propertyName.substr(3);
16612 es[propName] = undefined;
16615 },{"ev-store":9}],191:[function(require,module,exports){
16618 module.exports = SoftSetHook;
16620 function SoftSetHook(value) {
16621 if (!(this instanceof SoftSetHook)) {
16622 return new SoftSetHook(value);
16625 this.value = value;
16628 SoftSetHook.prototype.hook = function (node, propertyName) {
16629 if (node[propertyName] !== this.value) {
16630 node[propertyName] = this.value;
16634 },{}],192:[function(require,module,exports){
16637 var isArray = require('x-is-array');
16639 var VNode = require('../vnode/vnode.js');
16640 var VText = require('../vnode/vtext.js');
16641 var isVNode = require('../vnode/is-vnode');
16642 var isVText = require('../vnode/is-vtext');
16643 var isWidget = require('../vnode/is-widget');
16644 var isHook = require('../vnode/is-vhook');
16645 var isVThunk = require('../vnode/is-thunk');
16647 var parseTag = require('./parse-tag.js');
16648 var softSetHook = require('./hooks/soft-set-hook.js');
16649 var evHook = require('./hooks/ev-hook.js');
16651 module.exports = h;
16653 function h(tagName, properties, children) {
16654 var childNodes = [];
16655 var tag, props, key, namespace;
16657 if (!children && isChildren(properties)) {
16658 children = properties;
16662 props = props || properties || {};
16663 tag = parseTag(tagName, props);
16666 if (props.hasOwnProperty('key')) {
16668 props.key = undefined;
16671 // support namespace
16672 if (props.hasOwnProperty('namespace')) {
16673 namespace = props.namespace;
16674 props.namespace = undefined;
16678 if (tag === 'INPUT' &&
16680 props.hasOwnProperty('value') &&
16681 props.value !== undefined &&
16682 !isHook(props.value)
16684 props.value = softSetHook(props.value);
16687 transformProperties(props);
16689 if (children !== undefined && children !== null) {
16690 addChild(children, childNodes, tag, props);
16694 return new VNode(tag, props, childNodes, key, namespace);
16697 function addChild(c, childNodes, tag, props) {
16698 if (typeof c === 'string') {
16699 childNodes.push(new VText(c));
16700 } else if (typeof c === 'number') {
16701 childNodes.push(new VText(String(c)));
16702 } else if (isChild(c)) {
16703 childNodes.push(c);
16704 } else if (isArray(c)) {
16705 for (var i = 0; i < c.length; i++) {
16706 addChild(c[i], childNodes, tag, props);
16708 } else if (c === null || c === undefined) {
16711 throw UnexpectedVirtualElement({
16721 function transformProperties(props) {
16722 for (var propName in props) {
16723 if (props.hasOwnProperty(propName)) {
16724 var value = props[propName];
16726 if (isHook(value)) {
16730 if (propName.substr(0, 3) === 'ev-') {
16731 // add ev-foo support
16732 props[propName] = evHook(value);
16738 function isChild(x) {
16739 return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x);
16742 function isChildren(x) {
16743 return typeof x === 'string' || isArray(x) || isChild(x);
16746 function UnexpectedVirtualElement(data) {
16747 var err = new Error();
16749 err.type = 'virtual-hyperscript.unexpected.virtual-element';
16750 err.message = 'Unexpected virtual child passed to h().\n' +
16751 'Expected a VNode / Vthunk / VWidget / string but:\n' +
16753 errorString(data.foreignObject) +
16755 'The parent vnode is:\n' +
16756 errorString(data.parentVnode)
16758 'Suggested fix: change your `h(..., [ ... ])` callsite.';
16759 err.foreignObject = data.foreignObject;
16760 err.parentVnode = data.parentVnode;
16765 function errorString(obj) {
16767 return JSON.stringify(obj, null, ' ');
16769 return String(obj);
16773 },{"../vnode/is-thunk":195,"../vnode/is-vhook":196,"../vnode/is-vnode":197,"../vnode/is-vtext":198,"../vnode/is-widget":199,"../vnode/vnode.js":201,"../vnode/vtext.js":203,"./hooks/ev-hook.js":190,"./hooks/soft-set-hook.js":191,"./parse-tag.js":193,"x-is-array":224}],193:[function(require,module,exports){
16776 var split = require('browser-split');
16778 var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
16779 var notClassId = /^\.|#/;
16781 module.exports = parseTag;
16783 function parseTag(tag, props) {
16788 var noId = !(props.hasOwnProperty('id'));
16790 var tagParts = split(tag, classIdSplit);
16791 var tagName = null;
16793 if (notClassId.test(tagParts[1])) {
16797 var classes, part, type, i;
16799 for (i = 0; i < tagParts.length; i++) {
16800 part = tagParts[i];
16806 type = part.charAt(0);
16810 } else if (type === '.') {
16811 classes = classes || [];
16812 classes.push(part.substring(1, part.length));
16813 } else if (type === '#' && noId) {
16814 props.id = part.substring(1, part.length);
16819 if (props.className) {
16820 classes.push(props.className);
16823 props.className = classes.join(' ');
16826 return props.namespace ? tagName : tagName.toUpperCase();
16829 },{"browser-split":5}],194:[function(require,module,exports){
16830 var isVNode = require("./is-vnode")
16831 var isVText = require("./is-vtext")
16832 var isWidget = require("./is-widget")
16833 var isThunk = require("./is-thunk")
16835 module.exports = handleThunk
16837 function handleThunk(a, b) {
16842 renderedB = renderThunk(b, a)
16846 renderedA = renderThunk(a, null)
16855 function renderThunk(thunk, previous) {
16856 var renderedThunk = thunk.vnode
16858 if (!renderedThunk) {
16859 renderedThunk = thunk.vnode = thunk.render(previous)
16862 if (!(isVNode(renderedThunk) ||
16863 isVText(renderedThunk) ||
16864 isWidget(renderedThunk))) {
16865 throw new Error("thunk did not return a valid node");
16868 return renderedThunk
16871 },{"./is-thunk":195,"./is-vnode":197,"./is-vtext":198,"./is-widget":199}],195:[function(require,module,exports){
16872 module.exports = isThunk
16874 function isThunk(t) {
16875 return t && t.type === "Thunk"
16878 },{}],196:[function(require,module,exports){
16879 module.exports = isHook
16881 function isHook(hook) {
16883 (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") ||
16884 typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook"))
16887 },{}],197:[function(require,module,exports){
16888 var version = require("./version")
16890 module.exports = isVirtualNode
16892 function isVirtualNode(x) {
16893 return x && x.type === "VirtualNode" && x.version === version
16896 },{"./version":200}],198:[function(require,module,exports){
16897 var version = require("./version")
16899 module.exports = isVirtualText
16901 function isVirtualText(x) {
16902 return x && x.type === "VirtualText" && x.version === version
16905 },{"./version":200}],199:[function(require,module,exports){
16906 module.exports = isWidget
16908 function isWidget(w) {
16909 return w && w.type === "Widget"
16912 },{}],200:[function(require,module,exports){
16913 module.exports = "2"
16915 },{}],201:[function(require,module,exports){
16916 var version = require("./version")
16917 var isVNode = require("./is-vnode")
16918 var isWidget = require("./is-widget")
16919 var isThunk = require("./is-thunk")
16920 var isVHook = require("./is-vhook")
16922 module.exports = VirtualNode
16924 var noProperties = {}
16925 var noChildren = []
16927 function VirtualNode(tagName, properties, children, key, namespace) {
16928 this.tagName = tagName
16929 this.properties = properties || noProperties
16930 this.children = children || noChildren
16931 this.key = key != null ? String(key) : undefined
16932 this.namespace = (typeof namespace === "string") ? namespace : null
16934 var count = (children && children.length) || 0
16935 var descendants = 0
16936 var hasWidgets = false
16937 var hasThunks = false
16938 var descendantHooks = false
16941 for (var propName in properties) {
16942 if (properties.hasOwnProperty(propName)) {
16943 var property = properties[propName]
16944 if (isVHook(property) && property.unhook) {
16949 hooks[propName] = property
16954 for (var i = 0; i < count; i++) {
16955 var child = children[i]
16956 if (isVNode(child)) {
16957 descendants += child.count || 0
16959 if (!hasWidgets && child.hasWidgets) {
16963 if (!hasThunks && child.hasThunks) {
16967 if (!descendantHooks && (child.hooks || child.descendantHooks)) {
16968 descendantHooks = true
16970 } else if (!hasWidgets && isWidget(child)) {
16971 if (typeof child.destroy === "function") {
16974 } else if (!hasThunks && isThunk(child)) {
16979 this.count = count + descendants
16980 this.hasWidgets = hasWidgets
16981 this.hasThunks = hasThunks
16983 this.descendantHooks = descendantHooks
16986 VirtualNode.prototype.version = version
16987 VirtualNode.prototype.type = "VirtualNode"
16989 },{"./is-thunk":195,"./is-vhook":196,"./is-vnode":197,"./is-widget":199,"./version":200}],202:[function(require,module,exports){
16990 var version = require("./version")
16992 VirtualPatch.NONE = 0
16993 VirtualPatch.VTEXT = 1
16994 VirtualPatch.VNODE = 2
16995 VirtualPatch.WIDGET = 3
16996 VirtualPatch.PROPS = 4
16997 VirtualPatch.ORDER = 5
16998 VirtualPatch.INSERT = 6
16999 VirtualPatch.REMOVE = 7
17000 VirtualPatch.THUNK = 8
17002 module.exports = VirtualPatch
17004 function VirtualPatch(type, vNode, patch) {
17005 this.type = Number(type)
17010 VirtualPatch.prototype.version = version
17011 VirtualPatch.prototype.type = "VirtualPatch"
17013 },{"./version":200}],203:[function(require,module,exports){
17014 var version = require("./version")
17016 module.exports = VirtualText
17018 function VirtualText(text) {
17019 this.text = String(text)
17022 VirtualText.prototype.version = version
17023 VirtualText.prototype.type = "VirtualText"
17025 },{"./version":200}],204:[function(require,module,exports){
17026 var isObject = require("is-object")
17027 var isHook = require("../vnode/is-vhook")
17029 module.exports = diffProps
17031 function diffProps(a, b) {
17034 for (var aKey in a) {
17035 if (!(aKey in b)) {
17037 diff[aKey] = undefined
17040 var aValue = a[aKey]
17041 var bValue = b[aKey]
17043 if (aValue === bValue) {
17045 } else if (isObject(aValue) && isObject(bValue)) {
17046 if (getPrototype(bValue) !== getPrototype(aValue)) {
17048 diff[aKey] = bValue
17049 } else if (isHook(bValue)) {
17051 diff[aKey] = bValue
17053 var objectDiff = diffProps(aValue, bValue)
17056 diff[aKey] = objectDiff
17061 diff[aKey] = bValue
17065 for (var bKey in b) {
17066 if (!(bKey in a)) {
17068 diff[bKey] = b[bKey]
17075 function getPrototype(value) {
17076 if (Object.getPrototypeOf) {
17077 return Object.getPrototypeOf(value)
17078 } else if (value.__proto__) {
17079 return value.__proto__
17080 } else if (value.constructor) {
17081 return value.constructor.prototype
17085 },{"../vnode/is-vhook":196,"is-object":20}],205:[function(require,module,exports){
17086 var isArray = require("x-is-array")
17088 var VPatch = require("../vnode/vpatch")
17089 var isVNode = require("../vnode/is-vnode")
17090 var isVText = require("../vnode/is-vtext")
17091 var isWidget = require("../vnode/is-widget")
17092 var isThunk = require("../vnode/is-thunk")
17093 var handleThunk = require("../vnode/handle-thunk")
17095 var diffProps = require("./diff-props")
17097 module.exports = diff
17099 function diff(a, b) {
17100 var patch = { a: a }
17101 walk(a, b, patch, 0)
17105 function walk(a, b, patch, index) {
17110 var apply = patch[index]
17111 var applyClear = false
17113 if (isThunk(a) || isThunk(b)) {
17114 thunks(a, b, patch, index)
17115 } else if (b == null) {
17117 // If a is a widget we will add a remove patch for it
17118 // Otherwise any child widgets/hooks must be destroyed.
17119 // This prevents adding two remove patches for a widget.
17120 if (!isWidget(a)) {
17121 clearState(a, patch, index)
17122 apply = patch[index]
17125 apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
17126 } else if (isVNode(b)) {
17128 if (a.tagName === b.tagName &&
17129 a.namespace === b.namespace &&
17131 var propsPatch = diffProps(a.properties, b.properties)
17133 apply = appendPatch(apply,
17134 new VPatch(VPatch.PROPS, a, propsPatch))
17136 apply = diffChildren(a, b, patch, apply, index)
17138 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
17142 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
17145 } else if (isVText(b)) {
17147 apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
17149 } else if (a.text !== b.text) {
17150 apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
17152 } else if (isWidget(b)) {
17153 if (!isWidget(a)) {
17157 apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
17161 patch[index] = apply
17165 clearState(a, patch, index)
17169 function diffChildren(a, b, patch, apply, index) {
17170 var aChildren = a.children
17171 var orderedSet = reorder(aChildren, b.children)
17172 var bChildren = orderedSet.children
17174 var aLen = aChildren.length
17175 var bLen = bChildren.length
17176 var len = aLen > bLen ? aLen : bLen
17178 for (var i = 0; i < len; i++) {
17179 var leftNode = aChildren[i]
17180 var rightNode = bChildren[i]
17185 // Excess nodes in b need to be added
17186 apply = appendPatch(apply,
17187 new VPatch(VPatch.INSERT, null, rightNode))
17190 walk(leftNode, rightNode, patch, index)
17193 if (isVNode(leftNode) && leftNode.count) {
17194 index += leftNode.count
17198 if (orderedSet.moves) {
17199 // Reorder nodes last
17200 apply = appendPatch(apply, new VPatch(
17210 function clearState(vNode, patch, index) {
17211 // TODO: Make this a single walk, not two
17212 unhook(vNode, patch, index)
17213 destroyWidgets(vNode, patch, index)
17216 // Patch records for all destroyed widgets must be added because we need
17217 // a DOM node reference for the destroy function
17218 function destroyWidgets(vNode, patch, index) {
17219 if (isWidget(vNode)) {
17220 if (typeof vNode.destroy === "function") {
17221 patch[index] = appendPatch(
17223 new VPatch(VPatch.REMOVE, vNode, null)
17226 } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
17227 var children = vNode.children
17228 var len = children.length
17229 for (var i = 0; i < len; i++) {
17230 var child = children[i]
17233 destroyWidgets(child, patch, index)
17235 if (isVNode(child) && child.count) {
17236 index += child.count
17239 } else if (isThunk(vNode)) {
17240 thunks(vNode, null, patch, index)
17244 // Create a sub-patch for thunks
17245 function thunks(a, b, patch, index) {
17246 var nodes = handleThunk(a, b)
17247 var thunkPatch = diff(nodes.a, nodes.b)
17248 if (hasPatches(thunkPatch)) {
17249 patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
17253 function hasPatches(patch) {
17254 for (var index in patch) {
17255 if (index !== "a") {
17263 // Execute hooks when two nodes are identical
17264 function unhook(vNode, patch, index) {
17265 if (isVNode(vNode)) {
17267 patch[index] = appendPatch(
17272 undefinedKeys(vNode.hooks)
17277 if (vNode.descendantHooks || vNode.hasThunks) {
17278 var children = vNode.children
17279 var len = children.length
17280 for (var i = 0; i < len; i++) {
17281 var child = children[i]
17284 unhook(child, patch, index)
17286 if (isVNode(child) && child.count) {
17287 index += child.count
17291 } else if (isThunk(vNode)) {
17292 thunks(vNode, null, patch, index)
17296 function undefinedKeys(obj) {
17299 for (var key in obj) {
17300 result[key] = undefined
17306 // List diff, naive left to right reordering
17307 function reorder(aChildren, bChildren) {
17308 // O(M) time, O(M) memory
17309 var bChildIndex = keyIndex(bChildren)
17310 var bKeys = bChildIndex.keys
17311 var bFree = bChildIndex.free
17313 if (bFree.length === bChildren.length) {
17315 children: bChildren,
17320 // O(N) time, O(N) memory
17321 var aChildIndex = keyIndex(aChildren)
17322 var aKeys = aChildIndex.keys
17323 var aFree = aChildIndex.free
17325 if (aFree.length === aChildren.length) {
17327 children: bChildren,
17332 // O(MAX(N, M)) memory
17333 var newChildren = []
17336 var freeCount = bFree.length
17337 var deletedItems = 0
17339 // Iterate through a and match a node in b
17341 for (var i = 0 ; i < aChildren.length; i++) {
17342 var aItem = aChildren[i]
17346 if (bKeys.hasOwnProperty(aItem.key)) {
17347 // Match up the old keys
17348 itemIndex = bKeys[aItem.key]
17349 newChildren.push(bChildren[itemIndex])
17352 // Remove old keyed items
17353 itemIndex = i - deletedItems++
17354 newChildren.push(null)
17357 // Match the item in a with the next free item in b
17358 if (freeIndex < freeCount) {
17359 itemIndex = bFree[freeIndex++]
17360 newChildren.push(bChildren[itemIndex])
17362 // There are no free items in b to match with
17363 // the free items in a, so the extra free nodes
17365 itemIndex = i - deletedItems++
17366 newChildren.push(null)
17371 var lastFreeIndex = freeIndex >= bFree.length ?
17375 // Iterate through b and append any new keys
17377 for (var j = 0; j < bChildren.length; j++) {
17378 var newItem = bChildren[j]
17381 if (!aKeys.hasOwnProperty(newItem.key)) {
17382 // Add any new keyed items
17383 // We are adding new items to the end and then sorting them
17384 // in place. In future we should insert new items in place.
17385 newChildren.push(newItem)
17387 } else if (j >= lastFreeIndex) {
17388 // Add any leftover non-keyed items
17389 newChildren.push(newItem)
17393 var simulate = newChildren.slice()
17394 var simulateIndex = 0
17399 for (var k = 0; k < bChildren.length;) {
17400 var wantedItem = bChildren[k]
17401 simulateItem = simulate[simulateIndex]
17404 while (simulateItem === null && simulate.length) {
17405 removes.push(remove(simulate, simulateIndex, null))
17406 simulateItem = simulate[simulateIndex]
17409 if (!simulateItem || simulateItem.key !== wantedItem.key) {
17410 // if we need a key in this position...
17411 if (wantedItem.key) {
17412 if (simulateItem && simulateItem.key) {
17413 // if an insert doesn't put this key in place, it needs to move
17414 if (bKeys[simulateItem.key] !== k + 1) {
17415 removes.push(remove(simulate, simulateIndex, simulateItem.key))
17416 simulateItem = simulate[simulateIndex]
17417 // if the remove didn't put the wanted item in place, we need to insert it
17418 if (!simulateItem || simulateItem.key !== wantedItem.key) {
17419 inserts.push({key: wantedItem.key, to: k})
17421 // items are matching, so skip ahead
17427 inserts.push({key: wantedItem.key, to: k})
17431 inserts.push({key: wantedItem.key, to: k})
17435 // a key in simulate has no matching wanted key, remove it
17436 else if (simulateItem && simulateItem.key) {
17437 removes.push(remove(simulate, simulateIndex, simulateItem.key))
17446 // remove all the remaining nodes from simulate
17447 while(simulateIndex < simulate.length) {
17448 simulateItem = simulate[simulateIndex]
17449 removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key))
17452 // If the only moves we have are deletes then we can just
17453 // let the delete patch remove these items.
17454 if (removes.length === deletedItems && !inserts.length) {
17456 children: newChildren,
17462 children: newChildren,
17470 function remove(arr, index, key) {
17471 arr.splice(index, 1)
17479 function keyIndex(children) {
17482 var length = children.length
17484 for (var i = 0; i < length; i++) {
17485 var child = children[i]
17488 keys[child.key] = i
17495 keys: keys, // A hash of key name to index
17496 free: free // An array of unkeyed item indices
17500 function appendPatch(apply, patch) {
17502 if (isArray(apply)) {
17505 apply = [apply, patch]
17514 },{"../vnode/handle-thunk":194,"../vnode/is-thunk":195,"../vnode/is-vnode":197,"../vnode/is-vtext":198,"../vnode/is-widget":199,"../vnode/vpatch":202,"./diff-props":204,"x-is-array":224}],206:[function(require,module,exports){
17515 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17516 /** @author Brian Cavalier */
17517 /** @author John Hann */
17519 (function(define) { 'use strict';
17520 define(function (require) {
17522 var makePromise = require('./makePromise');
17523 var Scheduler = require('./Scheduler');
17524 var async = require('./env').asap;
17526 return makePromise({
17527 scheduler: new Scheduler(async)
17531 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
17533 },{"./Scheduler":207,"./env":219,"./makePromise":221}],207:[function(require,module,exports){
17534 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17535 /** @author Brian Cavalier */
17536 /** @author John Hann */
17538 (function(define) { 'use strict';
17539 define(function() {
17541 // Credit to Twisol (https://github.com/Twisol) for suggesting
17542 // this type of extensible queue + trampoline approach for next-tick conflation.
17545 * Async task scheduler
17546 * @param {function} async function to schedule a single async function
17549 function Scheduler(async) {
17550 this._async = async;
17551 this._running = false;
17553 this._queue = this;
17554 this._queueLen = 0;
17555 this._afterQueue = {};
17556 this._afterQueueLen = 0;
17559 this.drain = function() {
17566 * @param {{ run:function }} task
17568 Scheduler.prototype.enqueue = function(task) {
17569 this._queue[this._queueLen++] = task;
17574 * Enqueue a task to run after the main task queue
17575 * @param {{ run:function }} task
17577 Scheduler.prototype.afterQueue = function(task) {
17578 this._afterQueue[this._afterQueueLen++] = task;
17582 Scheduler.prototype.run = function() {
17583 if (!this._running) {
17584 this._running = true;
17585 this._async(this.drain);
17590 * Drain the handler queue entirely, and then the after queue
17592 Scheduler.prototype._drain = function() {
17594 for (; i < this._queueLen; ++i) {
17595 this._queue[i].run();
17596 this._queue[i] = void 0;
17599 this._queueLen = 0;
17600 this._running = false;
17602 for (i = 0; i < this._afterQueueLen; ++i) {
17603 this._afterQueue[i].run();
17604 this._afterQueue[i] = void 0;
17607 this._afterQueueLen = 0;
17613 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17615 },{}],208:[function(require,module,exports){
17616 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17617 /** @author Brian Cavalier */
17618 /** @author John Hann */
17620 (function(define) { 'use strict';
17621 define(function() {
17624 * Custom error type for promises rejected by promise.timeout
17625 * @param {string} message
17628 function TimeoutError (message) {
17630 this.message = message;
17631 this.name = TimeoutError.name;
17632 if (typeof Error.captureStackTrace === 'function') {
17633 Error.captureStackTrace(this, TimeoutError);
17637 TimeoutError.prototype = Object.create(Error.prototype);
17638 TimeoutError.prototype.constructor = TimeoutError;
17640 return TimeoutError;
17642 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17643 },{}],209:[function(require,module,exports){
17644 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17645 /** @author Brian Cavalier */
17646 /** @author John Hann */
17648 (function(define) { 'use strict';
17649 define(function() {
17651 makeApply.tryCatchResolve = tryCatchResolve;
17655 function makeApply(Promise, call) {
17656 if(arguments.length < 2) {
17657 call = tryCatchResolve;
17662 function apply(f, thisArg, args) {
17663 var p = Promise._defer();
17664 var l = args.length;
17665 var params = new Array(l);
17666 callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
17671 function callAndResolve(c, h) {
17673 return call(c.f, c.thisArg, c.params, h);
17676 var handler = Promise._handler(c.args[c.i]);
17677 handler.fold(callAndResolveNext, c, void 0, h);
17680 function callAndResolveNext(c, x, h) {
17683 callAndResolve(c, h);
17687 function tryCatchResolve(f, thisArg, args, resolver) {
17689 resolver.resolve(f.apply(thisArg, args));
17691 resolver.reject(e);
17696 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17700 },{}],210:[function(require,module,exports){
17701 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17702 /** @author Brian Cavalier */
17703 /** @author John Hann */
17705 (function(define) { 'use strict';
17706 define(function(require) {
17708 var state = require('../state');
17709 var applier = require('../apply');
17711 return function array(Promise) {
17713 var applyFold = applier(Promise);
17714 var toPromise = Promise.resolve;
17715 var all = Promise.all;
17717 var ar = Array.prototype.reduce;
17718 var arr = Array.prototype.reduceRight;
17719 var slice = Array.prototype.slice;
17721 // Additional array combinators
17724 Promise.some = some;
17725 Promise.settle = settle;
17728 Promise.filter = filter;
17729 Promise.reduce = reduce;
17730 Promise.reduceRight = reduceRight;
17733 * When this promise fulfills with an array, do
17734 * onFulfilled.apply(void 0, array)
17735 * @param {function} onFulfilled function to apply
17736 * @returns {Promise} promise for the result of applying onFulfilled
17738 Promise.prototype.spread = function(onFulfilled) {
17739 return this.then(all).then(function(array) {
17740 return onFulfilled.apply(this, array);
17747 * One-winner competitive race.
17748 * Return a promise that will fulfill when one of the promises
17749 * in the input array fulfills, or will reject when all promises
17751 * @param {array} promises
17752 * @returns {Promise} promise for the first fulfilled value
17754 function any(promises) {
17755 var p = Promise._defer();
17756 var resolver = p._handler;
17757 var l = promises.length>>>0;
17762 for (var h, x, i = 0; i < l; ++i) {
17764 if(x === void 0 && !(i in promises)) {
17769 h = Promise._handler(x);
17770 if(h.state() > 0) {
17771 resolver.become(h);
17772 Promise._visitRemaining(promises, i, h);
17775 h.visit(resolver, handleFulfill, handleReject);
17779 if(pending === 0) {
17780 resolver.reject(new RangeError('any(): array must not be empty'));
17785 function handleFulfill(x) {
17786 /*jshint validthis:true*/
17788 this.resolve(x); // this === resolver
17791 function handleReject(e) {
17792 /*jshint validthis:true*/
17793 if(this.resolved) { // this === resolver
17798 if(--pending === 0) {
17799 this.reject(errors);
17805 * N-winner competitive race
17806 * Return a promise that will fulfill when n input promises have
17807 * fulfilled, or will reject when it becomes impossible for n
17808 * input promises to fulfill (ie when promises.length - n + 1
17810 * @param {array} promises
17811 * @param {number} n
17812 * @returns {Promise} promise for the earliest n fulfillment values
17816 function some(promises, n) {
17817 /*jshint maxcomplexity:7*/
17818 var p = Promise._defer();
17819 var resolver = p._handler;
17824 var l = promises.length>>>0;
17827 var x, i; // reused in both for() loops
17829 // First pass: count actual array items
17830 for(i=0; i<l; ++i) {
17832 if(x === void 0 && !(i in promises)) {
17838 // Compute actual goals
17839 n = Math.max(n, 0);
17840 nReject = (nFulfill - n + 1);
17841 nFulfill = Math.min(n, nFulfill);
17844 resolver.reject(new RangeError('some(): array must contain at least '
17845 + n + ' item(s), but had ' + nFulfill));
17846 } else if(nFulfill === 0) {
17847 resolver.resolve(results);
17850 // Second pass: observe each array item, make progress toward goals
17851 for(i=0; i<l; ++i) {
17853 if(x === void 0 && !(i in promises)) {
17857 Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
17862 function fulfill(x) {
17863 /*jshint validthis:true*/
17864 if(this.resolved) { // this === resolver
17869 if(--nFulfill === 0) {
17871 this.resolve(results);
17875 function reject(e) {
17876 /*jshint validthis:true*/
17877 if(this.resolved) { // this === resolver
17882 if(--nReject === 0) {
17884 this.reject(errors);
17890 * Apply f to the value of each promise in a list of promises
17891 * and return a new list containing the results.
17892 * @param {array} promises
17893 * @param {function(x:*, index:Number):*} f mapping function
17894 * @returns {Promise}
17896 function map(promises, f) {
17897 return Promise._traverse(f, promises);
17901 * Filter the provided array of promises using the provided predicate. Input may
17902 * contain promises and values
17903 * @param {Array} promises array of promises and values
17904 * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
17905 * Must return truthy (or promise for truthy) for items to retain.
17906 * @returns {Promise} promise that will fulfill with an array containing all items
17907 * for which predicate returned truthy.
17909 function filter(promises, predicate) {
17910 var a = slice.call(promises);
17911 return Promise._traverse(predicate, a).then(function(keep) {
17912 return filterSync(a, keep);
17916 function filterSync(promises, keep) {
17917 // Safe because we know all promises have fulfilled if we've made it this far
17918 var l = keep.length;
17919 var filtered = new Array(l);
17920 for(var i=0, j=0; i<l; ++i) {
17922 filtered[j++] = Promise._handler(promises[i]).value;
17925 filtered.length = j;
17931 * Return a promise that will always fulfill with an array containing
17932 * the outcome states of all input promises. The returned promise
17933 * will never reject.
17934 * @param {Array} promises
17935 * @returns {Promise} promise for array of settled state descriptors
17937 function settle(promises) {
17938 return all(promises.map(settleOne));
17941 function settleOne(p) {
17942 // Optimize the case where we get an already-resolved when.js promise
17943 // by extracting its state:
17945 if (p instanceof Promise) {
17946 // This is our own Promise type and we can reach its handler internals:
17947 handler = p._handler.join();
17949 if((handler && handler.state() === 0) || !handler) {
17950 // Either still pending, or not a Promise at all:
17951 return toPromise(p).then(state.fulfilled, state.rejected);
17954 // The promise is our own, but it is already resolved. Take a shortcut.
17955 // Since we're not actually handling the resolution, we need to disable
17956 // rejection reporting.
17957 handler._unreport();
17958 return state.inspect(handler);
17962 * Traditional reduce function, similar to `Array.prototype.reduce()`, but
17963 * input may contain promises and/or values, and reduceFunc
17964 * may return either a value or a promise, *and* initialValue may
17965 * be a promise for the starting value.
17966 * @param {Array|Promise} promises array or promise for an array of anything,
17967 * may contain a mix of promises and values.
17968 * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
17969 * @returns {Promise} that will resolve to the final reduced value
17971 function reduce(promises, f /*, initialValue */) {
17972 return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
17973 : ar.call(promises, liftCombine(f));
17977 * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
17978 * input may contain promises and/or values, and reduceFunc
17979 * may return either a value or a promise, *and* initialValue may
17980 * be a promise for the starting value.
17981 * @param {Array|Promise} promises array or promise for an array of anything,
17982 * may contain a mix of promises and values.
17983 * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
17984 * @returns {Promise} that will resolve to the final reduced value
17986 function reduceRight(promises, f /*, initialValue */) {
17987 return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
17988 : arr.call(promises, liftCombine(f));
17991 function liftCombine(f) {
17992 return function(z, x, i) {
17993 return applyFold(f, void 0, [z,x,i]);
17999 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18001 },{"../apply":209,"../state":222}],211:[function(require,module,exports){
18002 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18003 /** @author Brian Cavalier */
18004 /** @author John Hann */
18006 (function(define) { 'use strict';
18007 define(function() {
18009 return function flow(Promise) {
18011 var resolve = Promise.resolve;
18012 var reject = Promise.reject;
18013 var origCatch = Promise.prototype['catch'];
18016 * Handle the ultimate fulfillment value or rejection reason, and assume
18017 * responsibility for all errors. If an error propagates out of result
18018 * or handleFatalError, it will be rethrown to the host, resulting in a
18019 * loud stack track on most platforms and a crash on some.
18020 * @param {function?} onResult
18021 * @param {function?} onError
18022 * @returns {undefined}
18024 Promise.prototype.done = function(onResult, onError) {
18025 this._handler.visit(this._handler.receiver, onResult, onError);
18029 * Add Error-type and predicate matching to catch. Examples:
18030 * promise.catch(TypeError, handleTypeError)
18031 * .catch(predicate, handleMatchedErrors)
18032 * .catch(handleRemainingErrors)
18033 * @param onRejected
18036 Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
18037 if (arguments.length < 2) {
18038 return origCatch.call(this, onRejected);
18041 if(typeof onRejected !== 'function') {
18042 return this.ensure(rejectInvalidPredicate);
18045 return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
18049 * Wraps the provided catch handler, so that it will only be called
18050 * if the predicate evaluates truthy
18051 * @param {?function} handler
18052 * @param {function} predicate
18053 * @returns {function} conditional catch handler
18055 function createCatchFilter(handler, predicate) {
18056 return function(e) {
18057 return evaluatePredicate(e, predicate)
18058 ? handler.call(this, e)
18064 * Ensures that onFulfilledOrRejected will be called regardless of whether
18065 * this promise is fulfilled or rejected. onFulfilledOrRejected WILL NOT
18066 * receive the promises' value or reason. Any returned value will be disregarded.
18067 * onFulfilledOrRejected may throw or return a rejected promise to signal
18068 * an additional error.
18069 * @param {function} handler handler to be called regardless of
18070 * fulfillment or rejection
18071 * @returns {Promise}
18073 Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
18074 if(typeof handler !== 'function') {
18078 return this.then(function(x) {
18079 return runSideEffect(handler, this, identity, x);
18081 return runSideEffect(handler, this, reject, e);
18085 function runSideEffect (handler, thisArg, propagate, value) {
18086 var result = handler.call(thisArg);
18087 return maybeThenable(result)
18088 ? propagateValue(result, propagate, value)
18089 : propagate(value);
18092 function propagateValue (result, propagate, x) {
18093 return resolve(result).then(function () {
18094 return propagate(x);
18099 * Recover from a failure by returning a defaultValue. If defaultValue
18100 * is a promise, it's fulfillment value will be used. If defaultValue is
18101 * a promise that rejects, the returned promise will reject with the
18103 * @param {*} defaultValue
18104 * @returns {Promise} new promise
18106 Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
18107 return this.then(void 0, function() {
18108 return defaultValue;
18113 * Shortcut for .then(function() { return value; })
18115 * @return {Promise} a promise that:
18116 * - is fulfilled if value is not a promise, or
18117 * - if value is a promise, will fulfill with its value, or reject
18120 Promise.prototype['yield'] = function(value) {
18121 return this.then(function() {
18127 * Runs a side effect when this promise fulfills, without changing the
18128 * fulfillment value.
18129 * @param {function} onFulfilledSideEffect
18130 * @returns {Promise}
18132 Promise.prototype.tap = function(onFulfilledSideEffect) {
18133 return this.then(onFulfilledSideEffect)['yield'](this);
18139 function rejectInvalidPredicate() {
18140 throw new TypeError('catch predicate must be a function');
18143 function evaluatePredicate(e, predicate) {
18144 return isError(predicate) ? e instanceof predicate : predicate(e);
18147 function isError(predicate) {
18148 return predicate === Error
18149 || (predicate != null && predicate.prototype instanceof Error);
18152 function maybeThenable(x) {
18153 return (typeof x === 'object' || typeof x === 'function') && x !== null;
18156 function identity(x) {
18161 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18163 },{}],212:[function(require,module,exports){
18164 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18165 /** @author Brian Cavalier */
18166 /** @author John Hann */
18167 /** @author Jeff Escalante */
18169 (function(define) { 'use strict';
18170 define(function() {
18172 return function fold(Promise) {
18174 Promise.prototype.fold = function(f, z) {
18175 var promise = this._beget();
18177 this._handler.fold(function(z, x, to) {
18178 Promise._handler(z).fold(function(x, z, to) {
18179 to.resolve(f.call(this, z, x));
18181 }, z, promise._handler.receiver, promise._handler);
18190 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18192 },{}],213:[function(require,module,exports){
18193 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18194 /** @author Brian Cavalier */
18195 /** @author John Hann */
18197 (function(define) { 'use strict';
18198 define(function(require) {
18200 var inspect = require('../state').inspect;
18202 return function inspection(Promise) {
18204 Promise.prototype.inspect = function() {
18205 return inspect(Promise._handler(this));
18212 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18214 },{"../state":222}],214:[function(require,module,exports){
18215 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18216 /** @author Brian Cavalier */
18217 /** @author John Hann */
18219 (function(define) { 'use strict';
18220 define(function() {
18222 return function generate(Promise) {
18224 var resolve = Promise.resolve;
18226 Promise.iterate = iterate;
18227 Promise.unfold = unfold;
18232 * @deprecated Use github.com/cujojs/most streams and most.iterate
18233 * Generate a (potentially infinite) stream of promised values:
18234 * x, f(x), f(f(x)), etc. until condition(x) returns true
18235 * @param {function} f function to generate a new x from the previous x
18236 * @param {function} condition function that, given the current x, returns
18237 * truthy when the iterate should stop
18238 * @param {function} handler function to handle the value produced by f
18239 * @param {*|Promise} x starting value, may be a promise
18240 * @return {Promise} the result of the last call to f before
18241 * condition returns true
18243 function iterate(f, condition, handler, x) {
18244 return unfold(function(x) {
18246 }, condition, handler, x);
18250 * @deprecated Use github.com/cujojs/most streams and most.unfold
18251 * Generate a (potentially infinite) stream of promised values
18252 * by applying handler(generator(seed)) iteratively until
18253 * condition(seed) returns true.
18254 * @param {function} unspool function that generates a [value, newSeed]
18256 * @param {function} condition function that, given the current seed, returns
18257 * truthy when the unfold should stop
18258 * @param {function} handler function to handle the value produced by unspool
18259 * @param x {*|Promise} starting value, may be a promise
18260 * @return {Promise} the result of the last value produced by unspool before
18261 * condition returns true
18263 function unfold(unspool, condition, handler, x) {
18264 return resolve(x).then(function(seed) {
18265 return resolve(condition(seed)).then(function(done) {
18266 return done ? seed : resolve(unspool(seed)).spread(next);
18270 function next(item, newSeed) {
18271 return resolve(handler(item)).then(function() {
18272 return unfold(unspool, condition, handler, newSeed);
18279 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18281 },{}],215:[function(require,module,exports){
18282 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18283 /** @author Brian Cavalier */
18284 /** @author John Hann */
18286 (function(define) { 'use strict';
18287 define(function() {
18289 return function progress(Promise) {
18293 * Register a progress handler for this promise
18294 * @param {function} onProgress
18295 * @returns {Promise}
18297 Promise.prototype.progress = function(onProgress) {
18298 return this.then(void 0, void 0, onProgress);
18305 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18307 },{}],216:[function(require,module,exports){
18308 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18309 /** @author Brian Cavalier */
18310 /** @author John Hann */
18312 (function(define) { 'use strict';
18313 define(function(require) {
18315 var env = require('../env');
18316 var TimeoutError = require('../TimeoutError');
18318 function setTimeout(f, ms, x, y) {
18319 return env.setTimer(function() {
18324 return function timed(Promise) {
18326 * Return a new promise whose fulfillment value is revealed only
18327 * after ms milliseconds
18328 * @param {number} ms milliseconds
18329 * @returns {Promise}
18331 Promise.prototype.delay = function(ms) {
18332 var p = this._beget();
18333 this._handler.fold(handleDelay, ms, void 0, p._handler);
18337 function handleDelay(ms, x, h) {
18338 setTimeout(resolveDelay, ms, x, h);
18341 function resolveDelay(x, h) {
18346 * Return a new promise that rejects after ms milliseconds unless
18347 * this promise fulfills earlier, in which case the returned promise
18348 * fulfills with the same value.
18349 * @param {number} ms milliseconds
18350 * @param {Error|*=} reason optional rejection reason to use, defaults
18351 * to a TimeoutError if not provided
18352 * @returns {Promise}
18354 Promise.prototype.timeout = function(ms, reason) {
18355 var p = this._beget();
18356 var h = p._handler;
18358 var t = setTimeout(onTimeout, ms, reason, p._handler);
18360 this._handler.visit(h,
18361 function onFulfill(x) {
18363 this.resolve(x); // this = h
18365 function onReject(x) {
18367 this.reject(x); // this = h
18374 function onTimeout(reason, h, ms) {
18375 var e = typeof reason === 'undefined'
18376 ? new TimeoutError('timed out after ' + ms + 'ms')
18385 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18387 },{"../TimeoutError":208,"../env":219}],217:[function(require,module,exports){
18388 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18389 /** @author Brian Cavalier */
18390 /** @author John Hann */
18392 (function(define) { 'use strict';
18393 define(function(require) {
18395 var setTimer = require('../env').setTimer;
18396 var format = require('../format');
18398 return function unhandledRejection(Promise) {
18400 var logError = noop;
18401 var logInfo = noop;
18404 if(typeof console !== 'undefined') {
18405 // Alias console to prevent things like uglify's drop_console option from
18406 // removing console.log/error. Unhandled rejections fall into the same
18407 // category as uncaught exceptions, and build tools shouldn't silence them.
18408 localConsole = console;
18409 logError = typeof localConsole.error !== 'undefined'
18410 ? function (e) { localConsole.error(e); }
18411 : function (e) { localConsole.log(e); };
18413 logInfo = typeof localConsole.info !== 'undefined'
18414 ? function (e) { localConsole.info(e); }
18415 : function (e) { localConsole.log(e); };
18418 Promise.onPotentiallyUnhandledRejection = function(rejection) {
18419 enqueue(report, rejection);
18422 Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
18423 enqueue(unreport, rejection);
18426 Promise.onFatalRejection = function(rejection) {
18427 enqueue(throwit, rejection.value);
18432 var running = null;
18434 function report(r) {
18437 logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
18441 function unreport(r) {
18442 var i = reported.indexOf(r);
18444 reported.splice(i, 1);
18445 logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
18449 function enqueue(f, x) {
18451 if(running === null) {
18452 running = setTimer(flush, 0);
18458 while(tasks.length > 0) {
18459 tasks.shift()(tasks.shift());
18466 function throwit(e) {
18473 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18475 },{"../env":219,"../format":220}],218:[function(require,module,exports){
18476 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18477 /** @author Brian Cavalier */
18478 /** @author John Hann */
18480 (function(define) { 'use strict';
18481 define(function() {
18483 return function addWith(Promise) {
18485 * Returns a promise whose handlers will be called with `this` set to
18486 * the supplied receiver. Subsequent promises derived from the
18487 * returned promise will also have their handlers called with receiver
18488 * as `this`. Calling `with` with undefined or no arguments will return
18489 * a promise whose handlers will again be called in the usual Promises/A+
18490 * way (no `this`) thus safely undoing any previous `with` in the
18493 * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
18494 * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
18496 * @param {object} receiver `this` value for all handlers attached to
18497 * the returned promise.
18498 * @returns {Promise}
18500 Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
18501 var p = this._beget();
18502 var child = p._handler;
18503 child.receiver = receiver;
18504 this._handler.chain(child, receiver);
18512 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18515 },{}],219:[function(require,module,exports){
18516 (function (process){
18517 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18518 /** @author Brian Cavalier */
18519 /** @author John Hann */
18521 /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
18522 (function(define) { 'use strict';
18523 define(function(require) {
18524 /*jshint maxcomplexity:6*/
18526 // Sniff "best" async scheduling option
18527 // Prefer process.nextTick or MutationObserver, then check for
18528 // setTimeout, and finally vertx, since its the only env that doesn't
18532 var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
18535 var setTimer = function(f, ms) { return setTimeout(f, ms); };
18536 var clearTimer = function(t) { return clearTimeout(t); };
18537 var asap = function (f) { return capturedSetTimeout(f, 0); };
18539 // Detect specific env
18540 if (isNode()) { // Node
18541 asap = function (f) { return process.nextTick(f); };
18543 } else if (MutationObs = hasMutationObserver()) { // Modern browser
18544 asap = initMutationObserver(MutationObs);
18546 } else if (!capturedSetTimeout) { // vert.x
18547 var vertxRequire = require;
18548 var vertx = vertxRequire('vertx');
18549 setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
18550 clearTimer = vertx.cancelTimer;
18551 asap = vertx.runOnLoop || vertx.runOnContext;
18555 setTimer: setTimer,
18556 clearTimer: clearTimer,
18560 function isNode () {
18561 return typeof process !== 'undefined' &&
18562 Object.prototype.toString.call(process) === '[object process]';
18565 function hasMutationObserver () {
18566 return (typeof MutationObserver !== 'undefined' && MutationObserver) ||
18567 (typeof WebKitMutationObserver !== 'undefined' && WebKitMutationObserver);
18570 function initMutationObserver(MutationObserver) {
18572 var node = document.createTextNode('');
18573 var o = new MutationObserver(run);
18574 o.observe(node, { characterData: true });
18578 scheduled = void 0;
18583 return function (f) {
18585 node.data = (i ^= 1);
18589 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18591 }).call(this,require('_process'))
18593 },{"_process":6}],220:[function(require,module,exports){
18594 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18595 /** @author Brian Cavalier */
18596 /** @author John Hann */
18598 (function(define) { 'use strict';
18599 define(function() {
18602 formatError: formatError,
18603 formatObject: formatObject,
18604 tryStringify: tryStringify
18608 * Format an error into a string. If e is an Error and has a stack property,
18609 * it's returned. Otherwise, e is formatted using formatObject, with a
18610 * warning added about e not being a proper Error.
18612 * @returns {String} formatted string, suitable for output to developers
18614 function formatError(e) {
18615 var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
18616 return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
18620 * Format an object, detecting "plain" objects and running them through
18621 * JSON.stringify if possible.
18622 * @param {Object} o
18623 * @returns {string}
18625 function formatObject(o) {
18627 if(s === '[object Object]' && typeof JSON !== 'undefined') {
18628 s = tryStringify(o, s);
18634 * Try to return the result of JSON.stringify(x). If that fails, return
18637 * @param {*} defaultValue
18638 * @returns {String|*} JSON.stringify(x) or defaultValue
18640 function tryStringify(x, defaultValue) {
18642 return JSON.stringify(x);
18644 return defaultValue;
18649 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18651 },{}],221:[function(require,module,exports){
18652 (function (process){
18653 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18654 /** @author Brian Cavalier */
18655 /** @author John Hann */
18657 (function(define) { 'use strict';
18658 define(function() {
18660 return function makePromise(environment) {
18662 var tasks = environment.scheduler;
18663 var emitRejection = initEmitRejection();
18665 var objectCreate = Object.create ||
18667 function Child() {}
18668 Child.prototype = proto;
18669 return new Child();
18673 * Create a promise whose fate is determined by resolver
18675 * @returns {Promise} promise
18678 function Promise(resolver, handler) {
18679 this._handler = resolver === Handler ? handler : init(resolver);
18683 * Run the supplied resolver
18685 * @returns {Pending}
18687 function init(resolver) {
18688 var handler = new Pending();
18691 resolver(promiseResolve, promiseReject, promiseNotify);
18699 * Transition from pre-resolution state to post-resolution state, notifying
18700 * all listeners of the ultimate fulfillment or rejection
18701 * @param {*} x resolution value
18703 function promiseResolve (x) {
18704 handler.resolve(x);
18707 * Reject this promise with reason, which will be used verbatim
18708 * @param {Error|*} reason rejection reason, strongly suggested
18709 * to be an Error type
18711 function promiseReject (reason) {
18712 handler.reject(reason);
18717 * Issue a progress event, notifying all progress listeners
18718 * @param {*} x progress event payload to pass to all listeners
18720 function promiseNotify (x) {
18727 Promise.resolve = resolve;
18728 Promise.reject = reject;
18729 Promise.never = never;
18731 Promise._defer = defer;
18732 Promise._handler = getHandler;
18735 * Returns a trusted promise. If x is already a trusted promise, it is
18736 * returned, otherwise returns a new trusted Promise which follows x.
18738 * @return {Promise} promise
18740 function resolve(x) {
18741 return isPromise(x) ? x
18742 : new Promise(Handler, new Async(getHandler(x)));
18746 * Return a reject promise with x as its reason (x is used verbatim)
18748 * @returns {Promise} rejected promise
18750 function reject(x) {
18751 return new Promise(Handler, new Async(new Rejected(x)));
18755 * Return a promise that remains pending forever
18756 * @returns {Promise} forever-pending promise.
18759 return foreverPendingPromise; // Should be frozen
18763 * Creates an internal {promise, resolver} pair
18765 * @returns {Promise}
18768 return new Promise(Handler, new Pending());
18771 // Transformation and flow control
18774 * Transform this promise's fulfillment value, returning a new Promise
18775 * for the transformed result. If the promise cannot be fulfilled, onRejected
18776 * is called with the reason. onProgress *may* be called with updates toward
18777 * this promise's fulfillment.
18778 * @param {function=} onFulfilled fulfillment handler
18779 * @param {function=} onRejected rejection handler
18780 * @param {function=} onProgress @deprecated progress handler
18781 * @return {Promise} new promise
18783 Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
18784 var parent = this._handler;
18785 var state = parent.join().state();
18787 if ((typeof onFulfilled !== 'function' && state > 0) ||
18788 (typeof onRejected !== 'function' && state < 0)) {
18789 // Short circuit: value will not change, simply share handler
18790 return new this.constructor(Handler, parent);
18793 var p = this._beget();
18794 var child = p._handler;
18796 parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
18802 * If this promise cannot be fulfilled due to an error, call onRejected to
18803 * handle the error. Shortcut for .then(undefined, onRejected)
18804 * @param {function?} onRejected
18805 * @return {Promise}
18807 Promise.prototype['catch'] = function(onRejected) {
18808 return this.then(void 0, onRejected);
18812 * Creates a new, pending promise of the same type as this promise
18814 * @returns {Promise}
18816 Promise.prototype._beget = function() {
18817 return begetFrom(this._handler, this.constructor);
18820 function begetFrom(parent, Promise) {
18821 var child = new Pending(parent.receiver, parent.join().context);
18822 return new Promise(Handler, child);
18825 // Array combinators
18828 Promise.race = race;
18829 Promise._traverse = traverse;
18832 * Return a promise that will fulfill when all promises in the
18833 * input array have fulfilled, or will reject when one of the
18834 * promises rejects.
18835 * @param {array} promises array of promises
18836 * @returns {Promise} promise for array of fulfillment values
18838 function all(promises) {
18839 return traverseWith(snd, null, promises);
18843 * Array<Promise<X>> -> Promise<Array<f(X)>>
18845 * @param {function} f function to apply to each promise's value
18846 * @param {Array} promises array of promises
18847 * @returns {Promise} promise for transformed values
18849 function traverse(f, promises) {
18850 return traverseWith(tryCatch2, f, promises);
18853 function traverseWith(tryMap, f, promises) {
18854 var handler = typeof f === 'function' ? mapAt : settleAt;
18856 var resolver = new Pending();
18857 var pending = promises.length >>> 0;
18858 var results = new Array(pending);
18860 for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
18863 if (x === void 0 && !(i in promises)) {
18868 traverseAt(promises, handler, i, x, resolver);
18871 if(pending === 0) {
18872 resolver.become(new Fulfilled(results));
18875 return new Promise(Handler, resolver);
18877 function mapAt(i, x, resolver) {
18878 if(!resolver.resolved) {
18879 traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
18883 function settleAt(i, x, resolver) {
18885 if(--pending === 0) {
18886 resolver.become(new Fulfilled(results));
18891 function traverseAt(promises, handler, i, x, resolver) {
18892 if (maybeThenable(x)) {
18893 var h = getHandlerMaybeThenable(x);
18897 h.fold(handler, i, void 0, resolver);
18898 } else if (s > 0) {
18899 handler(i, h.value, resolver);
18901 resolver.become(h);
18902 visitRemaining(promises, i+1, h);
18905 handler(i, x, resolver);
18909 Promise._visitRemaining = visitRemaining;
18910 function visitRemaining(promises, start, handler) {
18911 for(var i=start; i<promises.length; ++i) {
18912 markAsHandled(getHandler(promises[i]), handler);
18916 function markAsHandled(h, handler) {
18917 if(h === handler) {
18923 h.visit(h, void 0, h._unreport);
18930 * Fulfill-reject competitive race. Return a promise that will settle
18931 * to the same state as the earliest input promise to settle.
18933 * WARNING: The ES6 Promise spec requires that race()ing an empty array
18934 * must return a promise that is pending forever. This implementation
18935 * returns a singleton forever-pending promise, the same singleton that is
18936 * returned by Promise.never(), thus can be checked with ===
18938 * @param {array} promises array of promises to race
18939 * @returns {Promise} if input is non-empty, a promise that will settle
18940 * to the same outcome as the earliest input promise to settle. if empty
18941 * is empty, returns a promise that will never settle.
18943 function race(promises) {
18944 if(typeof promises !== 'object' || promises === null) {
18945 return reject(new TypeError('non-iterable passed to race()'));
18948 // Sigh, race([]) is untestable unless we return *something*
18949 // that is recognizable without calling .then() on it.
18950 return promises.length === 0 ? never()
18951 : promises.length === 1 ? resolve(promises[0])
18952 : runRace(promises);
18955 function runRace(promises) {
18956 var resolver = new Pending();
18958 for(i=0; i<promises.length; ++i) {
18960 if (x === void 0 && !(i in promises)) {
18965 if(h.state() !== 0) {
18966 resolver.become(h);
18967 visitRemaining(promises, i+1, h);
18970 h.visit(resolver, resolver.resolve, resolver.reject);
18973 return new Promise(Handler, resolver);
18976 // Promise internals
18977 // Below this, everything is @private
18980 * Get an appropriate handler for x, without checking for cycles
18982 * @returns {object} handler
18984 function getHandler(x) {
18986 return x._handler.join();
18988 return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
18992 * Get a handler for thenable x.
18993 * NOTE: You must only call this if maybeThenable(x) == true
18994 * @param {object|function|Promise} x
18995 * @returns {object} handler
18997 function getHandlerMaybeThenable(x) {
18998 return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
19002 * Get a handler for potentially untrusted thenable x
19004 * @returns {object} handler
19006 function getHandlerUntrusted(x) {
19008 var untrustedThen = x.then;
19009 return typeof untrustedThen === 'function'
19010 ? new Thenable(untrustedThen, x)
19011 : new Fulfilled(x);
19013 return new Rejected(e);
19018 * Handler for a promise that is pending forever
19021 function Handler() {}
19023 Handler.prototype.when
19024 = Handler.prototype.become
19025 = Handler.prototype.notify // deprecated
19026 = Handler.prototype.fail
19027 = Handler.prototype._unreport
19028 = Handler.prototype._report
19031 Handler.prototype._state = 0;
19033 Handler.prototype.state = function() {
19034 return this._state;
19038 * Recursively collapse handler chain to find the handler
19039 * nearest to the fully resolved value.
19040 * @returns {object} handler nearest the fully resolved value
19042 Handler.prototype.join = function() {
19044 while(h.handler !== void 0) {
19050 Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
19053 receiver: receiver,
19054 fulfilled: fulfilled,
19055 rejected: rejected,
19060 Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
19061 this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
19064 Handler.prototype.fold = function(f, z, c, to) {
19065 this.when(new Fold(f, z, c, to));
19069 * Handler that invokes fail() on any handler it becomes
19072 function FailIfRejected() {}
19074 inherit(Handler, FailIfRejected);
19076 FailIfRejected.prototype.become = function(h) {
19080 var failIfRejected = new FailIfRejected();
19083 * Handler that manages a queue of consumers waiting on a pending promise
19086 function Pending(receiver, inheritedContext) {
19087 Promise.createContext(this, inheritedContext);
19089 this.consumers = void 0;
19090 this.receiver = receiver;
19091 this.handler = void 0;
19092 this.resolved = false;
19095 inherit(Handler, Pending);
19097 Pending.prototype._state = 0;
19099 Pending.prototype.resolve = function(x) {
19100 this.become(getHandler(x));
19103 Pending.prototype.reject = function(x) {
19104 if(this.resolved) {
19108 this.become(new Rejected(x));
19111 Pending.prototype.join = function() {
19112 if (!this.resolved) {
19118 while (h.handler !== void 0) {
19121 return this.handler = cycle();
19128 Pending.prototype.run = function() {
19129 var q = this.consumers;
19130 var handler = this.handler;
19131 this.handler = this.handler.join();
19132 this.consumers = void 0;
19134 for (var i = 0; i < q.length; ++i) {
19135 handler.when(q[i]);
19139 Pending.prototype.become = function(handler) {
19140 if(this.resolved) {
19144 this.resolved = true;
19145 this.handler = handler;
19146 if(this.consumers !== void 0) {
19147 tasks.enqueue(this);
19150 if(this.context !== void 0) {
19151 handler._report(this.context);
19155 Pending.prototype.when = function(continuation) {
19156 if(this.resolved) {
19157 tasks.enqueue(new ContinuationTask(continuation, this.handler));
19159 if(this.consumers === void 0) {
19160 this.consumers = [continuation];
19162 this.consumers.push(continuation);
19170 Pending.prototype.notify = function(x) {
19171 if(!this.resolved) {
19172 tasks.enqueue(new ProgressTask(x, this));
19176 Pending.prototype.fail = function(context) {
19177 var c = typeof context === 'undefined' ? this.context : context;
19178 this.resolved && this.handler.join().fail(c);
19181 Pending.prototype._report = function(context) {
19182 this.resolved && this.handler.join()._report(context);
19185 Pending.prototype._unreport = function() {
19186 this.resolved && this.handler.join()._unreport();
19190 * Wrap another handler and force it into a future stack
19191 * @param {object} handler
19194 function Async(handler) {
19195 this.handler = handler;
19198 inherit(Handler, Async);
19200 Async.prototype.when = function(continuation) {
19201 tasks.enqueue(new ContinuationTask(continuation, this));
19204 Async.prototype._report = function(context) {
19205 this.join()._report(context);
19208 Async.prototype._unreport = function() {
19209 this.join()._unreport();
19213 * Handler that wraps an untrusted thenable and assimilates it in a future stack
19214 * @param {function} then
19215 * @param {{then: function}} thenable
19218 function Thenable(then, thenable) {
19219 Pending.call(this);
19220 tasks.enqueue(new AssimilateTask(then, thenable, this));
19223 inherit(Pending, Thenable);
19226 * Handler for a fulfilled promise
19227 * @param {*} x fulfillment value
19230 function Fulfilled(x) {
19231 Promise.createContext(this);
19235 inherit(Handler, Fulfilled);
19237 Fulfilled.prototype._state = 1;
19239 Fulfilled.prototype.fold = function(f, z, c, to) {
19240 runContinuation3(f, z, this, c, to);
19243 Fulfilled.prototype.when = function(cont) {
19244 runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
19250 * Handler for a rejected promise
19251 * @param {*} x rejection reason
19254 function Rejected(x) {
19255 Promise.createContext(this);
19257 this.id = ++errorId;
19259 this.handled = false;
19260 this.reported = false;
19265 inherit(Handler, Rejected);
19267 Rejected.prototype._state = -1;
19269 Rejected.prototype.fold = function(f, z, c, to) {
19273 Rejected.prototype.when = function(cont) {
19274 if(typeof cont.rejected === 'function') {
19277 runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
19280 Rejected.prototype._report = function(context) {
19281 tasks.afterQueue(new ReportTask(this, context));
19284 Rejected.prototype._unreport = function() {
19288 this.handled = true;
19289 tasks.afterQueue(new UnreportTask(this));
19292 Rejected.prototype.fail = function(context) {
19293 this.reported = true;
19294 emitRejection('unhandledRejection', this);
19295 Promise.onFatalRejection(this, context === void 0 ? this.context : context);
19298 function ReportTask(rejection, context) {
19299 this.rejection = rejection;
19300 this.context = context;
19303 ReportTask.prototype.run = function() {
19304 if(!this.rejection.handled && !this.rejection.reported) {
19305 this.rejection.reported = true;
19306 emitRejection('unhandledRejection', this.rejection) ||
19307 Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
19311 function UnreportTask(rejection) {
19312 this.rejection = rejection;
19315 UnreportTask.prototype.run = function() {
19316 if(this.rejection.reported) {
19317 emitRejection('rejectionHandled', this.rejection) ||
19318 Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
19322 // Unhandled rejection hooks
19323 // By default, everything is a noop
19325 Promise.createContext
19326 = Promise.enterContext
19327 = Promise.exitContext
19328 = Promise.onPotentiallyUnhandledRejection
19329 = Promise.onPotentiallyUnhandledRejectionHandled
19330 = Promise.onFatalRejection
19333 // Errors and singletons
19335 var foreverPendingHandler = new Handler();
19336 var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
19339 return new Rejected(new TypeError('Promise cycle'));
19345 * Run a single consumer
19348 function ContinuationTask(continuation, handler) {
19349 this.continuation = continuation;
19350 this.handler = handler;
19353 ContinuationTask.prototype.run = function() {
19354 this.handler.join().when(this.continuation);
19358 * Run a queue of progress handlers
19361 function ProgressTask(value, handler) {
19362 this.handler = handler;
19363 this.value = value;
19366 ProgressTask.prototype.run = function() {
19367 var q = this.handler.consumers;
19372 for (var c, i = 0; i < q.length; ++i) {
19374 runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
19379 * Assimilate a thenable, sending it's value to resolver
19380 * @param {function} then
19381 * @param {object|function} thenable
19382 * @param {object} resolver
19385 function AssimilateTask(then, thenable, resolver) {
19387 this.thenable = thenable;
19388 this.resolver = resolver;
19391 AssimilateTask.prototype.run = function() {
19392 var h = this.resolver;
19393 tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
19395 function _resolve(x) { h.resolve(x); }
19396 function _reject(x) { h.reject(x); }
19397 function _notify(x) { h.notify(x); }
19400 function tryAssimilate(then, thenable, resolve, reject, notify) {
19402 then.call(thenable, resolve, reject, notify);
19409 * Fold a handler value with z
19412 function Fold(f, z, c, to) {
19413 this.f = f; this.z = z; this.c = c; this.to = to;
19414 this.resolver = failIfRejected;
19415 this.receiver = this;
19418 Fold.prototype.fulfilled = function(x) {
19419 this.f.call(this.c, this.z, x, this.to);
19422 Fold.prototype.rejected = function(x) {
19426 Fold.prototype.progress = function(x) {
19434 * @returns {boolean} true iff x is a trusted Promise
19436 function isPromise(x) {
19437 return x instanceof Promise;
19441 * Test just enough to rule out primitives, in order to take faster
19442 * paths in some code
19444 * @returns {boolean} false iff x is guaranteed *not* to be a thenable
19446 function maybeThenable(x) {
19447 return (typeof x === 'object' || typeof x === 'function') && x !== null;
19450 function runContinuation1(f, h, receiver, next) {
19451 if(typeof f !== 'function') {
19452 return next.become(h);
19455 Promise.enterContext(h);
19456 tryCatchReject(f, h.value, receiver, next);
19457 Promise.exitContext();
19460 function runContinuation3(f, x, h, receiver, next) {
19461 if(typeof f !== 'function') {
19462 return next.become(h);
19465 Promise.enterContext(h);
19466 tryCatchReject3(f, x, h.value, receiver, next);
19467 Promise.exitContext();
19473 function runNotify(f, x, h, receiver, next) {
19474 if(typeof f !== 'function') {
19475 return next.notify(x);
19478 Promise.enterContext(h);
19479 tryCatchReturn(f, x, receiver, next);
19480 Promise.exitContext();
19483 function tryCatch2(f, a, b) {
19492 * Return f.call(thisArg, x), or if it throws return a rejected promise for
19493 * the thrown exception
19495 function tryCatchReject(f, x, thisArg, next) {
19497 next.become(getHandler(f.call(thisArg, x)));
19499 next.become(new Rejected(e));
19504 * Same as above, but includes the extra argument parameter.
19506 function tryCatchReject3(f, x, y, thisArg, next) {
19508 f.call(thisArg, x, y, next);
19510 next.become(new Rejected(e));
19516 * Return f.call(thisArg, x), or if it throws, *return* the exception
19518 function tryCatchReturn(f, x, thisArg, next) {
19520 next.notify(f.call(thisArg, x));
19526 function inherit(Parent, Child) {
19527 Child.prototype = objectCreate(Parent.prototype);
19528 Child.prototype.constructor = Child;
19531 function snd(x, y) {
19537 function hasCustomEvent() {
19538 if(typeof CustomEvent === 'function') {
19540 var ev = new CustomEvent('unhandledRejection');
19541 return ev instanceof CustomEvent;
19542 } catch (ignoredException) {}
19547 function hasInternetExplorerCustomEvent() {
19548 if(typeof document !== 'undefined' && typeof document.createEvent === 'function') {
19550 // Try to create one event to make sure it's supported
19551 var ev = document.createEvent('CustomEvent');
19552 ev.initCustomEvent('eventType', false, true, {});
19554 } catch (ignoredException) {}
19559 function initEmitRejection() {
19560 /*global process, self, CustomEvent*/
19561 if(typeof process !== 'undefined' && process !== null
19562 && typeof process.emit === 'function') {
19563 // Returning falsy here means to call the default
19564 // onPotentiallyUnhandledRejection API. This is safe even in
19565 // browserify since process.emit always returns falsy in browserify:
19566 // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
19567 return function(type, rejection) {
19568 return type === 'unhandledRejection'
19569 ? process.emit(type, rejection.value, rejection)
19570 : process.emit(type, rejection);
19572 } else if(typeof self !== 'undefined' && hasCustomEvent()) {
19573 return (function (self, CustomEvent) {
19574 return function (type, rejection) {
19575 var ev = new CustomEvent(type, {
19577 reason: rejection.value,
19584 return !self.dispatchEvent(ev);
19586 }(self, CustomEvent));
19587 } else if(typeof self !== 'undefined' && hasInternetExplorerCustomEvent()) {
19588 return (function(self, document) {
19589 return function(type, rejection) {
19590 var ev = document.createEvent('CustomEvent');
19591 ev.initCustomEvent(type, false, true, {
19592 reason: rejection.value,
19596 return !self.dispatchEvent(ev);
19598 }(self, document));
19607 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19609 }).call(this,require('_process'))
19611 },{"_process":6}],222:[function(require,module,exports){
19612 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19613 /** @author Brian Cavalier */
19614 /** @author John Hann */
19616 (function(define) { 'use strict';
19617 define(function() {
19620 pending: toPendingState,
19621 fulfilled: toFulfilledState,
19622 rejected: toRejectedState,
19626 function toPendingState() {
19627 return { state: 'pending' };
19630 function toRejectedState(e) {
19631 return { state: 'rejected', reason: e };
19634 function toFulfilledState(x) {
19635 return { state: 'fulfilled', value: x };
19638 function inspect(handler) {
19639 var state = handler.state();
19640 return state === 0 ? toPendingState()
19641 : state > 0 ? toFulfilledState(handler.value)
19642 : toRejectedState(handler.value);
19646 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19648 },{}],223:[function(require,module,exports){
19649 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19652 * Promises/A+ and when() implementation
19653 * when is part of the cujoJS family of libraries (http://cujojs.com/)
19654 * @author Brian Cavalier
19655 * @author John Hann
19657 (function(define) { 'use strict';
19658 define(function (require) {
19660 var timed = require('./lib/decorators/timed');
19661 var array = require('./lib/decorators/array');
19662 var flow = require('./lib/decorators/flow');
19663 var fold = require('./lib/decorators/fold');
19664 var inspect = require('./lib/decorators/inspect');
19665 var generate = require('./lib/decorators/iterate');
19666 var progress = require('./lib/decorators/progress');
19667 var withThis = require('./lib/decorators/with');
19668 var unhandledRejection = require('./lib/decorators/unhandledRejection');
19669 var TimeoutError = require('./lib/TimeoutError');
19671 var Promise = [array, flow, fold, generate, progress,
19672 inspect, withThis, timed, unhandledRejection]
19673 .reduce(function(Promise, feature) {
19674 return feature(Promise);
19675 }, require('./lib/Promise'));
19677 var apply = require('./lib/apply')(Promise);
19681 when.promise = promise; // Create a pending promise
19682 when.resolve = Promise.resolve; // Create a resolved promise
19683 when.reject = Promise.reject; // Create a rejected promise
19685 when.lift = lift; // lift a function to return promises
19686 when['try'] = attempt; // call a function and return a promise
19687 when.attempt = attempt; // alias for when.try
19689 when.iterate = Promise.iterate; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
19690 when.unfold = Promise.unfold; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
19692 when.join = join; // Join 2 or more promises
19694 when.all = all; // Resolve a list of promises
19695 when.settle = settle; // Settle a list of promises
19697 when.any = lift(Promise.any); // One-winner race
19698 when.some = lift(Promise.some); // Multi-winner race
19699 when.race = lift(Promise.race); // First-to-settle race
19701 when.map = map; // Array.map() for promises
19702 when.filter = filter; // Array.filter() for promises
19703 when.reduce = lift(Promise.reduce); // Array.reduce() for promises
19704 when.reduceRight = lift(Promise.reduceRight); // Array.reduceRight() for promises
19706 when.isPromiseLike = isPromiseLike; // Is something promise-like, aka thenable
19708 when.Promise = Promise; // Promise constructor
19709 when.defer = defer; // Create a {promise, resolve, reject} tuple
19713 when.TimeoutError = TimeoutError;
19716 * Get a trusted promise for x, or by transforming x with onFulfilled
19719 * @param {function?} onFulfilled callback to be called when x is
19720 * successfully fulfilled. If promiseOrValue is an immediate value, callback
19721 * will be invoked immediately.
19722 * @param {function?} onRejected callback to be called when x is
19724 * @param {function?} onProgress callback to be called when progress updates
19725 * are issued for x. @deprecated
19726 * @returns {Promise} a new promise that will fulfill with the return
19727 * value of callback or errback or the completion value of promiseOrValue if
19728 * callback and/or errback is not supplied.
19730 function when(x, onFulfilled, onRejected, onProgress) {
19731 var p = Promise.resolve(x);
19732 if (arguments.length < 2) {
19736 return p.then(onFulfilled, onRejected, onProgress);
19740 * Creates a new promise whose fate is determined by resolver.
19741 * @param {function} resolver function(resolve, reject, notify)
19742 * @returns {Promise} promise whose fate is determine by resolver
19744 function promise(resolver) {
19745 return new Promise(resolver);
19749 * Lift the supplied function, creating a version of f that returns
19750 * promises, and accepts promises as arguments.
19751 * @param {function} f
19752 * @returns {Function} version of f that returns promises
19755 return function() {
19756 for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
19757 a[i] = arguments[i];
19759 return apply(f, this, a);
19764 * Call f in a future turn, with the supplied args, and return a promise
19766 * @param {function} f
19767 * @returns {Promise}
19769 function attempt(f /*, args... */) {
19770 /*jshint validthis:true */
19771 for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
19772 a[i] = arguments[i+1];
19774 return apply(f, this, a);
19778 * Creates a {promise, resolver} pair, either or both of which
19779 * may be given out safely to consumers.
19780 * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
19783 return new Deferred();
19786 function Deferred() {
19787 var p = Promise._defer();
19789 function resolve(x) { p._handler.resolve(x); }
19790 function reject(x) { p._handler.reject(x); }
19791 function notify(x) { p._handler.notify(x); }
19794 this.resolve = resolve;
19795 this.reject = reject;
19796 this.notify = notify;
19797 this.resolver = { resolve: resolve, reject: reject, notify: notify };
19801 * Determines if x is promise-like, i.e. a thenable object
19802 * NOTE: Will return true for *any thenable object*, and isn't truly
19803 * safe, since it may attempt to access the `then` property of x (i.e.
19804 * clever/malicious getters may do weird things)
19805 * @param {*} x anything
19806 * @returns {boolean} true if x is promise-like
19808 function isPromiseLike(x) {
19809 return x && typeof x.then === 'function';
19813 * Return a promise that will resolve only once all the supplied arguments
19814 * have resolved. The resolution value of the returned promise will be an array
19815 * containing the resolution values of each of the arguments.
19816 * @param {...*} arguments may be a mix of promises and values
19817 * @returns {Promise}
19819 function join(/* ...promises */) {
19820 return Promise.all(arguments);
19824 * Return a promise that will fulfill once all input promises have
19825 * fulfilled, or reject when any one input promise rejects.
19826 * @param {array|Promise} promises array (or promise for an array) of promises
19827 * @returns {Promise}
19829 function all(promises) {
19830 return when(promises, Promise.all);
19834 * Return a promise that will always fulfill with an array containing
19835 * the outcome states of all input promises. The returned promise
19836 * will only reject if `promises` itself is a rejected promise.
19837 * @param {array|Promise} promises array (or promise for an array) of promises
19838 * @returns {Promise} promise for array of settled state descriptors
19840 function settle(promises) {
19841 return when(promises, Promise.settle);
19845 * Promise-aware array map function, similar to `Array.prototype.map()`,
19846 * but input array may contain promises or values.
19847 * @param {Array|Promise} promises array of anything, may contain promises and values
19848 * @param {function(x:*, index:Number):*} mapFunc map function which may
19849 * return a promise or value
19850 * @returns {Promise} promise that will fulfill with an array of mapped values
19851 * or reject if any input promise rejects.
19853 function map(promises, mapFunc) {
19854 return when(promises, function(promises) {
19855 return Promise.map(promises, mapFunc);
19860 * Filter the provided array of promises using the provided predicate. Input may
19861 * contain promises and values
19862 * @param {Array|Promise} promises array of promises and values
19863 * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
19864 * Must return truthy (or promise for truthy) for items to retain.
19865 * @returns {Promise} promise that will fulfill with an array containing all items
19866 * for which predicate returned truthy.
19868 function filter(promises, predicate) {
19869 return when(promises, function(promises) {
19870 return Promise.filter(promises, predicate);
19876 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
19878 },{"./lib/Promise":206,"./lib/TimeoutError":208,"./lib/apply":209,"./lib/decorators/array":210,"./lib/decorators/flow":211,"./lib/decorators/fold":212,"./lib/decorators/inspect":213,"./lib/decorators/iterate":214,"./lib/decorators/progress":215,"./lib/decorators/timed":216,"./lib/decorators/unhandledRejection":217,"./lib/decorators/with":218}],224:[function(require,module,exports){
19879 var nativeIsArray = Array.isArray
19880 var toString = Object.prototype.toString
19882 module.exports = nativeIsArray || isArray
19884 function isArray(obj) {
19885 return toString.call(obj) === "[object Array]"
19888 },{}],225:[function(require,module,exports){
19890 Object.defineProperty(exports, "__esModule", { value: true });
19891 var APIv3_1 = require("./api/APIv3");
19892 exports.APIv3 = APIv3_1.APIv3;
19893 var ModelCreator_1 = require("./api/ModelCreator");
19894 exports.ModelCreator = ModelCreator_1.ModelCreator;
19896 },{"./api/APIv3":237,"./api/ModelCreator":238}],226:[function(require,module,exports){
19898 Object.defineProperty(exports, "__esModule", { value: true });
19899 var Component_1 = require("./component/Component");
19900 exports.Component = Component_1.Component;
19901 var ComponentService_1 = require("./component/ComponentService");
19902 exports.ComponentService = ComponentService_1.ComponentService;
19903 var AttributionComponent_1 = require("./component/AttributionComponent");
19904 exports.AttributionComponent = AttributionComponent_1.AttributionComponent;
19905 var BackgroundComponent_1 = require("./component/BackgroundComponent");
19906 exports.BackgroundComponent = BackgroundComponent_1.BackgroundComponent;
19907 var BearingComponent_1 = require("./component/BearingComponent");
19908 exports.BearingComponent = BearingComponent_1.BearingComponent;
19909 var CacheComponent_1 = require("./component/CacheComponent");
19910 exports.CacheComponent = CacheComponent_1.CacheComponent;
19911 var CoverComponent_1 = require("./component/CoverComponent");
19912 exports.CoverComponent = CoverComponent_1.CoverComponent;
19913 var DebugComponent_1 = require("./component/DebugComponent");
19914 exports.DebugComponent = DebugComponent_1.DebugComponent;
19915 var DirectionComponent_1 = require("./component/direction/DirectionComponent");
19916 exports.DirectionComponent = DirectionComponent_1.DirectionComponent;
19917 var DirectionDOMCalculator_1 = require("./component/direction/DirectionDOMCalculator");
19918 exports.DirectionDOMCalculator = DirectionDOMCalculator_1.DirectionDOMCalculator;
19919 var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer");
19920 exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer;
19921 var ImageComponent_1 = require("./component/ImageComponent");
19922 exports.ImageComponent = ImageComponent_1.ImageComponent;
19923 var KeyboardComponent_1 = require("./component/KeyboardComponent");
19924 exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent;
19925 var LoadingComponent_1 = require("./component/LoadingComponent");
19926 exports.LoadingComponent = LoadingComponent_1.LoadingComponent;
19927 var Marker_1 = require("./component/marker/marker/Marker");
19928 exports.Marker = Marker_1.Marker;
19929 var MarkerComponent_1 = require("./component/marker/MarkerComponent");
19930 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
19931 var MarkerScene_1 = require("./component/marker/MarkerScene");
19932 exports.MarkerScene = MarkerScene_1.MarkerScene;
19933 var MarkerSet_1 = require("./component/marker/MarkerSet");
19934 exports.MarkerSet = MarkerSet_1.MarkerSet;
19935 var MouseComponent_1 = require("./component/mouse/MouseComponent");
19936 exports.MouseComponent = MouseComponent_1.MouseComponent;
19937 var MouseHandlerBase_1 = require("./component/mouse/MouseHandlerBase");
19938 exports.MouseHandlerBase = MouseHandlerBase_1.MouseHandlerBase;
19939 var DragPanHandler_1 = require("./component/mouse/DragPanHandler");
19940 exports.DragPanHandler = DragPanHandler_1.DragPanHandler;
19941 var DoubleClickZoomHandler_1 = require("./component/mouse/DoubleClickZoomHandler");
19942 exports.DoubleClickZoomHandler = DoubleClickZoomHandler_1.DoubleClickZoomHandler;
19943 var ScrollZoomHandler_1 = require("./component/mouse/ScrollZoomHandler");
19944 exports.ScrollZoomHandler = ScrollZoomHandler_1.ScrollZoomHandler;
19945 var TouchZoomHandler_1 = require("./component/mouse/TouchZoomHandler");
19946 exports.TouchZoomHandler = TouchZoomHandler_1.TouchZoomHandler;
19947 var Popup_1 = require("./component/popup/popup/Popup");
19948 exports.Popup = Popup_1.Popup;
19949 var PopupComponent_1 = require("./component/popup/PopupComponent");
19950 exports.PopupComponent = PopupComponent_1.PopupComponent;
19951 var NavigationComponent_1 = require("./component/NavigationComponent");
19952 exports.NavigationComponent = NavigationComponent_1.NavigationComponent;
19953 var RouteComponent_1 = require("./component/RouteComponent");
19954 exports.RouteComponent = RouteComponent_1.RouteComponent;
19955 var SequenceComponent_1 = require("./component/sequence/SequenceComponent");
19956 exports.SequenceComponent = SequenceComponent_1.SequenceComponent;
19957 var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer");
19958 exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer;
19959 var SequenceDOMInteraction_1 = require("./component/sequence/SequenceDOMInteraction");
19960 exports.SequenceDOMInteraction = SequenceDOMInteraction_1.SequenceDOMInteraction;
19961 var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent");
19962 exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent;
19963 var ImagePlaneFactory_1 = require("./component/imageplane/ImagePlaneFactory");
19964 exports.ImagePlaneFactory = ImagePlaneFactory_1.ImagePlaneFactory;
19965 var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer");
19966 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer;
19967 var ImagePlaneScene_1 = require("./component/imageplane/ImagePlaneScene");
19968 exports.ImagePlaneScene = ImagePlaneScene_1.ImagePlaneScene;
19969 var ImagePlaneShaders_1 = require("./component/imageplane/ImagePlaneShaders");
19970 exports.ImagePlaneShaders = ImagePlaneShaders_1.ImagePlaneShaders;
19971 var SimpleMarker_1 = require("./component/marker/marker/SimpleMarker");
19972 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
19973 var CircleMarker_1 = require("./component/marker/marker/CircleMarker");
19974 exports.CircleMarker = CircleMarker_1.CircleMarker;
19975 var SliderComponent_1 = require("./component/imageplane/SliderComponent");
19976 exports.SliderComponent = SliderComponent_1.SliderComponent;
19977 var StatsComponent_1 = require("./component/StatsComponent");
19978 exports.StatsComponent = StatsComponent_1.StatsComponent;
19979 var Tag_1 = require("./component/tag/tag/Tag");
19980 exports.Tag = Tag_1.Tag;
19981 var OutlineTag_1 = require("./component/tag/tag/OutlineTag");
19982 exports.OutlineTag = OutlineTag_1.OutlineTag;
19983 var RenderTag_1 = require("./component/tag/tag/RenderTag");
19984 exports.RenderTag = RenderTag_1.RenderTag;
19985 var OutlineRenderTag_1 = require("./component/tag/tag/OutlineRenderTag");
19986 exports.OutlineRenderTag = OutlineRenderTag_1.OutlineRenderTag;
19987 var OutlineCreateTag_1 = require("./component/tag/tag/OutlineCreateTag");
19988 exports.OutlineCreateTag = OutlineCreateTag_1.OutlineCreateTag;
19989 var SpotTag_1 = require("./component/tag/tag/SpotTag");
19990 exports.SpotTag = SpotTag_1.SpotTag;
19991 var SpotRenderTag_1 = require("./component/tag/tag/SpotRenderTag");
19992 exports.SpotRenderTag = SpotRenderTag_1.SpotRenderTag;
19993 var TagComponent_1 = require("./component/tag/TagComponent");
19994 exports.TagComponent = TagComponent_1.TagComponent;
19995 var TagCreator_1 = require("./component/tag/TagCreator");
19996 exports.TagCreator = TagCreator_1.TagCreator;
19997 var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer");
19998 exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer;
19999 var TagMode_1 = require("./component/tag/TagMode");
20000 exports.TagMode = TagMode_1.TagMode;
20001 var TagOperation_1 = require("./component/tag/TagOperation");
20002 exports.TagOperation = TagOperation_1.TagOperation;
20003 var TagScene_1 = require("./component/tag/TagScene");
20004 exports.TagScene = TagScene_1.TagScene;
20005 var TagSet_1 = require("./component/tag/TagSet");
20006 exports.TagSet = TagSet_1.TagSet;
20007 var Geometry_1 = require("./component/tag/geometry/Geometry");
20008 exports.Geometry = Geometry_1.Geometry;
20009 var VertexGeometry_1 = require("./component/tag/geometry/VertexGeometry");
20010 exports.VertexGeometry = VertexGeometry_1.VertexGeometry;
20011 var RectGeometry_1 = require("./component/tag/geometry/RectGeometry");
20012 exports.RectGeometry = RectGeometry_1.RectGeometry;
20013 var PointGeometry_1 = require("./component/tag/geometry/PointGeometry");
20014 exports.PointGeometry = PointGeometry_1.PointGeometry;
20015 var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry");
20016 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
20017 var GeometryTagError_1 = require("./component/tag/error/GeometryTagError");
20018 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
20020 },{"./component/AttributionComponent":239,"./component/BackgroundComponent":240,"./component/BearingComponent":241,"./component/CacheComponent":242,"./component/Component":243,"./component/ComponentService":244,"./component/CoverComponent":245,"./component/DebugComponent":246,"./component/ImageComponent":247,"./component/KeyboardComponent":248,"./component/LoadingComponent":249,"./component/NavigationComponent":250,"./component/RouteComponent":251,"./component/StatsComponent":252,"./component/direction/DirectionComponent":253,"./component/direction/DirectionDOMCalculator":254,"./component/direction/DirectionDOMRenderer":255,"./component/imageplane/ImagePlaneComponent":256,"./component/imageplane/ImagePlaneFactory":257,"./component/imageplane/ImagePlaneGLRenderer":258,"./component/imageplane/ImagePlaneScene":259,"./component/imageplane/ImagePlaneShaders":260,"./component/imageplane/SliderComponent":261,"./component/marker/MarkerComponent":263,"./component/marker/MarkerScene":264,"./component/marker/MarkerSet":265,"./component/marker/marker/CircleMarker":266,"./component/marker/marker/Marker":267,"./component/marker/marker/SimpleMarker":268,"./component/mouse/DoubleClickZoomHandler":269,"./component/mouse/DragPanHandler":270,"./component/mouse/MouseComponent":271,"./component/mouse/MouseHandlerBase":272,"./component/mouse/ScrollZoomHandler":273,"./component/mouse/TouchZoomHandler":274,"./component/popup/PopupComponent":276,"./component/popup/popup/Popup":277,"./component/sequence/SequenceComponent":278,"./component/sequence/SequenceDOMInteraction":279,"./component/sequence/SequenceDOMRenderer":280,"./component/tag/TagComponent":282,"./component/tag/TagCreator":283,"./component/tag/TagDOMRenderer":284,"./component/tag/TagMode":285,"./component/tag/TagOperation":286,"./component/tag/TagScene":287,"./component/tag/TagSet":288,"./component/tag/error/GeometryTagError":289,"./component/tag/geometry/Geometry":290,"./component/tag/geometry/PointGeometry":291,"./component/tag/geometry/PolygonGeometry":292,"./component/tag/geometry/RectGeometry":293,"./component/tag/geometry/VertexGeometry":294,"./component/tag/tag/OutlineCreateTag":295,"./component/tag/tag/OutlineRenderTag":296,"./component/tag/tag/OutlineTag":297,"./component/tag/tag/RenderTag":298,"./component/tag/tag/SpotRenderTag":299,"./component/tag/tag/SpotTag":300,"./component/tag/tag/Tag":301}],227:[function(require,module,exports){
20022 Object.defineProperty(exports, "__esModule", { value: true });
20023 var EdgeDirection_1 = require("./graph/edge/EdgeDirection");
20024 exports.EdgeDirection = EdgeDirection_1.EdgeDirection;
20025 var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings");
20026 exports.EdgeCalculatorSettings = EdgeCalculatorSettings_1.EdgeCalculatorSettings;
20027 var EdgeCalculatorDirections_1 = require("./graph/edge/EdgeCalculatorDirections");
20028 exports.EdgeCalculatorDirections = EdgeCalculatorDirections_1.EdgeCalculatorDirections;
20029 var EdgeCalculatorCoefficients_1 = require("./graph/edge/EdgeCalculatorCoefficients");
20030 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculatorCoefficients;
20031 var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator");
20032 exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator;
20034 },{"./graph/edge/EdgeCalculator":319,"./graph/edge/EdgeCalculatorCoefficients":320,"./graph/edge/EdgeCalculatorDirections":321,"./graph/edge/EdgeCalculatorSettings":322,"./graph/edge/EdgeDirection":323}],228:[function(require,module,exports){
20036 Object.defineProperty(exports, "__esModule", { value: true });
20037 var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError");
20038 exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError;
20039 var GraphMapillaryError_1 = require("./error/GraphMapillaryError");
20040 exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError;
20041 var MapillaryError_1 = require("./error/MapillaryError");
20042 exports.MapillaryError = MapillaryError_1.MapillaryError;
20044 },{"./error/ArgumentMapillaryError":302,"./error/GraphMapillaryError":303,"./error/MapillaryError":304}],229:[function(require,module,exports){
20046 Object.defineProperty(exports, "__esModule", { value: true });
20047 var Camera_1 = require("./geo/Camera");
20048 exports.Camera = Camera_1.Camera;
20049 var GeoCoords_1 = require("./geo/GeoCoords");
20050 exports.GeoCoords = GeoCoords_1.GeoCoords;
20051 var ViewportCoords_1 = require("./geo/ViewportCoords");
20052 exports.ViewportCoords = ViewportCoords_1.ViewportCoords;
20053 var Spatial_1 = require("./geo/Spatial");
20054 exports.Spatial = Spatial_1.Spatial;
20055 var Transform_1 = require("./geo/Transform");
20056 exports.Transform = Transform_1.Transform;
20058 },{"./geo/Camera":305,"./geo/GeoCoords":306,"./geo/Spatial":307,"./geo/Transform":308,"./geo/ViewportCoords":309}],230:[function(require,module,exports){
20060 Object.defineProperty(exports, "__esModule", { value: true });
20061 var FilterCreator_1 = require("./graph/FilterCreator");
20062 exports.FilterCreator = FilterCreator_1.FilterCreator;
20063 var Graph_1 = require("./graph/Graph");
20064 exports.Graph = Graph_1.Graph;
20065 var GraphCalculator_1 = require("./graph/GraphCalculator");
20066 exports.GraphCalculator = GraphCalculator_1.GraphCalculator;
20067 var GraphService_1 = require("./graph/GraphService");
20068 exports.GraphService = GraphService_1.GraphService;
20069 var ImageLoadingService_1 = require("./graph/ImageLoadingService");
20070 exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService;
20071 var MeshReader_1 = require("./graph/MeshReader");
20072 exports.MeshReader = MeshReader_1.MeshReader;
20073 var Node_1 = require("./graph/Node");
20074 exports.Node = Node_1.Node;
20075 var NodeCache_1 = require("./graph/NodeCache");
20076 exports.NodeCache = NodeCache_1.NodeCache;
20077 var Sequence_1 = require("./graph/Sequence");
20078 exports.Sequence = Sequence_1.Sequence;
20080 },{"./graph/FilterCreator":310,"./graph/Graph":311,"./graph/GraphCalculator":312,"./graph/GraphService":313,"./graph/ImageLoadingService":314,"./graph/MeshReader":315,"./graph/Node":316,"./graph/NodeCache":317,"./graph/Sequence":318}],231:[function(require,module,exports){
20083 * MapillaryJS is a WebGL JavaScript library for exploring street level imagery
20086 Object.defineProperty(exports, "__esModule", { value: true });
20087 var Edge_1 = require("./Edge");
20088 exports.EdgeDirection = Edge_1.EdgeDirection;
20089 var Render_1 = require("./Render");
20090 exports.RenderMode = Render_1.RenderMode;
20091 var Viewer_1 = require("./Viewer");
20092 exports.Alignment = Viewer_1.Alignment;
20093 exports.ImageSize = Viewer_1.ImageSize;
20094 exports.Viewer = Viewer_1.Viewer;
20095 var TagComponent = require("./component/tag/Tag");
20096 exports.TagComponent = TagComponent;
20097 var MarkerComponent = require("./component/marker/Marker");
20098 exports.MarkerComponent = MarkerComponent;
20099 var PopupComponent = require("./component/popup/Popup");
20100 exports.PopupComponent = PopupComponent;
20102 },{"./Edge":227,"./Render":232,"./Viewer":236,"./component/marker/Marker":262,"./component/popup/Popup":275,"./component/tag/Tag":281}],232:[function(require,module,exports){
20104 Object.defineProperty(exports, "__esModule", { value: true });
20105 var DOMRenderer_1 = require("./render/DOMRenderer");
20106 exports.DOMRenderer = DOMRenderer_1.DOMRenderer;
20107 var GLRenderer_1 = require("./render/GLRenderer");
20108 exports.GLRenderer = GLRenderer_1.GLRenderer;
20109 var GLRenderStage_1 = require("./render/GLRenderStage");
20110 exports.GLRenderStage = GLRenderStage_1.GLRenderStage;
20111 var RenderCamera_1 = require("./render/RenderCamera");
20112 exports.RenderCamera = RenderCamera_1.RenderCamera;
20113 var RenderMode_1 = require("./render/RenderMode");
20114 exports.RenderMode = RenderMode_1.RenderMode;
20115 var RenderService_1 = require("./render/RenderService");
20116 exports.RenderService = RenderService_1.RenderService;
20118 },{"./render/DOMRenderer":324,"./render/GLRenderStage":325,"./render/GLRenderer":326,"./render/RenderCamera":327,"./render/RenderMode":328,"./render/RenderService":329}],233:[function(require,module,exports){
20120 Object.defineProperty(exports, "__esModule", { value: true });
20121 var State_1 = require("./state/State");
20122 exports.State = State_1.State;
20123 var StateBase_1 = require("./state/states/StateBase");
20124 exports.StateBase = StateBase_1.StateBase;
20125 var StateContext_1 = require("./state/StateContext");
20126 exports.StateContext = StateContext_1.StateContext;
20127 var StateService_1 = require("./state/StateService");
20128 exports.StateService = StateService_1.StateService;
20129 var TraversingState_1 = require("./state/states/TraversingState");
20130 exports.TraversingState = TraversingState_1.TraversingState;
20131 var WaitingState_1 = require("./state/states/WaitingState");
20132 exports.WaitingState = WaitingState_1.WaitingState;
20134 },{"./state/State":330,"./state/StateContext":331,"./state/StateService":332,"./state/states/StateBase":333,"./state/states/TraversingState":334,"./state/states/WaitingState":335}],234:[function(require,module,exports){
20136 Object.defineProperty(exports, "__esModule", { value: true });
20137 var ImageTileLoader_1 = require("./tiles/ImageTileLoader");
20138 exports.ImageTileLoader = ImageTileLoader_1.ImageTileLoader;
20139 var ImageTileStore_1 = require("./tiles/ImageTileStore");
20140 exports.ImageTileStore = ImageTileStore_1.ImageTileStore;
20141 var TextureProvider_1 = require("./tiles/TextureProvider");
20142 exports.TextureProvider = TextureProvider_1.TextureProvider;
20143 var RegionOfInterestCalculator_1 = require("./tiles/RegionOfInterestCalculator");
20144 exports.RegionOfInterestCalculator = RegionOfInterestCalculator_1.RegionOfInterestCalculator;
20146 },{"./tiles/ImageTileLoader":336,"./tiles/ImageTileStore":337,"./tiles/RegionOfInterestCalculator":338,"./tiles/TextureProvider":339}],235:[function(require,module,exports){
20148 Object.defineProperty(exports, "__esModule", { value: true });
20149 var EventEmitter_1 = require("./utils/EventEmitter");
20150 exports.EventEmitter = EventEmitter_1.EventEmitter;
20151 var Settings_1 = require("./utils/Settings");
20152 exports.Settings = Settings_1.Settings;
20153 var Urls_1 = require("./utils/Urls");
20154 exports.Urls = Urls_1.Urls;
20156 },{"./utils/EventEmitter":340,"./utils/Settings":341,"./utils/Urls":342}],236:[function(require,module,exports){
20158 Object.defineProperty(exports, "__esModule", { value: true });
20159 var Alignment_1 = require("./viewer/Alignment");
20160 exports.Alignment = Alignment_1.Alignment;
20161 var CacheService_1 = require("./viewer/CacheService");
20162 exports.CacheService = CacheService_1.CacheService;
20163 var ComponentController_1 = require("./viewer/ComponentController");
20164 exports.ComponentController = ComponentController_1.ComponentController;
20165 var Container_1 = require("./viewer/Container");
20166 exports.Container = Container_1.Container;
20167 var Observer_1 = require("./viewer/Observer");
20168 exports.Observer = Observer_1.Observer;
20169 var ImageSize_1 = require("./viewer/ImageSize");
20170 exports.ImageSize = ImageSize_1.ImageSize;
20171 var LoadingService_1 = require("./viewer/LoadingService");
20172 exports.LoadingService = LoadingService_1.LoadingService;
20173 var MouseService_1 = require("./viewer/MouseService");
20174 exports.MouseService = MouseService_1.MouseService;
20175 var Navigator_1 = require("./viewer/Navigator");
20176 exports.Navigator = Navigator_1.Navigator;
20177 var Projection_1 = require("./viewer/Projection");
20178 exports.Projection = Projection_1.Projection;
20179 var SpriteService_1 = require("./viewer/SpriteService");
20180 exports.SpriteService = SpriteService_1.SpriteService;
20181 var TouchService_1 = require("./viewer/TouchService");
20182 exports.TouchService = TouchService_1.TouchService;
20183 var Viewer_1 = require("./viewer/Viewer");
20184 exports.Viewer = Viewer_1.Viewer;
20186 },{"./viewer/Alignment":343,"./viewer/CacheService":344,"./viewer/ComponentController":345,"./viewer/Container":346,"./viewer/ImageSize":347,"./viewer/LoadingService":348,"./viewer/MouseService":349,"./viewer/Navigator":350,"./viewer/Observer":351,"./viewer/Projection":352,"./viewer/SpriteService":353,"./viewer/TouchService":354,"./viewer/Viewer":355}],237:[function(require,module,exports){
20188 /// <reference path="../../typings/index.d.ts" />
20189 Object.defineProperty(exports, "__esModule", { value: true });
20190 var Observable_1 = require("rxjs/Observable");
20191 require("rxjs/add/observable/defer");
20192 require("rxjs/add/observable/fromPromise");
20193 require("rxjs/add/operator/catch");
20194 require("rxjs/add/operator/map");
20195 var API_1 = require("../API");
20199 * @classdesc Provides methods for access of API v3.
20201 var APIv3 = (function () {
20203 * Create a new api v3 instance.
20205 * @param {number} clientId - Client id for API requests.
20206 * @param {number} [token] - Optional bearer token for API requests of
20207 * protected resources.
20208 * @param {ModelCreator} [creator] - Optional model creator instance.
20210 function APIv3(clientId, token, creator) {
20211 this._clientId = clientId;
20212 this._modelCreator = creator != null ? creator : new API_1.ModelCreator();
20213 this._model = this._modelCreator.createModel(clientId, token);
20214 this._pageCount = 999;
20215 this._pathImageByKey = "imageByKey";
20216 this._pathImageCloseTo = "imageCloseTo";
20217 this._pathImagesByH = "imagesByH";
20218 this._pathImageViewAdd = "imageViewAdd";
20219 this._pathSequenceByKey = "sequenceByKey";
20220 this._pathSequenceViewAdd = "sequenceViewAdd";
20221 this._propertiesCore = [
20226 this._propertiesFill = [
20231 this._propertiesKey = [
20234 this._propertiesSequence = [
20237 this._propertiesSpatial = [
20251 this._propertiesUser = [
20255 APIv3.prototype.imageByKeyFill$ = function (keys) {
20256 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20257 this._pathImageByKey,
20259 this._propertiesKey
20260 .concat(this._propertiesFill)
20261 .concat(this._propertiesSpatial),
20262 this._propertiesKey
20263 .concat(this._propertiesUser)
20265 .map(function (value) {
20267 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
20269 return value.json.imageByKey;
20270 }), this._pathImageByKey, keys);
20272 APIv3.prototype.imageByKeyFull$ = function (keys) {
20273 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20274 this._pathImageByKey,
20276 this._propertiesKey
20277 .concat(this._propertiesCore)
20278 .concat(this._propertiesFill)
20279 .concat(this._propertiesSpatial),
20280 this._propertiesKey
20281 .concat(this._propertiesUser)
20283 .map(function (value) {
20285 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
20287 return value.json.imageByKey;
20288 }), this._pathImageByKey, keys);
20290 APIv3.prototype.imageCloseTo$ = function (lat, lon) {
20291 var lonLat = lon + ":" + lat;
20292 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20293 this._pathImageCloseTo,
20295 this._propertiesKey
20296 .concat(this._propertiesCore)
20297 .concat(this._propertiesFill)
20298 .concat(this._propertiesSpatial),
20299 this._propertiesKey
20300 .concat(this._propertiesUser)
20302 .map(function (value) {
20303 return value != null ? value.json.imageCloseTo[lonLat] : null;
20304 }), this._pathImageCloseTo, [lonLat]);
20306 APIv3.prototype.imagesByH$ = function (hs) {
20308 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20309 this._pathImagesByH,
20311 { from: 0, to: this._pageCount },
20312 this._propertiesKey
20313 .concat(this._propertiesCore),
20314 this._propertiesKey
20316 .map(function (value) {
20317 if (value == null) {
20318 value = { json: { imagesByH: {} } };
20319 for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) {
20321 value.json.imagesByH[h] = {};
20322 for (var i = 0; i <= _this._pageCount; i++) {
20323 value.json.imagesByH[h][i] = null;
20327 return value.json.imagesByH;
20328 }), this._pathImagesByH, hs);
20330 APIv3.prototype.imageViewAdd$ = function (keys) {
20331 return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys);
20333 APIv3.prototype.invalidateImageByKey = function (keys) {
20334 this._invalidateGet(this._pathImageByKey, keys);
20336 APIv3.prototype.invalidateImagesByH = function (hs) {
20337 this._invalidateGet(this._pathImagesByH, hs);
20339 APIv3.prototype.invalidateSequenceByKey = function (sKeys) {
20340 this._invalidateGet(this._pathSequenceByKey, sKeys);
20342 APIv3.prototype.setToken = function (token) {
20343 this._model.invalidate([]);
20344 this._model = null;
20345 this._model = this._modelCreator.createModel(this._clientId, token);
20347 APIv3.prototype.sequenceByKey$ = function (sequenceKeys) {
20348 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20349 this._pathSequenceByKey,
20351 this._propertiesKey
20352 .concat(this._propertiesSequence)
20354 .map(function (value) {
20355 return value.json.sequenceByKey;
20356 }), this._pathSequenceByKey, sequenceKeys);
20358 APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) {
20359 return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys);
20361 Object.defineProperty(APIv3.prototype, "clientId", {
20363 return this._clientId;
20368 APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) {
20371 .catch(function (error) {
20372 _this._invalidateGet(path, paths);
20376 APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) {
20379 .catch(function (error) {
20380 _this._invalidateCall(path, paths);
20384 APIv3.prototype._invalidateGet = function (path, paths) {
20385 this._model.invalidate([path, paths]);
20387 APIv3.prototype._invalidateCall = function (path, paths) {
20388 this._model.invalidate([path], [paths]);
20390 APIv3.prototype._wrapPromise$ = function (promise) {
20391 return Observable_1.Observable.defer(function () { return Observable_1.Observable.fromPromise(promise); });
20395 exports.APIv3 = APIv3;
20396 exports.default = APIv3;
20398 },{"../API":225,"rxjs/Observable":29,"rxjs/add/observable/defer":39,"rxjs/add/observable/fromPromise":43,"rxjs/add/operator/catch":52,"rxjs/add/operator/map":65}],238:[function(require,module,exports){
20400 /// <reference path="../../typings/index.d.ts" />
20401 Object.defineProperty(exports, "__esModule", { value: true });
20402 var falcor = require("falcor");
20403 var HttpDataSource = require("falcor-http-datasource");
20404 var Utils_1 = require("../Utils");
20406 * @class ModelCreator
20408 * @classdesc Creates API models.
20410 var ModelCreator = (function () {
20411 function ModelCreator() {
20414 * Creates a Falcor model.
20416 * @description Max cache size will be set to 16 MB. Authorization
20417 * header will be added if bearer token is supplied.
20419 * @param {number} clientId - Client id for API requests.
20420 * @param {number} [token] - Optional bearer token for API requests of
20421 * protected resources.
20422 * @returns {falcor.Model} Falcor model for HTTP requests.
20424 ModelCreator.prototype.createModel = function (clientId, token) {
20425 var configuration = {
20427 withCredentials: false,
20429 if (token != null) {
20430 configuration.headers = { "Authorization": "Bearer " + token };
20432 return new falcor.Model({
20433 maxSize: 16 * 1024 * 1024,
20434 source: new HttpDataSource(Utils_1.Urls.falcorModel(clientId), configuration),
20437 return ModelCreator;
20439 exports.ModelCreator = ModelCreator;
20440 exports.default = ModelCreator;
20442 },{"../Utils":235,"falcor":15,"falcor-http-datasource":10}],239:[function(require,module,exports){
20444 /// <reference path="../../typings/index.d.ts" />
20445 var __extends = (this && this.__extends) || (function () {
20446 var extendStatics = Object.setPrototypeOf ||
20447 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20448 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20449 return function (d, b) {
20450 extendStatics(d, b);
20451 function __() { this.constructor = d; }
20452 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20455 Object.defineProperty(exports, "__esModule", { value: true });
20456 var vd = require("virtual-dom");
20457 var Component_1 = require("../Component");
20458 var AttributionComponent = (function (_super) {
20459 __extends(AttributionComponent, _super);
20460 function AttributionComponent(name, container, navigator) {
20461 return _super.call(this, name, container, navigator) || this;
20463 AttributionComponent.prototype._activate = function () {
20465 this._disposable = this._navigator.stateService.currentNode$
20466 .map(function (node) {
20467 return { name: _this._name, vnode: _this._getAttributionNode(node.username, node.key) };
20469 .subscribe(this._container.domRenderer.render$);
20471 AttributionComponent.prototype._deactivate = function () {
20472 this._disposable.unsubscribe();
20474 AttributionComponent.prototype._getDefaultConfiguration = function () {
20477 AttributionComponent.prototype._getAttributionNode = function (username, photoId) {
20478 return vd.h("div.Attribution", {}, [
20479 vd.h("a", { href: "https://www.mapillary.com/app/user/" + username,
20481 textContent: "@" + username,
20483 vd.h("span", { textContent: "|" }, []),
20484 vd.h("a", { href: "https://www.mapillary.com/app/?pKey=" + photoId + "&focus=photo",
20486 textContent: "mapillary.com",
20490 return AttributionComponent;
20491 }(Component_1.Component));
20492 AttributionComponent.componentName = "attribution";
20493 exports.AttributionComponent = AttributionComponent;
20494 Component_1.ComponentService.register(AttributionComponent);
20495 exports.default = AttributionComponent;
20497 },{"../Component":226,"virtual-dom":182}],240:[function(require,module,exports){
20499 /// <reference path="../../typings/index.d.ts" />
20500 var __extends = (this && this.__extends) || (function () {
20501 var extendStatics = Object.setPrototypeOf ||
20502 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20503 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20504 return function (d, b) {
20505 extendStatics(d, b);
20506 function __() { this.constructor = d; }
20507 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20510 Object.defineProperty(exports, "__esModule", { value: true });
20511 var vd = require("virtual-dom");
20512 var Component_1 = require("../Component");
20513 var BackgroundComponent = (function (_super) {
20514 __extends(BackgroundComponent, _super);
20515 function BackgroundComponent(name, container, navigator) {
20516 return _super.call(this, name, container, navigator) || this;
20518 BackgroundComponent.prototype._activate = function () {
20519 this._container.domRenderer.render$
20520 .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given photo.") });
20522 BackgroundComponent.prototype._deactivate = function () {
20525 BackgroundComponent.prototype._getDefaultConfiguration = function () {
20528 BackgroundComponent.prototype._getBackgroundNode = function (notice) {
20529 // todo: add condition for when to display the DOM node
20530 return vd.h("div.BackgroundWrapper", {}, [
20531 vd.h("p", { textContent: notice }, []),
20534 return BackgroundComponent;
20535 }(Component_1.Component));
20536 BackgroundComponent.componentName = "background";
20537 exports.BackgroundComponent = BackgroundComponent;
20538 Component_1.ComponentService.register(BackgroundComponent);
20539 exports.default = BackgroundComponent;
20541 },{"../Component":226,"virtual-dom":182}],241:[function(require,module,exports){
20543 /// <reference path="../../typings/index.d.ts" />
20544 var __extends = (this && this.__extends) || (function () {
20545 var extendStatics = Object.setPrototypeOf ||
20546 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20547 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20548 return function (d, b) {
20549 extendStatics(d, b);
20550 function __() { this.constructor = d; }
20551 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20554 Object.defineProperty(exports, "__esModule", { value: true });
20555 var vd = require("virtual-dom");
20556 var Observable_1 = require("rxjs/Observable");
20557 var Component_1 = require("../Component");
20558 var Geo_1 = require("../Geo");
20559 var BearingComponent = (function (_super) {
20560 __extends(BearingComponent, _super);
20561 function BearingComponent(name, container, navigator) {
20562 var _this = _super.call(this, name, container, navigator) || this;
20563 _this._spatial = new Geo_1.Spatial();
20564 _this._svgNamespace = "http://www.w3.org/2000/svg";
20565 _this._distinctThreshold = Math.PI / 90;
20568 BearingComponent.prototype._activate = function () {
20570 var nodeBearingFov$ = this._navigator.stateService.currentState$
20571 .distinctUntilChanged(undefined, function (frame) {
20572 return frame.state.currentNode.key;
20574 .map(function (frame) {
20575 var node = frame.state.currentNode;
20576 var transform = frame.state.currentTransform;
20578 var hFov_1 = 2 * Math.PI * node.gpano.CroppedAreaImageWidthPixels / node.gpano.FullPanoWidthPixels;
20579 return [_this._spatial.degToRad(node.ca), hFov_1];
20581 var size = Math.max(transform.basicWidth, transform.basicHeight);
20583 console.warn("Original image size (" + transform.basicWidth + ", " + transform.basicHeight + ") is invalid (" + node.key + ". " +
20584 "Not showing available fov.");
20586 var hFov = size > 0 ?
20587 2 * Math.atan(0.5 * transform.basicWidth / (size * transform.focal)) :
20589 return [_this._spatial.degToRad(node.ca), hFov];
20591 .distinctUntilChanged(function (a1, a2) {
20592 return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
20593 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
20595 var cameraBearingFov$ = this._container.renderService.renderCamera$
20596 .map(function (rc) {
20597 var vFov = _this._spatial.degToRad(rc.perspective.fov);
20598 var hFov = rc.perspective.aspect === Number.POSITIVE_INFINITY ?
20600 Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2;
20601 return [_this._spatial.azimuthalToBearing(rc.rotation.phi), hFov];
20603 .distinctUntilChanged(function (a1, a2) {
20604 return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
20605 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
20607 this._renderSubscription = Observable_1.Observable
20608 .combineLatest(nodeBearingFov$, cameraBearingFov$)
20609 .map(function (args) {
20610 var background = vd.h("div.BearingIndicatorBackground", { oncontextmenu: function (event) { event.preventDefault(); } }, [
20611 vd.h("div.BearingIndicatorBackgroundRectangle", {}, []),
20612 vd.h("div.BearingIndicatorBackgroundCircle", {}, []),
20614 var north = vd.h("div.BearingIndicatorNorth", {}, []);
20615 var nodeSector = _this._createCircleSector(args[0][0], args[0][1], "#000");
20616 var cameraSector = _this._createCircleSector(args[1][0], args[1][1], "#fff");
20617 var compass = _this._createCircleSectorCompass(nodeSector, cameraSector);
20620 vnode: vd.h("div.BearingIndicator", {}, [
20627 .subscribe(this._container.domRenderer.render$);
20629 BearingComponent.prototype._deactivate = function () {
20630 this._renderSubscription.unsubscribe();
20632 BearingComponent.prototype._getDefaultConfiguration = function () {
20635 BearingComponent.prototype._createCircleSectorCompass = function (nodeSector, cameraSector) {
20636 var group = vd.h("g", {
20637 attributes: { transform: "translate(1,1)" },
20638 namespace: this._svgNamespace,
20639 }, [nodeSector, cameraSector]);
20640 var centerCircle = vd.h("circle", {
20647 "stroke-width": "0.0833333",
20649 namespace: this._svgNamespace,
20651 var svg = vd.h("svg", {
20652 attributes: { viewBox: "0 0 2 2" },
20653 namespace: this._svgNamespace,
20658 position: "absolute",
20661 }, [group, centerCircle]);
20664 BearingComponent.prototype._createCircleSector = function (bearing, fov, fill) {
20665 if (fov > 2 * Math.PI - Math.PI / 90) {
20666 return vd.h("circle", {
20667 attributes: { cx: "0", cy: "0", fill: fill, r: "1" },
20668 namespace: this._svgNamespace,
20671 var arcStart = bearing - fov / 2 - Math.PI / 2;
20672 var arcEnd = arcStart + fov;
20673 var startX = Math.cos(arcStart);
20674 var startY = Math.sin(arcStart);
20675 var endX = Math.cos(arcEnd);
20676 var endY = Math.sin(arcEnd);
20677 var largeArc = fov >= Math.PI ? 1 : 0;
20678 var description = "M 0 0 " + startX + " " + startY + " A 1 1 0 " + largeArc + " 1 " + endX + " " + endY;
20679 return vd.h("path", {
20680 attributes: { d: description, fill: fill },
20681 namespace: this._svgNamespace,
20684 return BearingComponent;
20685 }(Component_1.Component));
20686 BearingComponent.componentName = "bearing";
20687 exports.BearingComponent = BearingComponent;
20688 Component_1.ComponentService.register(BearingComponent);
20689 exports.default = BearingComponent;
20691 },{"../Component":226,"../Geo":229,"rxjs/Observable":29,"virtual-dom":182}],242:[function(require,module,exports){
20693 var __extends = (this && this.__extends) || (function () {
20694 var extendStatics = Object.setPrototypeOf ||
20695 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20696 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20697 return function (d, b) {
20698 extendStatics(d, b);
20699 function __() { this.constructor = d; }
20700 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20703 Object.defineProperty(exports, "__esModule", { value: true });
20704 var Observable_1 = require("rxjs/Observable");
20705 require("rxjs/add/observable/combineLatest");
20706 require("rxjs/add/observable/from");
20707 require("rxjs/add/observable/merge");
20708 require("rxjs/add/observable/of");
20709 require("rxjs/add/observable/zip");
20710 require("rxjs/add/operator/catch");
20711 require("rxjs/add/operator/combineLatest");
20712 require("rxjs/add/operator/distinct");
20713 require("rxjs/add/operator/expand");
20714 require("rxjs/add/operator/filter");
20715 require("rxjs/add/operator/map");
20716 require("rxjs/add/operator/merge");
20717 require("rxjs/add/operator/mergeMap");
20718 require("rxjs/add/operator/mergeAll");
20719 require("rxjs/add/operator/skip");
20720 require("rxjs/add/operator/switchMap");
20721 var Edge_1 = require("../Edge");
20722 var Component_1 = require("../Component");
20723 var CacheComponent = (function (_super) {
20724 __extends(CacheComponent, _super);
20725 function CacheComponent(name, container, navigator) {
20726 return _super.call(this, name, container, navigator) || this;
20729 * Set the cache depth.
20731 * Configures the cache depth. The cache depth can be different for
20732 * different edge direction types.
20734 * @param {ICacheDepth} depth - Cache depth structure.
20736 CacheComponent.prototype.setDepth = function (depth) {
20737 this.configure({ depth: depth });
20739 CacheComponent.prototype._activate = function () {
20741 this._sequenceSubscription = Observable_1.Observable
20742 .combineLatest(this._navigator.stateService.currentNode$
20743 .switchMap(function (node) {
20744 return node.sequenceEdges$;
20746 .filter(function (status) {
20747 return status.cached;
20748 }), this._configuration$)
20749 .switchMap(function (nc) {
20750 var status = nc[0];
20751 var configuration = nc[1];
20752 var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence));
20753 var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth);
20754 var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth);
20755 return Observable_1.Observable
20756 .merge(next$, prev$)
20757 .catch(function (error, caught) {
20758 console.error("Failed to cache sequence edges.", error);
20759 return Observable_1.Observable.empty();
20762 .subscribe(function () { });
20763 this._spatialSubscription = this._navigator.stateService.currentNode$
20764 .switchMap(function (node) {
20765 return Observable_1.Observable
20766 .combineLatest(Observable_1.Observable.of(node), node.spatialEdges$
20767 .filter(function (status) {
20768 return status.cached;
20771 .combineLatest(this._configuration$, function (ns, configuration) {
20772 return [ns[0], ns[1], configuration];
20774 .switchMap(function (args) {
20775 var node = args[0];
20776 var edges = args[1].edges;
20777 var depth = args[2].depth;
20778 var panoDepth = Math.max(0, Math.min(2, depth.pano));
20779 var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step));
20780 var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn));
20781 var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth);
20782 var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth);
20783 var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth);
20784 var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth);
20785 var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth);
20786 var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth);
20787 var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth);
20788 var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth);
20789 return Observable_1.Observable
20790 .merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$)
20791 .catch(function (error, caught) {
20792 console.error("Failed to cache spatial edges.", error);
20793 return Observable_1.Observable.empty();
20796 .subscribe(function () { });
20798 CacheComponent.prototype._deactivate = function () {
20799 this._sequenceSubscription.unsubscribe();
20800 this._spatialSubscription.unsubscribe();
20802 CacheComponent.prototype._getDefaultConfiguration = function () {
20803 return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } };
20805 CacheComponent.prototype._cache$ = function (edges, direction, depth) {
20807 return Observable_1.Observable
20808 .zip(Observable_1.Observable.of(edges), Observable_1.Observable.of(depth))
20809 .expand(function (ed) {
20812 var edgesDepths$ = [];
20814 for (var _i = 0, es_1 = es; _i < es_1.length; _i++) {
20815 var edge = es_1[_i];
20816 if (edge.data.direction === direction) {
20817 edgesDepths$.push(Observable_1.Observable
20818 .zip(_this._navigator.graphService.cacheNode$(edge.to)
20819 .mergeMap(function (n) {
20820 return _this._nodeToEdges$(n, direction);
20821 }), Observable_1.Observable.of(d - 1)));
20825 return Observable_1.Observable
20826 .from(edgesDepths$)
20831 CacheComponent.prototype._nodeToEdges$ = function (node, direction) {
20832 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
20833 node.sequenceEdges$ :
20834 node.spatialEdges$)
20835 .first(function (status) {
20836 return status.cached;
20838 .map(function (status) {
20839 return status.edges;
20842 return CacheComponent;
20843 }(Component_1.Component));
20844 CacheComponent.componentName = "cache";
20845 exports.CacheComponent = CacheComponent;
20846 Component_1.ComponentService.register(CacheComponent);
20847 exports.default = CacheComponent;
20849 },{"../Component":226,"../Edge":227,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/from":41,"rxjs/add/observable/merge":44,"rxjs/add/observable/of":45,"rxjs/add/observable/zip":48,"rxjs/add/operator/catch":52,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/distinct":57,"rxjs/add/operator/expand":60,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeAll":67,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/skip":75,"rxjs/add/operator/switchMap":79}],243:[function(require,module,exports){
20851 var __extends = (this && this.__extends) || (function () {
20852 var extendStatics = Object.setPrototypeOf ||
20853 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20854 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20855 return function (d, b) {
20856 extendStatics(d, b);
20857 function __() { this.constructor = d; }
20858 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20861 Object.defineProperty(exports, "__esModule", { value: true });
20862 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
20863 var Subject_1 = require("rxjs/Subject");
20864 require("rxjs/add/operator/publishReplay");
20865 require("rxjs/add/operator/scan");
20866 require("rxjs/add/operator/startWith");
20867 var Utils_1 = require("../Utils");
20868 var Component = (function (_super) {
20869 __extends(Component, _super);
20870 function Component(name, container, navigator) {
20871 var _this = _super.call(this) || this;
20872 _this._activated$ = new BehaviorSubject_1.BehaviorSubject(false);
20873 _this._configurationSubject$ = new Subject_1.Subject();
20874 _this._activated = false;
20875 _this._container = container;
20876 _this._name = name;
20877 _this._navigator = navigator;
20878 _this._configuration$ =
20879 _this._configurationSubject$
20880 .startWith(_this.defaultConfiguration)
20881 .scan(function (conf, newConf) {
20882 for (var key in newConf) {
20883 if (newConf.hasOwnProperty(key)) {
20884 conf[key] = newConf[key];
20891 _this._configuration$.subscribe(function () { });
20894 Object.defineProperty(Component.prototype, "activated", {
20896 return this._activated;
20901 Object.defineProperty(Component.prototype, "activated$", {
20903 return this._activated$;
20908 Object.defineProperty(Component.prototype, "defaultConfiguration", {
20910 * Get default configuration.
20912 * @returns {TConfiguration} Default configuration for component.
20915 return this._getDefaultConfiguration();
20920 Object.defineProperty(Component.prototype, "configuration$", {
20922 return this._configuration$;
20927 Object.defineProperty(Component.prototype, "name", {
20934 Component.prototype.activate = function (conf) {
20935 if (this._activated) {
20938 if (conf !== undefined) {
20939 this._configurationSubject$.next(conf);
20941 this._activated = true;
20943 this._activated$.next(true);
20945 Component.prototype.configure = function (conf) {
20946 this._configurationSubject$.next(conf);
20948 Component.prototype.deactivate = function () {
20949 if (!this._activated) {
20952 this._activated = false;
20953 this._deactivate();
20954 this._container.domRenderer.clear(this._name);
20955 this._container.glRenderer.clear(this._name);
20956 this._activated$.next(false);
20959 * Detect the viewer's new width and height and resize the component's
20960 * rendered elements accordingly if applicable.
20962 Component.prototype.resize = function () { return; };
20964 }(Utils_1.EventEmitter));
20966 * Component name. Used when interacting with component through the Viewer's API.
20968 Component.componentName = "not_worthy";
20969 exports.Component = Component;
20970 exports.default = Component;
20972 },{"../Utils":235,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73,"rxjs/add/operator/startWith":78}],244:[function(require,module,exports){
20974 /// <reference path="../../typings/index.d.ts" />
20975 Object.defineProperty(exports, "__esModule", { value: true });
20976 var _ = require("underscore");
20977 var Error_1 = require("../Error");
20978 var ComponentService = (function () {
20979 function ComponentService(container, navigator) {
20980 this._components = {};
20981 this._container = container;
20982 this._navigator = navigator;
20983 for (var _i = 0, _a = _.values(ComponentService.registeredComponents); _i < _a.length; _i++) {
20984 var component = _a[_i];
20985 this._components[component.componentName] = {
20987 component: new component(component.componentName, container, navigator),
20990 this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator);
20991 this._coverComponent.activate();
20992 this._coverActivated = true;
20994 ComponentService.register = function (component) {
20995 if (ComponentService.registeredComponents[component.componentName] === undefined) {
20996 ComponentService.registeredComponents[component.componentName] = component;
20999 ComponentService.registerCover = function (coverComponent) {
21000 ComponentService.registeredCoverComponent = coverComponent;
21002 ComponentService.prototype.activateCover = function () {
21003 if (this._coverActivated) {
21006 this._coverActivated = true;
21007 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
21008 var component = _a[_i];
21009 if (component.active) {
21010 component.component.deactivate();
21015 ComponentService.prototype.deactivateCover = function () {
21016 if (!this._coverActivated) {
21019 this._coverActivated = false;
21020 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
21021 var component = _a[_i];
21022 if (component.active) {
21023 component.component.activate();
21028 ComponentService.prototype.activate = function (name) {
21029 this._checkName(name);
21030 this._components[name].active = true;
21031 if (!this._coverActivated) {
21032 this.get(name).activate();
21035 ComponentService.prototype.configure = function (name, conf) {
21036 this._checkName(name);
21037 this.get(name).configure(conf);
21039 ComponentService.prototype.deactivate = function (name) {
21040 this._checkName(name);
21041 this._components[name].active = false;
21042 if (!this._coverActivated) {
21043 this.get(name).deactivate();
21046 ComponentService.prototype.resize = function () {
21047 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
21048 var component = _a[_i];
21049 component.component.resize();
21052 ComponentService.prototype.get = function (name) {
21053 return this._components[name].component;
21055 ComponentService.prototype.getCover = function () {
21056 return this._coverComponent;
21058 ComponentService.prototype._checkName = function (name) {
21059 if (!(name in this._components)) {
21060 throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name);
21063 return ComponentService;
21065 ComponentService.registeredComponents = {};
21066 exports.ComponentService = ComponentService;
21067 exports.default = ComponentService;
21069 },{"../Error":228,"underscore":178}],245:[function(require,module,exports){
21071 /// <reference path="../../typings/index.d.ts" />
21072 var __extends = (this && this.__extends) || (function () {
21073 var extendStatics = Object.setPrototypeOf ||
21074 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21075 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21076 return function (d, b) {
21077 extendStatics(d, b);
21078 function __() { this.constructor = d; }
21079 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21082 Object.defineProperty(exports, "__esModule", { value: true });
21083 var vd = require("virtual-dom");
21084 require("rxjs/add/operator/filter");
21085 require("rxjs/add/operator/map");
21086 require("rxjs/add/operator/withLatestFrom");
21087 var Component_1 = require("../Component");
21088 var CoverComponent = (function (_super) {
21089 __extends(CoverComponent, _super);
21090 function CoverComponent(name, container, navigator) {
21091 return _super.call(this, name, container, navigator) || this;
21093 CoverComponent.prototype._activate = function () {
21095 this._keyDisposable = this._navigator.stateService.currentNode$
21096 .withLatestFrom(this._configuration$, function (node, configuration) {
21097 return [node, configuration];
21099 .filter(function (nc) {
21100 return nc[0].key !== nc[1].key;
21102 .map(function (nc) { return nc[0]; })
21103 .map(function (node) {
21104 return { key: node.key, src: node.image.src };
21106 .subscribe(this._configurationSubject$);
21107 this._disposable = this._configuration$
21108 .map(function (conf) {
21110 return { name: _this._name, vnode: vd.h("div", []) };
21112 if (!conf.visible) {
21113 return { name: _this._name, vnode: vd.h("div.Cover.CoverDone", [_this._getCoverBackgroundVNode(conf)]) };
21115 return { name: _this._name, vnode: _this._getCoverButtonVNode(conf) };
21117 .subscribe(this._container.domRenderer.render$);
21119 CoverComponent.prototype._deactivate = function () {
21120 this._disposable.unsubscribe();
21121 this._keyDisposable.unsubscribe();
21123 CoverComponent.prototype._getDefaultConfiguration = function () {
21124 return { "loading": false, "visible": true };
21126 CoverComponent.prototype._getCoverButtonVNode = function (conf) {
21128 var cover = conf.loading ? "div.Cover.CoverLoading" : "div.Cover";
21129 return vd.h(cover, [
21130 this._getCoverBackgroundVNode(conf),
21131 vd.h("button.CoverButton", { onclick: function () { _this.configure({ loading: true }); } }, ["Explore"]),
21132 vd.h("a.CoverLogo", { href: "https://www.mapillary.com", target: "_blank" }, []),
21135 CoverComponent.prototype._getCoverBackgroundVNode = function (conf) {
21136 var url = conf.src != null ?
21137 "url(" + conf.src + ")" :
21138 "url(https://d1cuyjsrcm0gby.cloudfront.net/" + conf.key + "/thumb-640.jpg)";
21139 var properties = { style: { backgroundImage: url } };
21141 if (conf.loading) {
21142 children.push(vd.h("div.Spinner", {}, []));
21144 children.push(vd.h("div.CoverBackgroundGradient", {}, []));
21145 return vd.h("div.CoverBackground", properties, children);
21147 return CoverComponent;
21148 }(Component_1.Component));
21149 CoverComponent.componentName = "cover";
21150 exports.CoverComponent = CoverComponent;
21151 Component_1.ComponentService.registerCover(CoverComponent);
21152 exports.default = CoverComponent;
21154 },{"../Component":226,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/withLatestFrom":83,"virtual-dom":182}],246:[function(require,module,exports){
21156 /// <reference path="../../typings/index.d.ts" />
21157 var __extends = (this && this.__extends) || (function () {
21158 var extendStatics = Object.setPrototypeOf ||
21159 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21160 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21161 return function (d, b) {
21162 extendStatics(d, b);
21163 function __() { this.constructor = d; }
21164 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21167 Object.defineProperty(exports, "__esModule", { value: true });
21168 var _ = require("underscore");
21169 var vd = require("virtual-dom");
21170 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
21171 require("rxjs/add/operator/combineLatest");
21172 var Component_1 = require("../Component");
21173 var DebugComponent = (function (_super) {
21174 __extends(DebugComponent, _super);
21175 function DebugComponent(name, container, navigator) {
21176 var _this = _super.call(this, name, container, navigator) || this;
21177 _this._open$ = new BehaviorSubject_1.BehaviorSubject(false);
21178 _this._displaying = false;
21181 DebugComponent.prototype._activate = function () {
21183 this._disposable = this._navigator.stateService.currentState$
21184 .combineLatest(this._open$, this._navigator.imageLoadingService.loadstatus$, function (frame, open, loadStatus) {
21185 return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) };
21187 .subscribe(this._container.domRenderer.render$);
21189 DebugComponent.prototype._deactivate = function () {
21190 this._disposable.unsubscribe();
21192 DebugComponent.prototype._getDefaultConfiguration = function () {
21195 DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) {
21197 ret.push(vd.h("h2", "Node"));
21198 if (frame.state.currentNode) {
21199 ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key));
21201 if (frame.state.previousNode) {
21202 ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key));
21204 ret.push(vd.h("h2", "Loading"));
21208 for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
21209 var loadStat = _a[_i];
21210 total += loadStat.loaded;
21211 if (loadStat.loaded !== loadStat.total) {
21218 ret.push(vd.h("p", "Loaded Images: " + loaded));
21219 ret.push(vd.h("p", "Loading Images: " + loading));
21220 ret.push(vd.h("p", "Total bytes loaded: " + total));
21221 ret.push(vd.h("h2", "Camera"));
21222 ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x));
21223 ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y));
21224 ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z));
21225 ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x));
21226 ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y));
21227 ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z));
21228 ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x));
21229 ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y));
21230 ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z));
21233 DebugComponent.prototype._getDebugVNode = function (open, info) {
21235 return vd.h("div.Debug", {}, [
21236 vd.h("h2", {}, ["Debug"]),
21237 this._getDebugVNodeButton(open),
21238 vd.h("pre", {}, info),
21242 return this._getDebugVNodeButton(open);
21245 DebugComponent.prototype._getDebugVNodeButton = function (open) {
21246 var buttonText = open ? "Disable Debug" : "D";
21247 var buttonCssClass = open ? "" : ".DebugButtonFixed";
21249 return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]);
21252 return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]);
21255 DebugComponent.prototype._closeDebugElement = function (open) {
21256 this._open$.next(false);
21258 DebugComponent.prototype._openDebugElement = function () {
21259 this._open$.next(true);
21261 return DebugComponent;
21262 }(Component_1.Component));
21263 DebugComponent.componentName = "debug";
21264 exports.DebugComponent = DebugComponent;
21265 Component_1.ComponentService.register(DebugComponent);
21266 exports.default = DebugComponent;
21268 },{"../Component":226,"rxjs/BehaviorSubject":26,"rxjs/add/operator/combineLatest":53,"underscore":178,"virtual-dom":182}],247:[function(require,module,exports){
21270 /// <reference path="../../typings/index.d.ts" />
21271 var __extends = (this && this.__extends) || (function () {
21272 var extendStatics = Object.setPrototypeOf ||
21273 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21274 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21275 return function (d, b) {
21276 extendStatics(d, b);
21277 function __() { this.constructor = d; }
21278 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21281 Object.defineProperty(exports, "__esModule", { value: true });
21282 var vd = require("virtual-dom");
21283 require("rxjs/add/operator/combineLatest");
21284 var Component_1 = require("../Component");
21285 var ImageComponent = (function (_super) {
21286 __extends(ImageComponent, _super);
21287 function ImageComponent(name, container, navigator) {
21288 var _this = _super.call(this, name, container, navigator) || this;
21289 _this._canvasId = container.id + "-" + _this._name;
21292 ImageComponent.prototype._activate = function () {
21294 this.drawSubscription = this._container.domRenderer.element$
21295 .combineLatest(this._navigator.stateService.currentNode$, function (element, node) {
21296 var canvas = document.getElementById(_this._canvasId);
21297 return { canvas: canvas, node: node };
21299 .subscribe(function (canvasNode) {
21300 var canvas = canvasNode.canvas;
21301 var node = canvasNode.node;
21302 if (!node || !canvas) {
21305 var adaptableDomRenderer = canvas.parentElement;
21306 var width = adaptableDomRenderer.offsetWidth;
21307 var height = adaptableDomRenderer.offsetHeight;
21308 canvas.width = width;
21309 canvas.height = height;
21310 var ctx = canvas.getContext("2d");
21311 ctx.drawImage(node.image, 0, 0, width, height);
21313 this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) });
21315 ImageComponent.prototype._deactivate = function () {
21316 this.drawSubscription.unsubscribe();
21318 ImageComponent.prototype._getDefaultConfiguration = function () {
21321 return ImageComponent;
21322 }(Component_1.Component));
21323 ImageComponent.componentName = "image";
21324 exports.ImageComponent = ImageComponent;
21325 Component_1.ComponentService.register(ImageComponent);
21326 exports.default = ImageComponent;
21328 },{"../Component":226,"rxjs/add/operator/combineLatest":53,"virtual-dom":182}],248:[function(require,module,exports){
21330 var __extends = (this && this.__extends) || (function () {
21331 var extendStatics = Object.setPrototypeOf ||
21332 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21333 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21334 return function (d, b) {
21335 extendStatics(d, b);
21336 function __() { this.constructor = d; }
21337 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21340 Object.defineProperty(exports, "__esModule", { value: true });
21341 var Observable_1 = require("rxjs/Observable");
21342 require("rxjs/add/observable/fromEvent");
21343 require("rxjs/add/operator/withLatestFrom");
21344 var Edge_1 = require("../Edge");
21345 var Component_1 = require("../Component");
21346 var Geo_1 = require("../Geo");
21347 var KeyboardComponent = (function (_super) {
21348 __extends(KeyboardComponent, _super);
21349 function KeyboardComponent(name, container, navigator) {
21350 var _this = _super.call(this, name, container, navigator) || this;
21351 _this._spatial = new Geo_1.Spatial();
21352 _this._perspectiveDirections = [
21353 Edge_1.EdgeDirection.StepForward,
21354 Edge_1.EdgeDirection.StepBackward,
21355 Edge_1.EdgeDirection.StepLeft,
21356 Edge_1.EdgeDirection.StepRight,
21357 Edge_1.EdgeDirection.TurnLeft,
21358 Edge_1.EdgeDirection.TurnRight,
21359 Edge_1.EdgeDirection.TurnU,
21363 KeyboardComponent.prototype._activate = function () {
21365 var sequenceEdges$ = this._navigator.stateService.currentNode$
21366 .switchMap(function (node) {
21367 return node.sequenceEdges$;
21369 var spatialEdges$ = this._navigator.stateService.currentNode$
21370 .switchMap(function (node) {
21371 return node.spatialEdges$;
21373 this._disposable = Observable_1.Observable
21374 .fromEvent(document, "keydown")
21375 .withLatestFrom(this._navigator.stateService.currentState$, sequenceEdges$, spatialEdges$, function (event, frame, sequenceEdges, spatialEdges) {
21376 return { event: event, frame: frame, sequenceEdges: sequenceEdges, spatialEdges: spatialEdges };
21378 .subscribe(function (kf) {
21379 if (!kf.frame.state.currentNode.pano) {
21380 _this._navigatePerspective(kf.event, kf.sequenceEdges, kf.spatialEdges);
21383 _this._navigatePanorama(kf.event, kf.sequenceEdges, kf.spatialEdges, kf.frame.state.camera);
21387 KeyboardComponent.prototype._deactivate = function () {
21388 this._disposable.unsubscribe();
21390 KeyboardComponent.prototype._getDefaultConfiguration = function () {
21393 KeyboardComponent.prototype._navigatePanorama = function (event, sequenceEdges, spatialEdges, camera) {
21394 var navigationAngle = 0;
21395 var stepDirection = null;
21396 var sequenceDirection = null;
21397 var phi = this._rotationFromCamera(camera).phi;
21398 switch (event.keyCode) {
21400 if (event.shiftKey || event.altKey) {
21403 navigationAngle = Math.PI / 2 + phi;
21404 stepDirection = Edge_1.EdgeDirection.StepLeft;
21407 if (event.shiftKey) {
21410 if (event.altKey) {
21411 sequenceDirection = Edge_1.EdgeDirection.Next;
21414 navigationAngle = phi;
21415 stepDirection = Edge_1.EdgeDirection.StepForward;
21418 if (event.shiftKey || event.altKey) {
21421 navigationAngle = -Math.PI / 2 + phi;
21422 stepDirection = Edge_1.EdgeDirection.StepRight;
21425 if (event.shiftKey) {
21428 if (event.altKey) {
21429 sequenceDirection = Edge_1.EdgeDirection.Prev;
21432 navigationAngle = Math.PI + phi;
21433 stepDirection = Edge_1.EdgeDirection.StepBackward;
21438 event.preventDefault();
21439 if (sequenceDirection != null) {
21440 this._moveInDir(sequenceDirection, sequenceEdges);
21443 if (stepDirection == null || !spatialEdges.cached) {
21446 navigationAngle = this._spatial.wrapAngle(navigationAngle);
21447 var threshold = Math.PI / 4;
21448 var edges = spatialEdges.edges.filter(function (e) {
21449 return e.data.direction === Edge_1.EdgeDirection.Pano ||
21450 e.data.direction === stepDirection;
21452 var smallestAngle = Number.MAX_VALUE;
21454 for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
21455 var edge = edges_1[_i];
21456 var angle = Math.abs(this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle));
21457 if (angle < Math.min(smallestAngle, threshold)) {
21458 smallestAngle = angle;
21462 if (toKey == null) {
21465 this._navigator.moveToKey$(toKey)
21466 .subscribe(function (n) { return; }, function (e) { console.error(e); });
21468 KeyboardComponent.prototype._rotationFromCamera = function (camera) {
21469 var direction = camera.lookat.clone().sub(camera.position);
21470 var upProjection = direction.clone().dot(camera.up);
21471 var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection));
21472 var phi = Math.atan2(planeProjection.y, planeProjection.x);
21473 var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
21474 return { phi: phi, theta: theta };
21476 KeyboardComponent.prototype._navigatePerspective = function (event, sequenceEdges, spatialEdges) {
21477 var direction = null;
21478 var sequenceDirection = null;
21479 switch (event.keyCode) {
21481 if (event.altKey) {
21484 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft;
21487 if (event.altKey) {
21488 sequenceDirection = Edge_1.EdgeDirection.Next;
21491 direction = event.shiftKey ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward;
21494 if (event.altKey) {
21497 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight;
21500 if (event.altKey) {
21501 sequenceDirection = Edge_1.EdgeDirection.Prev;
21504 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward;
21509 event.preventDefault();
21510 if (sequenceDirection != null) {
21511 this._moveInDir(sequenceDirection, sequenceEdges);
21514 this._moveInDir(direction, spatialEdges);
21516 KeyboardComponent.prototype._moveInDir = function (direction, edgeStatus) {
21517 if (!edgeStatus.cached) {
21520 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
21522 if (edge.data.direction === direction) {
21523 this._navigator.moveToKey$(edge.to)
21524 .subscribe(function (n) { return; }, function (e) { console.error(e); });
21529 return KeyboardComponent;
21530 }(Component_1.Component));
21531 KeyboardComponent.componentName = "keyboard";
21532 exports.KeyboardComponent = KeyboardComponent;
21533 Component_1.ComponentService.register(KeyboardComponent);
21534 exports.default = KeyboardComponent;
21536 },{"../Component":226,"../Edge":227,"../Geo":229,"rxjs/Observable":29,"rxjs/add/observable/fromEvent":42,"rxjs/add/operator/withLatestFrom":83}],249:[function(require,module,exports){
21538 /// <reference path="../../typings/index.d.ts" />
21539 var __extends = (this && this.__extends) || (function () {
21540 var extendStatics = Object.setPrototypeOf ||
21541 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21542 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21543 return function (d, b) {
21544 extendStatics(d, b);
21545 function __() { this.constructor = d; }
21546 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21549 Object.defineProperty(exports, "__esModule", { value: true });
21550 var _ = require("underscore");
21551 var vd = require("virtual-dom");
21552 require("rxjs/add/operator/combineLatest");
21553 var Component_1 = require("../Component");
21554 var LoadingComponent = (function (_super) {
21555 __extends(LoadingComponent, _super);
21556 function LoadingComponent(name, container, navigator) {
21557 return _super.call(this, name, container, navigator) || this;
21559 LoadingComponent.prototype._activate = function () {
21561 this._loadingSubscription = this._navigator.loadingService.loading$
21562 .combineLatest(this._navigator.imageLoadingService.loadstatus$, function (loading, loadStatus) {
21564 return { name: "loading", vnode: _this._getBarVNode(100) };
21568 for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
21569 var loadStat = _a[_i];
21570 if (loadStat.loaded !== loadStat.total) {
21571 loaded += loadStat.loaded;
21572 total += loadStat.total;
21575 var percentage = 100;
21577 percentage = (loaded / total) * 100;
21579 return { name: _this._name, vnode: _this._getBarVNode(percentage) };
21581 .subscribe(this._container.domRenderer.render$);
21583 LoadingComponent.prototype._deactivate = function () {
21584 this._loadingSubscription.unsubscribe();
21586 LoadingComponent.prototype._getDefaultConfiguration = function () {
21589 LoadingComponent.prototype._getBarVNode = function (percentage) {
21590 var loadingBarStyle = {};
21591 var loadingContainerStyle = {};
21592 if (percentage !== 100) {
21593 loadingBarStyle.width = percentage.toFixed(0) + "%";
21594 loadingBarStyle.opacity = "1";
21597 loadingBarStyle.width = "100%";
21598 loadingBarStyle.opacity = "0";
21600 return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]);
21602 return LoadingComponent;
21603 }(Component_1.Component));
21604 LoadingComponent.componentName = "loading";
21605 exports.LoadingComponent = LoadingComponent;
21606 Component_1.ComponentService.register(LoadingComponent);
21607 exports.default = LoadingComponent;
21609 },{"../Component":226,"rxjs/add/operator/combineLatest":53,"underscore":178,"virtual-dom":182}],250:[function(require,module,exports){
21611 /// <reference path="../../typings/index.d.ts" />
21612 var __extends = (this && this.__extends) || (function () {
21613 var extendStatics = Object.setPrototypeOf ||
21614 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21615 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21616 return function (d, b) {
21617 extendStatics(d, b);
21618 function __() { this.constructor = d; }
21619 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21622 Object.defineProperty(exports, "__esModule", { value: true });
21623 var vd = require("virtual-dom");
21624 var Observable_1 = require("rxjs/Observable");
21625 require("rxjs/add/operator/map");
21626 require("rxjs/add/operator/first");
21627 var Edge_1 = require("../Edge");
21628 var Component_1 = require("../Component");
21629 var NavigationComponent = (function (_super) {
21630 __extends(NavigationComponent, _super);
21631 function NavigationComponent(name, container, navigator) {
21632 var _this = _super.call(this, name, container, navigator) || this;
21633 _this._dirNames = {};
21634 _this._dirNames[Edge_1.EdgeDirection.StepForward] = "Forward";
21635 _this._dirNames[Edge_1.EdgeDirection.StepBackward] = "Backward";
21636 _this._dirNames[Edge_1.EdgeDirection.StepLeft] = "Left";
21637 _this._dirNames[Edge_1.EdgeDirection.StepRight] = "Right";
21638 _this._dirNames[Edge_1.EdgeDirection.TurnLeft] = "Turnleft";
21639 _this._dirNames[Edge_1.EdgeDirection.TurnRight] = "Turnright";
21640 _this._dirNames[Edge_1.EdgeDirection.TurnU] = "Turnaround";
21643 NavigationComponent.prototype._activate = function () {
21645 this._renderSubscription = this._navigator.stateService.currentNode$
21646 .switchMap(function (node) {
21648 Observable_1.Observable.of([]) :
21649 Observable_1.Observable.combineLatest(node.sequenceEdges$, node.spatialEdges$, function (seq, spa) {
21650 return seq.edges.concat(spa.edges);
21653 .map(function (edges) {
21655 for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
21656 var edge = edges_1[_i];
21657 var direction = edge.data.direction;
21658 var name_1 = _this._dirNames[direction];
21659 if (name_1 == null) {
21662 btns.push(_this._createVNode(direction, name_1));
21664 return { name: _this._name, vnode: vd.h("div.NavigationComponent", btns) };
21666 .subscribe(this._container.domRenderer.render$);
21668 NavigationComponent.prototype._deactivate = function () {
21669 this._renderSubscription.unsubscribe();
21671 NavigationComponent.prototype._getDefaultConfiguration = function () {
21674 NavigationComponent.prototype._createVNode = function (direction, name) {
21676 return vd.h("span.Direction.Direction" + name, {
21677 onclick: function (ev) {
21678 _this._navigator.moveDir$(direction)
21679 .subscribe(function (node) { return; }, function (error) { console.error(error); });
21683 return NavigationComponent;
21684 }(Component_1.Component));
21685 NavigationComponent.componentName = "navigation";
21686 exports.NavigationComponent = NavigationComponent;
21687 Component_1.ComponentService.register(NavigationComponent);
21688 exports.default = NavigationComponent;
21690 },{"../Component":226,"../Edge":227,"rxjs/Observable":29,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"virtual-dom":182}],251:[function(require,module,exports){
21692 /// <reference path="../../typings/index.d.ts" />
21693 var __extends = (this && this.__extends) || (function () {
21694 var extendStatics = Object.setPrototypeOf ||
21695 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21696 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21697 return function (d, b) {
21698 extendStatics(d, b);
21699 function __() { this.constructor = d; }
21700 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21703 Object.defineProperty(exports, "__esModule", { value: true });
21704 var _ = require("underscore");
21705 var vd = require("virtual-dom");
21706 var Observable_1 = require("rxjs/Observable");
21707 require("rxjs/add/observable/fromPromise");
21708 require("rxjs/add/observable/of");
21709 require("rxjs/add/operator/combineLatest");
21710 require("rxjs/add/operator/distinct");
21711 require("rxjs/add/operator/distinctUntilChanged");
21712 require("rxjs/add/operator/filter");
21713 require("rxjs/add/operator/map");
21714 require("rxjs/add/operator/mergeMap");
21715 require("rxjs/add/operator/pluck");
21716 require("rxjs/add/operator/scan");
21717 var Component_1 = require("../Component");
21718 var DescriptionState = (function () {
21719 function DescriptionState() {
21721 return DescriptionState;
21723 var RouteState = (function () {
21724 function RouteState() {
21728 var RouteTrack = (function () {
21729 function RouteTrack() {
21730 this.nodeInstructions = [];
21731 this.nodeInstructionsOrdered = [];
21735 var RouteComponent = (function (_super) {
21736 __extends(RouteComponent, _super);
21737 function RouteComponent(name, container, navigator) {
21738 return _super.call(this, name, container, navigator) || this;
21740 RouteComponent.prototype._activate = function () {
21742 var _slowedStream$;
21743 _slowedStream$ = this._navigator.stateService.currentState$.filter(function (frame) {
21744 return (frame.id % 2) === 0;
21745 }).filter(function (frame) {
21746 return frame.state.nodesAhead < 15;
21747 }).distinctUntilChanged(undefined, function (frame) {
21748 return frame.state.lastNode.key;
21751 _routeTrack$ = this.configuration$.mergeMap(function (conf) {
21752 return Observable_1.Observable.from(conf.paths);
21753 }).distinct(function (p) {
21754 return p.sequenceKey;
21755 }).mergeMap(function (path) {
21756 return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey])
21757 .map(function (sequenceByKey) {
21758 return sequenceByKey[path.sequenceKey];
21760 }).combineLatest(this.configuration$, function (sequence, conf) {
21762 var instructionPlaces = [];
21763 for (var _i = 0, _a = conf.paths; _i < _a.length; _i++) {
21765 if (path.sequenceKey === sequence.key) {
21766 var nodeInstructions = [];
21767 var saveKey = false;
21768 for (var _b = 0, _c = sequence.keys; _b < _c.length; _b++) {
21770 if (path.startKey === key) {
21774 var description = null;
21775 for (var _d = 0, _e = path.infoKeys; _d < _e.length; _d++) {
21776 var infoKey = _e[_d];
21777 if (infoKey.key === key) {
21778 description = infoKey.description;
21781 nodeInstructions.push({ description: description, key: key });
21783 if (path.stopKey === key) {
21787 instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i });
21791 return instructionPlaces;
21792 }).scan(function (routeTrack, instructionPlaces) {
21793 for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) {
21794 var instructionPlace = instructionPlaces_1[_i];
21795 routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions;
21797 routeTrack.nodeInstructions = _.flatten(routeTrack.nodeInstructionsOrdered);
21799 }, new RouteTrack());
21800 this._disposable = _slowedStream$
21801 .combineLatest(_routeTrack$, this.configuration$, function (frame, routeTrack, conf) {
21802 return { conf: conf, frame: frame, routeTrack: routeTrack };
21803 }).scan(function (routeState, rtAndFrame) {
21804 if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) {
21805 routeState.routeTrack = rtAndFrame.routeTrack;
21806 routeState.currentNode = rtAndFrame.frame.state.currentNode;
21807 routeState.lastNode = rtAndFrame.frame.state.lastNode;
21808 routeState.playing = true;
21811 _this._navigator.stateService.cutNodes();
21812 routeState.playing = false;
21815 }, new RouteState())
21816 .filter(function (routeState) {
21817 return routeState.playing;
21818 }).filter(function (routeState) {
21819 for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
21820 var nodeInstruction = _a[_i];
21821 if (!nodeInstruction) {
21824 if (nodeInstruction.key === routeState.lastNode.key) {
21829 }).distinctUntilChanged(undefined, function (routeState) {
21830 return routeState.lastNode.key;
21831 }).mergeMap(function (routeState) {
21833 for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
21834 var nodeInstruction = _a[_i];
21835 if (nodeInstruction.key === routeState.lastNode.key) {
21840 var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1];
21841 if (!nextInstruction) {
21842 return Observable_1.Observable.of(null);
21844 return _this._navigator.graphService.cacheNode$(nextInstruction.key);
21845 }).combineLatest(this.configuration$, function (node, conf) {
21846 return { conf: conf, node: node };
21847 }).filter(function (cAN) {
21848 return cAN.node !== null && cAN.conf.playing;
21849 }).pluck("node").subscribe(this._navigator.stateService.appendNode$);
21850 this._disposableDescription = this._navigator.stateService.currentNode$
21851 .combineLatest(_routeTrack$, this.configuration$, function (node, routeTrack, conf) {
21852 if (conf.playing !== undefined && !conf.playing) {
21855 var description = null;
21856 for (var _i = 0, _a = routeTrack.nodeInstructions; _i < _a.length; _i++) {
21857 var nodeInstruction = _a[_i];
21858 if (nodeInstruction.key === node.key) {
21859 description = nodeInstruction.description;
21863 return description;
21864 }).scan(function (descriptionState, description) {
21865 if (description !== descriptionState.description && description !== null) {
21866 descriptionState.description = description;
21867 descriptionState.showsLeft = 6;
21870 descriptionState.showsLeft--;
21872 if (description === "quit") {
21873 descriptionState.description = null;
21875 return descriptionState;
21876 }, new DescriptionState()).map(function (descriptionState) {
21877 if (descriptionState.showsLeft > 0 && descriptionState.description) {
21878 return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) };
21881 return { name: _this._name, vnode: vd.h("div", []) };
21883 }).subscribe(this._container.domRenderer.render$);
21885 RouteComponent.prototype._deactivate = function () {
21886 this._disposable.unsubscribe();
21887 this._disposableDescription.unsubscribe();
21889 RouteComponent.prototype._getDefaultConfiguration = function () {
21892 RouteComponent.prototype.play = function () {
21893 this.configure({ playing: true });
21895 RouteComponent.prototype.stop = function () {
21896 this.configure({ playing: false });
21898 RouteComponent.prototype._getRouteAnnotationNode = function (description) {
21899 return vd.h("div.RouteFrame", {}, [
21900 vd.h("p", { textContent: description }, []),
21903 return RouteComponent;
21904 }(Component_1.Component));
21905 RouteComponent.componentName = "route";
21906 exports.RouteComponent = RouteComponent;
21907 Component_1.ComponentService.register(RouteComponent);
21908 exports.default = RouteComponent;
21910 },{"../Component":226,"rxjs/Observable":29,"rxjs/add/observable/fromPromise":43,"rxjs/add/observable/of":45,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/distinct":57,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/pluck":70,"rxjs/add/operator/scan":73,"underscore":178,"virtual-dom":182}],252:[function(require,module,exports){
21912 var __extends = (this && this.__extends) || (function () {
21913 var extendStatics = Object.setPrototypeOf ||
21914 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21915 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21916 return function (d, b) {
21917 extendStatics(d, b);
21918 function __() { this.constructor = d; }
21919 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21922 Object.defineProperty(exports, "__esModule", { value: true });
21923 var Observable_1 = require("rxjs/Observable");
21924 require("rxjs/add/operator/buffer");
21925 require("rxjs/add/operator/debounceTime");
21926 require("rxjs/add/operator/filter");
21927 require("rxjs/add/operator/map");
21928 require("rxjs/add/operator/scan");
21929 var Component_1 = require("../Component");
21930 var StatsComponent = (function (_super) {
21931 __extends(StatsComponent, _super);
21932 function StatsComponent(name, container, navigator) {
21933 return _super.call(this, name, container, navigator) || this;
21935 StatsComponent.prototype._activate = function () {
21937 this._sequenceSubscription = this._navigator.stateService.currentNode$
21938 .scan(function (keys, node) {
21939 var sKey = node.sequenceKey;
21941 if (!(sKey in keys.reported)) {
21942 keys.report = [sKey];
21943 keys.reported[sKey] = true;
21946 }, { report: [], reported: {} })
21947 .filter(function (keys) {
21948 return keys.report.length > 0;
21950 .mergeMap(function (keys) {
21951 return _this._navigator.apiV3.sequenceViewAdd$(keys.report)
21952 .catch(function (error, caught) {
21953 console.error("Failed to report sequence stats (" + keys.report + ")", error);
21954 return Observable_1.Observable.empty();
21957 .subscribe(function () { });
21958 this._imageSubscription = this._navigator.stateService.currentNode$
21959 .map(function (node) {
21962 .buffer(this._navigator.stateService.currentNode$.debounceTime(5000))
21963 .scan(function (keys, newKeys) {
21965 for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
21966 var key = newKeys_1[_i];
21967 if (!(key in keys.reported)) {
21968 keys.report.push(key);
21969 keys.reported[key] = true;
21973 }, { report: [], reported: {} })
21974 .filter(function (keys) {
21975 return keys.report.length > 0;
21977 .mergeMap(function (keys) {
21978 return _this._navigator.apiV3.imageViewAdd$(keys.report)
21979 .catch(function (error, caught) {
21980 console.error("Failed to report image stats (" + keys.report + ")", error);
21981 return Observable_1.Observable.empty();
21984 .subscribe(function () { });
21986 StatsComponent.prototype._deactivate = function () {
21987 this._sequenceSubscription.unsubscribe();
21988 this._imageSubscription.unsubscribe();
21990 StatsComponent.prototype._getDefaultConfiguration = function () {
21993 return StatsComponent;
21994 }(Component_1.Component));
21995 StatsComponent.componentName = "stats";
21996 exports.StatsComponent = StatsComponent;
21997 Component_1.ComponentService.register(StatsComponent);
21998 exports.default = StatsComponent;
22000 },{"../Component":226,"rxjs/Observable":29,"rxjs/add/operator/buffer":49,"rxjs/add/operator/debounceTime":55,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/scan":73}],253:[function(require,module,exports){
22002 /// <reference path="../../../typings/index.d.ts" />
22003 var __extends = (this && this.__extends) || (function () {
22004 var extendStatics = Object.setPrototypeOf ||
22005 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22006 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22007 return function (d, b) {
22008 extendStatics(d, b);
22009 function __() { this.constructor = d; }
22010 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22013 Object.defineProperty(exports, "__esModule", { value: true });
22014 var vd = require("virtual-dom");
22015 var Observable_1 = require("rxjs/Observable");
22016 var Subject_1 = require("rxjs/Subject");
22017 require("rxjs/add/observable/combineLatest");
22018 require("rxjs/add/operator/do");
22019 require("rxjs/add/operator/distinctUntilChanged");
22020 require("rxjs/add/operator/filter");
22021 require("rxjs/add/operator/map");
22022 require("rxjs/add/operator/share");
22023 var Component_1 = require("../../Component");
22025 * @class DirectionComponent
22026 * @classdesc Component showing navigation arrows for steps and turns.
22028 var DirectionComponent = (function (_super) {
22029 __extends(DirectionComponent, _super);
22030 function DirectionComponent(name, container, navigator) {
22031 var _this = _super.call(this, name, container, navigator) || this;
22032 _this._renderer = new Component_1.DirectionDOMRenderer(_this.defaultConfiguration, container.element);
22033 _this._hoveredKeySubject$ = new Subject_1.Subject();
22034 _this._hoveredKey$ = _this._hoveredKeySubject$.share();
22037 Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", {
22039 * Get hovered key observable.
22041 * @description An observable emitting the key of the node for the direction
22042 * arrow that is being hovered. When the mouse leaves a direction arrow null
22045 * @returns {Observable<string>}
22048 return this._hoveredKey$;
22054 * Set highlight key.
22056 * @description The arrow pointing towards the node corresponding to the
22057 * highlight key will be highlighted.
22059 * @param {string} highlightKey Key of node to be highlighted if existing
22062 DirectionComponent.prototype.setHighlightKey = function (highlightKey) {
22063 this.configure({ highlightKey: highlightKey });
22066 * Set min width of container element.
22068 * @description Set min width of the non transformed container element holding
22069 * the navigation arrows. If the min width is larger than the max width the
22070 * min width value will be used.
22072 * The container element is automatically resized when the resize
22073 * method on the Viewer class is called.
22075 * @param {number} minWidth
22077 DirectionComponent.prototype.setMinWidth = function (minWidth) {
22078 this.configure({ minWidth: minWidth });
22081 * Set max width of container element.
22083 * @description Set max width of the non transformed container element holding
22084 * the navigation arrows. If the min width is larger than the max width the
22085 * min width value will be used.
22087 * The container element is automatically resized when the resize
22088 * method on the Viewer class is called.
22090 * @param {number} minWidth
22092 DirectionComponent.prototype.setMaxWidth = function (maxWidth) {
22093 this.configure({ maxWidth: maxWidth });
22096 DirectionComponent.prototype.resize = function () {
22097 this._renderer.resize(this._container.element);
22099 DirectionComponent.prototype._activate = function () {
22101 this._configurationSubscription = this._configuration$
22102 .subscribe(function (configuration) {
22103 _this._renderer.setConfiguration(configuration);
22105 this._nodeSubscription = this._navigator.stateService.currentNode$
22106 .do(function (node) {
22107 _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) });
22108 _this._renderer.setNode(node);
22110 .withLatestFrom(this._configuration$)
22111 .switchMap(function (nc) {
22113 var configuration = nc[1];
22114 return node.spatialEdges$
22115 .withLatestFrom(configuration.distinguishSequence ?
22116 _this._navigator.graphService
22117 .cacheSequence$(node.sequenceKey)
22118 .catch(function (error, caught) {
22119 console.error("Failed to cache sequence (" + node.sequenceKey + ")", error);
22120 return Observable_1.Observable.empty();
22122 Observable_1.Observable.of(null));
22124 .subscribe(function (es) {
22125 _this._renderer.setEdges(es[0], es[1]);
22127 this._renderCameraSubscription = this._container.renderService.renderCameraFrame$
22128 .do(function (renderCamera) {
22129 _this._renderer.setRenderCamera(renderCamera);
22131 .map(function (renderCamera) {
22132 return _this._renderer;
22134 .filter(function (renderer) {
22135 return renderer.needsRender;
22137 .map(function (renderer) {
22138 return { name: _this._name, vnode: renderer.render(_this._navigator) };
22140 .subscribe(this._container.domRenderer.render$);
22141 this._hoveredKeySubscription = Observable_1.Observable
22143 this._container.domRenderer.element$,
22144 this._container.renderService.renderCamera$,
22145 this._container.mouseService.mouseMove$.startWith(null),
22146 this._container.mouseService.mouseUp$.startWith(null),
22147 ], function (e, rc, mm, mu) {
22150 .map(function (element) {
22151 var elements = element.getElementsByClassName("DirectionsPerspective");
22152 for (var i = 0; i < elements.length; i++) {
22153 var hovered = elements.item(i).querySelector(":hover");
22154 if (hovered != null && hovered.hasAttribute("data-key")) {
22155 return hovered.getAttribute("data-key");
22160 .distinctUntilChanged()
22161 .subscribe(this._hoveredKeySubject$);
22163 DirectionComponent.prototype._deactivate = function () {
22164 this._configurationSubscription.unsubscribe();
22165 this._nodeSubscription.unsubscribe();
22166 this._renderCameraSubscription.unsubscribe();
22167 this._hoveredKeySubscription.unsubscribe();
22169 DirectionComponent.prototype._getDefaultConfiguration = function () {
22171 distinguishSequence: false,
22176 return DirectionComponent;
22177 }(Component_1.Component));
22179 DirectionComponent.componentName = "direction";
22180 exports.DirectionComponent = DirectionComponent;
22181 Component_1.ComponentService.register(DirectionComponent);
22182 exports.default = DirectionComponent;
22184 },{"../../Component":226,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/do":59,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/share":74,"virtual-dom":182}],254:[function(require,module,exports){
22186 Object.defineProperty(exports, "__esModule", { value: true });
22187 var Geo_1 = require("../../Geo");
22189 * @class DirectionDOMCalculator
22190 * @classdesc Helper class for calculating DOM CSS properties.
22192 var DirectionDOMCalculator = (function () {
22193 function DirectionDOMCalculator(configuration, element) {
22194 this._spatial = new Geo_1.Spatial();
22195 this._minThresholdWidth = 320;
22196 this._maxThresholdWidth = 1480;
22197 this._minThresholdHeight = 240;
22198 this._maxThresholdHeight = 820;
22199 this._configure(configuration);
22200 this._resize(element);
22203 Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", {
22205 return this._minWidth;
22210 Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", {
22212 return this._maxWidth;
22217 Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", {
22219 return this._containerWidth;
22224 Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", {
22226 return this._containerWidthCss;
22231 Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", {
22233 return this._containerMarginCss;
22238 Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", {
22240 return this._containerLeftCss;
22245 Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", {
22247 return this._containerHeight;
22252 Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", {
22254 return this._containerHeightCss;
22259 Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", {
22261 return this._containerBottomCss;
22266 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", {
22268 return this._stepCircleSize;
22273 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", {
22275 return this._stepCircleSizeCss;
22280 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", {
22282 return this._stepCircleMarginCss;
22287 Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", {
22289 return this._turnCircleSize;
22294 Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", {
22296 return this._turnCircleSizeCss;
22301 Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", {
22303 return this._outerRadius;
22308 Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", {
22310 return this._innerRadius;
22315 Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", {
22317 return this._shadowOffset;
22323 * Configures the min and max width values.
22325 * @param {IDirectionConfiguration} configuration Configuration
22326 * with min and max width values.
22328 DirectionDOMCalculator.prototype.configure = function (configuration) {
22329 this._configure(configuration);
22333 * Resizes all properties according to the width and height
22336 * @param {HTMLElement} element The container element from which to extract
22337 * the width and height.
22339 DirectionDOMCalculator.prototype.resize = function (element) {
22340 this._resize(element);
22344 * Calculates the coordinates on the unit circle for an angle.
22346 * @param {number} angle Angle in radians.
22347 * @returns {Array<number>} The x and y coordinates on the unit circle.
22349 DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) {
22350 return [Math.cos(angle), Math.sin(angle)];
22353 * Calculates the coordinates on the unit circle for the
22354 * relative angle between the first and second angle.
22356 * @param {number} first Angle in radians.
22357 * @param {number} second Angle in radians.
22358 * @returns {Array<number>} The x and y coordinates on the unit circle
22359 * for the relative angle between the first and second angle.
22361 DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) {
22362 var relativeAngle = this._spatial.wrapAngle(first - second);
22363 return this.angleToCoordinates(relativeAngle);
22365 DirectionDOMCalculator.prototype._configure = function (configuration) {
22366 this._minWidth = configuration.minWidth;
22367 this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth);
22369 DirectionDOMCalculator.prototype._resize = function (element) {
22370 this._elementWidth = element.offsetWidth;
22371 this._elementHeight = element.offsetHeight;
22373 DirectionDOMCalculator.prototype._reset = function () {
22374 this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight);
22375 this._containerHeight = this._getContainerHeight(this.containerWidth);
22376 this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight);
22377 this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight);
22378 this._outerRadius = this._getOuterRadius(this._containerHeight);
22379 this._innerRadius = this._getInnerRadius(this._containerHeight);
22380 this._shadowOffset = 3;
22381 this._containerWidthCss = this._numberToCssPixels(this._containerWidth);
22382 this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth);
22383 this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth));
22384 this._containerHeightCss = this._numberToCssPixels(this._containerHeight);
22385 this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight));
22386 this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize);
22387 this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize);
22388 this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize);
22390 DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) {
22391 var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
22392 var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
22393 var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
22394 coeff = 0.04 * Math.round(25 * coeff);
22395 return this._minWidth + coeff * (this._maxWidth - this._minWidth);
22397 DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) {
22398 return 0.77 * containerWidth;
22400 DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) {
22401 return 0.34 * containerHeight;
22403 DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) {
22404 return 0.3 * containerHeight;
22406 DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) {
22407 return 0.31 * containerHeight;
22409 DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) {
22410 return 0.125 * containerHeight;
22412 DirectionDOMCalculator.prototype._numberToCssPixels = function (value) {
22413 return value + "px";
22415 DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) {
22416 return value > minWidth ? value : minWidth;
22418 return DirectionDOMCalculator;
22420 exports.DirectionDOMCalculator = DirectionDOMCalculator;
22421 exports.default = DirectionDOMCalculator;
22423 },{"../../Geo":229}],255:[function(require,module,exports){
22425 /// <reference path="../../../typings/index.d.ts" />
22426 Object.defineProperty(exports, "__esModule", { value: true });
22427 var vd = require("virtual-dom");
22428 var Component_1 = require("../../Component");
22429 var Edge_1 = require("../../Edge");
22430 var Geo_1 = require("../../Geo");
22432 * @class DirectionDOMRenderer
22433 * @classdesc DOM renderer for direction arrows.
22435 var DirectionDOMRenderer = (function () {
22436 function DirectionDOMRenderer(configuration, element) {
22437 this._isEdge = false;
22438 this._spatial = new Geo_1.Spatial();
22439 this._calculator = new Component_1.DirectionDOMCalculator(configuration, element);
22441 this._rotation = { phi: 0, theta: 0 };
22442 this._epsilon = 0.5 * Math.PI / 180;
22443 this._highlightKey = null;
22444 this._distinguishSequence = false;
22445 this._needsRender = false;
22446 this._stepEdges = [];
22447 this._turnEdges = [];
22448 this._panoEdges = [];
22449 this._sequenceEdgeKeys = [];
22450 this._stepDirections = [
22451 Edge_1.EdgeDirection.StepForward,
22452 Edge_1.EdgeDirection.StepBackward,
22453 Edge_1.EdgeDirection.StepLeft,
22454 Edge_1.EdgeDirection.StepRight,
22456 this._turnDirections = [
22457 Edge_1.EdgeDirection.TurnLeft,
22458 Edge_1.EdgeDirection.TurnRight,
22459 Edge_1.EdgeDirection.TurnU,
22461 this._turnNames = {};
22462 this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft";
22463 this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight";
22464 this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround";
22465 // detects IE 8-11, then Edge 20+.
22466 var isIE = !!document.documentMode;
22467 this._isEdge = !isIE && !!window.StyleMedia;
22469 Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", {
22471 * Get needs render.
22473 * @returns {boolean} Value indicating whether render should be called.
22476 return this._needsRender;
22482 * Renders virtual DOM elements.
22484 * @description Calling render resets the needs render property.
22486 DirectionDOMRenderer.prototype.render = function (navigator) {
22487 this._needsRender = false;
22488 var rotation = this._rotation;
22491 if (this._node.pano) {
22492 steps = steps.concat(this._createPanoArrows(navigator, rotation));
22495 steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation));
22496 steps = steps.concat(this._createStepArrows(navigator, rotation));
22497 turns = turns.concat(this._createTurnArrows(navigator));
22499 return this._getContainer(steps, turns, rotation);
22501 DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) {
22502 this._setEdges(edgeStatus, sequence);
22503 this._setNeedsRender();
22506 * Set node for which to show edges.
22508 * @param {Node} node
22510 DirectionDOMRenderer.prototype.setNode = function (node) {
22512 this._clearEdges();
22513 this._setNeedsRender();
22516 * Set the render camera to use for calculating rotations.
22518 * @param {RenderCamera} renderCamera
22520 DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) {
22521 var rotation = renderCamera.rotation;
22522 if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) {
22525 this._rotation = rotation;
22526 this._setNeedsRender();
22529 * Set configuration values.
22531 * @param {IDirectionConfiguration} configuration
22533 DirectionDOMRenderer.prototype.setConfiguration = function (configuration) {
22534 var needsRender = false;
22535 if (this._highlightKey !== configuration.highlightKey ||
22536 this._distinguishSequence !== configuration.distinguishSequence) {
22537 this._highlightKey = configuration.highlightKey;
22538 this._distinguishSequence = configuration.distinguishSequence;
22539 needsRender = true;
22541 if (this._calculator.minWidth !== configuration.minWidth ||
22542 this._calculator.maxWidth !== configuration.maxWidth) {
22543 this._calculator.configure(configuration);
22544 needsRender = true;
22547 this._setNeedsRender();
22551 * Detect the element's width and height and resize
22552 * elements accordingly.
22554 * @param {HTMLElement} element Viewer container element.
22556 DirectionDOMRenderer.prototype.resize = function (element) {
22557 this._calculator.resize(element);
22558 this._setNeedsRender();
22560 DirectionDOMRenderer.prototype._setNeedsRender = function () {
22561 if (this._node != null) {
22562 this._needsRender = true;
22565 DirectionDOMRenderer.prototype._clearEdges = function () {
22566 this._stepEdges = [];
22567 this._turnEdges = [];
22568 this._panoEdges = [];
22569 this._sequenceEdgeKeys = [];
22571 DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) {
22572 this._stepEdges = [];
22573 this._turnEdges = [];
22574 this._panoEdges = [];
22575 this._sequenceEdgeKeys = [];
22576 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
22578 var direction = edge.data.direction;
22579 if (this._stepDirections.indexOf(direction) > -1) {
22580 this._stepEdges.push(edge);
22583 if (this._turnDirections.indexOf(direction) > -1) {
22584 this._turnEdges.push(edge);
22587 if (edge.data.direction === Edge_1.EdgeDirection.Pano) {
22588 this._panoEdges.push(edge);
22591 if (this._distinguishSequence && sequence != null) {
22592 var edges = this._panoEdges
22593 .concat(this._stepEdges)
22594 .concat(this._turnEdges);
22595 for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) {
22596 var edge = edges_1[_b];
22597 var edgeKey = edge.to;
22598 for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
22599 var sequenceKey = _d[_c];
22600 if (sequenceKey === edgeKey) {
22601 this._sequenceEdgeKeys.push(edgeKey);
22608 DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) {
22610 for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
22611 var panoEdge = _a[_i];
22612 arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano"));
22614 for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) {
22615 var stepEdge = _c[_b];
22616 arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
22620 DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) {
22621 var threshold = Math.PI / 8;
22622 var relativePhi = rotation.phi;
22623 switch (direction) {
22624 case Edge_1.EdgeDirection.StepBackward:
22625 relativePhi = rotation.phi - Math.PI;
22627 case Edge_1.EdgeDirection.StepLeft:
22628 relativePhi = rotation.phi + Math.PI / 2;
22630 case Edge_1.EdgeDirection.StepRight:
22631 relativePhi = rotation.phi - Math.PI / 2;
22636 if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) {
22637 return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep");
22639 return this._createVNodeDisabled(key, azimuth, rotation);
22641 DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) {
22643 for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
22644 var panoEdge = _a[_i];
22645 arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true));
22649 DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) {
22651 for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) {
22652 var stepEdge = _a[_i];
22653 arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
22657 DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) {
22659 for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) {
22660 var turnEdge = _a[_i];
22661 var direction = turnEdge.data.direction;
22662 var name_1 = this._turnNames[direction];
22663 turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction));
22667 DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) {
22668 var onClick = function (e) {
22669 navigator.moveToKey$(key)
22670 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22672 return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically);
22674 DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) {
22675 var onClick = function (e) {
22676 navigator.moveDir$(direction)
22677 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22679 return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick);
22681 DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) {
22682 var onClick = function (e) {
22683 navigator.moveDir$(direction)
22684 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22687 height: this._calculator.turnCircleSizeCss,
22688 transform: "rotate(0)",
22689 width: this._calculator.turnCircleSizeCss,
22691 switch (direction) {
22692 case Edge_1.EdgeDirection.TurnLeft:
22693 style.left = "5px";
22696 case Edge_1.EdgeDirection.TurnRight:
22697 style.right = "5px";
22700 case Edge_1.EdgeDirection.TurnU:
22701 style.left = "5px";
22702 style.bottom = "5px";
22707 var circleProperties = {
22714 var circleClassName = "TurnCircle";
22715 if (this._sequenceEdgeKeys.indexOf(key) > -1) {
22716 circleClassName += "Sequence";
22718 if (this._highlightKey === key) {
22719 circleClassName += "Highlight";
22721 var turn = vd.h("div." + className, {}, []);
22722 return vd.h("div." + circleClassName, circleProperties, [turn]);
22724 DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) {
22725 return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled");
22727 DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) {
22728 var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi);
22729 // rotate 90 degrees clockwise and flip over X-axis
22730 var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth);
22731 var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight);
22732 var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi);
22733 var shadowOffset = this._calculator.shadowOffset;
22734 var shadowTranslationX = -shadowOffset * shadowTranslation[1];
22735 var shadowTranslationY = shadowOffset * shadowTranslation[0];
22736 var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))";
22739 "-webkit-filter": filter,
22743 var chevron = vd.h("div." + className, properties, []);
22744 var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi);
22745 var circleTransform = shiftVertically ?
22746 "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" :
22747 "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)";
22748 var circleProperties = {
22749 attributes: { "data-key": key },
22752 height: this._calculator.stepCircleSizeCss,
22753 marginLeft: this._calculator.stepCircleMarginCss,
22754 marginTop: this._calculator.stepCircleMarginCss,
22755 transform: circleTransform,
22756 width: this._calculator.stepCircleSizeCss,
22759 if (this._sequenceEdgeKeys.indexOf(key) > -1) {
22760 circleClassName += "Sequence";
22762 if (this._highlightKey === key) {
22763 circleClassName += "Highlight";
22765 return vd.h("div." + circleClassName, circleProperties, [chevron]);
22767 DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) {
22768 // edge does not handle hover on perspective transforms.
22769 var transform = this._isEdge ?
22771 "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)";
22773 oncontextmenu: function (event) { event.preventDefault(); },
22775 bottom: this._calculator.containerBottomCss,
22776 height: this._calculator.containerHeightCss,
22777 left: this._calculator.containerLeftCss,
22778 marginLeft: this._calculator.containerMarginCss,
22779 transform: transform,
22780 width: this._calculator.containerWidthCss,
22783 return vd.h("div.DirectionsPerspective", properties, turns.concat(steps));
22785 return DirectionDOMRenderer;
22787 exports.DirectionDOMRenderer = DirectionDOMRenderer;
22788 exports.default = DirectionDOMRenderer;
22790 },{"../../Component":226,"../../Edge":227,"../../Geo":229,"virtual-dom":182}],256:[function(require,module,exports){
22792 var __extends = (this && this.__extends) || (function () {
22793 var extendStatics = Object.setPrototypeOf ||
22794 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22795 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22796 return function (d, b) {
22797 extendStatics(d, b);
22798 function __() { this.constructor = d; }
22799 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22802 Object.defineProperty(exports, "__esModule", { value: true });
22803 var Observable_1 = require("rxjs/Observable");
22804 var Subject_1 = require("rxjs/Subject");
22805 require("rxjs/add/operator/catch");
22806 require("rxjs/add/operator/combineLatest");
22807 require("rxjs/add/operator/debounceTime");
22808 require("rxjs/add/operator/distinctUntilChanged");
22809 require("rxjs/add/operator/filter");
22810 require("rxjs/add/operator/map");
22811 require("rxjs/add/operator/pairwise");
22812 require("rxjs/add/operator/publish");
22813 require("rxjs/add/operator/publishReplay");
22814 require("rxjs/add/operator/scan");
22815 require("rxjs/add/operator/skipWhile");
22816 require("rxjs/add/operator/startWith");
22817 require("rxjs/add/operator/switchMap");
22818 require("rxjs/add/operator/takeUntil");
22819 require("rxjs/add/operator/withLatestFrom");
22820 var Component_1 = require("../../Component");
22821 var Render_1 = require("../../Render");
22822 var Tiles_1 = require("../../Tiles");
22823 var Utils_1 = require("../../Utils");
22824 var ImagePlaneComponent = (function (_super) {
22825 __extends(ImagePlaneComponent, _super);
22826 function ImagePlaneComponent(name, container, navigator) {
22827 var _this = _super.call(this, name, container, navigator) || this;
22828 _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
22829 _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
22830 _this._rendererOperation$ = new Subject_1.Subject();
22831 _this._rendererCreator$ = new Subject_1.Subject();
22832 _this._rendererDisposer$ = new Subject_1.Subject();
22833 _this._renderer$ = _this._rendererOperation$
22834 .scan(function (renderer, operation) {
22835 return operation(renderer);
22837 .filter(function (renderer) {
22838 return renderer != null;
22840 .distinctUntilChanged(undefined, function (renderer) {
22841 return renderer.frameId;
22843 _this._rendererCreator$
22845 return function (renderer) {
22846 if (renderer != null) {
22847 throw new Error("Multiple image plane states can not be created at the same time");
22849 return new Component_1.ImagePlaneGLRenderer();
22852 .subscribe(_this._rendererOperation$);
22853 _this._rendererDisposer$
22855 return function (renderer) {
22856 renderer.dispose();
22860 .subscribe(_this._rendererOperation$);
22863 ImagePlaneComponent.prototype._activate = function () {
22865 this._rendererSubscription = this._renderer$
22866 .map(function (renderer) {
22870 frameId: renderer.frameId,
22871 needsRender: renderer.needsRender,
22872 render: renderer.render.bind(renderer),
22873 stage: Render_1.GLRenderStage.Background,
22876 renderer.clearNeedsRender();
22879 .subscribe(this._container.glRenderer.render$);
22880 this._rendererCreator$.next(null);
22881 this._stateSubscription = this._navigator.stateService.currentState$
22882 .map(function (frame) {
22883 return function (renderer) {
22884 renderer.updateFrame(frame);
22888 .subscribe(this._rendererOperation$);
22889 var textureProvider$ = this._navigator.stateService.currentState$
22890 .distinctUntilChanged(undefined, function (frame) {
22891 return frame.state.currentNode.key;
22893 .combineLatest(this._configuration$)
22894 .filter(function (args) {
22895 return args[1].imageTiling === true;
22897 .map(function (args) {
22900 .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$)
22901 .map(function (args) {
22902 var state = args[0].state;
22903 var renderer = args[1];
22904 var viewportSize = args[2];
22905 var currentNode = state.currentNode;
22906 var currentTransform = state.currentTransform;
22907 var tileSize = Math.max(viewportSize.width, viewportSize.height) > 1024 ? 1024 : 512;
22908 return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
22912 this._textureProviderSubscription = textureProvider$.subscribe(function () { });
22913 this._setTextureProviderSubscription = textureProvider$
22914 .map(function (provider) {
22915 return function (renderer) {
22916 renderer.setTextureProvider(provider.key, provider);
22920 .subscribe(this._rendererOperation$);
22921 this._abortTextureProviderSubscription = textureProvider$
22923 .subscribe(function (pair) {
22924 var previous = pair[0];
22927 var roiTrigger$ = this._container.renderService.renderCameraFrame$
22928 .map(function (renderCamera) {
22930 renderCamera.camera.position.clone(),
22931 renderCamera.camera.lookat.clone(),
22932 renderCamera.zoom.valueOf()
22936 .skipWhile(function (pls) {
22937 return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
22939 .map(function (pls) {
22940 var samePosition = pls[0][0].equals(pls[1][0]);
22941 var sameLookat = pls[0][1].equals(pls[1][1]);
22942 var sameZoom = pls[0][2] === pls[1][2];
22943 return samePosition && sameLookat && sameZoom;
22945 .distinctUntilChanged()
22946 .filter(function (stalled) {
22949 .switchMap(function (stalled) {
22950 return _this._container.renderService.renderCameraFrame$
22953 .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$);
22954 this._setRegionOfInterestSubscription = textureProvider$
22955 .switchMap(function (provider) {
22957 .map(function (args) {
22959 _this._roiCalculator.computeRegionOfInterest(args[0], args[1], args[2]),
22964 .filter(function (args) {
22965 return !args[1].disposed;
22967 .subscribe(function (args) {
22969 var provider = args[1];
22970 provider.setRegionOfInterest(roi);
22972 var hasTexture$ = textureProvider$
22973 .switchMap(function (provider) {
22974 return provider.hasTexture$;
22979 this._hasTextureSubscription = hasTexture$.subscribe(function () { });
22980 var nodeImage$ = this._navigator.stateService.currentNode$
22981 .debounceTime(1000)
22982 .withLatestFrom(hasTexture$)
22983 .filter(function (args) {
22986 .map(function (args) {
22989 .filter(function (node) {
22991 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
22992 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
22994 .switchMap(function (node) {
22995 var baseImageSize = node.pano ?
22996 Utils_1.Settings.basePanoramaSize :
22997 Utils_1.Settings.baseImageSize;
22998 if (Math.max(node.image.width, node.image.height) > baseImageSize) {
22999 return Observable_1.Observable.empty();
23002 .cacheImage$(Utils_1.Settings.maxImageSize)
23003 .map(function (n) {
23004 return [n.image, n];
23007 .takeUntil(hasTexture$
23008 .filter(function (hasTexture) {
23011 .catch(function (error, caught) {
23012 console.error("Failed to fetch high res image (" + node.key + ")", error);
23013 return Observable_1.Observable.empty();
23018 this._updateBackgroundSubscription = nodeImage$
23019 .withLatestFrom(textureProvider$)
23020 .subscribe(function (args) {
23021 if (args[0][1].key !== args[1].key ||
23022 args[1].disposed) {
23025 args[1].updateBackground(args[0][0]);
23027 this._updateTextureImageSubscription = nodeImage$
23028 .map(function (imn) {
23029 return function (renderer) {
23030 renderer.updateTextureImage(imn[0], imn[1]);
23034 .subscribe(this._rendererOperation$);
23036 ImagePlaneComponent.prototype._deactivate = function () {
23037 this._rendererDisposer$.next(null);
23038 this._abortTextureProviderSubscription.unsubscribe();
23039 this._hasTextureSubscription.unsubscribe();
23040 this._rendererSubscription.unsubscribe();
23041 this._setRegionOfInterestSubscription.unsubscribe();
23042 this._setTextureProviderSubscription.unsubscribe();
23043 this._stateSubscription.unsubscribe();
23044 this._textureProviderSubscription.unsubscribe();
23045 this._updateBackgroundSubscription.unsubscribe();
23046 this._updateTextureImageSubscription.unsubscribe();
23048 ImagePlaneComponent.prototype._getDefaultConfiguration = function () {
23049 return { imageTiling: false };
23051 return ImagePlaneComponent;
23052 }(Component_1.Component));
23053 ImagePlaneComponent.componentName = "imagePlane";
23054 exports.ImagePlaneComponent = ImagePlaneComponent;
23055 Component_1.ComponentService.register(ImagePlaneComponent);
23056 exports.default = ImagePlaneComponent;
23058 },{"../../Component":226,"../../Render":232,"../../Tiles":234,"../../Utils":235,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/operator/catch":52,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/debounceTime":55,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/pairwise":69,"rxjs/add/operator/publish":71,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73,"rxjs/add/operator/skipWhile":77,"rxjs/add/operator/startWith":78,"rxjs/add/operator/switchMap":79,"rxjs/add/operator/takeUntil":81,"rxjs/add/operator/withLatestFrom":83}],257:[function(require,module,exports){
23060 /// <reference path="../../../typings/index.d.ts" />
23061 Object.defineProperty(exports, "__esModule", { value: true });
23062 var THREE = require("three");
23063 var Component_1 = require("../../Component");
23064 var ImagePlaneFactory = (function () {
23065 function ImagePlaneFactory(imagePlaneDepth, imageSphereRadius) {
23066 this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200;
23067 this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200;
23069 ImagePlaneFactory.prototype.createMesh = function (node, transform) {
23070 var mesh = node.pano ?
23071 this._createImageSphere(node, transform) :
23072 this._createImagePlane(node, transform);
23075 ImagePlaneFactory.prototype._createImageSphere = function (node, transform) {
23076 var texture = this._createTexture(node.image);
23077 var materialParameters = this._createSphereMaterialParameters(transform, texture);
23078 var material = new THREE.ShaderMaterial(materialParameters);
23079 var mesh = this._useMesh(transform, node) ?
23080 new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
23081 new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
23084 ImagePlaneFactory.prototype._createImagePlane = function (node, transform) {
23085 var texture = this._createTexture(node.image);
23086 var materialParameters = this._createPlaneMaterialParameters(transform, texture);
23087 var material = new THREE.ShaderMaterial(materialParameters);
23088 var geometry = this._useMesh(transform, node) ?
23089 this._getImagePlaneGeo(transform, node) :
23090 this._getFlatImagePlaneGeo(transform);
23091 return new THREE.Mesh(geometry, material);
23093 ImagePlaneFactory.prototype._createSphereMaterialParameters = function (transform, texture) {
23094 var gpano = transform.gpano;
23095 var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
23096 var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
23097 var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
23098 var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
23099 var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
23100 var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
23101 var materialParameters = {
23103 fragmentShader: Component_1.ImagePlaneShaders.equirectangular.fragment,
23104 side: THREE.DoubleSide,
23121 value: transform.rt,
23129 value: thetaLength,
23136 vertexShader: Component_1.ImagePlaneShaders.equirectangular.vertex,
23138 return materialParameters;
23140 ImagePlaneFactory.prototype._createPlaneMaterialParameters = function (transform, texture) {
23141 var materialParameters = {
23143 fragmentShader: Component_1.ImagePlaneShaders.perspective.fragment,
23144 side: THREE.DoubleSide,
23149 value: new THREE.Vector4(0, 0, 1, 1),
23157 value: transform.projectorMatrix(),
23164 vertexShader: Component_1.ImagePlaneShaders.perspective.vertex,
23166 return materialParameters;
23168 ImagePlaneFactory.prototype._createTexture = function (image) {
23169 var texture = new THREE.Texture(image);
23170 texture.minFilter = THREE.LinearFilter;
23171 texture.needsUpdate = true;
23174 ImagePlaneFactory.prototype._useMesh = function (transform, node) {
23175 return node.mesh.vertices.length && transform.hasValidScale;
23177 ImagePlaneFactory.prototype._getImageSphereGeo = function (transform, node) {
23178 var t = new THREE.Matrix4().getInverse(transform.srt);
23179 // push everything at least 5 meters in front of the camera
23180 var minZ = 5.0 * transform.scale;
23181 var maxZ = this._imageSphereRadius * transform.scale;
23182 var vertices = node.mesh.vertices;
23183 var numVertices = vertices.length / 3;
23184 var positions = new Float32Array(vertices.length);
23185 for (var i = 0; i < numVertices; ++i) {
23187 var x = vertices[index + 0];
23188 var y = vertices[index + 1];
23189 var z = vertices[index + 2];
23190 var l = Math.sqrt(x * x + y * y + z * z);
23191 var boundedL = Math.max(minZ, Math.min(l, maxZ));
23192 var factor = boundedL / l;
23193 var p = new THREE.Vector3(x * factor, y * factor, z * factor);
23195 positions[index + 0] = p.x;
23196 positions[index + 1] = p.y;
23197 positions[index + 2] = p.z;
23199 var faces = node.mesh.faces;
23200 var indices = new Uint16Array(faces.length);
23201 for (var i = 0; i < faces.length; ++i) {
23202 indices[i] = faces[i];
23204 var geometry = new THREE.BufferGeometry();
23205 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
23206 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
23209 ImagePlaneFactory.prototype._getImagePlaneGeo = function (transform, node) {
23210 var t = new THREE.Matrix4().getInverse(transform.srt);
23211 // push everything at least 5 meters in front of the camera
23212 var minZ = 5.0 * transform.scale;
23213 var maxZ = this._imagePlaneDepth * transform.scale;
23214 var vertices = node.mesh.vertices;
23215 var numVertices = vertices.length / 3;
23216 var positions = new Float32Array(vertices.length);
23217 for (var i = 0; i < numVertices; ++i) {
23219 var x = vertices[index + 0];
23220 var y = vertices[index + 1];
23221 var z = vertices[index + 2];
23222 var boundedZ = Math.max(minZ, Math.min(z, maxZ));
23223 var factor = boundedZ / z;
23224 var p = new THREE.Vector3(x * factor, y * factor, boundedZ);
23226 positions[index + 0] = p.x;
23227 positions[index + 1] = p.y;
23228 positions[index + 2] = p.z;
23230 var faces = node.mesh.faces;
23231 var indices = new Uint16Array(faces.length);
23232 for (var i = 0; i < faces.length; ++i) {
23233 indices[i] = faces[i];
23235 var geometry = new THREE.BufferGeometry();
23236 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
23237 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
23240 ImagePlaneFactory.prototype._getFlatImageSphereGeo = function (transform) {
23241 var gpano = transform.gpano;
23242 var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels;
23243 var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
23244 var thetaStart = Math.PI *
23245 (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) /
23246 gpano.FullPanoHeightPixels;
23247 var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
23248 var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength);
23249 geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt));
23252 ImagePlaneFactory.prototype._getFlatImagePlaneGeo = function (transform) {
23253 var width = transform.width;
23254 var height = transform.height;
23255 var size = Math.max(width, height);
23256 var dx = width / 2.0 / size;
23257 var dy = height / 2.0 / size;
23259 vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
23260 vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
23261 vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
23262 vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
23263 var positions = new Float32Array(12);
23264 for (var i = 0; i < vertices.length; i++) {
23266 positions[index + 0] = vertices[i][0];
23267 positions[index + 1] = vertices[i][1];
23268 positions[index + 2] = vertices[i][2];
23270 var indices = new Uint16Array(6);
23277 var geometry = new THREE.BufferGeometry();
23278 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
23279 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
23282 return ImagePlaneFactory;
23284 exports.ImagePlaneFactory = ImagePlaneFactory;
23285 exports.default = ImagePlaneFactory;
23287 },{"../../Component":226,"three":176}],258:[function(require,module,exports){
23289 /// <reference path="../../../typings/index.d.ts" />
23290 Object.defineProperty(exports, "__esModule", { value: true });
23291 var Component_1 = require("../../Component");
23292 var Geo_1 = require("../../Geo");
23293 var ImagePlaneGLRenderer = (function () {
23294 function ImagePlaneGLRenderer() {
23295 this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
23296 this._imagePlaneScene = new Component_1.ImagePlaneScene();
23298 this._alphaOld = 0;
23299 this._fadeOutSpeed = 0.05;
23300 this._lastCamera = new Geo_1.Camera();
23301 this._epsilon = 0.000001;
23302 this._currentKey = null;
23303 this._previousKey = null;
23304 this._providerDisposers = {};
23306 this._needsRender = false;
23308 Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", {
23310 return this._frameId;
23315 Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", {
23317 return this._needsRender;
23322 ImagePlaneGLRenderer.prototype.indicateNeedsRender = function () {
23323 this._needsRender = true;
23325 ImagePlaneGLRenderer.prototype.updateFrame = function (frame) {
23326 this._updateFrameId(frame.id);
23327 this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender;
23328 this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender;
23329 this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender;
23331 ImagePlaneGLRenderer.prototype.setTextureProvider = function (key, provider) {
23333 if (key !== this._currentKey) {
23336 var createdSubscription = provider.textureCreated$
23337 .subscribe(function (texture) {
23338 _this._updateTexture(texture);
23340 var updatedSubscription = provider.textureUpdated$
23341 .subscribe(function (updated) {
23342 _this._needsRender = true;
23344 var dispose = function () {
23345 createdSubscription.unsubscribe();
23346 updatedSubscription.unsubscribe();
23347 provider.dispose();
23349 if (key in this._providerDisposers) {
23350 var disposeProvider = this._providerDisposers[key];
23352 delete this._providerDisposers[key];
23354 this._providerDisposers[key] = dispose;
23356 ImagePlaneGLRenderer.prototype._updateTexture = function (texture) {
23357 this._needsRender = true;
23358 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23359 var plane = _a[_i];
23360 var material = plane.material;
23361 var oldTexture = material.uniforms.projectorTex.value;
23362 material.uniforms.projectorTex.value = null;
23363 oldTexture.dispose();
23364 material.uniforms.projectorTex.value = texture;
23367 ImagePlaneGLRenderer.prototype.updateTextureImage = function (image, node) {
23368 if (this._currentKey !== node.key) {
23371 this._needsRender = true;
23372 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23373 var plane = _a[_i];
23374 var material = plane.material;
23375 var texture = material.uniforms.projectorTex.value;
23376 texture.image = image;
23377 texture.needsUpdate = true;
23380 ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
23381 var planeAlpha = this._imagePlaneScene.imagePlanesOld.length ? 1 : this._alpha;
23382 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23383 var plane = _a[_i];
23384 plane.material.uniforms.opacity.value = planeAlpha;
23386 for (var _b = 0, _c = this._imagePlaneScene.imagePlanesOld; _b < _c.length; _b++) {
23387 var plane = _c[_b];
23388 plane.material.uniforms.opacity.value = this._alphaOld;
23390 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23391 renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
23392 for (var _d = 0, _e = this._imagePlaneScene.imagePlanes; _d < _e.length; _d++) {
23393 var plane = _e[_d];
23394 plane.material.uniforms.opacity.value = this._alpha;
23396 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23398 ImagePlaneGLRenderer.prototype.clearNeedsRender = function () {
23399 this._needsRender = false;
23401 ImagePlaneGLRenderer.prototype.dispose = function () {
23402 this._imagePlaneScene.clear();
23404 ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) {
23405 this._frameId = frameId;
23407 ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) {
23408 if (alpha === this._alpha) {
23411 this._alpha = alpha;
23414 ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) {
23415 if (alpha < 1 || this._alphaOld === 0) {
23418 this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed);
23421 ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) {
23422 if (state.currentNode == null || state.currentNode.key === this._currentKey) {
23425 var previousKey = state.previousNode != null ? state.previousNode.key : null;
23426 var currentKey = state.currentNode.key;
23427 if (this._previousKey !== previousKey &&
23428 this._previousKey !== currentKey &&
23429 this._previousKey in this._providerDisposers) {
23430 var disposeProvider = this._providerDisposers[this._previousKey];
23432 delete this._providerDisposers[this._previousKey];
23434 if (previousKey != null) {
23435 if (previousKey !== this._currentKey && previousKey !== this._previousKey) {
23436 var previousMesh = this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform);
23437 this._imagePlaneScene.updateImagePlanes([previousMesh]);
23439 this._previousKey = previousKey;
23441 this._currentKey = currentKey;
23442 var currentMesh = this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform);
23443 this._imagePlaneScene.updateImagePlanes([currentMesh]);
23444 this._alphaOld = 1;
23447 return ImagePlaneGLRenderer;
23449 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer;
23450 exports.default = ImagePlaneGLRenderer;
23452 },{"../../Component":226,"../../Geo":229}],259:[function(require,module,exports){
23454 /// <reference path="../../../typings/index.d.ts" />
23455 Object.defineProperty(exports, "__esModule", { value: true });
23456 var THREE = require("three");
23457 var ImagePlaneScene = (function () {
23458 function ImagePlaneScene() {
23459 this.scene = new THREE.Scene();
23460 this.sceneOld = new THREE.Scene();
23461 this.imagePlanes = [];
23462 this.imagePlanesOld = [];
23464 ImagePlaneScene.prototype.updateImagePlanes = function (planes) {
23465 this._dispose(this.imagePlanesOld, this.sceneOld);
23466 for (var _i = 0, _a = this.imagePlanes; _i < _a.length; _i++) {
23467 var plane = _a[_i];
23468 this.scene.remove(plane);
23469 this.sceneOld.add(plane);
23471 for (var _b = 0, planes_1 = planes; _b < planes_1.length; _b++) {
23472 var plane = planes_1[_b];
23473 this.scene.add(plane);
23475 this.imagePlanesOld = this.imagePlanes;
23476 this.imagePlanes = planes;
23478 ImagePlaneScene.prototype.addImagePlanes = function (planes) {
23479 for (var _i = 0, planes_2 = planes; _i < planes_2.length; _i++) {
23480 var plane = planes_2[_i];
23481 this.scene.add(plane);
23482 this.imagePlanes.push(plane);
23485 ImagePlaneScene.prototype.addImagePlanesOld = function (planes) {
23486 for (var _i = 0, planes_3 = planes; _i < planes_3.length; _i++) {
23487 var plane = planes_3[_i];
23488 this.sceneOld.add(plane);
23489 this.imagePlanesOld.push(plane);
23492 ImagePlaneScene.prototype.setImagePlanes = function (planes) {
23494 this.addImagePlanes(planes);
23496 ImagePlaneScene.prototype.setImagePlanesOld = function (planes) {
23498 this.addImagePlanesOld(planes);
23500 ImagePlaneScene.prototype.clear = function () {
23504 ImagePlaneScene.prototype._clear = function () {
23505 this._dispose(this.imagePlanes, this.scene);
23506 this.imagePlanes.length = 0;
23508 ImagePlaneScene.prototype._clearOld = function () {
23509 this._dispose(this.imagePlanesOld, this.sceneOld);
23510 this.imagePlanesOld.length = 0;
23512 ImagePlaneScene.prototype._dispose = function (planes, scene) {
23513 for (var _i = 0, planes_4 = planes; _i < planes_4.length; _i++) {
23514 var plane = planes_4[_i];
23515 scene.remove(plane);
23516 plane.geometry.dispose();
23517 plane.material.dispose();
23518 var texture = plane.material.uniforms.projectorTex.value;
23519 if (texture != null) {
23524 return ImagePlaneScene;
23526 exports.ImagePlaneScene = ImagePlaneScene;
23527 exports.default = ImagePlaneScene;
23529 },{"three":176}],260:[function(require,module,exports){
23531 /// <reference path="../../../typings/index.d.ts" />
23532 Object.defineProperty(exports, "__esModule", { value: true });
23534 var path = require("path");
23535 var ImagePlaneShaders = (function () {
23536 function ImagePlaneShaders() {
23538 return ImagePlaneShaders;
23540 ImagePlaneShaders.equirectangular = {
23541 fragment: "#ifdef GL_ES\nprecision highp 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}",
23542 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}",
23544 ImagePlaneShaders.perspective = {
23545 fragment: "#ifdef GL_ES\nprecision highp 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;\n if (x > bbox[0] && y > bbox[1] && x < bbox[2] && y < bbox[3]) {\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}",
23546 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}",
23548 exports.ImagePlaneShaders = ImagePlaneShaders;
23550 },{"path":22}],261:[function(require,module,exports){
23552 /// <reference path="../../../typings/index.d.ts" />
23553 var __extends = (this && this.__extends) || (function () {
23554 var extendStatics = Object.setPrototypeOf ||
23555 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23556 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23557 return function (d, b) {
23558 extendStatics(d, b);
23559 function __() { this.constructor = d; }
23560 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23563 Object.defineProperty(exports, "__esModule", { value: true });
23564 var Observable_1 = require("rxjs/Observable");
23565 var Subject_1 = require("rxjs/Subject");
23566 require("rxjs/add/observable/combineLatest");
23567 require("rxjs/add/observable/fromEvent");
23568 require("rxjs/add/observable/of");
23569 require("rxjs/add/observable/zip");
23570 require("rxjs/add/operator/distinctUntilChanged");
23571 require("rxjs/add/operator/filter");
23572 require("rxjs/add/operator/first");
23573 require("rxjs/add/operator/map");
23574 require("rxjs/add/operator/merge");
23575 require("rxjs/add/operator/mergeMap");
23576 require("rxjs/add/operator/scan");
23577 require("rxjs/add/operator/switchMap");
23578 require("rxjs/add/operator/withLatestFrom");
23579 require("rxjs/add/operator/zip");
23580 var State_1 = require("../../State");
23581 var Render_1 = require("../../Render");
23582 var Utils_1 = require("../../Utils");
23583 var Component_1 = require("../../Component");
23584 var SliderState = (function () {
23585 function SliderState() {
23586 this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
23587 this._imagePlaneScene = new Component_1.ImagePlaneScene();
23588 this._currentKey = null;
23589 this._previousKey = null;
23590 this._currentPano = false;
23592 this._glNeedsRender = false;
23593 this._domNeedsRender = true;
23596 Object.defineProperty(SliderState.prototype, "frameId", {
23598 return this._frameId;
23603 Object.defineProperty(SliderState.prototype, "curtain", {
23605 return this._curtain;
23610 Object.defineProperty(SliderState.prototype, "glNeedsRender", {
23612 return this._glNeedsRender;
23617 Object.defineProperty(SliderState.prototype, "domNeedsRender", {
23619 return this._domNeedsRender;
23624 Object.defineProperty(SliderState.prototype, "sliderVisible", {
23626 return this._sliderVisible;
23628 set: function (value) {
23629 this._sliderVisible = value;
23630 this._domNeedsRender = true;
23635 Object.defineProperty(SliderState.prototype, "disabled", {
23637 return this._currentKey == null ||
23638 this._previousKey == null ||
23644 SliderState.prototype.update = function (frame) {
23645 this._updateFrameId(frame.id);
23646 var needsRender = this._updateImagePlanes(frame.state);
23647 this._domNeedsRender = needsRender || this._domNeedsRender;
23648 needsRender = this._updateCurtain(frame.state.alpha) || needsRender;
23649 this._glNeedsRender = needsRender || this._glNeedsRender;
23651 SliderState.prototype.updateTexture = function (image, node) {
23652 var imagePlanes = node.key === this._currentKey ?
23653 this._imagePlaneScene.imagePlanes :
23654 node.key === this._previousKey ?
23655 this._imagePlaneScene.imagePlanesOld :
23657 if (imagePlanes.length === 0) {
23660 this._glNeedsRender = true;
23661 for (var _i = 0, imagePlanes_1 = imagePlanes; _i < imagePlanes_1.length; _i++) {
23662 var plane = imagePlanes_1[_i];
23663 var material = plane.material;
23664 var texture = material.uniforms.projectorTex.value;
23665 texture.image = image;
23666 texture.needsUpdate = true;
23669 SliderState.prototype.render = function (perspectiveCamera, renderer) {
23670 if (!this.disabled) {
23671 renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
23673 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23675 SliderState.prototype.dispose = function () {
23676 this._imagePlaneScene.clear();
23678 SliderState.prototype.clearGLNeedsRender = function () {
23679 this._glNeedsRender = false;
23681 SliderState.prototype.clearDomNeedsRender = function () {
23682 this._domNeedsRender = false;
23684 SliderState.prototype._updateFrameId = function (frameId) {
23685 this._frameId = frameId;
23687 SliderState.prototype._updateImagePlanes = function (state) {
23688 if (state.currentNode == null) {
23691 var needsRender = false;
23692 if (state.previousNode != null && this._previousKey !== state.previousNode.key) {
23693 needsRender = true;
23694 this._previousKey = state.previousNode.key;
23695 this._imagePlaneScene.setImagePlanesOld([
23696 this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform),
23699 if (this._currentKey !== state.currentNode.key) {
23700 needsRender = true;
23701 this._currentKey = state.currentNode.key;
23702 this._currentPano = state.currentNode.pano;
23703 this._imagePlaneScene.setImagePlanes([
23704 this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform),
23706 if (!this.disabled) {
23707 this._updateBbox();
23710 return needsRender;
23712 SliderState.prototype._updateCurtain = function (alpha) {
23713 if (this.disabled ||
23714 Math.abs(this._curtain - alpha) < 0.001) {
23717 this._curtain = alpha;
23718 this._updateBbox();
23721 SliderState.prototype._updateBbox = function () {
23722 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23723 var plane = _a[_i];
23724 var shaderMaterial = plane.material;
23725 var bbox = shaderMaterial.uniforms.bbox.value;
23726 bbox.z = this._curtain;
23729 return SliderState;
23731 var SliderComponent = (function (_super) {
23732 __extends(SliderComponent, _super);
23734 * Create a new slider component instance.
23735 * @class SliderComponent
23737 function SliderComponent(name, container, navigator) {
23738 var _this = _super.call(this, name, container, navigator) || this;
23739 _this._sliderStateOperation$ = new Subject_1.Subject();
23740 _this._sliderStateCreator$ = new Subject_1.Subject();
23741 _this._sliderStateDisposer$ = new Subject_1.Subject();
23742 _this._sliderState$ = _this._sliderStateOperation$
23743 .scan(function (sliderState, operation) {
23744 return operation(sliderState);
23746 .filter(function (sliderState) {
23747 return sliderState != null;
23749 .distinctUntilChanged(undefined, function (sliderState) {
23750 return sliderState.frameId;
23752 _this._sliderStateCreator$
23754 return function (sliderState) {
23755 if (sliderState != null) {
23756 throw new Error("Multiple slider states can not be created at the same time");
23758 return new SliderState();
23761 .subscribe(_this._sliderStateOperation$);
23762 _this._sliderStateDisposer$
23764 return function (sliderState) {
23765 sliderState.dispose();
23769 .subscribe(_this._sliderStateOperation$);
23773 * Set the image keys.
23775 * Configures the component to show the image planes for the supplied image keys.
23777 * @param {keys} ISliderKeys - Slider keys object specifying the images to be shown in the foreground and the background.
23779 SliderComponent.prototype.setKeys = function (keys) {
23780 this.configure({ keys: keys });
23783 * Set the initial position.
23785 * Configures the intial position of the slider. The inital position value will be used when the component is activated.
23787 * @param {number} initialPosition - Initial slider position.
23789 SliderComponent.prototype.setInitialPosition = function (initialPosition) {
23790 this.configure({ initialPosition: initialPosition });
23793 * Set the value controlling if the slider is visible.
23795 * @param {boolean} sliderVisible - Value indicating if the slider should be visible or not.
23797 SliderComponent.prototype.setSliderVisible = function (sliderVisible) {
23798 this.configure({ sliderVisible: sliderVisible });
23800 SliderComponent.prototype._activate = function () {
23802 this._sliderContainer = this._createElement("div", "mapillary-js-slider-container", this._container.element);
23803 this._sliderWrapper = this._createElement("div", "SliderWrapper", this._sliderContainer);
23804 this._sliderControl = this._createElement("input", "SliderControl", this._sliderWrapper);
23805 this._sliderControl.setAttribute("type", "range");
23806 this._sliderControl.setAttribute("min", "0");
23807 this._sliderControl.setAttribute("max", "1000");
23808 this._sliderControl.style.visibility = "hidden";
23809 this._moveToHandler = function (e) {
23810 var curtain = Number(e.target.value) / 1000;
23811 _this._navigator.stateService.moveTo(curtain);
23813 this._sliderControl.addEventListener("input", this._moveToHandler);
23814 this._sliderControl.addEventListener("change", this._moveToHandler);
23815 Observable_1.Observable
23816 .combineLatest(this._navigator.stateService.state$, this._configuration$)
23818 .subscribe(function (_a) {
23819 var state = _a[0], configuration = _a[1];
23820 if (state === State_1.State.Traversing) {
23821 _this._navigator.stateService.wait();
23822 var position = configuration.initialPosition != null ? configuration.initialPosition : 1;
23823 _this._sliderControl.value = (1000 * position).toString();
23824 _this._navigator.stateService.moveTo(position);
23827 this._glRenderSubscription = this._sliderState$
23828 .map(function (sliderState) {
23832 frameId: sliderState.frameId,
23833 needsRender: sliderState.glNeedsRender,
23834 render: sliderState.render.bind(sliderState),
23835 stage: Render_1.GLRenderStage.Background,
23838 sliderState.clearGLNeedsRender();
23841 .subscribe(this._container.glRenderer.render$);
23842 this._domRenderSubscription = this._sliderState$
23843 .filter(function (sliderState) {
23844 return sliderState.domNeedsRender;
23846 .subscribe(function (sliderState) {
23847 _this._sliderControl.value = (1000 * sliderState.curtain).toString();
23848 var visibility = sliderState.disabled || !sliderState.sliderVisible ? "hidden" : "visible";
23849 _this._sliderControl.style.visibility = visibility;
23850 sliderState.clearDomNeedsRender();
23852 this._sliderStateCreator$.next(null);
23853 this._stateSubscription = this._navigator.stateService.currentState$
23854 .map(function (frame) {
23855 return function (sliderState) {
23856 sliderState.update(frame);
23857 return sliderState;
23860 .subscribe(this._sliderStateOperation$);
23861 this._setSliderVisibleSubscription = this._configuration$
23862 .map(function (configuration) {
23863 return configuration.sliderVisible == null || configuration.sliderVisible;
23865 .distinctUntilChanged()
23866 .map(function (sliderVisible) {
23867 return function (sliderState) {
23868 sliderState.sliderVisible = sliderVisible;
23869 return sliderState;
23872 .subscribe(this._sliderStateOperation$);
23873 this._setKeysSubscription = this._configuration$
23874 .filter(function (configuration) {
23875 return configuration.keys != null;
23877 .switchMap(function (configuration) {
23878 return Observable_1.Observable
23879 .zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground))
23880 .map(function (nodes) {
23881 return { background: nodes[0], foreground: nodes[1] };
23883 .zip(_this._navigator.stateService.currentState$.first())
23884 .map(function (nf) {
23885 return { nodes: nf[0], state: nf[1].state };
23888 .subscribe(function (co) {
23889 if (co.state.currentNode != null &&
23890 co.state.previousNode != null &&
23891 co.state.currentNode.key === co.nodes.foreground.key &&
23892 co.state.previousNode.key === co.nodes.background.key) {
23895 if (co.state.currentNode.key === co.nodes.background.key) {
23896 _this._navigator.stateService.setNodes([co.nodes.foreground]);
23899 if (co.state.currentNode.key === co.nodes.foreground.key &&
23900 co.state.trajectory.length === 1) {
23901 _this._navigator.stateService.prependNodes([co.nodes.background]);
23904 _this._navigator.stateService.setNodes([co.nodes.background]);
23905 _this._navigator.stateService.setNodes([co.nodes.foreground]);
23909 var previousNode$ = this._navigator.stateService.currentState$
23910 .map(function (frame) {
23911 return frame.state.previousNode;
23913 .filter(function (node) {
23914 return node != null;
23916 .distinctUntilChanged(undefined, function (node) {
23919 this._nodeSubscription = Observable_1.Observable
23920 .merge(previousNode$, this._navigator.stateService.currentNode$)
23921 .filter(function (node) {
23923 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
23924 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
23926 .mergeMap(function (node) {
23927 var baseImageSize = node.pano ?
23928 Utils_1.Settings.basePanoramaSize :
23929 Utils_1.Settings.baseImageSize;
23930 if (Math.max(node.image.width, node.image.height) > baseImageSize) {
23931 return Observable_1.Observable.empty();
23933 return node.cacheImage$(Utils_1.Settings.maxImageSize)
23934 .map(function (n) {
23935 return [n.image, n];
23937 .catch(function (error, caught) {
23938 console.error("Failed to fetch high res slider image (" + node.key + ")", error);
23939 return Observable_1.Observable.empty();
23942 .map(function (_a) {
23943 var element = _a[0], node = _a[1];
23944 return function (sliderState) {
23945 sliderState.updateTexture(element, node);
23946 return sliderState;
23949 .subscribe(this._sliderStateOperation$);
23951 SliderComponent.prototype._deactivate = function () {
23953 this._navigator.stateService.state$
23955 .subscribe(function (state) {
23956 if (state === State_1.State.Waiting) {
23957 _this._navigator.stateService.traverse();
23960 this._sliderStateDisposer$.next(null);
23961 this._setKeysSubscription.unsubscribe();
23962 this._setSliderVisibleSubscription.unsubscribe();
23963 this._stateSubscription.unsubscribe();
23964 this._glRenderSubscription.unsubscribe();
23965 this._domRenderSubscription.unsubscribe();
23966 this._nodeSubscription.unsubscribe();
23967 this.configure({ keys: null });
23968 this._sliderControl.removeEventListener("input", this._moveToHandler);
23969 this._sliderControl.removeEventListener("change", this._moveToHandler);
23970 this._container.element.removeChild(this._sliderContainer);
23971 this._moveToHandler = null;
23972 this._sliderControl = null;
23973 this._sliderWrapper = null;
23974 this._sliderContainer = null;
23976 SliderComponent.prototype._getDefaultConfiguration = function () {
23979 SliderComponent.prototype._catchCacheNode$ = function (key) {
23980 return this._navigator.graphService.cacheNode$(key)
23981 .catch(function (error, caught) {
23982 console.error("Failed to cache slider node (" + key + ")", error);
23983 return Observable_1.Observable.empty();
23986 SliderComponent.prototype._createElement = function (tagName, className, container) {
23987 var element = document.createElement(tagName);
23989 element.className = className;
23992 container.appendChild(element);
23996 return SliderComponent;
23997 }(Component_1.Component));
23998 SliderComponent.componentName = "slider";
23999 exports.SliderComponent = SliderComponent;
24000 Component_1.ComponentService.register(SliderComponent);
24001 exports.default = SliderComponent;
24003 },{"../../Component":226,"../../Render":232,"../../State":233,"../../Utils":235,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/fromEvent":42,"rxjs/add/observable/of":45,"rxjs/add/observable/zip":48,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/scan":73,"rxjs/add/operator/switchMap":79,"rxjs/add/operator/withLatestFrom":83,"rxjs/add/operator/zip":84}],262:[function(require,module,exports){
24005 Object.defineProperty(exports, "__esModule", { value: true });
24006 var MarkerComponent_1 = require("./MarkerComponent");
24007 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
24008 var SimpleMarker_1 = require("./marker/SimpleMarker");
24009 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
24010 var CircleMarker_1 = require("./marker/CircleMarker");
24011 exports.CircleMarker = CircleMarker_1.CircleMarker;
24013 },{"./MarkerComponent":263,"./marker/CircleMarker":266,"./marker/SimpleMarker":268}],263:[function(require,module,exports){
24015 /// <reference path="../../../typings/index.d.ts" />
24016 var __extends = (this && this.__extends) || (function () {
24017 var extendStatics = Object.setPrototypeOf ||
24018 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24019 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24020 return function (d, b) {
24021 extendStatics(d, b);
24022 function __() { this.constructor = d; }
24023 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24026 Object.defineProperty(exports, "__esModule", { value: true });
24027 var THREE = require("three");
24028 var when = require("when");
24029 var Observable_1 = require("rxjs/Observable");
24030 require("rxjs/add/observable/combineLatest");
24031 require("rxjs/add/operator/distinctUntilChanged");
24032 require("rxjs/add/operator/map");
24033 var Component_1 = require("../../Component");
24034 var Render_1 = require("../../Render");
24035 var Graph_1 = require("../../Graph");
24036 var Geo_1 = require("../../Geo");
24038 * @class MarkerComponent
24040 * @classdesc Component for showing and editing 3D marker objects.
24042 * The `add` method is used for adding new markers or replacing
24043 * markers already in the set.
24045 * If a marker already in the set has the same
24046 * id as one of the markers added, the old marker will be removed and
24047 * the added marker will take its place.
24049 * It is not possible to update markers in the set by updating any properties
24050 * directly on the marker object. Markers need to be replaced by
24051 * re-adding them for updates to geographic position or configuration
24054 * Markers added to the marker component can be either interactive
24055 * or non-interactive. Different marker types define their behavior.
24056 * Markers with interaction support can be configured with options
24057 * to respond to dragging inside the viewer and be detected when
24058 * retrieving markers from pixel points with the `getMarkerIdAt` method.
24060 * To retrive and use the marker component
24064 * var viewer = new Mapillary.Viewer(
24068 * { component: { marker: true } });
24070 * var markerComponent = viewer.getComponent("marker");
24073 var MarkerComponent = (function (_super) {
24074 __extends(MarkerComponent, _super);
24075 function MarkerComponent(name, container, navigator) {
24076 var _this = _super.call(this, name, container, navigator) || this;
24077 _this._relativeGroundAltitude = -2;
24078 _this._geoCoords = new Geo_1.GeoCoords();
24079 _this._graphCalculator = new Graph_1.GraphCalculator();
24080 _this._markerScene = new Component_1.MarkerScene();
24081 _this._markerSet = new Component_1.MarkerSet();
24082 _this._viewportCoords = new Geo_1.ViewportCoords();
24086 * Add markers to the marker set or replace markers in the marker set.
24088 * @description If a marker already in the set has the same
24089 * id as one of the markers added, the old marker will be removed
24090 * the added marker will take its place.
24092 * Any marker inside the visible bounding bbox
24093 * will be initialized and placed in the viewer.
24095 * @param {Array<Marker>} markers - Markers to add.
24097 * @example ```markerComponent.add([marker1, marker2]);```
24099 MarkerComponent.prototype.add = function (markers) {
24100 this._markerSet.add(markers);
24103 * Returns the marker in the marker set with the specified id, or
24104 * undefined if the id matches no marker.
24106 * @param {string} markerId - Id of the marker.
24108 * @example ```var marker = markerComponent.get("markerId");```
24111 MarkerComponent.prototype.get = function (markerId) {
24112 return this._markerSet.get(markerId);
24115 * Returns an array of all markers.
24117 * @example ```var markers = markerComponent.getAll();```
24119 MarkerComponent.prototype.getAll = function () {
24120 return this._markerSet.getAll();
24123 * Returns the id of the interactive marker closest to the current camera
24124 * position at the specified point.
24126 * @description Notice that the pixelPoint argument requires x, y
24127 * coordinates from pixel space.
24129 * With this function, you can use the coordinates provided by mouse
24130 * events to get information out of the marker component.
24132 * If no interactive geometry of an interactive marker exist at the pixel
24133 * point, `null` will be returned.
24135 * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
24136 * @returns {string} Id of the interactive marker closest to the camera. If no
24137 * interactive marker exist at the pixel point, `null` will be returned.
24141 * markerComponent.getMarkerIdAt([100, 100])
24142 * .then((markerId) => { console.log(markerId); });
24145 MarkerComponent.prototype.getMarkerIdAt = function (pixelPoint) {
24147 return when.promise(function (resolve, reject) {
24148 _this._container.renderService.renderCamera$
24150 .map(function (render) {
24151 var viewport = _this._viewportCoords
24152 .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
24153 var id = _this._markerScene.intersectObjects(viewport, render.perspective);
24156 .subscribe(function (id) {
24158 }, function (error) {
24164 * Check if a marker exist in the marker set.
24166 * @param {string} markerId - Id of the marker.
24168 * @example ```var markerExists = markerComponent.has("markerId");```
24170 MarkerComponent.prototype.has = function (markerId) {
24171 return this._markerSet.has(markerId);
24174 * Remove markers with the specified ids from the marker set.
24176 * @param {Array<string>} markerIds - Ids for markers to remove.
24178 * @example ```markerComponent.remove(["id-1", "id-2"]);```
24180 MarkerComponent.prototype.remove = function (markerIds) {
24181 this._markerSet.remove(markerIds);
24184 * Remove all markers from the marker set.
24186 * @example ```markerComponent.removeAll();```
24188 MarkerComponent.prototype.removeAll = function () {
24189 this._markerSet.removeAll();
24191 MarkerComponent.prototype._activate = function () {
24193 var groundAltitude$ = this._navigator.stateService.currentState$
24194 .map(function (frame) {
24195 return frame.state.camera.position.z + _this._relativeGroundAltitude;
24197 .distinctUntilChanged(function (a1, a2) {
24198 return Math.abs(a1 - a2) < 0.01;
24202 var geoInitiated$ = Observable_1.Observable
24203 .combineLatest(groundAltitude$, this._navigator.stateService.reference$)
24205 .map(function () { })
24208 var clampedConfiguration$ = this._configuration$
24209 .map(function (configuration) {
24210 return { visibleBBoxSize: Math.max(1, Math.min(200, configuration.visibleBBoxSize)) };
24212 var currentlatLon$ = this._navigator.stateService.currentNode$
24213 .map(function (node) { return node.latLon; })
24216 var visibleBBox$ = Observable_1.Observable
24217 .combineLatest(clampedConfiguration$, currentlatLon$)
24218 .map(function (_a) {
24219 var configuration = _a[0], latLon = _a[1];
24220 return _this._graphCalculator
24221 .boundingBoxCorners(latLon, configuration.visibleBBoxSize / 2);
24225 var visibleMarkers$ = Observable_1.Observable
24226 .combineLatest(Observable_1.Observable
24227 .of(this._markerSet)
24228 .concat(this._markerSet.changed$), visibleBBox$)
24229 .map(function (_a) {
24230 var set = _a[0], bbox = _a[1];
24231 return set.search(bbox);
24233 this._setChangedSubscription = geoInitiated$
24234 .switchMap(function () {
24235 return visibleMarkers$
24236 .withLatestFrom(_this._navigator.stateService.reference$, groundAltitude$);
24238 .subscribe(function (_a) {
24239 var markers = _a[0], reference = _a[1], alt = _a[2];
24240 var geoCoords = _this._geoCoords;
24241 var markerScene = _this._markerScene;
24242 var sceneMarkers = markerScene.markers;
24243 var markersToRemove = Object.assign({}, sceneMarkers);
24244 for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
24245 var marker = markers_1[_i];
24246 if (marker.id in sceneMarkers) {
24247 delete markersToRemove[marker.id];
24250 var point3d = geoCoords
24251 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24252 markerScene.add(marker, point3d);
24255 for (var id in markersToRemove) {
24256 if (!markersToRemove.hasOwnProperty(id)) {
24259 markerScene.remove(id);
24262 this._markersUpdatedSubscription = geoInitiated$
24263 .switchMap(function () {
24264 return _this._markerSet.updated$
24265 .withLatestFrom(visibleBBox$, _this._navigator.stateService.reference$, groundAltitude$);
24267 .subscribe(function (_a) {
24268 var markers = _a[0], _b = _a[1], sw = _b[0], ne = _b[1], reference = _a[2], alt = _a[3];
24269 var geoCoords = _this._geoCoords;
24270 var markerScene = _this._markerScene;
24271 for (var _i = 0, markers_2 = markers; _i < markers_2.length; _i++) {
24272 var marker = markers_2[_i];
24273 var exists = markerScene.has(marker.id);
24274 var visible = marker.latLon.lat > sw.lat &&
24275 marker.latLon.lat < ne.lat &&
24276 marker.latLon.lon > sw.lon &&
24277 marker.latLon.lon < ne.lon;
24279 var point3d = geoCoords
24280 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24281 markerScene.add(marker, point3d);
24283 else if (!visible && exists) {
24284 markerScene.remove(marker.id);
24288 this._referenceSubscription = this._navigator.stateService.reference$
24290 .withLatestFrom(groundAltitude$)
24291 .subscribe(function (_a) {
24292 var reference = _a[0], alt = _a[1];
24293 var geoCoords = _this._geoCoords;
24294 var markerScene = _this._markerScene;
24295 for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
24296 var marker = _b[_i];
24297 var point3d = geoCoords
24298 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24299 markerScene.update(marker.id, point3d);
24302 this._adjustHeightSubscription = groundAltitude$
24304 .withLatestFrom(this._navigator.stateService.reference$, currentlatLon$)
24305 .subscribe(function (_a) {
24306 var alt = _a[0], reference = _a[1], latLon = _a[2];
24307 var geoCoords = _this._geoCoords;
24308 var markerScene = _this._markerScene;
24309 var position = geoCoords
24310 .geodeticToEnu(latLon.lat, latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24311 for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
24312 var marker = _b[_i];
24313 var point3d = geoCoords
24314 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24315 var distanceX = point3d[0] - position[0];
24316 var distanceY = point3d[1] - position[1];
24317 var groundDistance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
24318 if (groundDistance > 50) {
24321 markerScene.lerpAltitude(marker.id, alt, Math.min(1, Math.max(0, 1.2 - 1.2 * groundDistance / 50)));
24324 this._renderSubscription = this._navigator.stateService.currentState$
24325 .map(function (frame) {
24326 var scene = _this._markerScene;
24331 needsRender: scene.needsRender,
24332 render: scene.render.bind(scene),
24333 stage: Render_1.GLRenderStage.Foreground,
24337 .subscribe(this._container.glRenderer.render$);
24338 var hoveredMarkerId$ = Observable_1.Observable
24339 .combineLatest(this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$)
24340 .map(function (_a) {
24341 var render = _a[0], event = _a[1];
24342 var element = _this._container.element;
24343 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
24344 var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element);
24345 var markerId = _this._markerScene.intersectObjects(viewport, render.perspective);
24350 var draggingStarted$ = this._container.mouseService
24351 .filtered$(this._name, this._container.mouseService.mouseDragStart$)
24352 .map(function (event) {
24355 var draggingStopped$ = this._container.mouseService
24356 .filtered$(this._name, this._container.mouseService.mouseDragEnd$)
24357 .map(function (event) {
24360 var dragging$ = Observable_1.Observable
24361 .merge(draggingStarted$, draggingStopped$)
24363 this._dragEventSubscription = draggingStarted$
24364 .withLatestFrom(hoveredMarkerId$)
24365 .merge(Observable_1.Observable
24366 .combineLatest(draggingStopped$, Observable_1.Observable.of(null)))
24367 .startWith([false, null])
24369 .subscribe(function (_a) {
24370 var previous = _a[0], current = _a[1];
24371 var dragging = current[0];
24372 var eventType = dragging ? MarkerComponent.dragstart : MarkerComponent.dragend;
24373 var id = dragging ? current[1] : previous[1];
24374 var marker = _this._markerScene.get(id);
24375 var markerEvent = { marker: marker, target: _this, type: eventType };
24376 _this.fire(eventType, markerEvent);
24378 this._mouseClaimSubscription = Observable_1.Observable
24379 .combineLatest(this._container.mouseService.active$, hoveredMarkerId$, dragging$)
24380 .map(function (_a) {
24381 var active = _a[0], markerId = _a[1], dragging = _a[2];
24382 return (!active && markerId != null) || dragging;
24384 .distinctUntilChanged()
24385 .subscribe(function (hovered) {
24387 _this._container.mouseService.claimMouse(_this._name, 1);
24390 _this._container.mouseService.unclaimMouse(_this._name);
24393 var offset$ = this._container.mouseService
24394 .filtered$(this._name, this._container.mouseService.mouseDragStart$)
24395 .withLatestFrom(hoveredMarkerId$, this._container.renderService.renderCamera$)
24396 .map(function (_a) {
24397 var e = _a[0], id = _a[1], r = _a[2];
24398 var marker = _this._markerScene.get(id);
24399 var element = _this._container.element;
24400 var _b = _this._viewportCoords.projectToCanvas(marker.geometry.position.toArray(), element, r.perspective), groundCanvasX = _b[0], groundCanvasY = _b[1];
24401 var _c = _this._viewportCoords.canvasPosition(e, element), canvasX = _c[0], canvasY = _c[1];
24402 var offset = [canvasX - groundCanvasX, canvasY - groundCanvasY];
24403 return [marker, offset, r];
24407 this._updateMarkerSubscription = this._container.mouseService
24408 .filtered$(this._name, this._container.mouseService.mouseDrag$)
24409 .withLatestFrom(offset$, this._navigator.stateService.reference$, clampedConfiguration$)
24410 .subscribe(function (_a) {
24411 var event = _a[0], _b = _a[1], marker = _b[0], offset = _b[1], render = _b[2], reference = _a[2], configuration = _a[3];
24412 if (!_this._markerScene.has(marker.id)) {
24415 var element = _this._container.element;
24416 var _c = _this._viewportCoords.canvasPosition(event, element), canvasX = _c[0], canvasY = _c[1];
24417 var groundX = canvasX - offset[0];
24418 var groundY = canvasY - offset[1];
24419 var _d = _this._viewportCoords
24420 .canvasToViewport(groundX, groundY, element), viewportX = _d[0], viewportY = _d[1];
24421 var direction = new THREE.Vector3(viewportX, viewportY, 1)
24422 .unproject(render.perspective)
24423 .sub(render.perspective.position)
24425 var distance = Math.min(_this._relativeGroundAltitude / direction.z, configuration.visibleBBoxSize / 2 - 0.1);
24426 if (distance < 0) {
24429 var intersection = direction
24431 .multiplyScalar(distance)
24432 .add(render.perspective.position);
24433 intersection.z = render.perspective.position.z + _this._relativeGroundAltitude;
24434 var _e = _this._geoCoords
24435 .enuToGeodetic(intersection.x, intersection.y, intersection.z, reference.lat, reference.lon, reference.alt), lat = _e[0], lon = _e[1];
24436 _this._markerScene.update(marker.id, intersection.toArray(), { lat: lat, lon: lon });
24437 _this._markerSet.update(marker);
24438 var markerEvent = { marker: marker, target: _this, type: MarkerComponent.changed };
24439 _this.fire(MarkerComponent.changed, markerEvent);
24442 MarkerComponent.prototype._deactivate = function () {
24443 this._adjustHeightSubscription.unsubscribe();
24444 this._dragEventSubscription.unsubscribe();
24445 this._markersUpdatedSubscription.unsubscribe();
24446 this._mouseClaimSubscription.unsubscribe();
24447 this._referenceSubscription.unsubscribe();
24448 this._renderSubscription.unsubscribe();
24449 this._setChangedSubscription.unsubscribe();
24450 this._updateMarkerSubscription.unsubscribe();
24451 this._markerScene.clear();
24453 MarkerComponent.prototype._getDefaultConfiguration = function () {
24454 return { visibleBBoxSize: 100 };
24456 return MarkerComponent;
24457 }(Component_1.Component));
24458 MarkerComponent.componentName = "marker";
24460 * Fired when the position of a marker is changed.
24462 * @type {IMarkerEvent} markerEvent - Marker event data.
24465 * markerComponent.on("changed", function(e) {
24466 * console.log(e.marker.id, e.marker.latLon);
24470 MarkerComponent.changed = "changed";
24472 * Fired when a marker drag interaction starts.
24474 * @type {IMarkerEvent} markerEvent - Marker event data.
24477 * markerComponent.on("dragstart", function(e) {
24478 * console.log(e.marker.id, e.marker.latLon);
24482 MarkerComponent.dragstart = "dragstart";
24484 * Fired when a marker drag interaction ends.
24486 * @type {IMarkerEvent} markerEvent - Marker event data.
24489 * markerComponent.on("dragend", function(e) {
24490 * console.log(e.marker.id, e.marker.latLon);
24494 MarkerComponent.dragend = "dragend";
24495 exports.MarkerComponent = MarkerComponent;
24496 Component_1.ComponentService.register(MarkerComponent);
24497 exports.default = MarkerComponent;
24499 },{"../../Component":226,"../../Geo":229,"../../Graph":230,"../../Render":232,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"three":176,"when":223}],264:[function(require,module,exports){
24501 /// <reference path="../../../typings/index.d.ts" />
24502 Object.defineProperty(exports, "__esModule", { value: true });
24503 var THREE = require("three");
24504 var MarkerScene = (function () {
24505 function MarkerScene(scene, raycaster) {
24506 this._needsRender = false;
24507 this._interactiveObjects = [];
24508 this._markers = {};
24509 this._objectMarkers = {};
24510 this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
24511 this._scene = !!scene ? scene : new THREE.Scene();
24513 Object.defineProperty(MarkerScene.prototype, "markers", {
24515 return this._markers;
24520 Object.defineProperty(MarkerScene.prototype, "needsRender", {
24522 return this._needsRender;
24527 MarkerScene.prototype.add = function (marker, position) {
24528 if (marker.id in this._markers) {
24529 this._dispose(marker.id);
24531 marker.createGeometry(position);
24532 this._scene.add(marker.geometry);
24533 this._markers[marker.id] = marker;
24534 for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
24535 var interactiveObject = _a[_i];
24536 this._interactiveObjects.push(interactiveObject);
24537 this._objectMarkers[interactiveObject.uuid] = marker.id;
24539 this._needsRender = true;
24541 MarkerScene.prototype.clear = function () {
24542 for (var id in this._markers) {
24543 if (!this._markers.hasOwnProperty) {
24548 this._needsRender = true;
24550 MarkerScene.prototype.get = function (id) {
24551 return this._markers[id];
24553 MarkerScene.prototype.getAll = function () {
24556 .keys(this._markers)
24557 .map(function (id) { return _this._markers[id]; });
24559 MarkerScene.prototype.has = function (id) {
24560 return id in this._markers;
24562 MarkerScene.prototype.intersectObjects = function (_a, camera) {
24563 var viewportX = _a[0], viewportY = _a[1];
24564 this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
24565 var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
24566 for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
24567 var intersect = intersects_1[_i];
24568 if (intersect.object.uuid in this._objectMarkers) {
24569 return this._objectMarkers[intersect.object.uuid];
24574 MarkerScene.prototype.lerpAltitude = function (id, alt, alpha) {
24575 if (!(id in this._markers)) {
24578 this._markers[id].lerpAltitude(alt, alpha);
24579 this._needsRender = true;
24581 MarkerScene.prototype.remove = function (id) {
24582 if (!(id in this._markers)) {
24586 this._needsRender = true;
24588 MarkerScene.prototype.render = function (perspectiveCamera, renderer) {
24589 renderer.render(this._scene, perspectiveCamera);
24590 this._needsRender = false;
24592 MarkerScene.prototype.update = function (id, position, latLon) {
24593 if (!(id in this._markers)) {
24596 var marker = this._markers[id];
24597 marker.updatePosition(position, latLon);
24598 this._needsRender = true;
24600 MarkerScene.prototype._dispose = function (id) {
24601 var marker = this._markers[id];
24602 this._scene.remove(marker.geometry);
24603 for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
24604 var interactiveObject = _a[_i];
24605 var index = this._interactiveObjects.indexOf(interactiveObject);
24606 if (index !== -1) {
24607 this._interactiveObjects.splice(index, 1);
24610 console.warn("Object does not exist (" + interactiveObject.id + ") for " + id);
24612 delete this._objectMarkers[interactiveObject.uuid];
24614 marker.disposeGeometry();
24615 delete this._markers[id];
24617 return MarkerScene;
24619 exports.MarkerScene = MarkerScene;
24620 exports.default = MarkerScene;
24622 },{"three":176}],265:[function(require,module,exports){
24624 /// <reference path="../../../typings/index.d.ts" />
24625 Object.defineProperty(exports, "__esModule", { value: true });
24626 var rbush = require("rbush");
24627 var Subject_1 = require("rxjs/Subject");
24628 require("rxjs/add/operator/map");
24629 require("rxjs/add/operator/publishReplay");
24630 require("rxjs/add/operator/scan");
24631 var MarkerSet = (function () {
24632 function MarkerSet() {
24634 this._index = rbush(16, [".lon", ".lat", ".lon", ".lat"]);
24635 this._indexChanged$ = new Subject_1.Subject();
24636 this._updated$ = new Subject_1.Subject();
24638 Object.defineProperty(MarkerSet.prototype, "changed$", {
24640 return this._indexChanged$;
24645 Object.defineProperty(MarkerSet.prototype, "updated$", {
24647 return this._updated$;
24652 MarkerSet.prototype.add = function (markers) {
24654 var hash = this._hash;
24655 var index = this._index;
24656 for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
24657 var marker = markers_1[_i];
24658 var id = marker.id;
24660 index.remove(hash[id]);
24661 updated.push(marker);
24664 lat: marker.latLon.lat,
24665 lon: marker.latLon.lon,
24669 index.insert(item);
24671 if (updated.length > 0) {
24672 this._updated$.next(updated);
24674 if (markers.length > updated.length) {
24675 this._indexChanged$.next(this);
24678 MarkerSet.prototype.has = function (id) {
24679 return id in this._hash;
24681 MarkerSet.prototype.get = function (id) {
24682 return this.has(id) ? this._hash[id].marker : undefined;
24684 MarkerSet.prototype.getAll = function () {
24687 .map(function (indexItem) {
24688 return indexItem.marker;
24691 MarkerSet.prototype.remove = function (ids) {
24692 var hash = this._hash;
24693 var index = this._index;
24694 var changed = false;
24695 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
24696 var id = ids_1[_i];
24697 if (!(id in hash)) {
24700 var item = hash[id];
24701 index.remove(item);
24706 this._indexChanged$.next(this);
24709 MarkerSet.prototype.removeAll = function () {
24711 this._index.clear();
24712 this._indexChanged$.next(this);
24714 MarkerSet.prototype.search = function (_a) {
24715 var sw = _a[0], ne = _a[1];
24717 .search({ maxX: ne.lon, maxY: ne.lat, minX: sw.lon, minY: sw.lat })
24718 .map(function (indexItem) {
24719 return indexItem.marker;
24722 MarkerSet.prototype.update = function (marker) {
24723 var hash = this._hash;
24724 var index = this._index;
24725 var id = marker.id;
24726 if (!(id in hash)) {
24729 index.remove(hash[id]);
24731 lat: marker.latLon.lat,
24732 lon: marker.latLon.lon,
24736 index.insert(item);
24740 exports.MarkerSet = MarkerSet;
24741 exports.default = MarkerSet;
24743 },{"rbush":25,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73}],266:[function(require,module,exports){
24745 /// <reference path="../../../../typings/index.d.ts" />
24746 var __extends = (this && this.__extends) || (function () {
24747 var extendStatics = Object.setPrototypeOf ||
24748 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24749 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24750 return function (d, b) {
24751 extendStatics(d, b);
24752 function __() { this.constructor = d; }
24753 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24756 Object.defineProperty(exports, "__esModule", { value: true });
24757 var THREE = require("three");
24758 var Component_1 = require("../../../Component");
24760 * @class CircleMarker
24762 * @classdesc Non-interactive marker with a flat circle shape. The circle
24763 * marker can not be configured to be interactive.
24765 * Circle marker properties can not be updated after creation.
24767 * To create and add one `CircleMarker` with default configuration
24768 * and one with configuration use
24772 * var defaultMarker = new Mapillary.MarkerComponent.CircleMarker(
24774 * { lat: 0, lon: 0, });
24776 * var configuredMarker = new Mapillary.MarkerComponent.CircleMarker(
24778 * { lat: 0, lon: 0, },
24785 * markerComponent.add([defaultMarker, configuredMarker]);
24788 var CircleMarker = (function (_super) {
24789 __extends(CircleMarker, _super);
24790 function CircleMarker(id, latLon, options) {
24791 var _this = _super.call(this, id, latLon) || this;
24792 options = !!options ? options : {};
24793 _this._color = options.color != null ? options.color : 0xffffff;
24794 _this._opacity = options.opacity != null ? options.opacity : 0.4;
24795 _this._radius = options.radius != null ? options.radius : 1;
24798 CircleMarker.prototype._createGeometry = function (position) {
24799 var circle = new THREE.Mesh(new THREE.CircleGeometry(this._radius, 16), new THREE.MeshBasicMaterial({
24800 color: this._color,
24801 opacity: this._opacity,
24804 circle.up.fromArray([0, 0, 1]);
24805 circle.renderOrder = -1;
24806 var group = new THREE.Object3D();
24808 group.position.fromArray(position);
24809 this._geometry = group;
24811 CircleMarker.prototype._disposeGeometry = function () {
24812 for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
24814 mesh.geometry.dispose();
24815 mesh.material.dispose();
24818 CircleMarker.prototype._getInteractiveObjects = function () {
24821 return CircleMarker;
24822 }(Component_1.Marker));
24823 exports.CircleMarker = CircleMarker;
24824 exports.default = CircleMarker;
24826 },{"../../../Component":226,"three":176}],267:[function(require,module,exports){
24828 /// <reference path="../../../../typings/index.d.ts" />
24829 Object.defineProperty(exports, "__esModule", { value: true });
24833 * @classdesc Represents an abstract marker class that should be extended
24834 * by marker implementations used in the marker component.
24836 var Marker = (function () {
24837 function Marker(id, latLon) {
24839 this._latLon = latLon;
24841 Object.defineProperty(Marker.prototype, "id", {
24844 * @returns {string} The id of the marker.
24852 Object.defineProperty(Marker.prototype, "geometry", {
24854 return this._geometry;
24859 Object.defineProperty(Marker.prototype, "latLon", {
24862 * @returns {ILatLon} The geographic coordinates of the marker.
24865 return this._latLon;
24870 Marker.prototype.createGeometry = function (position) {
24871 if (!!this._geometry) {
24874 this._createGeometry(position);
24875 // update matrix world if raycasting occurs before first render
24876 this._geometry.updateMatrixWorld(true);
24878 Marker.prototype.disposeGeometry = function () {
24879 if (!this._geometry) {
24882 this._disposeGeometry();
24883 this._geometry = undefined;
24885 Marker.prototype.getInteractiveObjects = function () {
24886 if (!this._geometry) {
24889 return this._getInteractiveObjects();
24891 Marker.prototype.lerpAltitude = function (alt, alpha) {
24892 if (!this._geometry) {
24895 this._geometry.position.z = (1 - alpha) * this._geometry.position.z + alpha * alt;
24897 Marker.prototype.updatePosition = function (position, latLon) {
24899 this._latLon.lat = latLon.lat;
24900 this._latLon.lon = latLon.lon;
24902 if (!this._geometry) {
24905 this._geometry.position.fromArray(position);
24906 this._geometry.updateMatrixWorld(true);
24910 exports.Marker = Marker;
24911 exports.default = Marker;
24913 },{}],268:[function(require,module,exports){
24915 /// <reference path="../../../../typings/index.d.ts" />
24916 var __extends = (this && this.__extends) || (function () {
24917 var extendStatics = Object.setPrototypeOf ||
24918 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24919 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24920 return function (d, b) {
24921 extendStatics(d, b);
24922 function __() { this.constructor = d; }
24923 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24926 Object.defineProperty(exports, "__esModule", { value: true });
24927 var THREE = require("three");
24928 var Component_1 = require("../../../Component");
24930 * @class SimpleMarker
24932 * @classdesc Interactive marker with ice cream shape. The sphere
24933 * inside the ice cream can be configured to be interactive.
24935 * Simple marker properties can not be updated after creation.
24937 * To create and add one `SimpleMarker` with default configuration
24938 * (non-interactive) and one interactive with configuration use
24942 * var defaultMarker = new Mapillary.MarkerComponent.SimpleMarker(
24944 * { lat: 0, lon: 0, });
24946 * var interactiveMarker = new Mapillary.MarkerComponent.SimpleMarker(
24948 * { lat: 0, lon: 0, },
24950 * ballColor: "#00f",
24951 * ballOpacity: 0.5,
24953 * interactive: true,
24958 * markerComponent.add([defaultMarker, interactiveMarker]);
24961 var SimpleMarker = (function (_super) {
24962 __extends(SimpleMarker, _super);
24963 function SimpleMarker(id, latLon, options) {
24964 var _this = _super.call(this, id, latLon) || this;
24965 options = !!options ? options : {};
24966 _this._ballColor = options.ballColor != null ? options.ballColor : 0xff0000;
24967 _this._ballOpacity = options.ballOpacity != null ? options.ballOpacity : 0.8;
24968 _this._circleToRayAngle = 2;
24969 _this._color = options.color != null ? options.color : 0xff0000;
24970 _this._interactive = !!options.interactive;
24971 _this._opacity = options.opacity != null ? options.opacity : 0.4;
24972 _this._radius = options.radius != null ? options.radius : 1;
24975 SimpleMarker.prototype._createGeometry = function (position) {
24976 var radius = this._radius;
24977 var cone = new THREE.Mesh(this._markerGeometry(radius, 8, 8), new THREE.MeshBasicMaterial({
24978 color: this._color,
24979 opacity: this._opacity,
24980 shading: THREE.SmoothShading,
24983 cone.renderOrder = 1;
24984 var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 8, 8), new THREE.MeshBasicMaterial({
24985 color: this._ballColor,
24986 opacity: this._ballOpacity,
24987 shading: THREE.SmoothShading,
24990 ball.position.z = this._markerHeight(radius);
24991 var group = new THREE.Object3D();
24994 group.position.fromArray(position);
24995 this._geometry = group;
24997 SimpleMarker.prototype._disposeGeometry = function () {
24998 for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
25000 mesh.geometry.dispose();
25001 mesh.material.dispose();
25004 SimpleMarker.prototype._getInteractiveObjects = function () {
25005 return this._interactive ? [this._geometry.children[0]] : [];
25007 SimpleMarker.prototype._markerHeight = function (radius) {
25008 var t = Math.tan(Math.PI - this._circleToRayAngle);
25009 return radius * Math.sqrt(1 + t * t);
25011 SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) {
25012 var geometry = new THREE.Geometry();
25013 widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
25014 heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
25015 var height = this._markerHeight(radius);
25017 for (var y = 0; y <= heightSegments; ++y) {
25018 var verticesRow = [];
25019 for (var x = 0; x <= widthSegments; ++x) {
25020 var u = x / widthSegments * Math.PI * 2;
25021 var v = y / heightSegments * Math.PI;
25023 if (v < this._circleToRayAngle) {
25027 var t = Math.tan(v - this._circleToRayAngle);
25028 r = radius * Math.sqrt(1 + t * t);
25030 var vertex = new THREE.Vector3();
25031 vertex.x = r * Math.cos(u) * Math.sin(v);
25032 vertex.y = r * Math.sin(u) * Math.sin(v);
25033 vertex.z = r * Math.cos(v) + height;
25034 geometry.vertices.push(vertex);
25035 verticesRow.push(geometry.vertices.length - 1);
25037 vertices.push(verticesRow);
25039 for (var y = 0; y < heightSegments; ++y) {
25040 for (var x = 0; x < widthSegments; ++x) {
25041 var v1 = vertices[y][x + 1];
25042 var v2 = vertices[y][x];
25043 var v3 = vertices[y + 1][x];
25044 var v4 = vertices[y + 1][x + 1];
25045 var n1 = geometry.vertices[v1].clone().normalize();
25046 var n2 = geometry.vertices[v2].clone().normalize();
25047 var n3 = geometry.vertices[v3].clone().normalize();
25048 var n4 = geometry.vertices[v4].clone().normalize();
25049 geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4]));
25050 geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()]));
25053 geometry.computeFaceNormals();
25054 geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height);
25057 return SimpleMarker;
25058 }(Component_1.Marker));
25059 exports.SimpleMarker = SimpleMarker;
25060 exports.default = SimpleMarker;
25062 },{"../../../Component":226,"three":176}],269:[function(require,module,exports){
25064 var __extends = (this && this.__extends) || (function () {
25065 var extendStatics = Object.setPrototypeOf ||
25066 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25067 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25068 return function (d, b) {
25069 extendStatics(d, b);
25070 function __() { this.constructor = d; }
25071 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25074 Object.defineProperty(exports, "__esModule", { value: true });
25075 var Observable_1 = require("rxjs/Observable");
25076 var Component_1 = require("../../Component");
25078 * The `DoubleClickZoomHandler` allows the user to zoom the viewer photo at a point by double clicking.
25082 * var mouseComponent = viewer.getComponent("mouse");
25084 * mouseComponent.doubleClickZoom.disable();
25085 * mouseComponent.doubleClickZoom.enable();
25087 * var isEnabled = mouseComponent.doubleClickZoom.isEnabled;
25090 var DoubleClickZoomHandler = (function (_super) {
25091 __extends(DoubleClickZoomHandler, _super);
25092 function DoubleClickZoomHandler() {
25093 return _super !== null && _super.apply(this, arguments) || this;
25095 DoubleClickZoomHandler.prototype._enable = function () {
25097 this._zoomSubscription = Observable_1.Observable
25098 .merge(this._container.mouseService
25099 .filtered$(this._component.name, this._container.mouseService.dblClick$), this._container.touchService.doubleTap$
25100 .map(function (e) {
25101 var touch = e.touches[0];
25102 return { clientX: touch.clientX, clientY: touch.clientY, shiftKey: e.shiftKey };
25104 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
25105 .subscribe(function (_a) {
25106 var event = _a[0], render = _a[1], transform = _a[2];
25107 var element = _this._container.element;
25108 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
25109 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
25110 var reference = transform.projectBasic(unprojected.toArray());
25111 var delta = !!event.shiftKey ? -1 : 1;
25112 _this._navigator.stateService.zoomIn(delta, reference);
25115 DoubleClickZoomHandler.prototype._disable = function () {
25116 this._zoomSubscription.unsubscribe();
25118 DoubleClickZoomHandler.prototype._getConfiguration = function (enable) {
25119 return { doubleClickZoom: enable };
25121 return DoubleClickZoomHandler;
25122 }(Component_1.MouseHandlerBase));
25123 exports.DoubleClickZoomHandler = DoubleClickZoomHandler;
25124 exports.default = DoubleClickZoomHandler;
25126 },{"../../Component":226,"rxjs/Observable":29}],270:[function(require,module,exports){
25128 /// <reference path="../../../typings/index.d.ts" />
25129 var __extends = (this && this.__extends) || (function () {
25130 var extendStatics = Object.setPrototypeOf ||
25131 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25132 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25133 return function (d, b) {
25134 extendStatics(d, b);
25135 function __() { this.constructor = d; }
25136 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25139 Object.defineProperty(exports, "__esModule", { value: true });
25140 var THREE = require("three");
25141 var Observable_1 = require("rxjs/Observable");
25142 var Component_1 = require("../../Component");
25144 * The `DragPanHandler` allows the user to pan the viewer photo by clicking and dragging the cursor.
25148 * var mouseComponent = viewer.getComponent("mouse");
25150 * mouseComponent.dragPan.disable();
25151 * mouseComponent.dragPan.enable();
25153 * var isEnabled = mouseComponent.dragPan.isEnabled;
25156 var DragPanHandler = (function (_super) {
25157 __extends(DragPanHandler, _super);
25158 function DragPanHandler(component, container, navigator, viewportCoords, spatial) {
25159 var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
25160 _this._spatial = spatial;
25161 _this._basicRotationThreshold = 5e-2;
25162 _this._forceCoeff = 2e-1;
25165 DragPanHandler.prototype._enable = function () {
25167 var draggingStarted$ = this._container.mouseService
25168 .filtered$(this._component.name, this._container.mouseService.mouseDragStart$)
25169 .map(function (event) {
25172 var draggingStopped$ = this._container.mouseService
25173 .filtered$(this._component.name, this._container.mouseService.mouseDragEnd$)
25174 .map(function (event) {
25177 this._activeMouseSubscription = Observable_1.Observable
25178 .merge(draggingStarted$, draggingStopped$)
25179 .subscribe(this._container.mouseService.activate$);
25180 this._preventDefaultSubscription = Observable_1.Observable
25181 .merge(draggingStarted$, draggingStopped$)
25182 .switchMap(function (dragging) {
25184 _this._container.mouseService.documentMouseMove$ :
25185 Observable_1.Observable.empty();
25187 .merge(this._container.touchService.touchMove$)
25188 .subscribe(function (event) {
25189 event.preventDefault(); // prevent selection of content outside the viewer
25191 var touchMovingStarted$ = this._container.touchService.singleTouchDragStart$
25192 .map(function (event) {
25195 var touchMovingStopped$ = this._container.touchService.singleTouchDragEnd$
25196 .map(function (event) {
25199 this._activeTouchSubscription = Observable_1.Observable
25200 .merge(touchMovingStarted$, touchMovingStopped$)
25201 .subscribe(this._container.touchService.activate$);
25202 this._rotateBasicSubscription = this._navigator.stateService.currentState$
25203 .map(function (frame) {
25204 return frame.state.currentNode.fullPano || frame.state.nodesAhead < 1;
25206 .distinctUntilChanged()
25207 .switchMap(function (enable) {
25209 return Observable_1.Observable.empty();
25211 var mouseDrag$ = Observable_1.Observable
25212 .merge(_this._container.mouseService.filtered$(_this._component.name, _this._container.mouseService.mouseDragStart$), _this._container.mouseService.filtered$(_this._component.name, _this._container.mouseService.mouseDrag$), _this._container.mouseService.filtered$(_this._component.name, _this._container.mouseService.mouseDragEnd$)
25213 .map(function (e) { return null; }))
25215 .filter(function (pair) {
25216 return pair[0] != null && pair[1] != null;
25218 var singleTouchDrag$ = Observable_1.Observable
25219 .merge(_this._container.touchService.singleTouchDragStart$, _this._container.touchService.singleTouchDrag$, _this._container.touchService.singleTouchDragEnd$.map(function (t) { return null; }))
25220 .map(function (event) {
25221 return event != null && event.touches.length > 0 ?
25222 event.touches[0] : null;
25225 .filter(function (pair) {
25226 return pair[0] != null && pair[1] != null;
25228 return Observable_1.Observable
25229 .merge(mouseDrag$, singleTouchDrag$);
25231 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.stateService.currentCamera$)
25232 .map(function (_a) {
25233 var events = _a[0], render = _a[1], transform = _a[2], c = _a[3];
25234 var camera = c.clone();
25235 var previousEvent = events[0];
25236 var event = events[1];
25237 var movementX = event.clientX - previousEvent.clientX;
25238 var movementY = event.clientY - previousEvent.clientY;
25239 var element = _this._container.element;
25240 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
25241 var currentDirection = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective)
25242 .sub(render.perspective.position);
25243 var directionX = _this._viewportCoords.unprojectFromCanvas(canvasX - movementX, canvasY, element, render.perspective)
25244 .sub(render.perspective.position);
25245 var directionY = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY - movementY, element, render.perspective)
25246 .sub(render.perspective.position);
25247 var deltaPhi = (movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection);
25248 var deltaTheta = (movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection);
25249 var upQuaternion = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
25250 var upQuaternionInverse = upQuaternion.clone().inverse();
25251 var offset = new THREE.Vector3();
25252 offset.copy(camera.lookat).sub(camera.position);
25253 offset.applyQuaternion(upQuaternion);
25254 var length = offset.length();
25255 var phi = Math.atan2(offset.y, offset.x);
25257 var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
25258 theta += deltaTheta;
25259 theta = Math.max(0.01, Math.min(Math.PI - 0.01, theta));
25260 offset.x = Math.sin(theta) * Math.cos(phi);
25261 offset.y = Math.sin(theta) * Math.sin(phi);
25262 offset.z = Math.cos(theta);
25263 offset.applyQuaternion(upQuaternionInverse);
25264 var lookat = new THREE.Vector3().copy(camera.position).add(offset.multiplyScalar(length));
25265 var basic = transform.projectBasic(lookat.toArray());
25266 var original = transform.projectBasic(camera.lookat.toArray());
25267 var x = basic[0] - original[0];
25268 var y = basic[1] - original[1];
25269 if (Math.abs(x) > 1) {
25272 else if (x > 0.5) {
25275 else if (x < -0.5) {
25278 var rotationThreshold = _this._basicRotationThreshold;
25279 x = _this._spatial.clamp(x, -rotationThreshold, rotationThreshold);
25280 y = _this._spatial.clamp(y, -rotationThreshold, rotationThreshold);
25281 if (transform.fullPano) {
25284 var pixelDistances = _this._viewportCoords.getPixelDistances(_this._container.element, transform, render.perspective);
25285 var coeff = _this._forceCoeff;
25286 if (pixelDistances[0] > 0 && y < 0 && basic[1] < 0.5) {
25287 y /= Math.max(1, coeff * pixelDistances[0]);
25289 if (pixelDistances[1] > 0 && x > 0 && basic[0] > 0.5) {
25290 x /= Math.max(1, coeff * pixelDistances[1]);
25292 if (pixelDistances[2] > 0 && y > 0 && basic[1] > 0.5) {
25293 y /= Math.max(1, coeff * pixelDistances[2]);
25295 if (pixelDistances[3] > 0 && x < 0 && basic[0] < 0.5) {
25296 x /= Math.max(1, coeff * pixelDistances[3]);
25300 .subscribe(function (basicRotation) {
25301 _this._navigator.stateService.rotateBasic(basicRotation);
25304 DragPanHandler.prototype._disable = function () {
25305 this._activeMouseSubscription.unsubscribe();
25306 this._activeTouchSubscription.unsubscribe();
25307 this._preventDefaultSubscription.unsubscribe();
25308 this._rotateBasicSubscription.unsubscribe();
25309 this._activeMouseSubscription = null;
25310 this._activeTouchSubscription = null;
25311 this._rotateBasicSubscription = null;
25313 DragPanHandler.prototype._getConfiguration = function (enable) {
25314 return { dragPan: enable };
25316 return DragPanHandler;
25317 }(Component_1.MouseHandlerBase));
25318 exports.DragPanHandler = DragPanHandler;
25319 exports.default = DragPanHandler;
25321 },{"../../Component":226,"rxjs/Observable":29,"three":176}],271:[function(require,module,exports){
25323 /// <reference path="../../../typings/index.d.ts" />
25324 var __extends = (this && this.__extends) || (function () {
25325 var extendStatics = Object.setPrototypeOf ||
25326 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25327 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25328 return function (d, b) {
25329 extendStatics(d, b);
25330 function __() { this.constructor = d; }
25331 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25334 Object.defineProperty(exports, "__esModule", { value: true });
25335 var Observable_1 = require("rxjs/Observable");
25336 require("rxjs/add/observable/merge");
25337 require("rxjs/add/operator/filter");
25338 require("rxjs/add/operator/map");
25339 require("rxjs/add/operator/withLatestFrom");
25340 var Component_1 = require("../../Component");
25341 var Geo_1 = require("../../Geo");
25343 * @class MouseComponent
25345 * @classdesc Component handling mouse and touch events for camera movement.
25347 var MouseComponent = (function (_super) {
25348 __extends(MouseComponent, _super);
25349 function MouseComponent(name, container, navigator) {
25350 var _this = _super.call(this, name, container, navigator) || this;
25351 _this._basicDistanceThreshold = 1e-3;
25352 _this._basicRotationThreshold = 5e-2;
25353 _this._bounceCoeff = 1e-1;
25354 var spatial = new Geo_1.Spatial();
25355 var viewportCoords = new Geo_1.ViewportCoords();
25356 _this._spatial = spatial;
25357 _this._viewportCoords = viewportCoords;
25358 _this._doubleClickZoomHandler = new Component_1.DoubleClickZoomHandler(_this, container, navigator, viewportCoords);
25359 _this._dragPanHandler = new Component_1.DragPanHandler(_this, container, navigator, viewportCoords, spatial);
25360 _this._scrollZoomHandler = new Component_1.ScrollZoomHandler(_this, container, navigator, viewportCoords);
25361 _this._touchZoomHandler = new Component_1.TouchZoomHandler(_this, container, navigator, viewportCoords);
25364 Object.defineProperty(MouseComponent.prototype, "doubleClickZoom", {
25366 * Get double click zoom.
25368 * @returns {DoubleClickZoomHandler} The double click zoom handler.
25371 return this._doubleClickZoomHandler;
25376 Object.defineProperty(MouseComponent.prototype, "dragPan", {
25380 * @returns {DragPanHandler} The drag pan handler.
25383 return this._dragPanHandler;
25388 Object.defineProperty(MouseComponent.prototype, "scrollZoom", {
25392 * @returns {ScrollZoomHandler} The scroll zoom handler.
25395 return this._scrollZoomHandler;
25400 Object.defineProperty(MouseComponent.prototype, "touchZoom", {
25404 * @returns {TouchZoomHandler} The touch zoom handler.
25407 return this._touchZoomHandler;
25412 MouseComponent.prototype._activate = function () {
25414 this._configurationSubscription = this._configuration$
25415 .subscribe(function (configuration) {
25416 if (configuration.doubleClickZoom) {
25417 _this._doubleClickZoomHandler.enable();
25420 _this._doubleClickZoomHandler.disable();
25422 if (configuration.dragPan) {
25423 _this._dragPanHandler.enable();
25426 _this._dragPanHandler.disable();
25428 if (configuration.scrollZoom) {
25429 _this._scrollZoomHandler.enable();
25432 _this._scrollZoomHandler.disable();
25434 if (configuration.touchZoom) {
25435 _this._touchZoomHandler.enable();
25438 _this._touchZoomHandler.disable();
25441 var inTransition$ = this._navigator.stateService.currentState$
25442 .map(function (frame) {
25443 return frame.state.alpha < 1;
25445 this._bounceSubscription = Observable_1.Observable
25446 .combineLatest(inTransition$, this._navigator.stateService.inTranslation$, this._container.mouseService.active$, this._container.touchService.active$)
25447 .map(function (noForce) {
25448 return noForce[0] || noForce[1] || noForce[2] || noForce[3];
25450 .distinctUntilChanged()
25451 .switchMap(function (noForce) {
25453 Observable_1.Observable.empty() :
25454 Observable_1.Observable.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$.first());
25456 .subscribe(function (args) {
25457 var renderCamera = args[0];
25458 var perspectiveCamera = renderCamera.perspective;
25459 var transform = args[1];
25460 if (!transform.hasValidScale && renderCamera.camera.focal < 0.1) {
25463 if (renderCamera.perspective.aspect === 0 || renderCamera.perspective.aspect === Number.POSITIVE_INFINITY) {
25466 var distanceThreshold = _this._basicDistanceThreshold / Math.pow(2, renderCamera.zoom);
25467 var basicCenter = _this._viewportCoords.viewportToBasic(0, 0, transform, perspectiveCamera);
25468 if (Math.abs(basicCenter[0] - 0.5) < distanceThreshold && Math.abs(basicCenter[1] - 0.5) < distanceThreshold) {
25471 var basicDistances = _this._viewportCoords.getBasicDistances(transform, perspectiveCamera);
25474 if (basicDistances[0] < distanceThreshold && basicDistances[1] < distanceThreshold &&
25475 basicDistances[2] < distanceThreshold && basicDistances[3] < distanceThreshold) {
25478 if (Math.abs(basicDistances[0] - basicDistances[2]) < distanceThreshold &&
25479 Math.abs(basicDistances[1] - basicDistances[3]) < distanceThreshold) {
25482 var coeff = _this._bounceCoeff;
25483 if (basicDistances[1] > 0 && basicDistances[3] === 0) {
25484 basicX = -coeff * basicDistances[1];
25486 else if (basicDistances[1] === 0 && basicDistances[3] > 0) {
25487 basicX = coeff * basicDistances[3];
25489 else if (basicDistances[1] > 0 && basicDistances[3] > 0) {
25490 basicX = coeff * (basicDistances[3] - basicDistances[1]) / 2;
25492 if (basicDistances[0] > 0 && basicDistances[2] === 0) {
25493 basicY = coeff * basicDistances[0];
25495 else if (basicDistances[0] === 0 && basicDistances[2] > 0) {
25496 basicY = -coeff * basicDistances[2];
25498 else if (basicDistances[0] > 0 && basicDistances[2] > 0) {
25499 basicY = coeff * (basicDistances[0] - basicDistances[2]) / 2;
25501 var rotationThreshold = _this._basicRotationThreshold;
25502 basicX = _this._spatial.clamp(basicX, -rotationThreshold, rotationThreshold);
25503 basicY = _this._spatial.clamp(basicY, -rotationThreshold, rotationThreshold);
25504 _this._navigator.stateService.rotateBasicUnbounded([basicX, basicY]);
25506 this._container.mouseService.claimMouse(this._name, 0);
25508 MouseComponent.prototype._deactivate = function () {
25509 this._container.mouseService.unclaimMouse(this._name);
25510 this._bounceSubscription.unsubscribe();
25511 this._configurationSubscription.unsubscribe();
25512 this._doubleClickZoomHandler.disable();
25513 this._dragPanHandler.disable();
25514 this._scrollZoomHandler.disable();
25515 this._touchZoomHandler.disable();
25517 MouseComponent.prototype._getDefaultConfiguration = function () {
25518 return { doubleClickZoom: true, dragPan: true, scrollZoom: true, touchZoom: true };
25520 return MouseComponent;
25521 }(Component_1.Component));
25523 MouseComponent.componentName = "mouse";
25524 exports.MouseComponent = MouseComponent;
25525 Component_1.ComponentService.register(MouseComponent);
25526 exports.default = MouseComponent;
25528 },{"../../Component":226,"../../Geo":229,"rxjs/Observable":29,"rxjs/add/observable/merge":44,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/withLatestFrom":83}],272:[function(require,module,exports){
25530 Object.defineProperty(exports, "__esModule", { value: true });
25531 var MouseHandlerBase = (function () {
25532 function MouseHandlerBase(component, container, navigator, viewportCoords) {
25533 this._component = component;
25534 this._container = container;
25535 this._navigator = navigator;
25536 this._viewportCoords = viewportCoords;
25537 this._enabled = false;
25539 Object.defineProperty(MouseHandlerBase.prototype, "isEnabled", {
25541 * Returns a Boolean indicating whether the interaction is enabled.
25543 * @returns {boolean} `true` if the interaction is enabled.
25546 return this._enabled;
25552 * Enables the interaction.
25554 * @example ```mouseComponent.<handler-name>.enable();```
25556 MouseHandlerBase.prototype.enable = function () {
25557 if (this._enabled || !this._component.activated) {
25561 this._enabled = true;
25562 this._component.configure(this._getConfiguration(true));
25565 * Disables the interaction.
25567 * @example ```mouseComponent.<handler-name>.disable();```
25569 MouseHandlerBase.prototype.disable = function () {
25570 if (!this._enabled) {
25574 this._enabled = false;
25575 if (this._component.activated) {
25576 this._component.configure(this._getConfiguration(false));
25579 return MouseHandlerBase;
25581 exports.MouseHandlerBase = MouseHandlerBase;
25582 exports.default = MouseHandlerBase;
25584 },{}],273:[function(require,module,exports){
25586 var __extends = (this && this.__extends) || (function () {
25587 var extendStatics = Object.setPrototypeOf ||
25588 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25589 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25590 return function (d, b) {
25591 extendStatics(d, b);
25592 function __() { this.constructor = d; }
25593 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25596 Object.defineProperty(exports, "__esModule", { value: true });
25597 var Component_1 = require("../../Component");
25599 * The `ScrollZoomHandler` allows the user to zoom the viewer photo by scrolling.
25603 * var mouseComponent = viewer.getComponent("mouse");
25605 * mouseComponent.scrollZoom.disable();
25606 * mouseComponent.scrollZoom.enable();
25608 * var isEnabled = mouseComponent.scrollZoom.isEnabled;
25611 var ScrollZoomHandler = (function (_super) {
25612 __extends(ScrollZoomHandler, _super);
25613 function ScrollZoomHandler() {
25614 return _super !== null && _super.apply(this, arguments) || this;
25616 ScrollZoomHandler.prototype._enable = function () {
25618 this._preventDefaultSubscription = this._container.mouseService.mouseWheel$
25619 .subscribe(function (event) {
25620 event.preventDefault();
25622 this._zoomSubscription = this._container.mouseService
25623 .filtered$(this._component.name, this._container.mouseService.mouseWheel$)
25624 .withLatestFrom(this._navigator.stateService.currentState$, function (w, f) {
25627 .filter(function (args) {
25628 var state = args[1].state;
25629 return state.currentNode.fullPano || state.nodesAhead < 1;
25631 .map(function (args) {
25634 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) {
25637 .subscribe(function (args) {
25638 var event = args[0];
25639 var render = args[1];
25640 var transform = args[2];
25641 var element = _this._container.element;
25642 var _a = _this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
25643 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
25644 var reference = transform.projectBasic(unprojected.toArray());
25645 var deltaY = event.deltaY;
25646 if (event.deltaMode === 1) {
25647 deltaY = 40 * deltaY;
25649 else if (event.deltaMode === 2) {
25650 deltaY = 800 * deltaY;
25652 var canvasSize = _this._viewportCoords.containerToCanvas(element);
25653 var zoom = -3 * deltaY / canvasSize[1];
25654 _this._navigator.stateService.zoomIn(zoom, reference);
25657 ScrollZoomHandler.prototype._disable = function () {
25658 this._preventDefaultSubscription.unsubscribe();
25659 this._zoomSubscription.unsubscribe();
25660 this._preventDefaultSubscription = null;
25661 this._zoomSubscription = null;
25663 ScrollZoomHandler.prototype._getConfiguration = function (enable) {
25664 return { scrollZoom: enable };
25666 return ScrollZoomHandler;
25667 }(Component_1.MouseHandlerBase));
25668 exports.ScrollZoomHandler = ScrollZoomHandler;
25669 exports.default = ScrollZoomHandler;
25671 },{"../../Component":226}],274:[function(require,module,exports){
25673 /// <reference path="../../../typings/index.d.ts" />
25674 var __extends = (this && this.__extends) || (function () {
25675 var extendStatics = Object.setPrototypeOf ||
25676 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25677 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25678 return function (d, b) {
25679 extendStatics(d, b);
25680 function __() { this.constructor = d; }
25681 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25684 Object.defineProperty(exports, "__esModule", { value: true });
25685 var Observable_1 = require("rxjs/Observable");
25686 var Component_1 = require("../../Component");
25688 * The `TouchZoomHandler` allows the user to zoom the viewer photo by pinching on a touchscreen.
25692 * var mouseComponent = viewer.getComponent("mouse");
25694 * mouseComponent.touchZoom.disable();
25695 * mouseComponent.touchZoom.enable();
25697 * var isEnabled = mouseComponent.touchZoom.isEnabled;
25700 var TouchZoomHandler = (function (_super) {
25701 __extends(TouchZoomHandler, _super);
25702 function TouchZoomHandler() {
25703 return _super !== null && _super.apply(this, arguments) || this;
25705 TouchZoomHandler.prototype._enable = function () {
25707 this._preventDefaultSubscription = this._container.touchService.pinch$
25708 .subscribe(function (pinch) {
25709 pinch.originalEvent.preventDefault();
25711 var pinchStarted$ = this._container.touchService.pinchStart$
25712 .map(function (event) {
25715 var pinchStopped$ = this._container.touchService.pinchEnd$
25716 .map(function (event) {
25719 this._activeSubscription = Observable_1.Observable
25720 .merge(pinchStarted$, pinchStopped$)
25721 .subscribe(this._container.touchService.activate$);
25722 this._zoomSubscription = this._container.touchService.pinch$
25723 .withLatestFrom(this._navigator.stateService.currentState$)
25724 .filter(function (args) {
25725 var state = args[1].state;
25726 return state.currentNode.fullPano || state.nodesAhead < 1;
25728 .map(function (args) {
25731 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
25732 .subscribe(function (_a) {
25733 var pinch = _a[0], render = _a[1], transform = _a[2];
25734 var element = _this._container.element;
25735 var _b = _this._viewportCoords.canvasPosition(pinch, element), canvasX = _b[0], canvasY = _b[1];
25736 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
25737 var reference = transform.projectBasic(unprojected.toArray());
25738 var _c = _this._viewportCoords.containerToCanvas(element), canvasWidth = _c[0], canvasHeight = _c[1];
25739 var zoom = 3 * pinch.distanceChange / Math.min(canvasWidth, canvasHeight);
25740 _this._navigator.stateService.zoomIn(zoom, reference);
25743 TouchZoomHandler.prototype._disable = function () {
25744 this._activeSubscription.unsubscribe();
25745 this._preventDefaultSubscription.unsubscribe();
25746 this._zoomSubscription.unsubscribe();
25747 this._preventDefaultSubscription = null;
25748 this._zoomSubscription = null;
25750 TouchZoomHandler.prototype._getConfiguration = function (enable) {
25751 return { touchZoom: enable };
25753 return TouchZoomHandler;
25754 }(Component_1.MouseHandlerBase));
25755 exports.TouchZoomHandler = TouchZoomHandler;
25756 exports.default = TouchZoomHandler;
25758 },{"../../Component":226,"rxjs/Observable":29}],275:[function(require,module,exports){
25760 Object.defineProperty(exports, "__esModule", { value: true });
25761 var Popup_1 = require("./popup/Popup");
25762 exports.Popup = Popup_1.Popup;
25763 var PopupComponent_1 = require("./PopupComponent");
25764 exports.PopupComponent = PopupComponent_1.PopupComponent;
25766 },{"./PopupComponent":276,"./popup/Popup":277}],276:[function(require,module,exports){
25768 var __extends = (this && this.__extends) || (function () {
25769 var extendStatics = Object.setPrototypeOf ||
25770 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25771 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25772 return function (d, b) {
25773 extendStatics(d, b);
25774 function __() { this.constructor = d; }
25775 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25778 Object.defineProperty(exports, "__esModule", { value: true });
25779 var Observable_1 = require("rxjs/Observable");
25780 var Subject_1 = require("rxjs/Subject");
25781 var Component_1 = require("../../Component");
25783 * @class PopupComponent
25785 * @classdesc Component for showing HTML popup objects.
25787 * The `add` method is used for adding new popups. Popups are removed by reference.
25789 * It is not possible to update popups in the set by updating any properties
25790 * directly on the popup object. Popups need to be replaced by
25791 * removing them and creating new ones with relevant changed properties and
25792 * adding those instead.
25794 * Popups are only relevant to a single image because they are based on
25795 * 2D basic image coordinates. Popups related to a certain image should
25796 * be removed when the viewer is moved to another node.
25798 * To retrive and use the popup component
25802 * var viewer = new Mapillary.Viewer(
25806 * { component: { popup: true } });
25808 * var popupComponent = viewer.getComponent("popup");
25811 var PopupComponent = (function (_super) {
25812 __extends(PopupComponent, _super);
25813 function PopupComponent(name, container, navigator) {
25814 var _this = _super.call(this, name, container, navigator) || this;
25815 _this._popups = [];
25816 _this._added$ = new Subject_1.Subject();
25817 _this._popups$ = new Subject_1.Subject();
25821 * Add popups to the popups set.
25823 * @description Adding a new popup never replaces an old one
25824 * because they are stored by reference. Adding an already
25825 * existing popup has no effect.
25827 * @param {Array<Popup>} popups - Popups to add.
25829 * @example ```popupComponent.add([popup1, popup2]);```
25831 PopupComponent.prototype.add = function (popups) {
25832 for (var _i = 0, popups_1 = popups; _i < popups_1.length; _i++) {
25833 var popup = popups_1[_i];
25834 if (this._popups.indexOf(popup) !== -1) {
25837 this._popups.push(popup);
25838 if (this._activated) {
25839 popup.setParentContainer(this._popupContainer);
25842 this._added$.next(popups);
25843 this._popups$.next(this._popups);
25846 * Returns an array of all popups.
25848 * @example ```var popups = popupComponent.getAll();```
25850 PopupComponent.prototype.getAll = function () {
25851 return this._popups.slice();
25854 * Remove popups based on reference from the popup set.
25856 * @param {Array<Popup>} popups - Popups to remove.
25858 * @example ```popupComponent.remove([popup1, popup2]);```
25860 PopupComponent.prototype.remove = function (popups) {
25861 for (var _i = 0, popups_2 = popups; _i < popups_2.length; _i++) {
25862 var popup = popups_2[_i];
25863 this._remove(popup);
25865 this._popups$.next(this._popups);
25868 * Remove all popups from the popup set.
25870 * @example ```popupComponent.removeAll();```
25872 PopupComponent.prototype.removeAll = function () {
25873 for (var _i = 0, _a = this._popups.slice(); _i < _a.length; _i++) {
25874 var popup = _a[_i];
25875 this._remove(popup);
25877 this._popups$.next(this._popups);
25879 PopupComponent.prototype._activate = function () {
25881 this._popupContainer = document.createElement("div");
25882 this._popupContainer.className = "mapillary-js-popup-container";
25883 this._container.element.appendChild(this._popupContainer);
25884 for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
25885 var popup = _a[_i];
25886 popup.setParentContainer(this._popupContainer);
25888 this._updateAllSubscription = Observable_1.Observable
25889 .combineLatest(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
25890 .subscribe(function (_a) {
25891 var renderCamera = _a[0], size = _a[1], transform = _a[2];
25892 for (var _i = 0, _b = _this._popups; _i < _b.length; _i++) {
25893 var popup = _b[_i];
25894 popup.update(renderCamera, size, transform);
25897 var changed$ = this._popups$
25898 .startWith(this._popups)
25899 .switchMap(function (popups) {
25900 return Observable_1.Observable
25902 .mergeMap(function (popup) {
25903 return popup.changed$;
25906 .map(function (popup) {
25909 this._updateAddedChangedSubscription = this._added$
25911 .withLatestFrom(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
25912 .subscribe(function (_a) {
25913 var popups = _a[0], renderCamera = _a[1], size = _a[2], transform = _a[3];
25914 for (var _i = 0, popups_3 = popups; _i < popups_3.length; _i++) {
25915 var popup = popups_3[_i];
25916 popup.update(renderCamera, size, transform);
25920 PopupComponent.prototype._deactivate = function () {
25921 this._updateAllSubscription.unsubscribe();
25922 this._updateAddedChangedSubscription.unsubscribe();
25923 for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
25924 var popup = _a[_i];
25927 this._container.element.removeChild(this._popupContainer);
25928 delete this._popupContainer;
25930 PopupComponent.prototype._getDefaultConfiguration = function () {
25933 PopupComponent.prototype._remove = function (popup) {
25934 var index = this._popups.indexOf(popup);
25935 if (index === -1) {
25938 var removed = this._popups.splice(index, 1)[0];
25939 if (this._activated) {
25943 return PopupComponent;
25944 }(Component_1.Component));
25945 PopupComponent.componentName = "popup";
25946 exports.PopupComponent = PopupComponent;
25947 Component_1.ComponentService.register(PopupComponent);
25948 exports.default = PopupComponent;
25950 },{"../../Component":226,"rxjs/Observable":29,"rxjs/Subject":34}],277:[function(require,module,exports){
25952 /// <reference path="../../../../typings/index.d.ts" />
25953 Object.defineProperty(exports, "__esModule", { value: true });
25954 var Subject_1 = require("rxjs/Subject");
25955 var Geo_1 = require("../../../Geo");
25956 var Viewer_1 = require("../../../Viewer");
25960 * @classdesc Popup instance for rendering custom HTML content
25961 * on top of images. Popups are based on 2D basic image coordinates
25962 * (see the {@link Viewer} class documentation for more information about coordinate
25963 * systems) and a certain popup is therefore only relevant to a single image.
25964 * Popups related to a certain image should be removed when moving
25965 * to another image.
25967 * A popup must have both its content and its point or rect set to be
25968 * rendered. Popup options can not be updated after creation but the
25969 * basic point or rect as well as its content can be changed by calling
25970 * the appropriate methods.
25972 * To create and add one `Popup` with default configuration
25973 * (tooltip visuals and automatic float) and one with specific options
25978 * var defaultSpan = document.createElement('span');
25979 * defaultSpan.innerHTML = 'hello default';
25981 * var defaultPopup = new Mapillary.PopupComponent.Popup();
25982 * defaultPopup.setDOMContent(defaultSpan);
25983 * defaultPopup.setBasicPoint([0.3, 0.3]);
25985 * var cleanSpan = document.createElement('span');
25986 * cleanSpan.innerHTML = 'hello clean';
25988 * var cleanPopup = new Mapillary.PopupComponent.Popup({
25990 * float: Mapillary.Alignment.Top,
25995 * cleanPopup.setDOMContent(cleanSpan);
25996 * cleanPopup.setBasicPoint([0.6, 0.6]);
25998 * popupComponent.add([defaultPopup, cleanPopup]);
26001 * @description Implementation of API methods and API documentation inspired
26002 * by/used from https://github.com/mapbox/mapbox-gl-js/blob/v0.38.0/src/ui/popup.js
26004 var Popup = (function () {
26005 function Popup(options, viewportCoords) {
26006 this._options = {};
26008 this._options.clean = options.clean;
26009 this._options.float = options.float;
26010 this._options.offset = options.offset;
26011 this._options.opacity = options.opacity;
26012 this._options.position = options.position;
26014 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
26015 this._notifyChanged$ = new Subject_1.Subject();
26017 Object.defineProperty(Popup.prototype, "changed$", {
26021 * @description Internal observable used by the component to
26022 * render the popup when its position or content has changed.
26025 return this._notifyChanged$;
26033 * @description Internal method used by the component to
26034 * remove all references to the popup.
26036 Popup.prototype.remove = function () {
26037 if (this._content && this._content.parentNode) {
26038 this._content.parentNode.removeChild(this._content);
26040 if (this._container) {
26041 this._container.parentNode.removeChild(this._container);
26042 delete this._container;
26044 if (this._parentContainer) {
26045 delete this._parentContainer;
26049 * Sets a 2D basic image coordinates point to the popup's anchor, and
26050 * moves the popup to it.
26052 * @description Overwrites any previously set point or rect.
26054 * @param {Array<number>} basicPoint - Point in 2D basic image coordinates.
26058 * var popup = new Mapillary.PopupComponent.Popup();
26059 * popup.setText('hello image');
26060 * popup.setBasicPoint([0.3, 0.3]);
26062 * popupComponent.add([popup]);
26065 Popup.prototype.setBasicPoint = function (basicPoint) {
26066 this._point = basicPoint.slice();
26068 this._notifyChanged$.next(this);
26071 * Sets a 2D basic image coordinates rect to the popup's anchor, and
26072 * moves the popup to it.
26074 * @description Overwrites any previously set point or rect.
26076 * @param {Array<number>} basicRect - Rect in 2D basic image
26077 * coordinates ([topLeftX, topLeftY, bottomRightX, bottomRightY]) .
26081 * var popup = new Mapillary.PopupComponent.Popup();
26082 * popup.setText('hello image');
26083 * popup.setBasicRect([0.3, 0.3, 0.5, 0.6]);
26085 * popupComponent.add([popup]);
26088 Popup.prototype.setBasicRect = function (basicRect) {
26089 this._rect = basicRect.slice();
26090 this._point = null;
26091 this._notifyChanged$.next(this);
26094 * Sets the popup's content to the element provided as a DOM node.
26096 * @param {Node} htmlNode - A DOM node to be used as content for the popup.
26100 * var div = document.createElement('div');
26101 * div.innerHTML = 'hello image';
26103 * var popup = new Mapillary.PopupComponent.Popup();
26104 * popup.setDOMContent(div);
26105 * popup.setBasicPoint([0.3, 0.3]);
26107 * popupComponent.add([popup]);
26110 Popup.prototype.setDOMContent = function (htmlNode) {
26111 if (this._content && this._content.parentNode) {
26112 this._content.parentNode.removeChild(this._content);
26114 var className = "mapillaryjs-popup-content" + (this._options.clean === true ? "-clean" : "");
26115 this._content = this._createElement("div", className, this._container);
26116 this._content.appendChild(htmlNode);
26117 this._notifyChanged$.next(this);
26120 * Sets the popup's content to the HTML provided as a string.
26122 * @description This method does not perform HTML filtering or sanitization,
26123 * and must be used only with trusted content. Consider Popup#setText if the
26124 * content is an untrusted text string.
26126 * @param {string} html - A string representing HTML content for the popup.
26130 * var popup = new Mapillary.PopupComponent.Popup();
26131 * popup.setHTML('<div>hello image</div>');
26132 * popup.setBasicPoint([0.3, 0.3]);
26134 * popupComponent.add([popup]);
26137 Popup.prototype.setHTML = function (html) {
26138 var frag = document.createDocumentFragment();
26139 var temp = document.createElement("body");
26141 temp.innerHTML = html;
26143 child = temp.firstChild;
26147 frag.appendChild(child);
26149 this.setDOMContent(frag);
26152 * Sets the popup's content to a string of text.
26154 * @description This function creates a Text node in the DOM, so it cannot insert raw HTML.
26155 * Use this method for security against XSS if the popup content is user-provided.
26157 * @param {string} text - Textual content for the popup.
26161 * var popup = new Mapillary.PopupComponent.Popup();
26162 * popup.setText('hello image');
26163 * popup.setBasicPoint([0.3, 0.3]);
26165 * popupComponent.add([popup]);
26168 Popup.prototype.setText = function (text) {
26169 this.setDOMContent(document.createTextNode(text));
26174 * @description Internal method for attaching the popup to
26175 * its parent container so that it is rendered in the DOM tree.
26177 Popup.prototype.setParentContainer = function (parentContainer) {
26178 this._parentContainer = parentContainer;
26183 * @description Internal method for updating the rendered
26184 * position of the popup called by the popup component.
26186 Popup.prototype.update = function (renderCamera, size, transform) {
26187 if (!this._parentContainer || !this._content) {
26190 if (!this._point && !this._rect) {
26193 if (!this._container) {
26194 this._container = this._createElement("div", "mapillaryjs-popup", this._parentContainer);
26195 var showTip = this._options.clean !== true &&
26196 this._options.float !== Viewer_1.Alignment.Center;
26198 this._tip = this._createElement("div", "mapillaryjs-popup-tip", this._container);
26199 this._createElement("div", "mapillaryjs-popup-tip-inner", this._tip);
26201 this._container.appendChild(this._content);
26202 this._parentContainer.appendChild(this._container);
26203 if (this._options.opacity != null) {
26204 this._container.style.opacity = this._options.opacity.toString();
26207 var pointPixel = null;
26208 var position = this._alignmentToPopupAligment(this._options.position);
26209 var float = this._alignmentToPopupAligment(this._options.float);
26210 if (this._point != null) {
26212 this._viewportCoords.basicToCanvasSafe(this._point[0], this._point[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26215 _a = this._rectToPixel(this._rect, position, renderCamera, size, transform), pointPixel = _a[0], position = _a[1];
26220 if (pointPixel == null) {
26221 this._container.style.visibility = "hidden";
26224 this._container.style.visibility = "visible";
26226 var width = this._container.offsetWidth;
26227 var height = this._container.offsetHeight;
26228 var floats = this._pixelToFloats(pointPixel, size, width, height);
26229 float = floats.length === 0 ? "bottom" : floats.join("-");
26231 if (!!this._options.offset) {
26232 var offset = this._options.offset;
26233 var sign = offset >= 0 ? 1 : -1;
26234 var cornerOffset = sign * Math.round(Math.sqrt(0.5 * Math.pow(offset, 2)));
26235 var floatOffset = {
26236 "bottom": [0, offset],
26237 "bottom-left": [-cornerOffset, cornerOffset],
26238 "bottom-right": [cornerOffset, cornerOffset],
26240 "left": [-offset, 0],
26241 "right": [offset, 0],
26242 "top": [0, -offset],
26243 "top-left": [-cornerOffset, -cornerOffset],
26244 "top-right": [cornerOffset, -cornerOffset],
26246 pointPixel = [pointPixel[0] + floatOffset[float][0], pointPixel[1] + floatOffset[float][1]];
26248 pointPixel = [Math.round(pointPixel[0]), Math.round(pointPixel[1])];
26249 var floatTranslate = {
26250 "bottom": "translate(-50%,0)",
26251 "bottom-left": "translate(-100%,0)",
26252 "bottom-right": "translate(0,0)",
26253 "center": "translate(-50%,-50%)",
26254 "left": "translate(-100%,-50%)",
26255 "right": "translate(0,-50%)",
26256 "top": "translate(-50%,-100%)",
26257 "top-left": "translate(-100%,-100%)",
26258 "top-right": "translate(0,-100%)",
26260 var classList = this._container.classList;
26261 for (var key in floatTranslate) {
26262 if (!floatTranslate.hasOwnProperty(key)) {
26265 classList.remove("mapillaryjs-popup-float-" + key);
26267 classList.add("mapillaryjs-popup-float-" + float);
26268 this._container.style.transform = floatTranslate[float] + " translate(" + pointPixel[0] + "px," + pointPixel[1] + "px)";
26271 Popup.prototype._createElement = function (tagName, className, container) {
26272 var element = document.createElement(tagName);
26274 element.className = className;
26277 container.appendChild(element);
26281 Popup.prototype._rectToPixel = function (rect, position, renderCamera, size, transform) {
26283 var width = this._container.offsetWidth;
26284 var height = this._container.offsetHeight;
26285 var floatOffsets = {
26286 "bottom": [0, height / 2],
26287 "bottom-left": [-width / 2, height / 2],
26288 "bottom-right": [width / 2, height / 2],
26289 "left": [-width / 2, 0],
26290 "right": [width / 2, 0],
26291 "top": [0, -height / 2],
26292 "top-left": [-width / 2, -height / 2],
26293 "top-right": [width / 2, -height / 2],
26295 var automaticPositions = ["bottom", "top", "left", "right"];
26296 var largestVisibleArea = [0, null, null];
26297 for (var _i = 0, automaticPositions_1 = automaticPositions; _i < automaticPositions_1.length; _i++) {
26298 var automaticPosition = automaticPositions_1[_i];
26299 var pointBasic_1 = this._pointFromRectPosition(rect, automaticPosition);
26300 var pointPixel = this._viewportCoords.basicToCanvasSafe(pointBasic_1[0], pointBasic_1[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26301 if (pointPixel == null) {
26304 var floatOffset = floatOffsets[automaticPosition];
26305 var offsetedPosition = [pointPixel[0] + floatOffset[0], pointPixel[1] + floatOffset[1]];
26306 var floats = this._pixelToFloats(offsetedPosition, size, width, height / 2);
26307 if (floats.length === 0 &&
26308 pointPixel[0] > 0 &&
26309 pointPixel[0] < size.width &&
26310 pointPixel[1] > 0 &&
26311 pointPixel[1] < size.height) {
26312 return [pointPixel, automaticPosition];
26314 var minX = Math.max(offsetedPosition[0] - width / 2, 0);
26315 var maxX = Math.min(offsetedPosition[0] + width / 2, size.width);
26316 var minY = Math.max(offsetedPosition[1] - height / 2, 0);
26317 var maxY = Math.min(offsetedPosition[1] + height / 2, size.height);
26318 var visibleX = Math.max(0, maxX - minX);
26319 var visibleY = Math.max(0, maxY - minY);
26320 var visibleArea = visibleX * visibleY;
26321 if (visibleArea > largestVisibleArea[0]) {
26322 largestVisibleArea[0] = visibleArea;
26323 largestVisibleArea[1] = pointPixel;
26324 largestVisibleArea[2] = automaticPosition;
26327 if (largestVisibleArea[0] > 0) {
26328 return [largestVisibleArea[1], largestVisibleArea[2]];
26331 var pointBasic = this._pointFromRectPosition(rect, position);
26332 var pointCanvas = this._viewportCoords.basicToCanvasSafe(pointBasic[0], pointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26333 return [pointCanvas, position != null ? position : "bottom"];
26335 Popup.prototype._alignmentToPopupAligment = function (float) {
26337 case Viewer_1.Alignment.Bottom:
26339 case Viewer_1.Alignment.BottomLeft:
26340 return "bottom-left";
26341 case Viewer_1.Alignment.BottomRight:
26342 return "bottom-right";
26343 case Viewer_1.Alignment.Center:
26345 case Viewer_1.Alignment.Left:
26347 case Viewer_1.Alignment.Right:
26349 case Viewer_1.Alignment.Top:
26351 case Viewer_1.Alignment.TopLeft:
26353 case Viewer_1.Alignment.TopRight:
26354 return "top-right";
26359 Popup.prototype._pixelToFloats = function (pointPixel, size, width, height) {
26361 if (pointPixel[1] < height) {
26362 floats.push("bottom");
26364 else if (pointPixel[1] > size.height - height) {
26365 floats.push("top");
26367 if (pointPixel[0] < width / 2) {
26368 floats.push("right");
26370 else if (pointPixel[0] > size.width - width / 2) {
26371 floats.push("left");
26375 Popup.prototype._pointFromRectPosition = function (rect, position) {
26376 switch (position) {
26378 return [(rect[0] + rect[2]) / 2, rect[3]];
26379 case "bottom-left":
26380 return [rect[0], rect[3]];
26381 case "bottom-right":
26382 return [rect[2], rect[3]];
26384 return [(rect[0] + rect[2]) / 2, (rect[1] + rect[3]) / 2];
26386 return [rect[0], (rect[1] + rect[3]) / 2];
26388 return [rect[2], (rect[1] + rect[3]) / 2];
26390 return [(rect[0] + rect[2]) / 2, rect[1]];
26392 return [rect[0], rect[1]];
26394 return [rect[2], rect[1]];
26396 return [(rect[0] + rect[2]) / 2, rect[3]];
26401 exports.Popup = Popup;
26402 exports.default = Popup;
26404 },{"../../../Geo":229,"../../../Viewer":236,"rxjs/Subject":34}],278:[function(require,module,exports){
26406 /// <reference path="../../../typings/index.d.ts" />
26407 var __extends = (this && this.__extends) || (function () {
26408 var extendStatics = Object.setPrototypeOf ||
26409 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26410 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26411 return function (d, b) {
26412 extendStatics(d, b);
26413 function __() { this.constructor = d; }
26414 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26417 Object.defineProperty(exports, "__esModule", { value: true });
26418 var Observable_1 = require("rxjs/Observable");
26419 var Subject_1 = require("rxjs/Subject");
26420 require("rxjs/add/observable/combineLatest");
26421 require("rxjs/add/observable/of");
26422 require("rxjs/add/operator/bufferCount");
26423 require("rxjs/add/operator/concat");
26424 require("rxjs/add/operator/distinctUntilChanged");
26425 require("rxjs/add/operator/filter");
26426 require("rxjs/add/operator/finally");
26427 require("rxjs/add/operator/first");
26428 require("rxjs/add/operator/map");
26429 require("rxjs/add/operator/publishReplay");
26430 require("rxjs/add/operator/scan");
26431 require("rxjs/add/operator/share");
26432 require("rxjs/add/operator/switchMap");
26433 require("rxjs/add/operator/takeUntil");
26434 require("rxjs/add/operator/withLatestFrom");
26435 var Component_1 = require("../../Component");
26436 var Edge_1 = require("../../Edge");
26438 * @class SequenceComponent
26439 * @classdesc Component showing navigation arrows for sequence directions
26440 * as well as playing button. Exposes an API to start and stop play.
26442 var SequenceComponent = (function (_super) {
26443 __extends(SequenceComponent, _super);
26444 function SequenceComponent(name, container, navigator) {
26445 var _this = _super.call(this, name, container, navigator) || this;
26446 _this._nodesAhead = 5;
26447 _this._configurationOperation$ = new Subject_1.Subject();
26448 _this._sequenceDOMRenderer = new Component_1.SequenceDOMRenderer(container.element);
26449 _this._sequenceDOMInteraction = new Component_1.SequenceDOMInteraction();
26450 _this._containerWidth$ = new Subject_1.Subject();
26451 _this._hoveredKeySubject$ = new Subject_1.Subject();
26452 _this._hoveredKey$ = _this._hoveredKeySubject$.share();
26453 _this._edgeStatus$ = _this._navigator.stateService.currentNode$
26454 .switchMap(function (node) {
26455 return node.sequenceEdges$;
26461 Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", {
26463 * Get hovered key observable.
26465 * @description An observable emitting the key of the node for the direction
26466 * arrow that is being hovered. When the mouse leaves a direction arrow null
26469 * @returns {Observable<string>}
26472 return this._hoveredKey$;
26480 * @fires PlayerComponent#playingchanged
26482 SequenceComponent.prototype.play = function () {
26483 this.configure({ playing: true });
26488 * @fires PlayerComponent#playingchanged
26490 SequenceComponent.prototype.stop = function () {
26491 this.configure({ playing: false });
26494 * Set the direction to follow when playing.
26496 * @param {EdgeDirection} direction - The direction that will be followed when playing.
26498 SequenceComponent.prototype.setDirection = function (direction) {
26499 this.configure({ direction: direction });
26502 * Set highlight key.
26504 * @description The arrow pointing towards the node corresponding to the
26505 * highlight key will be highlighted.
26507 * @param {string} highlightKey Key of node to be highlighted if existing.
26509 SequenceComponent.prototype.setHighlightKey = function (highlightKey) {
26510 this.configure({ highlightKey: highlightKey });
26513 * Set max width of container element.
26515 * @description Set max width of the container element holding
26516 * the sequence navigation elements. If the min width is larger than the
26517 * max width the min width value will be used.
26519 * The container element is automatically resized when the resize
26520 * method on the Viewer class is called.
26522 * @param {number} minWidth
26524 SequenceComponent.prototype.setMaxWidth = function (maxWidth) {
26525 this.configure({ maxWidth: maxWidth });
26528 * Set min width of container element.
26530 * @description Set min width of the container element holding
26531 * the sequence navigation elements. If the min width is larger than the
26532 * max width the min width value will be used.
26534 * The container element is automatically resized when the resize
26535 * method on the Viewer class is called.
26537 * @param {number} minWidth
26539 SequenceComponent.prototype.setMinWidth = function (minWidth) {
26540 this.configure({ minWidth: minWidth });
26543 * Set the value indicating whether the sequence UI elements should be visible.
26545 * @param {boolean} visible
26547 SequenceComponent.prototype.setVisible = function (visible) {
26548 this.configure({ visible: visible });
26551 SequenceComponent.prototype.resize = function () {
26553 this._configuration$
26555 .map(function (configuration) {
26556 return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
26558 .subscribe(function (containerWidth) {
26559 _this._containerWidth$.next(containerWidth);
26562 SequenceComponent.prototype._activate = function () {
26564 this._renderSubscription = Observable_1.Observable
26565 .combineLatest(this._edgeStatus$, this._configuration$, this._containerWidth$)
26566 .map(function (ec) {
26567 var edgeStatus = ec[0];
26568 var configuration = ec[1];
26569 var containerWidth = ec[2];
26570 var vNode = _this._sequenceDOMRenderer
26571 .render(edgeStatus, configuration, containerWidth, _this, _this._sequenceDOMInteraction, _this._navigator);
26572 return { name: _this._name, vnode: vNode };
26574 .subscribe(this._container.domRenderer.render$);
26575 this._containerWidthSubscription = this._configuration$
26576 .distinctUntilChanged(function (value1, value2) {
26577 return value1[0] === value2[0] && value1[1] === value2[1];
26578 }, function (configuration) {
26579 return [configuration.minWidth, configuration.maxWidth];
26581 .map(function (configuration) {
26582 return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
26584 .subscribe(this._containerWidth$);
26585 this._configurationSubscription = this._configurationOperation$
26586 .scan(function (configuration, operation) {
26587 return operation(configuration);
26588 }, { playing: false })
26589 .finally(function () {
26590 if (_this._playingSubscription != null) {
26591 _this._navigator.stateService.cutNodes();
26595 .subscribe(function () { });
26596 this._configuration$
26597 .map(function (newConfiguration) {
26598 return function (configuration) {
26599 if (newConfiguration.playing !== configuration.playing) {
26600 _this._navigator.stateService.cutNodes();
26601 if (newConfiguration.playing) {
26608 configuration.playing = newConfiguration.playing;
26609 return configuration;
26612 .subscribe(this._configurationOperation$);
26613 this._stopSubscription = this._configuration$
26614 .switchMap(function (configuration) {
26615 var edgeStatus$ = configuration.playing ?
26616 _this._edgeStatus$ :
26617 Observable_1.Observable.empty();
26618 var edgeDirection$ = Observable_1.Observable
26619 .of(configuration.direction);
26620 return Observable_1.Observable
26621 .combineLatest(edgeStatus$, edgeDirection$);
26623 .map(function (ne) {
26624 var edgeStatus = ne[0];
26625 var direction = ne[1];
26626 if (!edgeStatus.cached) {
26629 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
26631 if (edge.data.direction === direction) {
26637 .filter(function (hasEdge) {
26640 .map(function (hasEdge) {
26641 return { playing: false };
26643 .subscribe(this._configurationSubject$);
26644 this._hoveredKeySubscription = this._sequenceDOMInteraction.mouseEnterDirection$
26645 .switchMap(function (direction) {
26646 return _this._edgeStatus$
26647 .map(function (edgeStatus) {
26648 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
26650 if (edge.data.direction === direction) {
26656 .takeUntil(_this._sequenceDOMInteraction.mouseLeaveDirection$)
26657 .concat(Observable_1.Observable.of(null));
26659 .distinctUntilChanged()
26660 .subscribe(this._hoveredKeySubject$);
26662 SequenceComponent.prototype._deactivate = function () {
26663 this._stopSubscription.unsubscribe();
26664 this._renderSubscription.unsubscribe();
26665 this._configurationSubscription.unsubscribe();
26666 this._containerWidthSubscription.unsubscribe();
26667 this._hoveredKeySubscription.unsubscribe();
26670 SequenceComponent.prototype._getDefaultConfiguration = function () {
26672 direction: Edge_1.EdgeDirection.Next,
26679 SequenceComponent.prototype._play = function () {
26681 this._playingSubscription = this._navigator.stateService.currentState$
26682 .filter(function (frame) {
26683 return frame.state.nodesAhead < _this._nodesAhead;
26685 .map(function (frame) {
26686 return frame.state.lastNode;
26688 .distinctUntilChanged(undefined, function (lastNode) {
26689 return lastNode.key;
26691 .withLatestFrom(this._configuration$, function (lastNode, configuration) {
26692 return [lastNode, configuration.direction];
26694 .switchMap(function (nd) {
26695 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(nd[1]) > -1 ?
26696 nd[0].sequenceEdges$ :
26697 nd[0].spatialEdges$)
26698 .filter(function (status) {
26699 return status.cached;
26701 .zip(Observable_1.Observable.of(nd[1]), function (status, direction) {
26702 return [status, direction];
26705 .map(function (ed) {
26706 var direction = ed[1];
26707 for (var _i = 0, _a = ed[0].edges; _i < _a.length; _i++) {
26709 if (edge.data.direction === direction) {
26715 .filter(function (key) {
26716 return key != null;
26718 .switchMap(function (key) {
26719 return _this._navigator.graphService.cacheNode$(key);
26721 .subscribe(function (node) {
26722 _this._navigator.stateService.appendNodes([node]);
26723 }, function (error) {
26724 console.error(error);
26727 this._clearSubscription = this._navigator.stateService.currentNode$
26729 .subscribe(function (nodes) {
26730 _this._navigator.stateService.clearPriorNodes();
26732 this.fire(SequenceComponent.playingchanged, true);
26734 SequenceComponent.prototype._stop = function () {
26735 this._playingSubscription.unsubscribe();
26736 this._playingSubscription = null;
26737 this._clearSubscription.unsubscribe();
26738 this._clearSubscription = null;
26739 this.fire(SequenceComponent.playingchanged, false);
26741 return SequenceComponent;
26742 }(Component_1.Component));
26744 SequenceComponent.componentName = "sequence";
26746 * Event fired when playing starts or stops.
26748 * @event PlayerComponent#playingchanged
26749 * @type {boolean} Indicates whether the player is playing.
26751 SequenceComponent.playingchanged = "playingchanged";
26752 exports.SequenceComponent = SequenceComponent;
26753 Component_1.ComponentService.register(SequenceComponent);
26754 exports.default = SequenceComponent;
26756 },{"../../Component":226,"../../Edge":227,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/of":45,"rxjs/add/operator/bufferCount":50,"rxjs/add/operator/concat":54,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/finally":62,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73,"rxjs/add/operator/share":74,"rxjs/add/operator/switchMap":79,"rxjs/add/operator/takeUntil":81,"rxjs/add/operator/withLatestFrom":83}],279:[function(require,module,exports){
26758 Object.defineProperty(exports, "__esModule", { value: true });
26759 var Subject_1 = require("rxjs/Subject");
26760 var SequenceDOMInteraction = (function () {
26761 function SequenceDOMInteraction() {
26762 this._mouseEnterDirection$ = new Subject_1.Subject();
26763 this._mouseLeaveDirection$ = new Subject_1.Subject();
26765 Object.defineProperty(SequenceDOMInteraction.prototype, "mouseEnterDirection$", {
26767 return this._mouseEnterDirection$;
26772 Object.defineProperty(SequenceDOMInteraction.prototype, "mouseLeaveDirection$", {
26774 return this._mouseLeaveDirection$;
26779 return SequenceDOMInteraction;
26781 exports.SequenceDOMInteraction = SequenceDOMInteraction;
26782 exports.default = SequenceDOMInteraction;
26784 },{"rxjs/Subject":34}],280:[function(require,module,exports){
26786 /// <reference path="../../../typings/index.d.ts" />
26787 Object.defineProperty(exports, "__esModule", { value: true });
26788 var vd = require("virtual-dom");
26789 var Edge_1 = require("../../Edge");
26790 var SequenceDOMRenderer = (function () {
26791 function SequenceDOMRenderer(element) {
26792 this._minThresholdWidth = 320;
26793 this._maxThresholdWidth = 1480;
26794 this._minThresholdHeight = 240;
26795 this._maxThresholdHeight = 820;
26797 SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, component, interaction, navigator) {
26798 if (configuration.visible === false) {
26799 return vd.h("div.SequenceContainer", {}, []);
26801 var nextKey = null;
26802 var prevKey = null;
26803 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
26805 if (edge.data.direction === Edge_1.EdgeDirection.Next) {
26808 if (edge.data.direction === Edge_1.EdgeDirection.Prev) {
26812 var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component);
26813 var arrows = this._createSequenceArrows(nextKey, prevKey, configuration, interaction, navigator);
26814 var containerProperties = {
26815 oncontextmenu: function (event) { event.preventDefault(); },
26816 style: { height: (0.27 * containerWidth) + "px", width: containerWidth + "px" },
26818 return vd.h("div.SequenceContainer", containerProperties, arrows.concat([playingButton]));
26820 SequenceDOMRenderer.prototype.getContainerWidth = function (element, configuration) {
26821 var elementWidth = element.offsetWidth;
26822 var elementHeight = element.offsetHeight;
26823 var minWidth = configuration.minWidth;
26824 var maxWidth = configuration.maxWidth;
26825 if (maxWidth < minWidth) {
26826 maxWidth = minWidth;
26828 var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
26829 var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
26830 var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
26831 return minWidth + coeff * (maxWidth - minWidth);
26833 SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) {
26834 var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null ||
26835 configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null;
26836 var onclick = configuration.playing ?
26837 function (e) { component.stop(); } :
26838 canPlay ? function (e) { component.play(); } : null;
26839 var buttonProperties = {
26843 var iconClass = configuration.playing ?
26845 canPlay ? "Play" : "PlayDisabled";
26846 var icon = vd.h("div.SequenceComponentIcon", { className: iconClass }, []);
26847 var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled";
26848 return vd.h("div." + buttonClass, buttonProperties, [icon]);
26850 SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, configuration, interaction, navigator) {
26851 var nextProperties = {
26852 onclick: nextKey != null ?
26854 navigator.moveDir$(Edge_1.EdgeDirection.Next)
26855 .subscribe(function (node) { return; }, function (error) { console.error(error); });
26858 onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); },
26859 onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); },
26862 var prevProperties = {
26863 onclick: prevKey != null ?
26865 navigator.moveDir$(Edge_1.EdgeDirection.Prev)
26866 .subscribe(function (node) { return; }, function (error) { console.error(error); });
26869 onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); },
26870 onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); },
26873 var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey);
26874 var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey);
26875 var nextIcon = vd.h("div.SequenceComponentIcon", []);
26876 var prevIcon = vd.h("div.SequenceComponentIcon", []);
26878 vd.h("div." + nextClass, nextProperties, [nextIcon]),
26879 vd.h("div." + prevClass, prevProperties, [prevIcon]),
26882 SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) {
26883 var className = direction === Edge_1.EdgeDirection.Next ?
26884 "SequenceStepNext" :
26885 "SequenceStepPrev";
26887 className += "Disabled";
26890 if (highlightKey === key) {
26891 className += "Highlight";
26896 return SequenceDOMRenderer;
26898 exports.SequenceDOMRenderer = SequenceDOMRenderer;
26899 exports.default = SequenceDOMRenderer;
26901 },{"../../Edge":227,"virtual-dom":182}],281:[function(require,module,exports){
26903 Object.defineProperty(exports, "__esModule", { value: true });
26904 var GeometryTagError_1 = require("./error/GeometryTagError");
26905 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
26906 var PointGeometry_1 = require("./geometry/PointGeometry");
26907 exports.PointGeometry = PointGeometry_1.PointGeometry;
26908 var RectGeometry_1 = require("./geometry/RectGeometry");
26909 exports.RectGeometry = RectGeometry_1.RectGeometry;
26910 var PolygonGeometry_1 = require("./geometry/PolygonGeometry");
26911 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
26912 var OutlineTag_1 = require("./tag/OutlineTag");
26913 exports.OutlineTag = OutlineTag_1.OutlineTag;
26914 var SpotTag_1 = require("./tag/SpotTag");
26915 exports.SpotTag = SpotTag_1.SpotTag;
26916 var TagComponent_1 = require("./TagComponent");
26917 exports.TagComponent = TagComponent_1.TagComponent;
26918 var TagMode_1 = require("./TagMode");
26919 exports.TagMode = TagMode_1.TagMode;
26921 },{"./TagComponent":282,"./TagMode":285,"./error/GeometryTagError":289,"./geometry/PointGeometry":291,"./geometry/PolygonGeometry":292,"./geometry/RectGeometry":293,"./tag/OutlineTag":297,"./tag/SpotTag":300}],282:[function(require,module,exports){
26923 /// <reference path="../../../typings/index.d.ts" />
26924 var __extends = (this && this.__extends) || (function () {
26925 var extendStatics = Object.setPrototypeOf ||
26926 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26927 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26928 return function (d, b) {
26929 extendStatics(d, b);
26930 function __() { this.constructor = d; }
26931 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26934 Object.defineProperty(exports, "__esModule", { value: true });
26935 var Observable_1 = require("rxjs/Observable");
26936 var Subject_1 = require("rxjs/Subject");
26937 require("rxjs/add/observable/combineLatest");
26938 require("rxjs/add/observable/empty");
26939 require("rxjs/add/observable/from");
26940 require("rxjs/add/observable/merge");
26941 require("rxjs/add/observable/of");
26942 require("rxjs/add/operator/combineLatest");
26943 require("rxjs/add/operator/concat");
26944 require("rxjs/add/operator/distinctUntilChanged");
26945 require("rxjs/add/operator/do");
26946 require("rxjs/add/operator/filter");
26947 require("rxjs/add/operator/map");
26948 require("rxjs/add/operator/merge");
26949 require("rxjs/add/operator/mergeMap");
26950 require("rxjs/add/operator/publishReplay");
26951 require("rxjs/add/operator/scan");
26952 require("rxjs/add/operator/share");
26953 require("rxjs/add/operator/skip");
26954 require("rxjs/add/operator/skipUntil");
26955 require("rxjs/add/operator/startWith");
26956 require("rxjs/add/operator/switchMap");
26957 require("rxjs/add/operator/take");
26958 require("rxjs/add/operator/takeUntil");
26959 require("rxjs/add/operator/withLatestFrom");
26960 var Component_1 = require("../../Component");
26961 var Geo_1 = require("../../Geo");
26962 var Render_1 = require("../../Render");
26964 * @class TagComponent
26966 * @classdesc Component for showing and editing tags with different
26967 * geometries composed from 2D basic image coordinates (see the
26968 * {@link Viewer} class documentation for more information about coordinate
26971 * The `add` method is used for adding new tags or replacing
26972 * tags already in the set. Tags are removed by id.
26974 * If a tag already in the set has the same
26975 * id as one of the tags added, the old tag will be removed and
26976 * the added tag will take its place.
26978 * The tag component mode can be set to either be non interactive or
26979 * to be in creating mode of a certain geometry type.
26981 * The tag properties can be updated at any time and the change will
26982 * be visibile immediately.
26984 * Tags are only relevant to a single image because they are based on
26985 * 2D basic image coordinates. Tags related to a certain image should
26986 * be removed when the viewer is moved to another node.
26988 * To retrive and use the tag component
26992 * var viewer = new Mapillary.Viewer(
26996 * { component: { tag: true } });
26998 * var tagComponent = viewer.getComponent("tag");
27001 var TagComponent = (function (_super) {
27002 __extends(TagComponent, _super);
27003 function TagComponent(name, container, navigator) {
27004 var _this = _super.call(this, name, container, navigator) || this;
27005 _this._tagDomRenderer = new Component_1.TagDOMRenderer();
27006 _this._tagScene = new Component_1.TagScene();
27007 _this._tagSet = new Component_1.TagSet();
27008 _this._tagCreator = new Component_1.TagCreator(_this, navigator);
27009 _this._viewportCoords = new Geo_1.ViewportCoords();
27010 _this._renderTags$ = _this._tagSet.changed$
27011 .map(function (tagSet) {
27012 var tags = tagSet.getAll();
27013 // ensure that tags are always rendered in the same order
27014 // to avoid hover tracking problems on first resize.
27015 tags.sort(function (t1, t2) {
27016 var id1 = t1.tag.id;
27017 var id2 = t2.tag.id;
27029 _this._tagChanged$ = _this._renderTags$
27030 .switchMap(function (tags) {
27031 return Observable_1.Observable
27033 .mergeMap(function (tag) {
27034 return Observable_1.Observable
27035 .merge(tag.tag.changed$, tag.tag.geometryChanged$);
27039 _this._renderTagGLChanged$ = _this._renderTags$
27040 .switchMap(function (tags) {
27041 return Observable_1.Observable
27043 .mergeMap(function (tag) {
27044 return tag.glObjectsChanged$;
27048 _this._tagInterationInitiated$ = _this._renderTags$
27049 .switchMap(function (tags) {
27050 return Observable_1.Observable
27052 .mergeMap(function (tag) {
27053 return tag.interact$
27054 .map(function (interaction) {
27055 return interaction.tag.id;
27060 _this._tagInteractionAbort$ = Observable_1.Observable
27061 .merge(_this._container.mouseService.documentMouseUp$)
27062 .map(function (e) { })
27064 _this._activeTag$ = _this._renderTags$
27065 .switchMap(function (tags) {
27066 return Observable_1.Observable
27068 .mergeMap(function (tag) {
27069 return tag.interact$;
27072 .merge(_this._tagInteractionAbort$
27074 return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null };
27077 _this._createGeometryChanged$ = _this._tagCreator.tag$
27078 .switchMap(function (tag) {
27079 return tag != null ?
27080 tag.geometryChanged$ :
27081 Observable_1.Observable.empty();
27084 _this._createGLObjectsChanged$ = _this._tagCreator.tag$
27085 .switchMap(function (tag) {
27086 return tag != null ?
27087 tag.glObjectsChanged$ :
27088 Observable_1.Observable.empty();
27091 _this._tagCreated$ = _this._tagCreator.tag$
27092 .switchMap(function (tag) {
27093 return tag != null ?
27095 Observable_1.Observable.empty();
27098 _this._vertexGeometryCreated$ = _this._tagCreated$
27099 .map(function (tag) {
27100 return tag.geometry;
27103 _this._pointGeometryCreated$ = new Subject_1.Subject();
27104 _this._geometryCreated$ = Observable_1.Observable
27105 .merge(_this._vertexGeometryCreated$, _this._pointGeometryCreated$)
27107 _this._basicClick$ = _this._container.mouseService.staticClick$
27108 .withLatestFrom(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$, function (event, renderCamera, transform) {
27109 return [event, renderCamera, transform];
27111 .map(function (ert) {
27112 var event = ert[0];
27113 var camera = ert[1];
27114 var transform = ert[2];
27115 var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
27119 _this._validBasicClick$ = _this._basicClick$
27120 .filter(function (basic) {
27123 return 0 <= x && x <= 1 && 0 <= y && y <= 1;
27126 _this._creatingConfiguration$ = _this._configuration$
27127 .distinctUntilChanged(function (c1, c2) {
27128 return c1.mode === c2.mode;
27129 }, function (configuration) {
27131 createColor: configuration.createColor,
27132 mode: configuration.mode,
27137 _this._creating$ = _this._creatingConfiguration$
27138 .map(function (configuration) {
27139 return configuration.mode !== Component_1.TagMode.Default;
27143 _this._creatingConfiguration$
27144 .subscribe(function (configuration) {
27145 _this.fire(TagComponent.modechanged, configuration.mode);
27150 * Add tags to the tag set or replace tags in the tag set.
27152 * @description If a tag already in the set has the same
27153 * id as one of the tags added, the old tag will be removed
27154 * the added tag will take its place.
27156 * @param {Array<Tag>} tags - Tags to add.
27158 * @example ```tagComponent.add([tag1, tag2]);```
27160 TagComponent.prototype.add = function (tags) {
27162 if (this._activated) {
27163 this._navigator.stateService.currentTransform$
27165 .subscribe(function (transform) {
27166 _this._tagSet.add(tags, transform);
27167 var renderTags = tags
27168 .map(function (tag) {
27169 return _this._tagSet.get(tag.id);
27171 _this._tagScene.add(renderTags);
27175 this._tagSet.addDeactivated(tags);
27179 * Change the current tag mode.
27181 * @description Change the tag mode to one of the create modes for creating new geometries.
27183 * @param {TagMode} mode - New tag mode.
27185 * @fires TagComponent#modechanged
27187 * @example ```tagComponent.changeMode(Mapillary.TagComponent.TagMode.CreateRect);```
27189 TagComponent.prototype.changeMode = function (mode) {
27190 this.configure({ mode: mode });
27193 * Returns the tag in the tag set with the specified id, or
27194 * undefined if the id matches no tag.
27196 * @param {string} tagId - Id of the tag.
27198 * @example ```var tag = tagComponent.get("tagId");```
27200 TagComponent.prototype.get = function (tagId) {
27201 if (this._activated) {
27202 var renderTag = this._tagSet.get(tagId);
27203 return renderTag !== undefined ? renderTag.tag : undefined;
27206 return this._tagSet.getDeactivated(tagId);
27210 * Returns an array of all tags.
27212 * @example ```var tags = tagComponent.getAll();```
27214 TagComponent.prototype.getAll = function () {
27215 if (this.activated) {
27216 return this._tagSet
27218 .map(function (renderTag) {
27219 return renderTag.tag;
27223 return this._tagSet.getAllDeactivated();
27227 * Check if a tag exist in the tag set.
27229 * @param {string} tagId - Id of the tag.
27231 * @example ```var tagExists = tagComponent.has("tagId");```
27233 TagComponent.prototype.has = function (tagId) {
27234 return this._activated ? this._tagSet.has(tagId) : this._tagSet.hasDeactivated(tagId);
27237 * Remove tags with the specified ids from the tag set.
27239 * @param {Array<string>} tagIds - Ids for tags to remove.
27241 * @example ```tagComponent.remove(["id-1", "id-2"]);```
27243 TagComponent.prototype.remove = function (tagIds) {
27244 if (this._activated) {
27245 this._tagSet.remove(tagIds);
27246 this._tagScene.remove(tagIds);
27249 this._tagSet.removeDeactivated(tagIds);
27253 * Remove all tags from the tag set.
27255 * @example ```tagComponent.removeAll();```
27257 TagComponent.prototype.removeAll = function () {
27258 if (this._activated) {
27259 this._tagSet.removeAll();
27260 this._tagScene.removeAll();
27263 this._tagSet.removeAllDeactivated();
27266 TagComponent.prototype._activate = function () {
27268 this._preventDefaultSubscription = this._activeTag$
27269 .switchMap(function (interaction) {
27270 return interaction.tag != null ?
27271 _this._container.mouseService.documentMouseMove$ :
27272 Observable_1.Observable.empty();
27274 .subscribe(function (event) {
27275 event.preventDefault(); // prevent selection of content outside the viewer
27277 this._geometryCreatedEventSubscription = this._geometryCreated$
27278 .subscribe(function (geometry) {
27279 _this.fire(TagComponent.geometrycreated, geometry);
27281 this._tagsChangedEventSubscription = this._renderTags$
27282 .subscribe(function (tags) {
27283 _this.fire(TagComponent.tagschanged, _this);
27285 var transformChanged$ = this.configuration$
27286 .switchMap(function (configuration) {
27287 return configuration.mode !== Component_1.TagMode.Default ?
27288 _this._navigator.stateService.currentTransform$
27289 .map(function (n) { return null; }) :
27290 Observable_1.Observable.empty();
27294 this._deleteCreatingSubscription = transformChanged$
27296 .subscribe(function () {
27297 _this._tagCreator.delete$.next(null);
27299 var tagAborted$ = this._tagCreator.tag$
27300 .switchMap(function (tag) {
27301 return tag != null ?
27303 .map(function (t) { return null; }) :
27304 Observable_1.Observable.empty();
27306 var tagCreated$ = this._tagCreated$
27307 .map(function (t) { return null; });
27308 var pointGeometryCreated$ = this._pointGeometryCreated$
27309 .map(function (p) { return null; });
27310 this._stopCreateSubscription = Observable_1.Observable
27311 .merge(tagAborted$, tagCreated$, pointGeometryCreated$)
27312 .subscribe(function () { _this.changeMode(Component_1.TagMode.Default); });
27313 var creatingStarted$ = Observable_1.Observable
27314 .combineLatest(this._creatingConfiguration$, transformChanged$)
27315 .map(function (_a) {
27316 var configuration = _a[0];
27317 return configuration;
27321 this._createSubscription = creatingStarted$
27322 .switchMap(function (configuration) {
27323 return configuration.mode === Component_1.TagMode.CreateRect ||
27324 configuration.mode === Component_1.TagMode.CreatePolygon ?
27325 _this._validBasicClick$.take(1) :
27326 Observable_1.Observable.empty();
27328 .subscribe(this._tagCreator.create$);
27329 this._createPointSubscription = creatingStarted$
27330 .switchMap(function (configuration) {
27331 return configuration.mode === Component_1.TagMode.CreatePoint ?
27332 _this._validBasicClick$.take(1) :
27333 Observable_1.Observable.empty();
27335 .map(function (basic) {
27336 return new Component_1.PointGeometry(basic);
27338 .subscribe(this._pointGeometryCreated$);
27339 var containerMouseMove$ = Observable_1.Observable
27340 .merge(this._container.mouseService.mouseMove$, this._container.mouseService.domMouseMove$)
27342 this._setCreateVertexSubscription = Observable_1.Observable
27343 .combineLatest(containerMouseMove$, this._tagCreator.tag$, this._container.renderService.renderCamera$)
27344 .filter(function (etr) {
27345 return etr[1] != null;
27347 .withLatestFrom(this._navigator.stateService.currentTransform$, function (etr, transform) {
27348 return [etr[0], etr[1], etr[2], transform];
27350 .subscribe(function (etrt) {
27351 var event = etrt[0];
27353 var camera = etrt[2];
27354 var transform = etrt[3];
27355 var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
27356 if (tag.geometry instanceof Component_1.RectGeometry) {
27357 tag.geometry.setVertex2d(3, basic, transform);
27359 else if (tag.geometry instanceof Component_1.PolygonGeometry) {
27360 tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basic, transform);
27363 this._addPointSubscription = creatingStarted$
27364 .switchMap(function (configuration) {
27365 return configuration.mode === Component_1.TagMode.CreateRect || configuration.mode === Component_1.TagMode.CreatePolygon ?
27366 _this._basicClick$.skipUntil(_this._validBasicClick$).skip(1) :
27367 Observable_1.Observable.empty();
27369 .withLatestFrom(this._tagCreator.tag$, function (basic, tag) {
27370 return [basic, tag];
27372 .subscribe(function (bt) {
27375 tag.addPoint(basic);
27377 this._containerClassListSubscription = this._creating$
27378 .subscribe(function (creating) {
27380 _this._container.element.classList.add("component-tag-create");
27383 _this._container.element.classList.remove("component-tag-create");
27386 this._deleteCreatedSubscription = this._creating$
27387 .subscribe(function (creating) {
27388 _this._tagCreator.delete$.next(null);
27390 this._setGLCreateTagSubscription = this._tagCreator.tag$
27391 .subscribe(function (tag) {
27392 if (_this._tagScene.hasCreateTag()) {
27393 _this._tagScene.removeCreateTag();
27396 _this._tagScene.addCreateTag(tag);
27399 this._createGLObjectsChangedSubscription = this._createGLObjectsChanged$
27400 .subscribe(function (tag) {
27401 _this._tagScene.updateCreateTagObjects(tag);
27403 this._claimMouseSubscription = this._tagInterationInitiated$
27404 .switchMap(function (id) {
27405 return containerMouseMove$
27406 .takeUntil(_this._tagInteractionAbort$)
27409 .subscribe(function (e) {
27410 _this._container.mouseService.claimMouse(_this._name, 1);
27412 this._mouseDragSubscription = this._activeTag$
27413 .withLatestFrom(containerMouseMove$, function (a, e) {
27416 .switchMap(function (args) {
27417 var activeTag = args[0];
27418 var mouseMove = args[1];
27419 if (activeTag.operation === Component_1.TagOperation.None) {
27420 return Observable_1.Observable.empty();
27422 var mouseDrag$ = Observable_1.Observable
27424 .concat(_this._container.mouseService
27425 .filtered$(_this._name, _this._container.mouseService.domMouseDrag$)
27426 .filter(function (event) {
27427 return _this._viewportCoords.insideElement(event, _this._container.element);
27429 return Observable_1.Observable
27430 .combineLatest(mouseDrag$, _this._container.renderService.renderCamera$)
27431 .withLatestFrom(Observable_1.Observable.of(activeTag), _this._navigator.stateService.currentTransform$, function (ec, a, t) {
27432 return [ec[0], ec[1], a, t];
27435 .subscribe(function (args) {
27436 var mouseEvent = args[0];
27437 var renderCamera = args[1];
27438 var activeTag = args[2];
27439 var transform = args[3];
27440 if (activeTag.operation === Component_1.TagOperation.None) {
27443 var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, activeTag.offsetX, activeTag.offsetY);
27444 if (activeTag.operation === Component_1.TagOperation.Centroid) {
27445 activeTag.tag.geometry.setCentroid2d(basic, transform);
27447 else if (activeTag.operation === Component_1.TagOperation.Vertex) {
27448 var vertexGeometry = activeTag.tag.geometry;
27449 vertexGeometry.setVertex2d(activeTag.vertexIndex, basic, transform);
27452 this._unclaimMouseSubscription = this._container.mouseService
27453 .filtered$(this._name, this._container.mouseService.domMouseDragEnd$)
27454 .subscribe(function (e) {
27455 _this._container.mouseService.unclaimMouse(_this._name);
27457 this._updateGLObjectsSubscription = this._renderTagGLChanged$
27458 .subscribe(function (tag) {
27459 _this._tagScene.updateObjects(tag);
27461 this._updateTagSceneSubscription = this._tagChanged$
27462 .subscribe(function (tag) {
27463 _this._tagScene.update();
27465 this._domSubscription = this._renderTags$
27467 .do(function (tags) {
27468 _this._container.domRenderer.render$.next({
27470 vnode: _this._tagDomRenderer.clear(),
27473 .combineLatest(this._container.renderService.renderCamera$, this._container.spriteService.spriteAtlas$, this._tagChanged$.startWith(null), this._tagCreator.tag$.merge(this._createGeometryChanged$).startWith(null), function (renderTags, rc, atlas, tag, ct) {
27474 return [rc, atlas, renderTags, tag, ct];
27476 .map(function (args) {
27479 vnode: _this._tagDomRenderer.render(args[2], args[4], args[1], args[0].perspective),
27482 .subscribe(this._container.domRenderer.render$);
27483 this._glSubscription = this._navigator.stateService.currentState$
27484 .map(function (frame) {
27485 var tagScene = _this._tagScene;
27490 needsRender: tagScene.needsRender,
27491 render: tagScene.render.bind(tagScene),
27492 stage: Render_1.GLRenderStage.Foreground,
27496 .subscribe(this._container.glRenderer.render$);
27497 this._navigator.stateService.currentTransform$
27499 .subscribe(function (transform) {
27500 _this._tagSet.activate(transform);
27501 _this._tagScene.add(_this._tagSet.getAll());
27504 TagComponent.prototype._deactivate = function () {
27505 this._tagScene.clear();
27506 this._tagSet.deactivate();
27507 this._tagCreator.delete$.next(null);
27508 this._claimMouseSubscription.unsubscribe();
27509 this._mouseDragSubscription.unsubscribe();
27510 this._unclaimMouseSubscription.unsubscribe();
27511 this._updateGLObjectsSubscription.unsubscribe();
27512 this._updateTagSceneSubscription.unsubscribe();
27513 this._stopCreateSubscription.unsubscribe();
27514 this._deleteCreatingSubscription.unsubscribe();
27515 this._createSubscription.unsubscribe();
27516 this._createPointSubscription.unsubscribe();
27517 this._setCreateVertexSubscription.unsubscribe();
27518 this._addPointSubscription.unsubscribe();
27519 this._deleteCreatedSubscription.unsubscribe();
27520 this._setGLCreateTagSubscription.unsubscribe();
27521 this._createGLObjectsChangedSubscription.unsubscribe();
27522 this._preventDefaultSubscription.unsubscribe();
27523 this._containerClassListSubscription.unsubscribe();
27524 this._domSubscription.unsubscribe();
27525 this._glSubscription.unsubscribe();
27526 this._geometryCreatedEventSubscription.unsubscribe();
27527 this._tagsChangedEventSubscription.unsubscribe();
27528 this._container.element.classList.remove("component-tag-create");
27530 TagComponent.prototype._getDefaultConfiguration = function () {
27532 createColor: 0xFFFFFF,
27533 mode: Component_1.TagMode.Default,
27536 TagComponent.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) {
27537 offsetX = offsetX != null ? offsetX : 0;
27538 offsetY = offsetY != null ? offsetY : 0;
27539 var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
27540 var basic = this._viewportCoords.canvasToBasic(canvasX - offsetX, canvasY - offsetY, element, transform, camera.perspective);
27543 return TagComponent;
27544 }(Component_1.Component));
27546 TagComponent.componentName = "tag";
27548 * Event fired when the create mode is changed.
27550 * @event TagComponent#modechanged
27551 * @type {TagMode} Tag mode
27554 * tagComponent.on("modechanged", function(mode) {
27555 * console.log(mode);
27559 TagComponent.modechanged = "modechanged";
27561 * Event fired when a geometry has been created.
27563 * @event TagComponent#geometrycreated
27564 * @type {Geometry} Created geometry.
27567 * tagComponent.on("geometrycreated", function(geometry) {
27568 * console.log(geometry);
27572 TagComponent.geometrycreated = "geometrycreated";
27574 * Event fired when the tags collection has changed.
27576 * @event TagComponent#tagschanged
27577 * @type {TagComponent} Tag component.
27580 * tagComponent.on("tagschanged", function(component) {
27581 * console.log(component.getAll());
27585 TagComponent.tagschanged = "tagschanged";
27586 exports.TagComponent = TagComponent;
27587 Component_1.ComponentService.register(TagComponent);
27588 exports.default = TagComponent;
27590 },{"../../Component":226,"../../Geo":229,"../../Render":232,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/empty":40,"rxjs/add/observable/from":41,"rxjs/add/observable/merge":44,"rxjs/add/observable/of":45,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/concat":54,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/do":59,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73,"rxjs/add/operator/share":74,"rxjs/add/operator/skip":75,"rxjs/add/operator/skipUntil":76,"rxjs/add/operator/startWith":78,"rxjs/add/operator/switchMap":79,"rxjs/add/operator/take":80,"rxjs/add/operator/takeUntil":81,"rxjs/add/operator/withLatestFrom":83}],283:[function(require,module,exports){
27592 Object.defineProperty(exports, "__esModule", { value: true });
27593 var Subject_1 = require("rxjs/Subject");
27594 require("rxjs/add/operator/map");
27595 require("rxjs/add/operator/scan");
27596 require("rxjs/add/operator/share");
27597 require("rxjs/add/operator/withLatestFrom");
27598 var Component_1 = require("../../Component");
27599 var TagCreator = (function () {
27600 function TagCreator(component, navigator) {
27601 this._component = component;
27602 this._navigator = navigator;
27603 this._tagOperation$ = new Subject_1.Subject();
27604 this._create$ = new Subject_1.Subject();
27605 this._delete$ = new Subject_1.Subject();
27606 this._tag$ = this._tagOperation$
27607 .scan(function (tag, operation) {
27608 return operation(tag);
27612 .withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$)
27613 .map(function (_a) {
27614 var coord = _a[0], conf = _a[1], transform = _a[2];
27615 return function (tag) {
27616 if (conf.mode === Component_1.TagMode.CreateRect) {
27617 var geometry = new Component_1.RectGeometry([
27623 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
27625 else if (conf.mode === Component_1.TagMode.CreatePolygon) {
27626 var geometry = new Component_1.PolygonGeometry([
27627 [coord[0], coord[1]],
27628 [coord[0], coord[1]],
27629 [coord[0], coord[1]],
27631 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
27636 .subscribe(this._tagOperation$);
27639 return function (tag) {
27643 .subscribe(this._tagOperation$);
27645 Object.defineProperty(TagCreator.prototype, "create$", {
27647 return this._create$;
27652 Object.defineProperty(TagCreator.prototype, "delete$", {
27654 return this._delete$;
27659 Object.defineProperty(TagCreator.prototype, "tag$", {
27668 exports.TagCreator = TagCreator;
27669 exports.default = TagCreator;
27671 },{"../../Component":226,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/scan":73,"rxjs/add/operator/share":74,"rxjs/add/operator/withLatestFrom":83}],284:[function(require,module,exports){
27673 /// <reference path="../../../typings/index.d.ts" />
27674 Object.defineProperty(exports, "__esModule", { value: true });
27675 var THREE = require("three");
27676 var vd = require("virtual-dom");
27677 var TagDOMRenderer = (function () {
27678 function TagDOMRenderer() {
27680 TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera) {
27681 var matrixWorldInverse = new THREE.Matrix4().getInverse(camera.matrixWorld);
27682 var projectionMatrix = camera.projectionMatrix;
27684 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
27685 var tag = tags_1[_i];
27686 vNodes = vNodes.concat(tag.getDOMObjects(atlas, matrixWorldInverse, projectionMatrix));
27688 if (createTag != null) {
27689 vNodes = vNodes.concat(createTag.getDOMObjects(matrixWorldInverse, projectionMatrix));
27691 return vd.h("div.TagContainer", {}, vNodes);
27693 TagDOMRenderer.prototype.clear = function () {
27694 return vd.h("div", {}, []);
27696 return TagDOMRenderer;
27698 exports.TagDOMRenderer = TagDOMRenderer;
27700 },{"three":176,"virtual-dom":182}],285:[function(require,module,exports){
27702 Object.defineProperty(exports, "__esModule", { value: true });
27704 * Enumeration for tag modes
27707 * @description Modes for the interaction in the tag component.
27710 (function (TagMode) {
27712 * Disables creating tags.
27714 TagMode[TagMode["Default"] = 0] = "Default";
27716 * Create a point geometry through a click.
27718 TagMode[TagMode["CreatePoint"] = 1] = "CreatePoint";
27720 * Create a polygon geometry through clicks.
27722 TagMode[TagMode["CreatePolygon"] = 2] = "CreatePolygon";
27724 * Create a rect geometry through clicks.
27726 TagMode[TagMode["CreateRect"] = 3] = "CreateRect";
27727 })(TagMode = exports.TagMode || (exports.TagMode = {}));
27728 exports.default = TagMode;
27730 },{}],286:[function(require,module,exports){
27732 Object.defineProperty(exports, "__esModule", { value: true });
27734 (function (TagOperation) {
27735 TagOperation[TagOperation["None"] = 0] = "None";
27736 TagOperation[TagOperation["Centroid"] = 1] = "Centroid";
27737 TagOperation[TagOperation["Vertex"] = 2] = "Vertex";
27738 })(TagOperation = exports.TagOperation || (exports.TagOperation = {}));
27739 exports.default = TagOperation;
27741 },{}],287:[function(require,module,exports){
27743 /// <reference path="../../../typings/index.d.ts" />
27744 Object.defineProperty(exports, "__esModule", { value: true });
27745 var THREE = require("three");
27746 var TagScene = (function () {
27747 function TagScene() {
27748 this._createTag = null;
27749 this._needsRender = false;
27750 this._scene = new THREE.Scene();
27753 Object.defineProperty(TagScene.prototype, "needsRender", {
27755 return this._needsRender;
27760 TagScene.prototype.add = function (tags) {
27761 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
27762 var tag = tags_1[_i];
27763 if (tag.tag.id in this._tags) {
27764 this._remove(tag.tag.id);
27768 this._needsRender = true;
27770 TagScene.prototype.addCreateTag = function (tag) {
27771 for (var _i = 0, _a = tag.glObjects; _i < _a.length; _i++) {
27772 var object = _a[_i];
27773 this._scene.add(object);
27775 this._createTag = { tag: tag, objects: tag.glObjects };
27776 this._needsRender = true;
27778 TagScene.prototype.clear = function () {
27779 for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
27783 this._needsRender = false;
27785 TagScene.prototype.hasCreateTag = function () {
27786 return this._createTag != null;
27788 TagScene.prototype.remove = function (ids) {
27789 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
27790 var id = ids_1[_i];
27793 this._needsRender = true;
27795 TagScene.prototype.removeAll = function () {
27796 for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
27800 this._needsRender = true;
27802 TagScene.prototype.removeCreateTag = function () {
27803 if (this._createTag == null) {
27806 for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
27807 var object = _a[_i];
27808 this._scene.remove(object);
27810 this._createTag.tag.dispose();
27811 this._createTag = null;
27812 this._needsRender = true;
27814 TagScene.prototype.render = function (perspectiveCamera, renderer) {
27815 renderer.render(this._scene, perspectiveCamera);
27816 this._needsRender = false;
27818 TagScene.prototype.update = function () {
27819 this._needsRender = true;
27821 TagScene.prototype.updateCreateTagObjects = function (tag) {
27822 if (this._createTag.tag !== tag) {
27823 throw new Error("Create tags do not have the same reference.");
27825 for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
27826 var object = _a[_i];
27827 this._scene.remove(object);
27829 for (var _b = 0, _c = tag.glObjects; _b < _c.length; _b++) {
27830 var object = _c[_b];
27831 this._scene.add(object);
27833 this._createTag.objects = tag.glObjects;
27834 this._needsRender = true;
27836 TagScene.prototype.updateObjects = function (tag) {
27837 var id = tag.tag.id;
27838 for (var _i = 0, _a = this._tags[id].objects; _i < _a.length; _i++) {
27839 var object = _a[_i];
27840 this._scene.remove(object);
27842 delete this._tags[id];
27844 this._needsRender = true;
27846 TagScene.prototype._add = function (tag) {
27847 var id = tag.tag.id;
27848 var objects = tag.glObjects;
27849 this._tags[id] = { tag: tag, objects: [] };
27850 for (var _i = 0, objects_1 = objects; _i < objects_1.length; _i++) {
27851 var object = objects_1[_i];
27852 this._tags[id].objects.push(object);
27853 this._scene.add(object);
27856 TagScene.prototype._remove = function (id) {
27857 for (var _i = 0, _a = this._tags[id].objects; _i < _a.length; _i++) {
27858 var object = _a[_i];
27859 this._scene.remove(object);
27861 this._tags[id].tag.dispose();
27862 delete this._tags[id];
27866 exports.TagScene = TagScene;
27867 exports.default = TagScene;
27869 },{"three":176}],288:[function(require,module,exports){
27871 Object.defineProperty(exports, "__esModule", { value: true });
27872 var Subject_1 = require("rxjs/Subject");
27873 require("rxjs/add/operator/map");
27874 require("rxjs/add/operator/scan");
27875 require("rxjs/add/operator/share");
27876 var Component_1 = require("../../Component");
27877 var TagSet = (function () {
27878 function TagSet() {
27880 this._hashDeactivated = {};
27881 this._notifyChanged$ = new Subject_1.Subject();
27883 Object.defineProperty(TagSet.prototype, "changed$", {
27885 return this._notifyChanged$;
27890 TagSet.prototype.activate = function (transform) {
27891 for (var id in this._hashDeactivated) {
27892 if (!this._hashDeactivated.hasOwnProperty(id)) {
27895 var tag = this._hashDeactivated[id];
27896 this._add(tag, transform);
27898 this._hashDeactivated = {};
27899 this._notifyChanged$.next(this);
27901 TagSet.prototype.deactivate = function () {
27902 for (var id in this._hash) {
27903 if (!this._hash.hasOwnProperty(id)) {
27906 this._hashDeactivated[id] = this._hash[id].tag;
27910 TagSet.prototype.add = function (tags, transform) {
27911 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
27912 var tag = tags_1[_i];
27913 this._add(tag, transform);
27915 this._notifyChanged$.next(this);
27917 TagSet.prototype.addDeactivated = function (tags) {
27918 for (var _i = 0, tags_2 = tags; _i < tags_2.length; _i++) {
27919 var tag = tags_2[_i];
27920 this._hashDeactivated[tag.id] = tag;
27923 TagSet.prototype.get = function (id) {
27924 return this.has(id) ? this._hash[id] : undefined;
27926 TagSet.prototype.getAll = function () {
27927 var hash = this._hash;
27928 return Object.keys(hash)
27929 .map(function (id) {
27933 TagSet.prototype.getAllDeactivated = function () {
27934 var hashDeactivated = this._hashDeactivated;
27935 return Object.keys(hashDeactivated)
27936 .map(function (id) {
27937 return hashDeactivated[id];
27940 TagSet.prototype.getDeactivated = function (id) {
27941 return this.hasDeactivated(id) ? this._hashDeactivated[id] : undefined;
27943 TagSet.prototype.has = function (id) {
27944 return id in this._hash;
27946 TagSet.prototype.hasDeactivated = function (id) {
27947 return id in this._hashDeactivated;
27949 TagSet.prototype.remove = function (ids) {
27950 var hash = this._hash;
27951 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
27952 var id = ids_1[_i];
27953 if (!(id in hash)) {
27958 this._notifyChanged$.next(this);
27960 TagSet.prototype.removeAll = function () {
27962 this._notifyChanged$.next(this);
27964 TagSet.prototype.removeAllDeactivated = function () {
27965 this._hashDeactivated = {};
27967 TagSet.prototype.removeDeactivated = function (ids) {
27968 var hashDeactivated = this._hashDeactivated;
27969 for (var _i = 0, ids_2 = ids; _i < ids_2.length; _i++) {
27970 var id = ids_2[_i];
27971 if (!(id in hashDeactivated)) {
27974 delete hashDeactivated[id];
27977 TagSet.prototype._add = function (tag, transform) {
27978 if (tag instanceof Component_1.OutlineTag) {
27979 this._hash[tag.id] = new Component_1.OutlineRenderTag(tag, transform);
27981 else if (tag instanceof Component_1.SpotTag) {
27982 this._hash[tag.id] = new Component_1.SpotRenderTag(tag, transform);
27985 throw new Error("Tag type not supported");
27990 exports.TagSet = TagSet;
27991 exports.default = TagSet;
27993 },{"../../Component":226,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/scan":73,"rxjs/add/operator/share":74}],289:[function(require,module,exports){
27995 var __extends = (this && this.__extends) || (function () {
27996 var extendStatics = Object.setPrototypeOf ||
27997 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27998 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27999 return function (d, b) {
28000 extendStatics(d, b);
28001 function __() { this.constructor = d; }
28002 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28005 Object.defineProperty(exports, "__esModule", { value: true });
28006 var Error_1 = require("../../../Error");
28007 var GeometryTagError = (function (_super) {
28008 __extends(GeometryTagError, _super);
28009 function GeometryTagError(message) {
28010 var _this = _super.call(this, message != null ? message : "The provided geometry value is incorrect") || this;
28011 _this.name = "GeometryTagError";
28014 return GeometryTagError;
28015 }(Error_1.MapillaryError));
28016 exports.GeometryTagError = GeometryTagError;
28017 exports.default = Error_1.MapillaryError;
28019 },{"../../../Error":228}],290:[function(require,module,exports){
28021 Object.defineProperty(exports, "__esModule", { value: true });
28022 var Subject_1 = require("rxjs/Subject");
28026 * @classdesc Represents a geometry.
28028 var Geometry = (function () {
28030 * Create a geometry.
28034 function Geometry() {
28035 this._notifyChanged$ = new Subject_1.Subject();
28037 Object.defineProperty(Geometry.prototype, "changed$", {
28039 * Get changed observable.
28041 * @description Emits the geometry itself every time the geometry
28044 * @returns {Observable<Geometry>} Observable emitting the geometry instance.
28048 return this._notifyChanged$;
28055 exports.Geometry = Geometry;
28056 exports.default = Geometry;
28058 },{"rxjs/Subject":34}],291:[function(require,module,exports){
28060 var __extends = (this && this.__extends) || (function () {
28061 var extendStatics = Object.setPrototypeOf ||
28062 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28063 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28064 return function (d, b) {
28065 extendStatics(d, b);
28066 function __() { this.constructor = d; }
28067 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28070 Object.defineProperty(exports, "__esModule", { value: true });
28071 var Component_1 = require("../../../Component");
28073 * @class PointGeometry
28075 * @classdesc Represents a point geometry in the 2D basic image coordinate system.
28079 * var basicPoint = [0.5, 0.7];
28080 * var pointGeometry = new Mapillary.TagComponent.PointGeometry(basicPoint);
28083 var PointGeometry = (function (_super) {
28084 __extends(PointGeometry, _super);
28086 * Create a point geometry.
28089 * @param {Array<number>} point - An array representing the basic coordinates of
28092 * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
28094 function PointGeometry(point) {
28095 var _this = _super.call(this) || this;
28098 if (x < 0 || x > 1 || y < 0 || y > 1) {
28099 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
28101 _this._point = point.slice();
28104 Object.defineProperty(PointGeometry.prototype, "point", {
28106 * Get point property.
28107 * @returns {Array<number>} Array representing the basic coordinates of the point.
28110 return this._point;
28116 * Get the 3D world coordinates for the centroid of the point, i.e. the 3D
28117 * world coordinates of the point itself.
28119 * @param {Transform} transform - The transform of the node related to the point.
28120 * @returns {Array<number>} 3D world coordinates representing the centroid.
28122 PointGeometry.prototype.getCentroid3d = function (transform) {
28123 return transform.unprojectBasic(this._point, 200);
28126 * Set the centroid of the point, i.e. the point coordinates.
28128 * @param {Array<number>} value - The new value of the centroid.
28129 * @param {Transform} transform - The transform of the node related to the point.
28131 PointGeometry.prototype.setCentroid2d = function (value, transform) {
28133 Math.max(0, Math.min(1, value[0])),
28134 Math.max(0, Math.min(1, value[1])),
28136 this._point[0] = changed[0];
28137 this._point[1] = changed[1];
28138 this._notifyChanged$.next(this);
28140 return PointGeometry;
28141 }(Component_1.Geometry));
28142 exports.PointGeometry = PointGeometry;
28144 },{"../../../Component":226}],292:[function(require,module,exports){
28146 var __extends = (this && this.__extends) || (function () {
28147 var extendStatics = Object.setPrototypeOf ||
28148 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28149 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28150 return function (d, b) {
28151 extendStatics(d, b);
28152 function __() { this.constructor = d; }
28153 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28156 Object.defineProperty(exports, "__esModule", { value: true });
28157 var Component_1 = require("../../../Component");
28159 * @class PolygonGeometry
28161 * @classdesc Represents a polygon geometry in the 2D basic image coordinate system.
28162 * All polygons and holes provided to the constructor needs to be closed.
28166 * var basicPolygon = [[0.5, 0.3], [0.7, 0.3], [0.6, 0.5], [0.5, 0.3]];
28167 * var polygonGeometry = new Mapillary.TagComponent.PointGeometry(basicPolygon);
28170 var PolygonGeometry = (function (_super) {
28171 __extends(PolygonGeometry, _super);
28173 * Create a polygon geometry.
28176 * @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
28177 * @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
28178 * Each array of holes vertices must be closed.
28180 * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
28182 function PolygonGeometry(polygon, holes) {
28183 var _this = _super.call(this) || this;
28184 var polygonLength = polygon.length;
28185 if (polygonLength < 3) {
28186 throw new Component_1.GeometryTagError("A polygon must have three or more positions.");
28188 if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
28189 polygon[0][1] !== polygon[polygonLength - 1][1]) {
28190 throw new Component_1.GeometryTagError("First and last positions must be equivalent.");
28192 _this._polygon = [];
28193 for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) {
28194 var vertex = polygon_1[_i];
28195 if (vertex[0] < 0 || vertex[0] > 1 ||
28196 vertex[1] < 0 || vertex[1] > 1) {
28197 throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
28199 _this._polygon.push(vertex.slice());
28202 if (holes == null) {
28205 for (var i = 0; i < holes.length; i++) {
28206 var hole = holes[i];
28207 var holeLength = hole.length;
28208 if (holeLength < 3) {
28209 throw new Component_1.GeometryTagError("A polygon hole must have three or more positions.");
28211 if (hole[0][0] !== hole[holeLength - 1][0] ||
28212 hole[0][1] !== hole[holeLength - 1][1]) {
28213 throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent.");
28215 _this._holes.push([]);
28216 for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) {
28217 var vertex = hole_1[_a];
28218 if (vertex[0] < 0 || vertex[0] > 1 ||
28219 vertex[1] < 0 || vertex[1] > 1) {
28220 throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
28222 _this._holes[i].push(vertex.slice());
28227 Object.defineProperty(PolygonGeometry.prototype, "polygon", {
28229 * Get polygon property.
28230 * @returns {Array<Array<number>>} Closed 2d polygon.
28233 return this._polygon;
28238 Object.defineProperty(PolygonGeometry.prototype, "holes", {
28240 * Get holes property.
28241 * @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
28244 return this._holes;
28250 * Add a vertex to the polygon by appending it after the last vertex.
28252 * @param {Array<number>} vertex - Vertex to add.
28254 PolygonGeometry.prototype.addVertex2d = function (vertex) {
28256 Math.max(0, Math.min(1, vertex[0])),
28257 Math.max(0, Math.min(1, vertex[1])),
28259 this._polygon.splice(this._polygon.length - 1, 0, clamped);
28260 this._notifyChanged$.next(this);
28263 * Remove a vertex from the polygon.
28265 * @param {number} index - The index of the vertex to remove.
28267 PolygonGeometry.prototype.removeVertex2d = function (index) {
28269 index >= this._polygon.length ||
28270 this._polygon.length < 4) {
28271 throw new Component_1.GeometryTagError("Index for removed vertex must be valid.");
28273 if (index > 0 && index < this._polygon.length - 1) {
28274 this._polygon.splice(index, 1);
28277 this._polygon.splice(0, 1);
28278 this._polygon.pop();
28279 var closing = this._polygon[0].slice();
28280 this._polygon.push(closing);
28282 this._notifyChanged$.next(this);
28285 PolygonGeometry.prototype.setVertex2d = function (index, value, transform) {
28287 Math.max(0, Math.min(1, value[0])),
28288 Math.max(0, Math.min(1, value[1])),
28290 if (index === 0 || index === this._polygon.length - 1) {
28291 this._polygon[0] = changed.slice();
28292 this._polygon[this._polygon.length - 1] = changed.slice();
28295 this._polygon[index] = changed.slice();
28297 this._notifyChanged$.next(this);
28300 PolygonGeometry.prototype.setCentroid2d = function (value, transform) {
28301 var xs = this._polygon.map(function (point) { return point[0]; });
28302 var ys = this._polygon.map(function (point) { return point[1]; });
28303 var minX = Math.min.apply(Math, xs);
28304 var maxX = Math.max.apply(Math, xs);
28305 var minY = Math.min.apply(Math, ys);
28306 var maxY = Math.max.apply(Math, ys);
28307 var centroid = this._getCentroid2d();
28308 var minTranslationX = -minX;
28309 var maxTranslationX = 1 - maxX;
28310 var minTranslationY = -minY;
28311 var maxTranslationY = 1 - maxY;
28312 var translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
28313 var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
28314 for (var _i = 0, _a = this._polygon; _i < _a.length; _i++) {
28315 var point = _a[_i];
28316 point[0] += translationX;
28317 point[1] += translationY;
28319 this._notifyChanged$.next(this);
28322 PolygonGeometry.prototype.getPoints3d = function (transform) {
28323 return this.getVertices3d(transform);
28326 PolygonGeometry.prototype.getVertex3d = function (index, transform) {
28327 return transform.unprojectBasic(this._polygon[index], 200);
28330 PolygonGeometry.prototype.getVertices3d = function (transform) {
28331 return this._polygon
28332 .map(function (point) {
28333 return transform.unprojectBasic(point, 200);
28337 * Get a polygon representation of the 3D coordinates for the vertices of each hole
28340 * @param {Transform} transform - The transform of the node related to the geometry.
28341 * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
28342 * representing the vertices of each hole of the geometry.
28344 PolygonGeometry.prototype.getHoleVertices3d = function (transform) {
28346 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
28349 .map(function (point) {
28350 return transform.unprojectBasic(point, 200);
28352 holes3d.push(hole3d);
28357 PolygonGeometry.prototype.getCentroid3d = function (transform) {
28358 var centroid2d = this._getCentroid2d();
28359 return transform.unprojectBasic(centroid2d, 200);
28362 PolygonGeometry.prototype.getTriangles3d = function (transform) {
28363 return this._triangulate(this._polygon, this.getPoints3d(transform), this._holes, this.getHoleVertices3d(transform));
28366 PolygonGeometry.prototype.getPoleOfAccessibility3d = function (transform) {
28367 var pole2d = this._getPoleOfInaccessibility2d(this._polygon.slice());
28368 return transform.unprojectBasic(pole2d, 200);
28370 PolygonGeometry.prototype._getCentroid2d = function () {
28371 var polygon = this._polygon;
28375 for (var i = 0; i < polygon.length - 1; i++) {
28376 var xi = polygon[i][0];
28377 var yi = polygon[i][1];
28378 var xi1 = polygon[i + 1][0];
28379 var yi1 = polygon[i + 1][1];
28380 var a = xi * yi1 - xi1 * yi;
28382 centroidX += (xi + xi1) * a;
28383 centroidY += (yi + yi1) * a;
28386 centroidX /= 6 * area;
28387 centroidY /= 6 * area;
28388 return [centroidX, centroidY];
28390 return PolygonGeometry;
28391 }(Component_1.VertexGeometry));
28392 exports.PolygonGeometry = PolygonGeometry;
28393 exports.default = PolygonGeometry;
28395 },{"../../../Component":226}],293:[function(require,module,exports){
28397 var __extends = (this && this.__extends) || (function () {
28398 var extendStatics = Object.setPrototypeOf ||
28399 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28400 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28401 return function (d, b) {
28402 extendStatics(d, b);
28403 function __() { this.constructor = d; }
28404 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28407 Object.defineProperty(exports, "__esModule", { value: true });
28408 var Component_1 = require("../../../Component");
28410 * @class RectGeometry
28412 * @classdesc Represents a rectangle geometry in the 2D basic image coordinate system.
28416 * var basicRect = [0.5, 0.3, 0.7, 0.4];
28417 * var rectGeometry = new Mapillary.TagComponent.RectGeometry(basicRect);
28420 var RectGeometry = (function (_super) {
28421 __extends(RectGeometry, _super);
28423 * Create a rectangle geometry.
28426 * @param {Array<number>} rect - An array representing the top-left and bottom-right
28427 * corners of the rectangle in basic coordinates. Ordered according to [x0, y0, x1, y1].
28429 * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates.
28431 function RectGeometry(rect) {
28432 var _this = _super.call(this) || this;
28433 if (rect[1] > rect[3]) {
28434 throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted.");
28436 for (var _i = 0, rect_1 = rect; _i < rect_1.length; _i++) {
28437 var coord = rect_1[_i];
28438 if (coord < 0 || coord > 1) {
28439 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
28442 _this._rect = rect.slice(0, 4);
28443 if (_this._rect[0] > _this._rect[2]) {
28444 _this._inverted = true;
28448 Object.defineProperty(RectGeometry.prototype, "rect", {
28450 * Get rect property.
28451 * @returns {Array<number>} Array representing the top-left and bottom-right
28452 * corners of the rectangle in basic coordinates.
28461 * Set the value of a vertex in the polygon representation of the rectangle.
28463 * @description The polygon is defined to have the first vertex at the
28464 * bottom-left corner with the rest of the vertices following in clockwise order.
28466 * @param {number} index - The index of the vertex to be set.
28467 * @param {Array<number>} value - The new value of the vertex.
28468 * @param {Transform} transform - The transform of the node related to the rectangle.
28470 RectGeometry.prototype.setVertex2d = function (index, value, transform) {
28471 var original = this._rect.slice();
28473 Math.max(0, Math.min(1, value[0])),
28474 Math.max(0, Math.min(1, value[1])),
28478 rect[0] = changed[0];
28479 rect[1] = original[1];
28480 rect[2] = original[2];
28481 rect[3] = changed[1];
28483 else if (index === 1) {
28484 rect[0] = changed[0];
28485 rect[1] = changed[1];
28486 rect[2] = original[2];
28487 rect[3] = original[3];
28489 else if (index === 2) {
28490 rect[0] = original[0];
28491 rect[1] = changed[1];
28492 rect[2] = changed[0];
28493 rect[3] = original[3];
28495 else if (index === 3) {
28496 rect[0] = original[0];
28497 rect[1] = original[1];
28498 rect[2] = changed[0];
28499 rect[3] = changed[1];
28501 if (transform.gpano) {
28502 var passingBoundaryLeft = index < 2 && changed[0] > 0.75 && original[0] < 0.25 ||
28503 index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25;
28504 var passingBoundaryRight = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 ||
28505 index >= 2 && changed[0] < 0.25 && original[2] > 0.75;
28506 if (passingBoundaryLeft || passingBoundaryRight) {
28507 this._inverted = !this._inverted;
28510 if (rect[0] - original[0] < -0.25) {
28511 rect[0] = original[0];
28513 if (rect[2] - original[2] > 0.25) {
28514 rect[2] = original[2];
28517 if (!this._inverted && rect[0] > rect[2] ||
28518 this._inverted && rect[0] < rect[2]) {
28519 rect[0] = original[0];
28520 rect[2] = original[2];
28524 if (rect[0] > rect[2]) {
28525 rect[0] = original[0];
28526 rect[2] = original[2];
28529 if (rect[1] > rect[3]) {
28530 rect[1] = original[1];
28531 rect[3] = original[3];
28533 this._rect[0] = rect[0];
28534 this._rect[1] = rect[1];
28535 this._rect[2] = rect[2];
28536 this._rect[3] = rect[3];
28537 this._notifyChanged$.next(this);
28540 RectGeometry.prototype.setCentroid2d = function (value, transform) {
28541 var original = this._rect.slice();
28542 var x0 = original[0];
28543 var x1 = this._inverted ? original[2] + 1 : original[2];
28544 var y0 = original[1];
28545 var y1 = original[3];
28546 var centerX = x0 + (x1 - x0) / 2;
28547 var centerY = y0 + (y1 - y0) / 2;
28548 var translationX = 0;
28549 if (transform.gpano != null &&
28550 transform.gpano.CroppedAreaImageWidthPixels === transform.gpano.FullPanoWidthPixels) {
28551 translationX = this._inverted ? value[0] + 1 - centerX : value[0] - centerX;
28554 var minTranslationX = -x0;
28555 var maxTranslationX = 1 - x1;
28556 translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centerX));
28558 var minTranslationY = -y0;
28559 var maxTranslationY = 1 - y1;
28560 var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centerY));
28561 this._rect[0] = original[0] + translationX;
28562 this._rect[1] = original[1] + translationY;
28563 this._rect[2] = original[2] + translationX;
28564 this._rect[3] = original[3] + translationY;
28565 if (this._rect[0] < 0) {
28566 this._rect[0] += 1;
28567 this._inverted = !this._inverted;
28569 else if (this._rect[0] > 1) {
28570 this._rect[0] -= 1;
28571 this._inverted = !this._inverted;
28573 if (this._rect[2] < 0) {
28574 this._rect[2] += 1;
28575 this._inverted = !this._inverted;
28577 else if (this._rect[2] > 1) {
28578 this._rect[2] -= 1;
28579 this._inverted = !this._inverted;
28581 this._notifyChanged$.next(this);
28584 * Get the 3D coordinates for the vertices of the rectangle with
28585 * interpolated points along the lines.
28587 * @param {Transform} transform - The transform of the node related to
28589 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates
28590 * representing the rectangle.
28592 RectGeometry.prototype.getPoints3d = function (transform) {
28593 return this._getPoints2d(transform)
28594 .map(function (point) {
28595 return transform.unprojectBasic(point, 200);
28599 * Get a vertex from the polygon representation of the 3D coordinates for the
28600 * vertices of the geometry.
28602 * @description The first vertex represents the bottom-left corner with the rest of
28603 * the vertices following in clockwise order.
28605 * @param {number} index - Vertex index.
28606 * @param {Transform} transform - The transform of the node related to the geometry.
28607 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
28608 * the vertices of the geometry.
28610 RectGeometry.prototype.getVertex3d = function (index, transform) {
28611 return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200);
28614 * Get a polygon representation of the 3D coordinates for the vertices of the rectangle.
28616 * @description The first vertex represents the bottom-left corner with the rest of
28617 * the vertices following in clockwise order.
28619 * @param {Transform} transform - The transform of the node related to the rectangle.
28620 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
28621 * the rectangle vertices.
28623 RectGeometry.prototype.getVertices3d = function (transform) {
28624 return this._rectToVertices2d(this._rect)
28625 .map(function (vertex) {
28626 return transform.unprojectBasic(vertex, 200);
28630 RectGeometry.prototype.getCentroid3d = function (transform) {
28631 var rect = this._rect;
28633 var x1 = this._inverted ? rect[2] + 1 : rect[2];
28636 var centroidX = x0 + (x1 - x0) / 2;
28637 var centroidY = y0 + (y1 - y0) / 2;
28638 return transform.unprojectBasic([centroidX, centroidY], 200);
28641 RectGeometry.prototype.getPoleOfAccessibility3d = function (transform) {
28642 var pole2d = this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
28643 return transform.unprojectBasic(pole2d, 200);
28646 RectGeometry.prototype.getTriangles3d = function (transform) {
28647 return this._triangulate(this._rectToVertices2d(this._rect), this.getVertices3d(transform));
28650 * Check if a particular bottom-right value is valid according to the current
28651 * rectangle coordinates.
28653 * @param {Array<number>} bottomRight - The bottom-right coordinates to validate
28654 * @returns {boolean} Value indicating whether the provided bottom-right coordinates
28657 RectGeometry.prototype.validate = function (bottomRight) {
28658 var rect = this._rect;
28659 if (!this._inverted && bottomRight[0] < rect[0] ||
28660 bottomRight[0] - rect[2] > 0.25 ||
28661 bottomRight[1] < rect[1]) {
28667 * Get the 2D coordinates for the vertices of the rectangle with
28668 * interpolated points along the lines.
28670 * @param {Transform} transform - The transform of the node related to
28672 * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates
28673 * representing the rectangle.
28675 RectGeometry.prototype._getPoints2d = function (transform) {
28676 var vertices2d = this._rectToVertices2d(this._rect);
28677 var sides = vertices2d.length - 1;
28680 for (var i = 0; i < sides; ++i) {
28681 var startX = vertices2d[i][0];
28682 var startY = vertices2d[i][1];
28683 var endX = vertices2d[i + 1][0];
28684 var endY = vertices2d[i + 1][1];
28685 var intervalX = (endX - startX) / (sections - 1);
28686 var intervalY = (endY - startY) / (sections - 1);
28687 for (var j = 0; j < sections; ++j) {
28689 startX + j * intervalX,
28690 startY + j * intervalY,
28692 points2d.push(point);
28698 * Convert the top-left, bottom-right representation of a rectangle to a polygon
28699 * representation of the vertices starting at the bottom-right corner going
28702 * @param {Array<number>} rect - Top-left, bottom-right representation of a
28704 * @returns {Array<Array<number>>} Polygon representation of the vertices of the
28707 RectGeometry.prototype._rectToVertices2d = function (rect) {
28709 [rect[0], rect[3]],
28710 [rect[0], rect[1]],
28711 [this._inverted ? rect[2] + 1 : rect[2], rect[1]],
28712 [this._inverted ? rect[2] + 1 : rect[2], rect[3]],
28713 [rect[0], rect[3]],
28716 return RectGeometry;
28717 }(Component_1.VertexGeometry));
28718 exports.RectGeometry = RectGeometry;
28719 exports.default = RectGeometry;
28721 },{"../../../Component":226}],294:[function(require,module,exports){
28723 /// <reference path="../../../../typings/index.d.ts" />
28724 var __extends = (this && this.__extends) || (function () {
28725 var extendStatics = Object.setPrototypeOf ||
28726 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28727 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28728 return function (d, b) {
28729 extendStatics(d, b);
28730 function __() { this.constructor = d; }
28731 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28734 Object.defineProperty(exports, "__esModule", { value: true });
28735 var earcut = require("earcut");
28736 var polylabel = require("@mapbox/polylabel");
28737 var Component_1 = require("../../../Component");
28739 * @class VertexGeometry
28741 * @classdesc Represents a vertex geometry.
28743 var VertexGeometry = (function (_super) {
28744 __extends(VertexGeometry, _super);
28746 * Create a vertex geometry.
28750 function VertexGeometry() {
28751 return _super.call(this) || this;
28754 * Finds the polygon pole of inaccessibility, the most distant internal
28755 * point from the polygon outline.
28757 * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
28758 * @returns {Array<number>} Point of inaccessibility.
28761 VertexGeometry.prototype._getPoleOfInaccessibility2d = function (points2d) {
28762 var pole2d = polylabel([points2d], 3e-2);
28766 * Triangulates a 2d polygon and returns the triangle
28767 * representation as a flattened array of 3d points.
28769 * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
28770 * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points.
28771 * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate.
28772 * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points.
28773 * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles.
28776 VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) {
28777 var data = [points2d.slice(0, -1)];
28778 for (var _i = 0, _a = holes2d != null ? holes2d : []; _i < _a.length; _i++) {
28779 var hole2d = _a[_i];
28780 data.push(hole2d.slice(0, -1));
28782 var points = points3d.slice(0, -1);
28783 for (var _b = 0, _c = holes3d != null ? holes3d : []; _b < _c.length; _b++) {
28784 var hole3d = _c[_b];
28785 points = points.concat(hole3d.slice(0, -1));
28787 var flattened = earcut.flatten(data);
28788 var indices = earcut(flattened.vertices, flattened.holes, flattened.dimensions);
28789 var triangles = [];
28790 for (var i = 0; i < indices.length; ++i) {
28791 var point = points[indices[i]];
28792 triangles.push(point[0]);
28793 triangles.push(point[1]);
28794 triangles.push(point[2]);
28798 return VertexGeometry;
28799 }(Component_1.Geometry));
28800 exports.VertexGeometry = VertexGeometry;
28801 exports.default = VertexGeometry;
28803 },{"../../../Component":226,"@mapbox/polylabel":1,"earcut":8}],295:[function(require,module,exports){
28805 /// <reference path="../../../../typings/index.d.ts" />
28806 Object.defineProperty(exports, "__esModule", { value: true });
28807 var THREE = require("three");
28808 var vd = require("virtual-dom");
28809 var Subject_1 = require("rxjs/Subject");
28810 var Component_1 = require("../../../Component");
28811 var OutlineCreateTag = (function () {
28812 function OutlineCreateTag(geometry, options, transform) {
28814 this._geometry = geometry;
28815 this._options = { color: options.color == null ? 0xFFFFFF : options.color };
28816 this._transform = transform;
28817 this._outline = this._createOutine();
28818 this._glObjects = [this._outline];
28819 this._aborted$ = new Subject_1.Subject();
28820 this._created$ = new Subject_1.Subject();
28821 this._glObjectsChanged$ = new Subject_1.Subject();
28822 this._geometryChangedSubscription = this._geometry.changed$
28823 .subscribe(function (vertexGeometry) {
28824 _this._disposeOutline();
28825 _this._outline = _this._createOutine();
28826 _this._glObjects = [_this._outline];
28827 _this._glObjectsChanged$.next(_this);
28830 Object.defineProperty(OutlineCreateTag.prototype, "geometry", {
28832 return this._geometry;
28837 Object.defineProperty(OutlineCreateTag.prototype, "glObjects", {
28839 return this._glObjects;
28844 Object.defineProperty(OutlineCreateTag.prototype, "aborted$", {
28846 return this._aborted$;
28851 Object.defineProperty(OutlineCreateTag.prototype, "created$", {
28853 return this._created$;
28858 Object.defineProperty(OutlineCreateTag.prototype, "glObjectsChanged$", {
28860 return this._glObjectsChanged$;
28865 Object.defineProperty(OutlineCreateTag.prototype, "geometryChanged$", {
28868 return this._geometry.changed$
28869 .map(function (geometry) {
28876 OutlineCreateTag.prototype.dispose = function () {
28877 this._disposeOutline();
28878 this._geometryChangedSubscription.unsubscribe();
28880 OutlineCreateTag.prototype.getDOMObjects = function (matrixWorldInverse, projectionMatrix) {
28883 var abort = function (e) {
28884 e.stopPropagation();
28885 _this._aborted$.next(_this);
28887 if (this._geometry instanceof Component_1.RectGeometry) {
28888 var topLeftPoint3d = this._geometry.getVertex3d(1, this._transform);
28889 var topLeftCameraSpace = this._convertToCameraSpace(topLeftPoint3d, matrixWorldInverse);
28890 if (topLeftCameraSpace.z < 0) {
28891 var centerCanvas = this._projectToCanvas(topLeftCameraSpace, projectionMatrix);
28892 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
28893 var pointProperties = {
28895 background: "#" + ("000000" + this._options.color.toString(16)).substr(-6),
28896 left: centerCss[0],
28897 position: "absolute",
28901 var completerProperties = {
28903 style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
28905 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
28906 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
28909 else if (this._geometry instanceof Component_1.PolygonGeometry) {
28910 var polygonGeometry_1 = this._geometry;
28911 var firstVertex3d = this._geometry.getVertex3d(0, this._transform);
28912 var firstCameraSpace = this._convertToCameraSpace(firstVertex3d, matrixWorldInverse);
28913 if (firstCameraSpace.z < 0) {
28914 var centerCanvas = this._projectToCanvas(firstCameraSpace, projectionMatrix);
28915 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
28916 var firstOnclick = polygonGeometry_1.polygon.length > 4 ?
28918 e.stopPropagation();
28919 polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 2);
28920 _this._created$.next(_this);
28923 var completerProperties = {
28924 onclick: firstOnclick,
28925 style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
28927 var firstClass = polygonGeometry_1.polygon.length > 4 ?
28930 vNodes.push(vd.h("div." + firstClass, completerProperties, []));
28932 if (polygonGeometry_1.polygon.length > 3) {
28933 var lastVertex3d = this._geometry.getVertex3d(polygonGeometry_1.polygon.length - 3, this._transform);
28934 var lastCameraSpace = this._convertToCameraSpace(lastVertex3d, matrixWorldInverse);
28935 if (lastCameraSpace.z < 0) {
28936 var centerCanvas = this._projectToCanvas(lastCameraSpace, projectionMatrix);
28937 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
28938 var remove = function (e) {
28939 e.stopPropagation();
28940 polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3);
28942 var completerProperties = {
28944 style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
28946 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
28949 var vertices3d = this._geometry.getVertices3d(this._transform);
28950 vertices3d.splice(-2, 2);
28951 for (var _i = 0, vertices3d_1 = vertices3d; _i < vertices3d_1.length; _i++) {
28952 var vertex = vertices3d_1[_i];
28953 var vertexCameraSpace = this._convertToCameraSpace(vertex, matrixWorldInverse);
28954 if (vertexCameraSpace.z < 0) {
28955 var centerCanvas = this._projectToCanvas(vertexCameraSpace, projectionMatrix);
28956 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
28957 var pointProperties = {
28959 background: "#" + ("000000" + this._options.color.toString(16)).substr(-6),
28960 left: centerCss[0],
28961 position: "absolute",
28965 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
28971 OutlineCreateTag.prototype.addPoint = function (point) {
28972 if (this._geometry instanceof Component_1.RectGeometry) {
28973 var rectGeometry = this._geometry;
28974 if (!rectGeometry.validate(point)) {
28977 this._created$.next(this);
28979 else if (this._geometry instanceof Component_1.PolygonGeometry) {
28980 var polygonGeometry = this._geometry;
28981 polygonGeometry.addVertex2d(point);
28984 OutlineCreateTag.prototype._createOutine = function () {
28985 var polygon3d = this._geometry.getPoints3d(this._transform);
28986 var positions = this._getLinePositions(polygon3d);
28987 var geometry = new THREE.BufferGeometry();
28988 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
28989 var material = new THREE.LineBasicMaterial({
28990 color: this._options.color,
28993 return new THREE.Line(geometry, material);
28995 OutlineCreateTag.prototype._disposeOutline = function () {
28996 if (this._outline == null) {
28999 var line = this._outline;
29000 line.geometry.dispose();
29001 line.material.dispose();
29002 this._outline = null;
29003 this._glObjects = [];
29005 OutlineCreateTag.prototype._getLinePositions = function (polygon3d) {
29006 var length = polygon3d.length;
29007 var positions = new Float32Array(length * 3);
29008 for (var i = 0; i < length; ++i) {
29010 var position = polygon3d[i];
29011 positions[index] = position[0];
29012 positions[index + 1] = position[1];
29013 positions[index + 2] = position[2];
29017 OutlineCreateTag.prototype._projectToCanvas = function (point, projectionMatrix) {
29018 var projected = new THREE.Vector3(point.x, point.y, point.z)
29019 .applyMatrix4(projectionMatrix);
29020 return [(projected.x + 1) / 2, (-projected.y + 1) / 2];
29022 OutlineCreateTag.prototype._convertToCameraSpace = function (point, matrixWorldInverse) {
29023 return new THREE.Vector3(point[0], point[1], point[2]).applyMatrix4(matrixWorldInverse);
29025 return OutlineCreateTag;
29027 exports.OutlineCreateTag = OutlineCreateTag;
29028 exports.default = OutlineCreateTag;
29030 },{"../../../Component":226,"rxjs/Subject":34,"three":176,"virtual-dom":182}],296:[function(require,module,exports){
29032 /// <reference path="../../../../typings/index.d.ts" />
29033 var __extends = (this && this.__extends) || (function () {
29034 var extendStatics = Object.setPrototypeOf ||
29035 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29036 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29037 return function (d, b) {
29038 extendStatics(d, b);
29039 function __() { this.constructor = d; }
29040 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29043 Object.defineProperty(exports, "__esModule", { value: true });
29044 var THREE = require("three");
29045 var vd = require("virtual-dom");
29046 var Component_1 = require("../../../Component");
29048 * @class OutlineRenderTag
29049 * @classdesc Tag visualizing the properties of an OutlineTag.
29051 var OutlineRenderTag = (function (_super) {
29052 __extends(OutlineRenderTag, _super);
29053 function OutlineRenderTag(tag, transform) {
29054 var _this = _super.call(this, tag, transform) || this;
29055 _this._fill = _this._tag.fillOpacity > 0 && !transform.gpano ?
29056 _this._createFill() :
29058 _this._holes = _this._tag.lineWidth >= 1 ?
29059 _this._createHoles() :
29061 _this._outline = _this._tag.lineWidth >= 1 ?
29062 _this._createOutline() :
29064 _this._glObjects = _this._createGLObjects();
29065 _this._geometryChangedSubscription = _this._tag.geometry.changed$
29066 .subscribe(function (geometry) {
29067 if (_this._fill != null) {
29068 _this._updateFillGeometry();
29070 if (_this._holes.length > 0) {
29071 _this._updateHoleGeometries();
29073 if (_this._outline != null) {
29074 _this._updateOulineGeometry();
29077 _this._changedSubscription = _this._tag.changed$
29078 .subscribe(function (changedTag) {
29079 var glObjectsChanged = false;
29080 if (_this._fill == null) {
29081 if (_this._tag.fillOpacity > 0 && !_this._transform.gpano) {
29082 _this._fill = _this._createFill();
29083 glObjectsChanged = true;
29087 _this._updateFillMaterial();
29089 if (_this._outline == null) {
29090 if (_this._tag.lineWidth > 0) {
29091 _this._holes = _this._createHoles();
29092 _this._outline = _this._createOutline();
29093 glObjectsChanged = true;
29097 _this._updateHoleMaterials();
29098 _this._updateOutlineMaterial();
29100 if (glObjectsChanged) {
29101 _this._glObjects = _this._createGLObjects();
29102 _this._glObjectsChanged$.next(_this);
29107 OutlineRenderTag.prototype.dispose = function () {
29108 this._disposeFill();
29109 this._disposeHoles();
29110 this._disposeOutline();
29111 this._changedSubscription.unsubscribe();
29112 this._geometryChangedSubscription.unsubscribe();
29114 OutlineRenderTag.prototype.getDOMObjects = function (atlas, matrixWorldInverse, projectionMatrix) {
29117 var isRect = this._tag.geometry instanceof Component_1.RectGeometry;
29118 var isPerspective = !this._transform.gpano;
29119 if (this._tag.icon != null && (isRect || isPerspective)) {
29120 var icon3d = this._tag.geometry instanceof Component_1.RectGeometry ?
29121 this._tag.geometry.getVertex3d(this._tag.iconIndex, this._transform) :
29122 this._tag.geometry.getPoleOfAccessibility3d(this._transform);
29123 var iconCameraSpace = this._convertToCameraSpace(icon3d, matrixWorldInverse);
29124 if (iconCameraSpace.z < 0) {
29125 var interact = function (e) {
29126 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
29128 if (atlas.loaded) {
29129 var sprite = atlas.getDOMSprite(this._tag.icon, this._tag.iconFloat);
29130 var click = function (e) {
29131 e.stopPropagation();
29132 _this._tag.click$.next(_this._tag);
29134 var iconCanvas = this._projectToCanvas(iconCameraSpace, projectionMatrix);
29135 var iconCss = iconCanvas.map(function (coord) { return (100 * coord) + "%"; });
29138 onmousedown: interact,
29141 pointerEvents: "all",
29142 position: "absolute",
29146 vNodes.push(vd.h("div.TagSymbol", properties, [sprite]));
29150 else if (this._tag.text != null && (isRect || isPerspective)) {
29151 var text3d = this._tag.geometry instanceof Component_1.RectGeometry ?
29152 this._tag.geometry.getVertex3d(3, this._transform) :
29153 this._tag.geometry.getPoleOfAccessibility3d(this._transform);
29154 var textCameraSpace = this._convertToCameraSpace(text3d, matrixWorldInverse);
29155 if (textCameraSpace.z < 0) {
29156 var interact = function (e) {
29157 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
29159 var labelCanvas = this._projectToCanvas(textCameraSpace, projectionMatrix);
29160 var labelCss = labelCanvas.map(function (coord) { return (100 * coord) + "%"; });
29162 onmousedown: interact,
29164 color: "#" + ("000000" + this._tag.textColor.toString(16)).substr(-6),
29166 pointerEvents: "all",
29167 position: "absolute",
29169 transform: this._tag.geometry instanceof Component_1.RectGeometry ? undefined : "translate(-50%, -50%)",
29171 textContent: this._tag.text,
29173 vNodes.push(vd.h("span.TagSymbol", properties, []));
29176 if (!this._tag.editable) {
29179 var lineColor = "#" + ("000000" + this._tag.lineColor.toString(16)).substr(-6);
29180 if (this._tag.geometry instanceof Component_1.RectGeometry) {
29181 var centroid3d = this._tag.geometry.getCentroid3d(this._transform);
29182 var centroidCameraSpace = this._convertToCameraSpace(centroid3d, matrixWorldInverse);
29183 if (centroidCameraSpace.z < 0) {
29184 var interact = this._interact(Component_1.TagOperation.Centroid);
29185 var centerCanvas = this._projectToCanvas(centroidCameraSpace, projectionMatrix);
29186 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
29188 onmousedown: interact,
29189 style: { background: lineColor, left: centerCss[0], position: "absolute", top: centerCss[1] },
29191 vNodes.push(vd.h("div.TagMover", properties, []));
29194 var vertices3d = this._tag.geometry.getVertices3d(this._transform);
29195 for (var i = 0; i < vertices3d.length - 1; i++) {
29196 var isRectGeometry = this._tag.geometry instanceof Component_1.RectGeometry;
29197 if (isRectGeometry &&
29198 ((this._tag.icon != null && i === this._tag.iconIndex) ||
29199 (this._tag.icon == null && this._tag.text != null && i === 3))) {
29202 var vertexCameraSpace = this._convertToCameraSpace(vertices3d[i], matrixWorldInverse);
29203 if (vertexCameraSpace.z > 0) {
29206 var interact = this._interact(Component_1.TagOperation.Vertex, i);
29207 var vertexCanvas = this._projectToCanvas(vertexCameraSpace, projectionMatrix);
29208 var vertexCss = vertexCanvas.map(function (coord) { return (100 * coord) + "%"; });
29210 onmousedown: interact,
29212 background: lineColor,
29213 left: vertexCss[0],
29214 position: "absolute",
29218 if (isRectGeometry) {
29219 properties.style.cursor = i % 2 === 0 ? "nesw-resize" : "nwse-resize";
29221 vNodes.push(vd.h("div.TagResizer", properties, []));
29222 if (!this._tag.indicateVertices) {
29225 var pointProperties = {
29227 background: lineColor,
29228 left: vertexCss[0],
29229 position: "absolute",
29233 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
29237 OutlineRenderTag.prototype._createFill = function () {
29238 var triangles = this._tag.geometry.getTriangles3d(this._transform);
29239 var positions = new Float32Array(triangles);
29240 var geometry = new THREE.BufferGeometry();
29241 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
29242 geometry.computeBoundingSphere();
29243 var material = new THREE.MeshBasicMaterial({
29244 color: this._tag.fillColor,
29245 opacity: this._tag.fillOpacity,
29246 side: THREE.DoubleSide,
29249 return new THREE.Mesh(geometry, material);
29251 OutlineRenderTag.prototype._createGLObjects = function () {
29252 var glObjects = [];
29253 if (this._fill != null) {
29254 glObjects.push(this._fill);
29256 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
29258 glObjects.push(hole);
29260 if (this._outline != null) {
29261 glObjects.push(this._outline);
29265 OutlineRenderTag.prototype._createHoles = function () {
29267 if (this._tag.geometry instanceof Component_1.PolygonGeometry) {
29268 var polygonGeometry = this._tag.geometry;
29269 var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
29270 for (var _i = 0, holes3d_1 = holes3d; _i < holes3d_1.length; _i++) {
29271 var holePoints3d = holes3d_1[_i];
29272 var hole = this._createLine(holePoints3d);
29278 OutlineRenderTag.prototype._createLine = function (points3d) {
29279 var positions = this._getLinePositions(points3d);
29280 var geometry = new THREE.BufferGeometry();
29281 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
29282 geometry.computeBoundingSphere();
29283 var material = new THREE.LineBasicMaterial();
29284 this._updateLineBasicMaterial(material);
29285 var line = new THREE.Line(geometry, material);
29286 line.renderOrder = 1;
29289 OutlineRenderTag.prototype._createOutline = function () {
29290 var points3d = this._tag.geometry.getPoints3d(this._transform);
29291 return this._createLine(points3d);
29293 OutlineRenderTag.prototype._disposeFill = function () {
29294 if (this._fill == null) {
29297 this._fill.geometry.dispose();
29298 this._fill.material.dispose();
29301 OutlineRenderTag.prototype._disposeHoles = function () {
29302 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
29304 hole.geometry.dispose();
29305 hole.material.dispose();
29309 OutlineRenderTag.prototype._disposeOutline = function () {
29310 if (this._outline == null) {
29313 this._outline.geometry.dispose();
29314 this._outline.material.dispose();
29315 this._outline = null;
29317 OutlineRenderTag.prototype._getLinePositions = function (points3d) {
29318 var length = points3d.length;
29319 var positions = new Float32Array(length * 3);
29320 for (var i = 0; i < length; ++i) {
29322 var position = points3d[i];
29323 positions[index + 0] = position[0];
29324 positions[index + 1] = position[1];
29325 positions[index + 2] = position[2];
29329 OutlineRenderTag.prototype._interact = function (operation, vertexIndex) {
29331 return function (e) {
29332 var offsetX = e.offsetX - e.target.offsetWidth / 2;
29333 var offsetY = e.offsetY - e.target.offsetHeight / 2;
29334 _this._interact$.next({
29337 operation: operation,
29339 vertexIndex: vertexIndex,
29343 OutlineRenderTag.prototype._updateFillGeometry = function () {
29344 var triangles = this._tag.geometry.getTriangles3d(this._transform);
29345 var positions = new Float32Array(triangles);
29346 var geometry = this._fill.geometry;
29347 var attribute = geometry.getAttribute("position");
29348 if (attribute.array.length === positions.length) {
29349 attribute.set(positions);
29350 attribute.needsUpdate = true;
29353 geometry.removeAttribute("position");
29354 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
29356 geometry.computeBoundingSphere();
29358 OutlineRenderTag.prototype._updateFillMaterial = function () {
29359 var material = this._fill.material;
29360 material.color = new THREE.Color(this._tag.fillColor);
29361 material.opacity = this._tag.fillOpacity;
29362 material.needsUpdate = true;
29364 OutlineRenderTag.prototype._updateHoleGeometries = function () {
29365 var polygonGeometry = this._tag.geometry;
29366 var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
29367 if (holes3d.length !== this._holes.length) {
29368 throw new Error("Changing the number of holes is not supported.");
29370 for (var i = 0; i < this._holes.length; i++) {
29371 var holePoints3d = holes3d[i];
29372 var hole = this._holes[i];
29373 this._updateLine(hole, holePoints3d);
29376 OutlineRenderTag.prototype._updateHoleMaterials = function () {
29377 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
29379 var material = hole.material;
29380 this._updateLineBasicMaterial(material);
29383 OutlineRenderTag.prototype._updateLine = function (line, points3d) {
29384 var positions = this._getLinePositions(points3d);
29385 var geometry = line.geometry;
29386 var attribute = geometry.getAttribute("position");
29387 attribute.set(positions);
29388 attribute.needsUpdate = true;
29389 geometry.computeBoundingSphere();
29391 OutlineRenderTag.prototype._updateOulineGeometry = function () {
29392 var points3d = this._tag.geometry.getPoints3d(this._transform);
29393 this._updateLine(this._outline, points3d);
29395 OutlineRenderTag.prototype._updateOutlineMaterial = function () {
29396 var material = this._outline.material;
29397 this._updateLineBasicMaterial(material);
29399 OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) {
29400 material.color = new THREE.Color(this._tag.lineColor);
29401 material.linewidth = Math.max(this._tag.lineWidth, 1);
29402 material.opacity = this._tag.lineWidth >= 1 ? this._tag.lineOpacity : 0;
29403 material.transparent = this._tag.lineWidth <= 0 || this._tag.lineOpacity < 1;
29404 material.needsUpdate = true;
29406 return OutlineRenderTag;
29407 }(Component_1.RenderTag));
29408 exports.OutlineRenderTag = OutlineRenderTag;
29410 },{"../../../Component":226,"three":176,"virtual-dom":182}],297:[function(require,module,exports){
29412 var __extends = (this && this.__extends) || (function () {
29413 var extendStatics = Object.setPrototypeOf ||
29414 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29415 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29416 return function (d, b) {
29417 extendStatics(d, b);
29418 function __() { this.constructor = d; }
29419 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29422 Object.defineProperty(exports, "__esModule", { value: true });
29423 var Subject_1 = require("rxjs/Subject");
29424 var Component_1 = require("../../../Component");
29425 var Viewer_1 = require("../../../Viewer");
29427 * @class OutlineTag
29429 * @classdesc Tag holding properties for visualizing a geometry outline.
29433 * var geometry = new Mapillary.TagComponent.RectGeometry([0.3, 0.3, 0.5, 0.4]);
29434 * var tag = new Mapillary.TagComponent.OutlineTag(
29437 * { editable: true, lineColor: 0xff0000 });
29439 * tagComponent.add([tag]);
29442 var OutlineTag = (function (_super) {
29443 __extends(OutlineTag, _super);
29445 * Create an outline tag.
29449 * @param {string} id - Unique identifier of the tag.
29450 * @param {VertexGeometry} geometry - Geometry defining vertices of tag.
29451 * @param {IOutlineTagOptions} options - Options defining the visual appearance and
29452 * behavior of the outline tag.
29454 function OutlineTag(id, geometry, options) {
29455 var _this = _super.call(this, id, geometry) || this;
29456 _this._editable = options.editable == null ? false : options.editable;
29457 _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
29458 _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
29459 _this._icon = options.icon === undefined ? null : options.icon;
29460 _this._iconFloat = options.iconFloat == null ? Viewer_1.Alignment.Center : options.iconFloat;
29461 _this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
29462 _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
29463 _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
29464 _this._lineOpacity = options.lineOpacity == null ? 1 : options.lineOpacity;
29465 _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
29466 _this._text = options.text === undefined ? null : options.text;
29467 _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
29468 _this._click$ = new Subject_1.Subject();
29470 .subscribe(function (t) {
29471 _this.fire(OutlineTag.click, _this);
29475 Object.defineProperty(OutlineTag.prototype, "click$", {
29477 * Click observable.
29479 * @description An observable emitting the tag when the icon of the
29480 * tag has been clicked.
29482 * @returns {Observable<Tag>}
29485 return this._click$;
29490 Object.defineProperty(OutlineTag.prototype, "editable", {
29492 * Get editable property.
29493 * @returns {boolean} Value indicating if tag is editable.
29496 return this._editable;
29499 * Set editable property.
29502 * @fires Tag#changed
29504 set: function (value) {
29505 this._editable = value;
29506 this._notifyChanged$.next(this);
29511 Object.defineProperty(OutlineTag.prototype, "fillColor", {
29513 * Get fill color property.
29514 * @returns {number}
29517 return this._fillColor;
29520 * Set fill color property.
29523 * @fires Tag#changed
29525 set: function (value) {
29526 this._fillColor = value;
29527 this._notifyChanged$.next(this);
29532 Object.defineProperty(OutlineTag.prototype, "fillOpacity", {
29534 * Get fill opacity property.
29535 * @returns {number}
29538 return this._fillOpacity;
29541 * Set fill opacity property.
29544 * @fires Tag#changed
29546 set: function (value) {
29547 this._fillOpacity = value;
29548 this._notifyChanged$.next(this);
29553 Object.defineProperty(OutlineTag.prototype, "geometry", {
29556 return this._geometry;
29561 Object.defineProperty(OutlineTag.prototype, "icon", {
29563 * Get icon property.
29564 * @returns {string}
29570 * Set icon property.
29573 * @fires Tag#changed
29575 set: function (value) {
29576 this._icon = value;
29577 this._notifyChanged$.next(this);
29582 Object.defineProperty(OutlineTag.prototype, "iconFloat", {
29584 * Get icon float property.
29585 * @returns {Alignment}
29588 return this._iconFloat;
29591 * Set icon float property.
29592 * @param {Alignment}
29594 * @fires Tag#changed
29596 set: function (value) {
29597 this._iconFloat = value;
29598 this._notifyChanged$.next(this);
29603 Object.defineProperty(OutlineTag.prototype, "iconIndex", {
29605 * Get icon index property.
29606 * @returns {number}
29609 return this._iconIndex;
29612 * Set icon index property.
29615 * @fires Tag#changed
29617 set: function (value) {
29618 this._iconIndex = value;
29619 this._notifyChanged$.next(this);
29624 Object.defineProperty(OutlineTag.prototype, "indicateVertices", {
29626 * Get indicate vertices property.
29627 * @returns {boolean} Value indicating if vertices should be indicated
29628 * when tag is editable.
29631 return this._indicateVertices;
29634 * Set indicate vertices property.
29637 * @fires Tag#changed
29639 set: function (value) {
29640 this._indicateVertices = value;
29641 this._notifyChanged$.next(this);
29646 Object.defineProperty(OutlineTag.prototype, "lineColor", {
29648 * Get line color property.
29649 * @returns {number}
29652 return this._lineColor;
29655 * Set line color property.
29658 * @fires Tag#changed
29660 set: function (value) {
29661 this._lineColor = value;
29662 this._notifyChanged$.next(this);
29667 Object.defineProperty(OutlineTag.prototype, "lineOpacity", {
29669 * Get line opacity property.
29670 * @returns {number}
29673 return this._lineOpacity;
29676 * Set line opacity property.
29679 * @fires Tag#changed
29681 set: function (value) {
29682 this._lineOpacity = value;
29683 this._notifyChanged$.next(this);
29688 Object.defineProperty(OutlineTag.prototype, "lineWidth", {
29690 * Get line width property.
29691 * @returns {number}
29694 return this._lineWidth;
29697 * Set line width property.
29700 * @fires Tag#changed
29702 set: function (value) {
29703 this._lineWidth = value;
29704 this._notifyChanged$.next(this);
29709 Object.defineProperty(OutlineTag.prototype, "text", {
29711 * Get text property.
29712 * @returns {string}
29718 * Set text property.
29721 * @fires Tag#changed
29723 set: function (value) {
29724 this._text = value;
29725 this._notifyChanged$.next(this);
29730 Object.defineProperty(OutlineTag.prototype, "textColor", {
29732 * Get text color property.
29733 * @returns {number}
29736 return this._textColor;
29739 * Set text color property.
29742 * @fires Tag#changed
29744 set: function (value) {
29745 this._textColor = value;
29746 this._notifyChanged$.next(this);
29752 * Set options for tag.
29754 * @description Sets all the option properties provided and keeps
29755 * the rest of the values as is.
29757 * @param {IOutlineTagOptions} options - Outline tag options
29759 * @fires {Tag#changed}
29761 OutlineTag.prototype.setOptions = function (options) {
29762 this._editable = options.editable == null ? this._editable : options.editable;
29763 this._icon = options.icon === undefined ? this._icon : options.icon;
29764 this._iconFloat = options.iconFloat == null ? this._iconFloat : options.iconFloat;
29765 this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
29766 this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
29767 this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
29768 this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
29769 this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
29770 this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
29771 this._text = options.text === undefined ? this._text : options.text;
29772 this._textColor = options.textColor == null ? this._textColor : options.textColor;
29773 this._notifyChanged$.next(this);
29776 }(Component_1.Tag));
29778 * Event fired when the icon of the outline tag is clicked.
29780 * @event OutlineTag#click
29781 * @type {OutlineTag} The tag instance that was clicked.
29783 OutlineTag.click = "click";
29784 exports.OutlineTag = OutlineTag;
29785 exports.default = OutlineTag;
29787 },{"../../../Component":226,"../../../Viewer":236,"rxjs/Subject":34}],298:[function(require,module,exports){
29789 /// <reference path="../../../../typings/index.d.ts" />
29790 Object.defineProperty(exports, "__esModule", { value: true });
29791 var THREE = require("three");
29792 var Subject_1 = require("rxjs/Subject");
29793 var RenderTag = (function () {
29794 function RenderTag(tag, transform) {
29796 this._transform = transform;
29797 this._glObjects = [];
29798 this._glObjectsChanged$ = new Subject_1.Subject();
29799 this._interact$ = new Subject_1.Subject();
29801 Object.defineProperty(RenderTag.prototype, "glObjects", {
29803 * Get the GL objects for rendering of the tag.
29804 * @return {Array<Object3D>}
29807 return this._glObjects;
29812 Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", {
29814 return this._glObjectsChanged$;
29819 Object.defineProperty(RenderTag.prototype, "interact$", {
29821 return this._interact$;
29826 Object.defineProperty(RenderTag.prototype, "tag", {
29833 RenderTag.prototype._projectToCanvas = function (point3d, projectionMatrix) {
29834 var projected = new THREE.Vector3(point3d.x, point3d.y, point3d.z)
29835 .applyMatrix4(projectionMatrix);
29836 return [(projected.x + 1) / 2, (-projected.y + 1) / 2];
29838 RenderTag.prototype._convertToCameraSpace = function (point3d, matrixWorldInverse) {
29839 return new THREE.Vector3(point3d[0], point3d[1], point3d[2]).applyMatrix4(matrixWorldInverse);
29843 exports.RenderTag = RenderTag;
29844 exports.default = RenderTag;
29846 },{"rxjs/Subject":34,"three":176}],299:[function(require,module,exports){
29848 /// <reference path="../../../../typings/index.d.ts" />
29849 var __extends = (this && this.__extends) || (function () {
29850 var extendStatics = Object.setPrototypeOf ||
29851 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29852 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29853 return function (d, b) {
29854 extendStatics(d, b);
29855 function __() { this.constructor = d; }
29856 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29859 Object.defineProperty(exports, "__esModule", { value: true });
29860 var vd = require("virtual-dom");
29861 var Component_1 = require("../../../Component");
29862 var Viewer_1 = require("../../../Viewer");
29864 * @class SpotRenderTag
29865 * @classdesc Tag visualizing the properties of a SpotTag.
29867 var SpotRenderTag = (function (_super) {
29868 __extends(SpotRenderTag, _super);
29869 function SpotRenderTag() {
29870 return _super !== null && _super.apply(this, arguments) || this;
29872 SpotRenderTag.prototype.dispose = function () { return; };
29873 SpotRenderTag.prototype.getDOMObjects = function (atlas, matrixWorldInverse, projectionMatrix) {
29876 var centroid3d = this._tag.geometry.getCentroid3d(this._transform);
29877 var centroidCameraSpace = this._convertToCameraSpace(centroid3d, matrixWorldInverse);
29878 if (centroidCameraSpace.z < 0) {
29879 var centroidCanvas = this._projectToCanvas(centroidCameraSpace, projectionMatrix);
29880 var centroidCss = centroidCanvas.map(function (coord) { return (100 * coord) + "%"; });
29881 var interactNone = function (e) {
29882 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
29884 if (this._tag.icon != null) {
29885 if (atlas.loaded) {
29886 var sprite = atlas.getDOMSprite(this._tag.icon, Viewer_1.Alignment.Bottom);
29888 onmousedown: interactNone,
29890 left: centroidCss[0],
29891 pointerEvents: "all",
29892 position: "absolute",
29893 top: centroidCss[1],
29894 transform: "translate(0, 8px)",
29897 vNodes.push(vd.h("div", properties, [sprite]));
29900 else if (this._tag.text != null) {
29902 onmousedown: interactNone,
29904 color: "#" + ("000000" + this._tag.textColor.toString(16)).substr(-6),
29905 left: centroidCss[0],
29906 pointerEvents: "all",
29907 position: "absolute",
29908 top: centroidCss[1],
29909 transform: "translate(-50%, 8px)",
29911 textContent: this._tag.text,
29913 vNodes.push(vd.h("span.TagSymbol", properties, []));
29915 var interact = this._interact(Component_1.TagOperation.Centroid);
29916 var background = "#" + ("000000" + this._tag.color.toString(16)).substr(-6);
29917 if (this._tag.editable) {
29918 var interactorProperties = {
29919 onmousedown: interact,
29921 background: background,
29922 left: centroidCss[0],
29923 pointerEvents: "all",
29924 position: "absolute",
29925 top: centroidCss[1],
29928 vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, []));
29930 var pointProperties = {
29932 background: background,
29933 left: centroidCss[0],
29934 position: "absolute",
29935 top: centroidCss[1],
29938 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
29942 SpotRenderTag.prototype._interact = function (operation, vertexIndex) {
29944 return function (e) {
29945 var offsetX = e.offsetX - e.target.offsetWidth / 2;
29946 var offsetY = e.offsetY - e.target.offsetHeight / 2;
29947 _this._interact$.next({
29950 operation: operation,
29952 vertexIndex: vertexIndex,
29956 return SpotRenderTag;
29957 }(Component_1.RenderTag));
29958 exports.SpotRenderTag = SpotRenderTag;
29960 },{"../../../Component":226,"../../../Viewer":236,"virtual-dom":182}],300:[function(require,module,exports){
29962 var __extends = (this && this.__extends) || (function () {
29963 var extendStatics = Object.setPrototypeOf ||
29964 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29965 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29966 return function (d, b) {
29967 extendStatics(d, b);
29968 function __() { this.constructor = d; }
29969 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29972 Object.defineProperty(exports, "__esModule", { value: true });
29973 var Component_1 = require("../../../Component");
29977 * @classdesc Tag holding properties for visualizing the centroid of a geometry.
29981 * var geometry = new Mapillary.TagComponent.PointGeometry([0.3, 0.3]);
29982 * var tag = new Mapillary.TagComponent.SpotTag(
29985 * { editable: true, color: 0xff0000 });
29987 * tagComponent.add([tag]);
29990 var SpotTag = (function (_super) {
29991 __extends(SpotTag, _super);
29993 * Create a spot tag.
29997 * @param {string} id
29998 * @param {Geometry} geometry
29999 * @param {IOutlineTagOptions} options - Options defining the visual appearance and
30000 * behavior of the spot tag.
30002 function SpotTag(id, geometry, options) {
30003 var _this = _super.call(this, id, geometry) || this;
30004 _this._color = options.color == null ? 0xFFFFFF : options.color;
30005 _this._editable = options.editable == null ? false : options.editable;
30006 _this._icon = options.icon === undefined ? null : options.icon;
30007 _this._text = options.text === undefined ? null : options.text;
30008 _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
30011 Object.defineProperty(SpotTag.prototype, "color", {
30013 * Get color property.
30014 * @returns {number} The color of the spot as a hexagonal number;
30017 return this._color;
30020 * Set color property.
30023 * @fires Tag#changed
30025 set: function (value) {
30026 this._color = value;
30027 this._notifyChanged$.next(this);
30032 Object.defineProperty(SpotTag.prototype, "editable", {
30034 * Get editable property.
30035 * @returns {boolean} Value indicating if tag is editable.
30038 return this._editable;
30041 * Set editable property.
30044 * @fires Tag#changed
30046 set: function (value) {
30047 this._editable = value;
30048 this._notifyChanged$.next(this);
30053 Object.defineProperty(SpotTag.prototype, "icon", {
30055 * Get icon property.
30056 * @returns {string}
30062 * Set icon property.
30065 * @fires Tag#changed
30067 set: function (value) {
30068 this._icon = value;
30069 this._notifyChanged$.next(this);
30074 Object.defineProperty(SpotTag.prototype, "text", {
30076 * Get text property.
30077 * @returns {string}
30083 * Set text property.
30086 * @fires Tag#changed
30088 set: function (value) {
30089 this._text = value;
30090 this._notifyChanged$.next(this);
30095 Object.defineProperty(SpotTag.prototype, "textColor", {
30097 * Get text color property.
30098 * @returns {number}
30101 return this._textColor;
30104 * Set text color property.
30107 * @fires Tag#changed
30109 set: function (value) {
30110 this._textColor = value;
30111 this._notifyChanged$.next(this);
30117 * Set options for tag.
30119 * @description Sets all the option properties provided and keps
30120 * the rest of the values as is.
30122 * @param {ISpotTagOptions} options - Spot tag options
30124 * @fires {Tag#changed}
30126 SpotTag.prototype.setOptions = function (options) {
30127 this._color = options.color == null ? this._color : options.color;
30128 this._editable = options.editable == null ? this._editable : options.editable;
30129 this._icon = options.icon === undefined ? this._icon : options.icon;
30130 this._text = options.text === undefined ? this._text : options.text;
30131 this._textColor = options.textColor == null ? this._textColor : options.textColor;
30132 this._notifyChanged$.next(this);
30135 }(Component_1.Tag));
30136 exports.SpotTag = SpotTag;
30137 exports.default = SpotTag;
30139 },{"../../../Component":226}],301:[function(require,module,exports){
30141 var __extends = (this && this.__extends) || (function () {
30142 var extendStatics = Object.setPrototypeOf ||
30143 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30144 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30145 return function (d, b) {
30146 extendStatics(d, b);
30147 function __() { this.constructor = d; }
30148 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30151 Object.defineProperty(exports, "__esModule", { value: true });
30152 var Subject_1 = require("rxjs/Subject");
30153 require("rxjs/add/operator/map");
30154 require("rxjs/add/operator/share");
30155 var Utils_1 = require("../../../Utils");
30159 * @classdesc Abstract class representing the basic functionality of for a tag.
30161 var Tag = (function (_super) {
30162 __extends(Tag, _super);
30167 * @param {string} id
30168 * @param {Geometry} geometry
30170 function Tag(id, geometry) {
30171 var _this = _super.call(this) || this;
30173 _this._geometry = geometry;
30174 _this._notifyChanged$ = new Subject_1.Subject();
30175 _this._notifyChanged$
30176 .subscribe(function (t) {
30177 _this.fire(Tag.changed, _this);
30179 _this._geometry.changed$
30180 .subscribe(function (g) {
30181 _this.fire(Tag.geometrychanged, _this);
30185 Object.defineProperty(Tag.prototype, "id", {
30188 * @returns {string}
30196 Object.defineProperty(Tag.prototype, "geometry", {
30198 * Get geometry property.
30199 * @returns {Geometry} The geometry of the tag.
30202 return this._geometry;
30207 Object.defineProperty(Tag.prototype, "changed$", {
30209 * Get changed observable.
30210 * @returns {Observable<Tag>}
30214 return this._notifyChanged$;
30219 Object.defineProperty(Tag.prototype, "geometryChanged$", {
30221 * Get geometry changed observable.
30222 * @returns {Observable<Tag>}
30227 return this._geometry.changed$
30228 .map(function (geometry) {
30237 }(Utils_1.EventEmitter));
30239 * Event fired when a property related to the visual appearance of the
30242 * @event Tag#changed
30243 * @type {Tag} The tag instance that has changed.
30245 Tag.changed = "changed";
30247 * Event fired when the geometry of the tag has changed.
30249 * @event Tag#geometrychanged
30250 * @type {Tag} The tag instance whose geometry has changed.
30252 Tag.geometrychanged = "geometrychanged";
30254 exports.default = Tag;
30256 },{"../../../Utils":235,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/share":74}],302:[function(require,module,exports){
30258 var __extends = (this && this.__extends) || (function () {
30259 var extendStatics = Object.setPrototypeOf ||
30260 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30261 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30262 return function (d, b) {
30263 extendStatics(d, b);
30264 function __() { this.constructor = d; }
30265 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30268 Object.defineProperty(exports, "__esModule", { value: true });
30269 var MapillaryError_1 = require("./MapillaryError");
30270 var ArgumentMapillaryError = (function (_super) {
30271 __extends(ArgumentMapillaryError, _super);
30272 function ArgumentMapillaryError(message) {
30273 var _this = _super.call(this, message != null ? message : "The argument is not valid.") || this;
30274 _this.name = "ArgumentMapillaryError";
30277 return ArgumentMapillaryError;
30278 }(MapillaryError_1.MapillaryError));
30279 exports.ArgumentMapillaryError = ArgumentMapillaryError;
30280 exports.default = ArgumentMapillaryError;
30282 },{"./MapillaryError":304}],303:[function(require,module,exports){
30284 var __extends = (this && this.__extends) || (function () {
30285 var extendStatics = Object.setPrototypeOf ||
30286 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30287 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30288 return function (d, b) {
30289 extendStatics(d, b);
30290 function __() { this.constructor = d; }
30291 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30294 Object.defineProperty(exports, "__esModule", { value: true });
30295 var MapillaryError_1 = require("./MapillaryError");
30296 var GraphMapillaryError = (function (_super) {
30297 __extends(GraphMapillaryError, _super);
30298 function GraphMapillaryError(message) {
30299 var _this = _super.call(this, message) || this;
30300 _this.name = "GraphMapillaryError";
30303 return GraphMapillaryError;
30304 }(MapillaryError_1.MapillaryError));
30305 exports.GraphMapillaryError = GraphMapillaryError;
30306 exports.default = GraphMapillaryError;
30308 },{"./MapillaryError":304}],304:[function(require,module,exports){
30310 var __extends = (this && this.__extends) || (function () {
30311 var extendStatics = Object.setPrototypeOf ||
30312 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30313 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30314 return function (d, b) {
30315 extendStatics(d, b);
30316 function __() { this.constructor = d; }
30317 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30320 Object.defineProperty(exports, "__esModule", { value: true });
30321 var MapillaryError = (function (_super) {
30322 __extends(MapillaryError, _super);
30323 function MapillaryError(message) {
30324 var _this = _super.call(this, message) || this;
30325 _this.name = "MapillaryError";
30328 return MapillaryError;
30330 exports.MapillaryError = MapillaryError;
30331 exports.default = MapillaryError;
30333 },{}],305:[function(require,module,exports){
30335 /// <reference path="../../typings/index.d.ts" />
30336 Object.defineProperty(exports, "__esModule", { value: true });
30337 var THREE = require("three");
30341 * @classdesc Holds information about a camera.
30343 var Camera = (function () {
30345 * Create a new camera instance.
30346 * @param {Transform} [transform] - Optional transform instance.
30348 function Camera(transform) {
30349 if (transform != null) {
30350 this._position = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0));
30351 this._lookat = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10));
30352 this._up = transform.upVector();
30353 this._focal = this._getFocal(transform);
30356 this._position = new THREE.Vector3(0, 0, 0);
30357 this._lookat = new THREE.Vector3(0, 0, 1);
30358 this._up = new THREE.Vector3(0, -1, 0);
30362 Object.defineProperty(Camera.prototype, "position", {
30365 * @returns {THREE.Vector3} The position vector.
30368 return this._position;
30373 Object.defineProperty(Camera.prototype, "lookat", {
30376 * @returns {THREE.Vector3} The lookat vector.
30379 return this._lookat;
30384 Object.defineProperty(Camera.prototype, "up", {
30387 * @returns {THREE.Vector3} The up vector.
30395 Object.defineProperty(Camera.prototype, "focal", {
30398 * @returns {number} The focal length.
30401 return this._focal;
30406 set: function (value) {
30407 this._focal = value;
30413 * Update this camera to the linearly interpolated value of two other cameras.
30415 * @param {Camera} a - First camera.
30416 * @param {Camera} b - Second camera.
30417 * @param {number} alpha - Interpolation value on the interval [0, 1].
30419 Camera.prototype.lerpCameras = function (a, b, alpha) {
30420 this._position.subVectors(b.position, a.position).multiplyScalar(alpha).add(a.position);
30421 this._lookat.subVectors(b.lookat, a.lookat).multiplyScalar(alpha).add(a.lookat);
30422 this._up.subVectors(b.up, a.up).multiplyScalar(alpha).add(a.up);
30423 this._focal = (1 - alpha) * a.focal + alpha * b.focal;
30426 * Copy the properties of another camera to this camera.
30428 * @param {Camera} other - Another camera.
30430 Camera.prototype.copy = function (other) {
30431 this._position.copy(other.position);
30432 this._lookat.copy(other.lookat);
30433 this._up.copy(other.up);
30434 this._focal = other.focal;
30437 * Clone this camera.
30439 * @returns {Camera} A camera with cloned properties equal to this camera.
30441 Camera.prototype.clone = function () {
30442 var camera = new Camera();
30443 camera.position.copy(this._position);
30444 camera.lookat.copy(this._lookat);
30445 camera.up.copy(this._up);
30446 camera.focal = this._focal;
30450 * Determine the distance between this camera and another camera.
30452 * @param {Camera} other - Another camera.
30453 * @returns {number} The distance between the cameras.
30455 Camera.prototype.diff = function (other) {
30456 var pd = this._position.distanceToSquared(other.position);
30457 var ld = this._lookat.distanceToSquared(other.lookat);
30458 var ud = this._up.distanceToSquared(other.up);
30459 var fd = 100 * Math.abs(this._focal - other.focal);
30460 return Math.max(pd, ld, ud, fd);
30463 * Get the focal length based on the transform.
30465 * @description Returns the focal length of the transform if gpano info is not available.
30466 * Returns a focal length corresponding to a vertical fov clamped to [45, 90] degrees based on
30467 * the gpano information if available.
30469 * @returns {number} Focal length.
30471 Camera.prototype._getFocal = function (transform) {
30472 if (transform.gpano == null) {
30473 return transform.focal;
30475 var vFov = Math.PI * transform.gpano.CroppedAreaImageHeightPixels / transform.gpano.FullPanoHeightPixels;
30476 var focal = 0.5 / Math.tan(vFov / 2);
30477 return Math.min(1 / (2 * (Math.sqrt(2) - 1)), Math.max(0.5, focal));
30481 exports.Camera = Camera;
30483 },{"three":176}],306:[function(require,module,exports){
30485 Object.defineProperty(exports, "__esModule", { value: true });
30489 * @classdesc Converts coordinates between the geodetic (WGS84),
30490 * Earth-Centered, Earth-Fixed (ECEF) and local topocentric
30491 * East, North, Up (ENU) reference frames.
30493 * The WGS84 has latitude (degrees), longitude (degrees) and
30494 * altitude (meters) values.
30496 * The ECEF Z-axis pierces the north pole and the
30497 * XY-axis defines the equatorial plane. The X-axis extends
30498 * from the geocenter to the intersection of the Equator and
30499 * the Greenwich Meridian. All values in meters.
30501 * The WGS84 parameters are:
30505 * f = 1 / 298.257223563
30506 * e = Math.sqrt((a^2 - b^2) / a^2)
30507 * e' = Math.sqrt((a^2 - b^2) / b^2)
30509 * The WGS84 to ECEF conversion is performed using the following:
30511 * X = (N - h) * cos(phi) * cos(lambda)
30512 * Y = (N + h) * cos(phi) * sin(lambda)
30513 * Z = (b^2 * N / a^2 + h) * sin(phi)
30518 * lambda = longitude
30519 * h = height above ellipsoid (altitude)
30520 * N = Radius of curvature (meters)
30521 * = a / Math.sqrt(1 - e^2 * sin(phi)^2)
30523 * The ECEF to WGS84 conversion is performed using the following:
30525 * phi = arctan((Z + e'^2 * b * sin(theta)^3) / (p - e^2 * a * cos(theta)^3))
30526 * lambda = arctan(Y / X)
30527 * h = p / cos(phi) - N
30531 * p = Math.sqrt(X^2 + Y^2)
30532 * theta = arctan(Z * a / p * b)
30534 * In the ENU reference frame the x-axis points to the
30535 * East, the y-axis to the North and the z-axis Up. All values
30538 * The ECEF to ENU conversion is performed using the following:
30540 * | x | | -sin(lambda_r) cos(lambda_r) 0 | | X - X_r |
30541 * | y | = | -sin(phi_r) * cos(lambda_r) -sin(phi_r) * sin(lambda_r) cos(phi_r) | | Y - Y_r |
30542 * | z | | cos(phi_r) * cos(lambda_r) cos(phi_r) * sin(lambda_r) sin(phi_r) | | Z - Z_r |
30546 * phi_r = latitude of reference
30547 * lambda_r = longitude of reference
30548 * X_r, Y_r, Z_r = ECEF coordinates of reference
30550 * The ENU to ECEF conversion is performed by solving the above equation for X, Y, Z.
30552 * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in
30553 * the first step for both conversions.
30555 var GeoCoords = (function () {
30556 function GeoCoords() {
30557 this._wgs84a = 6378137.0;
30558 this._wgs84b = 6356752.31424518;
30561 * Convert coordinates from geodetic (WGS84) reference to local topocentric
30564 * @param {number} lat Latitude in degrees.
30565 * @param {number} lon Longitude in degrees.
30566 * @param {number} alt Altitude in meters.
30567 * @param {number} refLat Reference latitude in degrees.
30568 * @param {number} refLon Reference longitude in degrees.
30569 * @param {number} refAlt Reference altitude in meters.
30570 * @returns {Array<number>} The x, y, z local topocentric ENU coordinates.
30572 GeoCoords.prototype.geodeticToEnu = function (lat, lon, alt, refLat, refLon, refAlt) {
30573 var ecef = this.geodeticToEcef(lat, lon, alt);
30574 return this.ecefToEnu(ecef[0], ecef[1], ecef[2], refLat, refLon, refAlt);
30577 * Convert coordinates from local topocentric (ENU) reference to
30578 * geodetic (WGS84) reference.
30580 * @param {number} x Topocentric ENU coordinate in East direction.
30581 * @param {number} y Topocentric ENU coordinate in North direction.
30582 * @param {number} z Topocentric ENU coordinate in Up direction.
30583 * @param {number} refLat Reference latitude in degrees.
30584 * @param {number} refLon Reference longitude in degrees.
30585 * @param {number} refAlt Reference altitude in meters.
30586 * @returns {Array<number>} The latitude and longitude in degrees
30587 * as well as altitude in meters.
30589 GeoCoords.prototype.enuToGeodetic = function (x, y, z, refLat, refLon, refAlt) {
30590 var ecef = this.enuToEcef(x, y, z, refLat, refLon, refAlt);
30591 return this.ecefToGeodetic(ecef[0], ecef[1], ecef[2]);
30594 * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
30595 * to local topocentric (ENU) reference.
30597 * @param {number} X ECEF X-value.
30598 * @param {number} Y ECEF Y-value.
30599 * @param {number} Z ECEF Z-value.
30600 * @param {number} refLat Reference latitude in degrees.
30601 * @param {number} refLon Reference longitude in degrees.
30602 * @param {number} refAlt Reference altitude in meters.
30603 * @returns {Array<number>} The x, y, z topocentric ENU coordinates in East, North
30604 * and Up directions respectively.
30606 GeoCoords.prototype.ecefToEnu = function (X, Y, Z, refLat, refLon, refAlt) {
30607 var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
30608 var V = [X - refEcef[0], Y - refEcef[1], Z - refEcef[2]];
30609 refLat = refLat * Math.PI / 180.0;
30610 refLon = refLon * Math.PI / 180.0;
30611 var cosLat = Math.cos(refLat);
30612 var sinLat = Math.sin(refLat);
30613 var cosLon = Math.cos(refLon);
30614 var sinLon = Math.sin(refLon);
30615 var x = -sinLon * V[0] + cosLon * V[1];
30616 var y = -sinLat * cosLon * V[0] - sinLat * sinLon * V[1] + cosLat * V[2];
30617 var z = cosLat * cosLon * V[0] + cosLat * sinLon * V[1] + sinLat * V[2];
30621 * Convert coordinates from local topocentric (ENU) reference
30622 * to Earth-Centered, Earth-Fixed (ECEF) reference.
30624 * @param {number} x Topocentric ENU coordinate in East direction.
30625 * @param {number} y Topocentric ENU coordinate in North direction.
30626 * @param {number} z Topocentric ENU coordinate in Up direction.
30627 * @param {number} refLat Reference latitude in degrees.
30628 * @param {number} refLon Reference longitude in degrees.
30629 * @param {number} refAlt Reference altitude in meters.
30630 * @returns {Array<number>} The X, Y, Z ECEF coordinates.
30632 GeoCoords.prototype.enuToEcef = function (x, y, z, refLat, refLon, refAlt) {
30633 var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
30634 refLat = refLat * Math.PI / 180.0;
30635 refLon = refLon * Math.PI / 180.0;
30636 var cosLat = Math.cos(refLat);
30637 var sinLat = Math.sin(refLat);
30638 var cosLon = Math.cos(refLon);
30639 var sinLon = Math.sin(refLon);
30640 var X = -sinLon * x - sinLat * cosLon * y + cosLat * cosLon * z + refEcef[0];
30641 var Y = cosLon * x - sinLat * sinLon * y + cosLat * sinLon * z + refEcef[1];
30642 var Z = cosLat * y + sinLat * z + refEcef[2];
30646 * Convert coordinates from geodetic reference (WGS84) to Earth-Centered,
30647 * Earth-Fixed (ECEF) reference.
30649 * @param {number} lat Latitude in degrees.
30650 * @param {number} lon Longitude in degrees.
30651 * @param {number} alt Altitude in meters.
30652 * @returns {Array<number>} The X, Y, Z ECEF coordinates.
30654 GeoCoords.prototype.geodeticToEcef = function (lat, lon, alt) {
30655 var a = this._wgs84a;
30656 var b = this._wgs84b;
30657 lat = lat * Math.PI / 180.0;
30658 lon = lon * Math.PI / 180.0;
30659 var cosLat = Math.cos(lat);
30660 var sinLat = Math.sin(lat);
30661 var cosLon = Math.cos(lon);
30662 var sinLon = Math.sin(lon);
30665 var L = 1.0 / Math.sqrt(a2 * cosLat * cosLat + b2 * sinLat * sinLat);
30666 var nhcl = (a2 * L + alt) * cosLat;
30667 var X = nhcl * cosLon;
30668 var Y = nhcl * sinLon;
30669 var Z = (b2 * L + alt) * sinLat;
30673 * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
30674 * to geodetic reference (WGS84).
30676 * @param {number} X ECEF X-value.
30677 * @param {number} Y ECEF Y-value.
30678 * @param {number} Z ECEF Z-value.
30679 * @returns {Array<number>} The latitude and longitude in degrees
30680 * as well as altitude in meters.
30682 GeoCoords.prototype.ecefToGeodetic = function (X, Y, Z) {
30683 var a = this._wgs84a;
30684 var b = this._wgs84b;
30687 var a2mb2 = a2 - b2;
30688 var ea = Math.sqrt(a2mb2 / a2);
30689 var eb = Math.sqrt(a2mb2 / b2);
30690 var p = Math.sqrt(X * X + Y * Y);
30691 var theta = Math.atan2(Z * a, p * b);
30692 var sinTheta = Math.sin(theta);
30693 var cosTheta = Math.cos(theta);
30694 var lon = Math.atan2(Y, X);
30695 var lat = Math.atan2(Z + eb * eb * b * sinTheta * sinTheta * sinTheta, p - ea * ea * a * cosTheta * cosTheta * cosTheta);
30696 var sinLat = Math.sin(lat);
30697 var cosLat = Math.cos(lat);
30698 var N = a / Math.sqrt(1 - ea * ea * sinLat * sinLat);
30699 var alt = p / cosLat - N;
30700 return [lat * 180.0 / Math.PI, lon * 180.0 / Math.PI, alt];
30704 exports.GeoCoords = GeoCoords;
30705 exports.default = GeoCoords;
30707 },{}],307:[function(require,module,exports){
30709 /// <reference path="../../typings/index.d.ts" />
30710 Object.defineProperty(exports, "__esModule", { value: true });
30711 var THREE = require("three");
30715 * @classdesc Provides methods for scalar, vector and matrix calculations.
30717 var Spatial = (function () {
30718 function Spatial() {
30719 this._epsilon = 1e-9;
30722 * Converts azimuthal phi rotation (counter-clockwise with origin on X-axis) to
30723 * bearing (clockwise with origin at north or Y-axis).
30725 * @param {number} phi - Azimuthal phi angle in radians.
30726 * @returns {number} Bearing in radians.
30728 Spatial.prototype.azimuthalToBearing = function (phi) {
30729 return -phi + Math.PI / 2;
30732 * Converts degrees to radians.
30734 * @param {number} deg - Degrees.
30735 * @returns {number} Radians.
30737 Spatial.prototype.degToRad = function (deg) {
30738 return Math.PI * deg / 180;
30741 * Converts radians to degrees.
30743 * @param {number} rad - Radians.
30744 * @returns {number} Degrees.
30746 Spatial.prototype.radToDeg = function (rad) {
30747 return 180 * rad / Math.PI;
30750 * Creates a rotation matrix from an angle-axis vector.
30752 * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
30753 * @returns {THREE.Matrix4} Rotation matrix.
30755 Spatial.prototype.rotationMatrix = function (angleAxis) {
30756 var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]);
30757 var angle = axis.length();
30761 return new THREE.Matrix4().makeRotationAxis(axis, angle);
30764 * Rotates a vector according to a angle-axis rotation vector.
30766 * @param {Array<number>} vector - Vector to rotate.
30767 * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
30768 * @returns {THREE.Vector3} Rotated vector.
30770 Spatial.prototype.rotate = function (vector, angleAxis) {
30771 var v = new THREE.Vector3(vector[0], vector[1], vector[2]);
30772 var rotationMatrix = this.rotationMatrix(angleAxis);
30773 v.applyMatrix4(rotationMatrix);
30777 * Calculates the optical center from a rotation vector
30778 * on the angle-axis representation and a translation vector
30779 * according to C = -R^T t.
30781 * @param {Array<number>} rotation - Angle-axis representation of a rotation.
30782 * @param {Array<number>} translation - Translation vector.
30783 * @returns {THREE.Vector3} Optical center.
30785 Spatial.prototype.opticalCenter = function (rotation, translation) {
30786 var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
30787 var vector = [-translation[0], -translation[1], -translation[2]];
30788 return this.rotate(vector, angleAxis);
30791 * Calculates the viewing direction from a rotation vector
30792 * on the angle-axis representation.
30794 * @param {number[]} rotation - Angle-axis representation of a rotation.
30795 * @returns {THREE.Vector3} Viewing direction.
30797 Spatial.prototype.viewingDirection = function (rotation) {
30798 var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
30799 return this.rotate([0, 0, 1], angleAxis);
30802 * Wrap a number on the interval [min, max].
30804 * @param {number} value - Value to wrap.
30805 * @param {number} min - Lower endpoint of interval.
30806 * @param {number} max - Upper endpoint of interval.
30807 * @returns {number} The wrapped number.
30809 Spatial.prototype.wrap = function (value, min, max) {
30811 throw new Error("Invalid arguments: max must be larger than min.");
30813 var interval = (max - min);
30814 while (value > max || value < min) {
30816 value = value - interval;
30818 else if (value < min) {
30819 value = value + interval;
30825 * Wrap an angle on the interval [-Pi, Pi].
30827 * @param {number} angle - Value to wrap.
30828 * @returns {number} Wrapped angle.
30830 Spatial.prototype.wrapAngle = function (angle) {
30831 return this.wrap(angle, -Math.PI, Math.PI);
30834 * Limit the value to the interval [min, max] by changing the value to
30835 * the nearest available one when it is outside the interval.
30837 * @param {number} value - Value to clamp.
30838 * @param {number} min - Minimum of the interval.
30839 * @param {number} max - Maximum of the interval.
30840 * @returns {number} Clamped value.
30842 Spatial.prototype.clamp = function (value, min, max) {
30852 * Calculates the counter-clockwise angle from the first
30853 * vector (x1, y1)^T to the second (x2, y2)^T.
30855 * @param {number} x1 - X coordinate of first vector.
30856 * @param {number} y1 - Y coordinate of first vector.
30857 * @param {number} x2 - X coordinate of second vector.
30858 * @param {number} y2 - Y coordinate of second vector.
30859 * @returns {number} Counter clockwise angle between the vectors.
30861 Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) {
30862 var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1);
30863 return this.wrapAngle(angle);
30866 * Calculates the minimum (absolute) angle change for rotation
30867 * from one angle to another on the [-Pi, Pi] interval.
30869 * @param {number} angle1 - Start angle.
30870 * @param {number} angle2 - Destination angle.
30871 * @returns {number} Absolute angle change between angles.
30873 Spatial.prototype.angleDifference = function (angle1, angle2) {
30874 var angle = angle2 - angle1;
30875 return this.wrapAngle(angle);
30878 * Calculates the relative rotation angle between two
30879 * angle-axis vectors.
30881 * @param {number} rotation1 - First angle-axis vector.
30882 * @param {number} rotation2 - Second angle-axis vector.
30883 * @returns {number} Relative rotation angle.
30885 Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) {
30886 var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]);
30887 var R2 = this.rotationMatrix(rotation2);
30888 var R = R1T.multiply(R2);
30889 var elements = R.elements;
30890 // from Tr(R) = 1 + 2*cos(theta)
30891 var theta = Math.acos((elements[0] + elements[5] + elements[10] - 1) / 2);
30895 * Calculates the angle from a vector to a plane.
30897 * @param {Array<number>} vector - The vector.
30898 * @param {Array<number>} planeNormal - Normal of the plane.
30899 * @returns {number} Angle from between plane and vector.
30901 Spatial.prototype.angleToPlane = function (vector, planeNormal) {
30902 var v = new THREE.Vector3().fromArray(vector);
30903 var norm = v.length();
30904 if (norm < this._epsilon) {
30907 var projection = v.dot(new THREE.Vector3().fromArray(planeNormal));
30908 return Math.asin(projection / norm);
30911 * Calculates the distance between two coordinates
30912 * (latitude longitude pairs) in meters according to
30913 * the haversine formula.
30915 * @param {number} lat1 - Latitude of the first coordinate.
30916 * @param {number} lon1 - Longitude of the first coordinate.
30917 * @param {number} lat2 - Latitude of the second coordinate.
30918 * @param {number} lon2 - Longitude of the second coordinate.
30919 * @returns {number} Distance between lat lon positions.
30921 Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) {
30923 var dLat = this.degToRad(lat2 - lat1);
30924 var dLon = this.degToRad(lon2 - lon1);
30925 var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
30926 Math.cos(lat1) * Math.cos(lat2) *
30927 Math.sin(dLon / 2) * Math.sin(dLon / 2);
30928 var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav));
30933 exports.Spatial = Spatial;
30934 exports.default = Spatial;
30936 },{"three":176}],308:[function(require,module,exports){
30938 /// <reference path="../../typings/index.d.ts" />
30939 Object.defineProperty(exports, "__esModule", { value: true });
30940 var THREE = require("three");
30944 * @classdesc Class used for calculating coordinate transformations
30947 var Transform = (function () {
30949 * Create a new transform instance.
30950 * @param {Node} apiNavImIm - Node properties.
30951 * @param {HTMLImageElement} image - Node image.
30952 * @param {Array<number>} translation - Node translation vector in three dimensions.
30954 function Transform(node, image, translation) {
30955 this._orientation = this._getValue(node.orientation, 1);
30956 var imageWidth = image != null ? image.width : 4;
30957 var imageHeight = image != null ? image.height : 3;
30958 var keepOrientation = this._orientation < 5;
30959 this._width = this._getValue(node.width, keepOrientation ? imageWidth : imageHeight);
30960 this._height = this._getValue(node.height, keepOrientation ? imageHeight : imageWidth);
30961 this._basicAspect = keepOrientation ?
30962 this._width / this._height :
30963 this._height / this._width;
30964 this._basicWidth = keepOrientation ? node.width : node.height;
30965 this._basicHeight = keepOrientation ? node.height : node.width;
30966 this._focal = this._getValue(node.focal, 1);
30967 this._scale = this._getValue(node.scale, 0);
30968 this._gpano = node.gpano != null ? node.gpano : null;
30969 this._rt = this._getRt(node.rotation, translation);
30970 this._srt = this._getSrt(this._rt, this._scale);
30972 Object.defineProperty(Transform.prototype, "basicAspect", {
30974 * Get basic aspect.
30975 * @returns {number} The orientation adjusted aspect ratio.
30978 return this._basicAspect;
30983 Object.defineProperty(Transform.prototype, "basicHeight", {
30985 * Get basic height.
30987 * @description Does not fall back to node image height but
30988 * uses original value from API so can be faulty.
30990 * @returns {number} The height of the basic version image
30991 * (adjusted for orientation).
30994 return this._basicHeight;
30999 Object.defineProperty(Transform.prototype, "basicWidth", {
31003 * @description Does not fall back to node image width but
31004 * uses original value from API so can be faulty.
31006 * @returns {number} The width of the basic version image
31007 * (adjusted for orientation).
31010 return this._basicWidth;
31015 Object.defineProperty(Transform.prototype, "focal", {
31018 * @returns {number} The node focal length.
31021 return this._focal;
31026 Object.defineProperty(Transform.prototype, "fullPano", {
31030 * @returns {boolean} Value indicating whether the node is a complete
31034 return this._gpano != null &&
31035 this._gpano.CroppedAreaLeftPixels === 0 &&
31036 this._gpano.CroppedAreaTopPixels === 0 &&
31037 this._gpano.CroppedAreaImageWidthPixels === this._gpano.FullPanoWidthPixels &&
31038 this._gpano.CroppedAreaImageHeightPixels === this._gpano.FullPanoHeightPixels;
31043 Object.defineProperty(Transform.prototype, "gpano", {
31046 * @returns {number} The node gpano information.
31049 return this._gpano;
31054 Object.defineProperty(Transform.prototype, "height", {
31058 * @description Falls back to the node image height if
31059 * the API data is faulty.
31061 * @returns {number} The orientation adjusted image height.
31064 return this._height;
31069 Object.defineProperty(Transform.prototype, "orientation", {
31072 * @returns {number} The image orientation.
31075 return this._orientation;
31080 Object.defineProperty(Transform.prototype, "rt", {
31083 * @returns {THREE.Matrix4} The extrinsic camera matrix.
31091 Object.defineProperty(Transform.prototype, "srt", {
31094 * @returns {THREE.Matrix4} The scaled extrinsic camera matrix.
31102 Object.defineProperty(Transform.prototype, "scale", {
31105 * @returns {number} The node atomic reconstruction scale.
31108 return this._scale;
31113 Object.defineProperty(Transform.prototype, "hasValidScale", {
31115 * Get has valid scale.
31116 * @returns {boolean} Value indicating if the scale of the transform is valid.
31119 return this._scale > 1e-2 && this._scale < 50;
31124 Object.defineProperty(Transform.prototype, "width", {
31128 * @description Falls back to the node image width if
31129 * the API data is faulty.
31131 * @returns {number} The orientation adjusted image width.
31134 return this._width;
31140 * Calculate the up vector for the node transform.
31142 * @returns {THREE.Vector3} Normalized and orientation adjusted up vector.
31144 Transform.prototype.upVector = function () {
31145 var rte = this._rt.elements;
31146 switch (this._orientation) {
31148 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
31150 return new THREE.Vector3(rte[1], rte[5], rte[9]);
31152 return new THREE.Vector3(-rte[0], -rte[4], -rte[8]);
31154 return new THREE.Vector3(rte[0], rte[4], rte[8]);
31156 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
31160 * Calculate projector matrix for projecting 3D points to texture map
31161 * coordinates (u and v).
31163 * @returns {THREE.Matrix4} Projection matrix for 3D point to texture
31164 * map coordinate calculations.
31166 Transform.prototype.projectorMatrix = function () {
31167 var projector = this._normalizedToTextureMatrix();
31168 var f = this._focal;
31169 var projection = new THREE.Matrix4().set(f, 0, 0, 0, 0, f, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
31170 projector.multiply(projection);
31171 projector.multiply(this._rt);
31175 * Project 3D world coordinates to basic coordinates.
31177 * @param {Array<number>} point3d - 3D world coordinates.
31178 * @return {Array<number>} 2D basic coordinates.
31180 Transform.prototype.projectBasic = function (point3d) {
31181 var sfm = this.projectSfM(point3d);
31182 return this._sfmToBasic(sfm);
31185 * Unproject basic coordinates to 3D world coordinates.
31187 * @param {Array<number>} basic - 2D basic coordinates.
31188 * @param {Array<number>} distance - Depth to unproject from camera center.
31189 * @returns {Array<number>} Unprojected 3D world coordinates.
31191 Transform.prototype.unprojectBasic = function (basic, distance) {
31192 var sfm = this._basicToSfm(basic);
31193 return this.unprojectSfM(sfm, distance);
31196 * Project 3D world coordinates to SfM coordinates.
31198 * @param {Array<number>} point3d - 3D world coordinates.
31199 * @return {Array<number>} 2D SfM coordinates.
31201 Transform.prototype.projectSfM = function (point3d) {
31202 var v = new THREE.Vector4(point3d[0], point3d[1], point3d[2], 1);
31203 v.applyMatrix4(this._rt);
31204 return this._bearingToSfm([v.x, v.y, v.z]);
31207 * Unproject SfM coordinates to a 3D world coordinates.
31209 * @param {Array<number>} sfm - 2D SfM coordinates.
31210 * @param {Array<number>} distance - Depth to unproject from camera center.
31211 * @returns {Array<number>} Unprojected 3D world coordinates.
31213 Transform.prototype.unprojectSfM = function (sfm, distance) {
31214 var bearing = this._sfmToBearing(sfm);
31215 var v = new THREE.Vector4(distance * bearing[0], distance * bearing[1], distance * bearing[2], 1);
31216 v.applyMatrix4(new THREE.Matrix4().getInverse(this._rt));
31217 return [v.x / v.w, v.y / v.w, v.z / v.w];
31220 * Transform SfM coordinates to bearing vector (3D cartesian
31221 * coordinates on the unit sphere).
31223 * @param {Array<number>} sfm - 2D SfM coordinates.
31224 * @returns {Array<number>} Bearing vector (3D cartesian coordinates
31225 * on the unit sphere).
31227 Transform.prototype._sfmToBearing = function (sfm) {
31228 if (this._fullPano()) {
31229 var lon = sfm[0] * 2 * Math.PI;
31230 var lat = -sfm[1] * 2 * Math.PI;
31231 var x = Math.cos(lat) * Math.sin(lon);
31232 var y = -Math.sin(lat);
31233 var z = Math.cos(lat) * Math.cos(lon);
31236 else if (this._gpano) {
31237 var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
31238 var fullPanoPixel = [
31239 sfm[0] * size + this.gpano.CroppedAreaImageWidthPixels / 2 + this.gpano.CroppedAreaLeftPixels,
31240 sfm[1] * size + this.gpano.CroppedAreaImageHeightPixels / 2 + this.gpano.CroppedAreaTopPixels,
31242 var lon = 2 * Math.PI * (fullPanoPixel[0] / this.gpano.FullPanoWidthPixels - 0.5);
31243 var lat = -Math.PI * (fullPanoPixel[1] / this.gpano.FullPanoHeightPixels - 0.5);
31244 var x = Math.cos(lat) * Math.sin(lon);
31245 var y = -Math.sin(lat);
31246 var z = Math.cos(lat) * Math.cos(lon);
31250 var v = new THREE.Vector3(sfm[0], sfm[1], this._focal);
31252 return [v.x, v.y, v.z];
31256 * Transform bearing vector (3D cartesian coordiantes on the unit sphere) to
31259 * @param {Array<number>} bearing - Bearing vector (3D cartesian coordinates on the
31261 * @returns {Array<number>} 2D SfM coordinates.
31263 Transform.prototype._bearingToSfm = function (bearing) {
31264 if (this._fullPano()) {
31265 var x = bearing[0];
31266 var y = bearing[1];
31267 var z = bearing[2];
31268 var lon = Math.atan2(x, z);
31269 var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
31270 return [lon / (2 * Math.PI), -lat / (2 * Math.PI)];
31272 else if (this._gpano) {
31273 var x = bearing[0];
31274 var y = bearing[1];
31275 var z = bearing[2];
31276 var lon = Math.atan2(x, z);
31277 var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
31278 var fullPanoPixel = [
31279 (lon / (2 * Math.PI) + 0.5) * this.gpano.FullPanoWidthPixels,
31280 (-lat / Math.PI + 0.5) * this.gpano.FullPanoHeightPixels,
31282 var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
31284 (fullPanoPixel[0] - this.gpano.CroppedAreaLeftPixels - this.gpano.CroppedAreaImageWidthPixels / 2) / size,
31285 (fullPanoPixel[1] - this.gpano.CroppedAreaTopPixels - this.gpano.CroppedAreaImageHeightPixels / 2) / size,
31289 if (bearing[2] > 0) {
31291 bearing[0] * this._focal / bearing[2],
31292 bearing[1] * this._focal / bearing[2],
31297 bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
31298 bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
31304 * Convert basic coordinates to SfM coordinates.
31306 * @param {Array<number>} basic - 2D basic coordinates.
31307 * @returns {Array<number>} 2D SfM coordinates.
31309 Transform.prototype._basicToSfm = function (basic) {
31312 switch (this._orientation) {
31314 rotatedX = basic[0];
31315 rotatedY = basic[1];
31318 rotatedX = 1 - basic[0];
31319 rotatedY = 1 - basic[1];
31322 rotatedX = basic[1];
31323 rotatedY = 1 - basic[0];
31326 rotatedX = 1 - basic[1];
31327 rotatedY = basic[0];
31330 rotatedX = basic[0];
31331 rotatedY = basic[1];
31334 var w = this._width;
31335 var h = this._height;
31336 var s = Math.max(w, h);
31337 var sfmX = rotatedX * w / s - w / s / 2;
31338 var sfmY = rotatedY * h / s - h / s / 2;
31339 return [sfmX, sfmY];
31342 * Convert SfM coordinates to basic coordinates.
31344 * @param {Array<number>} sfm - 2D SfM coordinates.
31345 * @returns {Array<number>} 2D basic coordinates.
31347 Transform.prototype._sfmToBasic = function (sfm) {
31348 var w = this._width;
31349 var h = this._height;
31350 var s = Math.max(w, h);
31351 var rotatedX = (sfm[0] + w / s / 2) / w * s;
31352 var rotatedY = (sfm[1] + h / s / 2) / h * s;
31355 switch (this._orientation) {
31361 basicX = 1 - rotatedX;
31362 basicY = 1 - rotatedY;
31365 basicX = 1 - rotatedY;
31370 basicY = 1 - rotatedX;
31377 return [basicX, basicY];
31380 * Determines if the gpano information indicates a full panorama.
31382 * @returns {boolean} Value determining if the gpano information indicates
31385 Transform.prototype._fullPano = function () {
31386 return this.gpano != null &&
31387 this.gpano.CroppedAreaLeftPixels === 0 &&
31388 this.gpano.CroppedAreaTopPixels === 0 &&
31389 this.gpano.CroppedAreaImageWidthPixels === this.gpano.FullPanoWidthPixels &&
31390 this.gpano.CroppedAreaImageHeightPixels === this.gpano.FullPanoHeightPixels;
31393 * Checks a value and returns it if it exists and is larger than 0.
31394 * Fallbacks if it is null.
31396 * @param {number} value - Value to check.
31397 * @param {number} fallback - Value to fall back to.
31398 * @returns {number} The value or its fallback value if it is not defined or negative.
31400 Transform.prototype._getValue = function (value, fallback) {
31401 return value != null && value > 0 ? value : fallback;
31404 * Creates the extrinsic camera matrix [ R | t ].
31406 * @param {Array<number>} rotation - Rotation vector in angle axis representation.
31407 * @param {Array<number>} translation - Translation vector.
31408 * @returns {THREE.Matrix4} Extrisic camera matrix.
31410 Transform.prototype._getRt = function (rotation, translation) {
31411 var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]);
31412 var angle = axis.length();
31416 var rt = new THREE.Matrix4();
31417 rt.makeRotationAxis(axis, angle);
31418 rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2]));
31422 * Calculates the scaled extrinsic camera matrix scale * [ R | t ].
31424 * @param {THREE.Matrix4} rt - Extrisic camera matrix.
31425 * @param {number} scale - Scale factor.
31426 * @returns {THREE.Matrix4} Scaled extrisic camera matrix.
31428 Transform.prototype._getSrt = function (rt, scale) {
31429 var srt = rt.clone();
31430 var elements = srt.elements;
31431 elements[12] = scale * elements[12];
31432 elements[13] = scale * elements[13];
31433 elements[14] = scale * elements[14];
31434 srt.scale(new THREE.Vector3(scale, scale, scale));
31438 * Calculate a transformation matrix from normalized coordinates for
31439 * texture map coordinates.
31441 * @returns {THREE.Matrix4} Normalized coordinates to texture map
31442 * coordinates transformation matrix.
31444 Transform.prototype._normalizedToTextureMatrix = function () {
31445 var size = Math.max(this._width, this._height);
31446 var w = size / this._width;
31447 var h = size / this._height;
31448 switch (this._orientation) {
31450 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
31452 return new THREE.Matrix4().set(-w, 0, 0, 0.5, 0, h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
31454 return new THREE.Matrix4().set(0, -h, 0, 0.5, -w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
31456 return new THREE.Matrix4().set(0, h, 0, 0.5, w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
31458 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
31463 exports.Transform = Transform;
31465 },{"three":176}],309:[function(require,module,exports){
31467 /// <reference path="../../typings/index.d.ts" />
31468 Object.defineProperty(exports, "__esModule", { value: true });
31469 var THREE = require("three");
31471 * @class ViewportCoords
31473 * @classdesc Provides methods for calculating 2D coordinate conversions
31474 * as well as 3D projection and unprojection.
31476 * Basic coordinates are 2D coordinates on the [0, 1] interval and
31477 * have the origin point, (0, 0), at the top left corner and the
31478 * maximum value, (1, 1), at the bottom right corner of the original
31481 * Viewport coordinates are 2D coordinates on the [-1, 1] interval and
31482 * have the origin point in the center. The bottom left corner point is
31483 * (-1, -1) and the top right corner point is (1, 1).
31485 * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and
31486 * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left
31487 * corner and the maximum value is (canvasWidth, canvasHeight) is in the
31488 * bottom right corner.
31490 * 3D coordinates are in the topocentric world reference frame.
31492 var ViewportCoords = (function () {
31493 function ViewportCoords() {
31494 this._unprojectDepth = 200;
31497 * Convert basic coordinates to canvas coordinates.
31499 * @description Transform origin and camera position needs to be the
31500 * equal for reliable return value.
31502 * @param {number} basicX - Basic X coordinate.
31503 * @param {number} basicY - Basic Y coordinate.
31504 * @param {HTMLElement} container - The viewer container.
31505 * @param {Transform} transform - Transform of the node to unproject from.
31506 * @param {THREE.Camera} camera - Camera used in rendering.
31507 * @returns {Array<number>} 2D canvas coordinates.
31509 ViewportCoords.prototype.basicToCanvas = function (basicX, basicY, container, transform, camera) {
31510 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
31511 var canvas = this.projectToCanvas(point3d, container, camera);
31515 * Convert basic coordinates to canvas coordinates safely. If 3D point is
31516 * behind camera null will be returned.
31518 * @description Transform origin and camera position needs to be the
31519 * equal for reliable return value.
31521 * @param {number} basicX - Basic X coordinate.
31522 * @param {number} basicY - Basic Y coordinate.
31523 * @param {HTMLElement} container - The viewer container.
31524 * @param {Transform} transform - Transform of the node to unproject from.
31525 * @param {THREE.Camera} camera - Camera used in rendering.
31526 * @returns {Array<number>} 2D canvas coordinates if the basic point represents a 3D point
31527 * in front of the camera, otherwise null.
31529 ViewportCoords.prototype.basicToCanvasSafe = function (basicX, basicY, container, transform, camera) {
31530 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
31531 var pointCamera = this.worldToCamera(point3d, camera);
31532 if (pointCamera[2] > 0) {
31535 var _a = this.cameraToViewport(pointCamera, camera), viewportX = _a[0], viewportY = _a[1];
31536 var canvas = this.viewportToCanvas(viewportX, viewportY, container);
31540 * Convert basic coordinates to viewport coordinates.
31542 * @description Transform origin and camera position needs to be the
31543 * equal for reliable return value.
31545 * @param {number} basicX - Basic X coordinate.
31546 * @param {number} basicY - Basic Y coordinate.
31547 * @param {Transform} transform - Transform of the node to unproject from.
31548 * @param {THREE.Camera} camera - Camera used in rendering.
31549 * @returns {Array<number>} 2D viewport coordinates.
31551 ViewportCoords.prototype.basicToViewport = function (basicX, basicY, transform, camera) {
31552 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
31553 var viewport = this.projectToViewport(point3d, camera);
31557 * Convert camera 3D coordinates to viewport coordinates.
31559 * @param {number} pointCamera - 3D point in camera coordinate system.
31560 * @param {THREE.Camera} camera - Camera used in rendering.
31561 * @returns {Array<number>} 2D viewport coordinates.
31563 ViewportCoords.prototype.cameraToViewport = function (pointCamera, camera) {
31564 var viewport = new THREE.Vector3().fromArray(pointCamera)
31565 .applyMatrix4(camera.projectionMatrix);
31566 return [viewport.x, viewport.y];
31569 * Get canvas pixel position from event.
31571 * @param {Event} event - Event containing clientX and clientY properties.
31572 * @param {HTMLElement} element - HTML element.
31573 * @returns {Array<number>} 2D canvas coordinates.
31575 ViewportCoords.prototype.canvasPosition = function (event, element) {
31576 var clientRect = element.getBoundingClientRect();
31577 var canvasX = event.clientX - clientRect.left - element.clientLeft;
31578 var canvasY = event.clientY - clientRect.top - element.clientTop;
31579 return [canvasX, canvasY];
31582 * Convert canvas coordinates to basic coordinates.
31584 * @description Transform origin and camera position needs to be the
31585 * equal for reliable return value.
31587 * @param {number} canvasX - Canvas X coordinate.
31588 * @param {number} canvasY - Canvas Y coordinate.
31589 * @param {HTMLElement} container - The viewer container.
31590 * @param {Transform} transform - Transform of the node to unproject from.
31591 * @param {THREE.Camera} camera - Camera used in rendering.
31592 * @returns {Array<number>} 2D basic coordinates.
31594 ViewportCoords.prototype.canvasToBasic = function (canvasX, canvasY, container, transform, camera) {
31595 var point3d = this.unprojectFromCanvas(canvasX, canvasY, container, camera)
31597 var basic = transform.projectBasic(point3d);
31601 * Convert canvas coordinates to viewport coordinates.
31603 * @param {number} canvasX - Canvas X coordinate.
31604 * @param {number} canvasY - Canvas Y coordinate.
31605 * @param {HTMLElement} container - The viewer container.
31606 * @returns {Array<number>} 2D viewport coordinates.
31608 ViewportCoords.prototype.canvasToViewport = function (canvasX, canvasY, container) {
31609 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
31610 var viewportX = 2 * canvasX / canvasWidth - 1;
31611 var viewportY = 1 - 2 * canvasY / canvasHeight;
31612 return [viewportX, viewportY];
31615 * Determines the width and height of the container in canvas coordinates.
31617 * @param {HTMLElement} container - The viewer container.
31618 * @returns {Array<number>} 2D canvas coordinates.
31620 ViewportCoords.prototype.containerToCanvas = function (container) {
31621 return [container.offsetWidth, container.offsetHeight];
31624 * Determine basic distances from image to canvas corners.
31626 * @description Transform origin and camera position needs to be the
31627 * equal for reliable return value.
31629 * Determines the smallest basic distance for every side of the canvas.
31631 * @param {Transform} transform - Transform of the node to unproject from.
31632 * @param {THREE.Camera} camera - Camera used in rendering.
31633 * @returns {Array<number>} Array of basic distances as [top, right, bottom, left].
31635 ViewportCoords.prototype.getBasicDistances = function (transform, camera) {
31636 var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
31637 var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
31638 var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
31639 var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
31640 var topBasicDistance = 0;
31641 var rightBasicDistance = 0;
31642 var bottomBasicDistance = 0;
31643 var leftBasicDistance = 0;
31644 if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
31645 topBasicDistance = topLeftBasic[1] > topRightBasic[1] ?
31649 if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
31650 rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ?
31651 topRightBasic[0] - 1 :
31652 bottomRightBasic[0] - 1;
31654 if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
31655 bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ?
31656 bottomRightBasic[1] - 1 :
31657 bottomLeftBasic[1] - 1;
31659 if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
31660 leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ?
31661 -bottomLeftBasic[0] :
31664 return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance];
31667 * Determine pixel distances from image to canvas corners.
31669 * @description Transform origin and camera position needs to be the
31670 * equal for reliable return value.
31672 * Determines the smallest pixel distance for every side of the canvas.
31674 * @param {HTMLElement} container - The viewer container.
31675 * @param {Transform} transform - Transform of the node to unproject from.
31676 * @param {THREE.Camera} camera - Camera used in rendering.
31677 * @returns {Array<number>} Array of pixel distances as [top, right, bottom, left].
31679 ViewportCoords.prototype.getPixelDistances = function (container, transform, camera) {
31680 var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
31681 var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
31682 var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
31683 var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
31684 var topPixelDistance = 0;
31685 var rightPixelDistance = 0;
31686 var bottomPixelDistance = 0;
31687 var leftPixelDistance = 0;
31688 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
31689 if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
31690 var basicX = topLeftBasic[1] > topRightBasic[1] ?
31693 var canvas = this.basicToCanvas(basicX, 0, container, transform, camera);
31694 topPixelDistance = canvas[1] > 0 ? canvas[1] : 0;
31696 if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
31697 var basicY = topRightBasic[0] < bottomRightBasic[0] ?
31699 bottomRightBasic[1];
31700 var canvas = this.basicToCanvas(1, basicY, container, transform, camera);
31701 rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0;
31703 if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
31704 var basicX = bottomRightBasic[1] < bottomLeftBasic[1] ?
31705 bottomRightBasic[0] :
31706 bottomLeftBasic[0];
31707 var canvas = this.basicToCanvas(basicX, 1, container, transform, camera);
31708 bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0;
31710 if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
31711 var basicY = bottomLeftBasic[0] > topLeftBasic[0] ?
31712 bottomLeftBasic[1] :
31714 var canvas = this.basicToCanvas(0, basicY, container, transform, camera);
31715 leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0;
31717 return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance];
31720 * Determine if an event occured inside an element.
31722 * @param {Event} event - Event containing clientX and clientY properties.
31723 * @param {HTMLElement} element - HTML element.
31724 * @returns {boolean} Value indicating if the event occured inside the element or not.
31726 ViewportCoords.prototype.insideElement = function (event, element) {
31727 var clientRect = element.getBoundingClientRect();
31728 var minX = clientRect.left + element.clientLeft;
31729 var maxX = minX + element.clientWidth;
31730 var minY = clientRect.top + element.clientTop;
31731 var maxY = minY + element.clientHeight;
31732 return event.clientX > minX &&
31733 event.clientX < maxX &&
31734 event.clientY > minY &&
31735 event.clientY < maxY;
31738 * Project 3D world coordinates to canvas coordinates.
31740 * @param {Array<number>} point3D - 3D world coordinates.
31741 * @param {HTMLElement} container - The viewer container.
31742 * @param {THREE.Camera} camera - Camera used in rendering.
31743 * @returns {Array<number>} 2D canvas coordinates.
31745 ViewportCoords.prototype.projectToCanvas = function (point3d, container, camera) {
31746 var viewport = this.projectToViewport(point3d, camera);
31747 var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
31751 * Project 3D world coordinates to viewport coordinates.
31753 * @param {Array<number>} point3D - 3D world coordinates.
31754 * @param {THREE.Camera} camera - Camera used in rendering.
31755 * @returns {Array<number>} 2D viewport coordinates.
31757 ViewportCoords.prototype.projectToViewport = function (point3d, camera) {
31758 var viewport = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
31760 return [viewport.x, viewport.y];
31763 * Uproject canvas coordinates to 3D world coordinates.
31765 * @param {number} canvasX - Canvas X coordinate.
31766 * @param {number} canvasY - Canvas Y coordinate.
31767 * @param {HTMLElement} container - The viewer container.
31768 * @param {THREE.Camera} camera - Camera used in rendering.
31769 * @returns {Array<number>} 3D world coordinates.
31771 ViewportCoords.prototype.unprojectFromCanvas = function (canvasX, canvasY, container, camera) {
31772 var viewport = this.canvasToViewport(canvasX, canvasY, container);
31773 var point3d = this.unprojectFromViewport(viewport[0], viewport[1], camera);
31777 * Unproject viewport coordinates to 3D world coordinates.
31779 * @param {number} viewportX - Viewport X coordinate.
31780 * @param {number} viewportY - Viewport Y coordinate.
31781 * @param {THREE.Camera} camera - Camera used in rendering.
31782 * @returns {Array<number>} 3D world coordinates.
31784 ViewportCoords.prototype.unprojectFromViewport = function (viewportX, viewportY, camera) {
31785 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
31786 .unproject(camera);
31790 * Convert viewport coordinates to basic coordinates.
31792 * @description Transform origin and camera position needs to be the
31793 * equal for reliable return value.
31795 * @param {number} viewportX - Viewport X coordinate.
31796 * @param {number} viewportY - Viewport Y coordinate.
31797 * @param {Transform} transform - Transform of the node to unproject from.
31798 * @param {THREE.Camera} camera - Camera used in rendering.
31799 * @returns {Array<number>} 2D basic coordinates.
31801 ViewportCoords.prototype.viewportToBasic = function (viewportX, viewportY, transform, camera) {
31802 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
31805 var basic = transform.projectBasic(point3d);
31809 * Convert viewport coordinates to canvas coordinates.
31811 * @param {number} viewportX - Viewport X coordinate.
31812 * @param {number} viewportY - Viewport Y coordinate.
31813 * @param {HTMLElement} container - The viewer container.
31814 * @returns {Array<number>} 2D canvas coordinates.
31816 ViewportCoords.prototype.viewportToCanvas = function (viewportX, viewportY, container) {
31817 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
31818 var canvasX = canvasWidth * (viewportX + 1) / 2;
31819 var canvasY = -canvasHeight * (viewportY - 1) / 2;
31820 return [canvasX, canvasY];
31823 * Convert 3D world coordinates to 3D camera coordinates.
31825 * @param {number} point3D - 3D point in world coordinate system.
31826 * @param {THREE.Camera} camera - Camera used in rendering.
31827 * @returns {Array<number>} 3D camera coordinates.
31829 ViewportCoords.prototype.worldToCamera = function (point3d, camera) {
31830 var pointCamera = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
31831 .applyMatrix4(camera.matrixWorldInverse);
31832 return pointCamera.toArray();
31834 return ViewportCoords;
31836 exports.ViewportCoords = ViewportCoords;
31837 exports.default = ViewportCoords;
31839 },{"three":176}],310:[function(require,module,exports){
31841 Object.defineProperty(exports, "__esModule", { value: true });
31845 * @classdesc Represents a class for creating node filters. Implementation and
31846 * definitions based on https://github.com/mapbox/feature-filter.
31848 var FilterCreator = (function () {
31849 function FilterCreator() {
31852 * Create a filter from a filter expression.
31854 * @description The following filters are supported:
31871 * @param {FilterExpression} filter - Comparison, set membership or combinding filter
31873 * @returns {FilterFunction} Function taking a node and returning a boolean that
31874 * indicates whether the node passed the test or not.
31876 FilterCreator.prototype.createFilter = function (filter) {
31877 return new Function("node", "return " + this._compile(filter) + ";");
31879 FilterCreator.prototype._compile = function (filter) {
31880 if (filter == null || filter.length <= 1) {
31883 var operator = filter[0];
31884 var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) :
31885 operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) :
31886 operator === ">" ||
31887 operator === ">=" ||
31888 operator === "<" ||
31889 operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) :
31890 operator === "in" ?
31891 this._compileInOp(filter[1], filter.slice(2)) :
31892 operator === "!in" ?
31893 this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) :
31894 operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") :
31896 return "(" + operation + ")";
31898 FilterCreator.prototype._compare = function (a, b) {
31899 return a < b ? -1 : a > b ? 1 : 0;
31901 FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) {
31902 var left = this._compilePropertyReference(property);
31903 var right = JSON.stringify(value);
31904 return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right;
31906 FilterCreator.prototype._compileInOp = function (property, values) {
31907 var compare = this._compare;
31908 var left = JSON.stringify(values.sort(compare));
31909 var right = this._compilePropertyReference(property);
31910 return left + ".indexOf(" + right + ")!==-1";
31912 FilterCreator.prototype._compileLogicalOp = function (filters, operator) {
31913 var compile = this._compile.bind(this);
31914 return filters.map(compile).join(operator);
31916 FilterCreator.prototype._compileNegation = function (expression) {
31917 return "!(" + expression + ")";
31919 FilterCreator.prototype._compilePropertyReference = function (property) {
31920 return "node[" + JSON.stringify(property) + "]";
31922 return FilterCreator;
31924 exports.FilterCreator = FilterCreator;
31925 exports.default = FilterCreator;
31927 },{}],311:[function(require,module,exports){
31929 /// <reference path="../../typings/index.d.ts" />
31930 Object.defineProperty(exports, "__esModule", { value: true });
31931 var rbush = require("rbush");
31932 var Subject_1 = require("rxjs/Subject");
31933 require("rxjs/add/observable/from");
31934 require("rxjs/add/operator/catch");
31935 require("rxjs/add/operator/do");
31936 require("rxjs/add/operator/finally");
31937 require("rxjs/add/operator/map");
31938 require("rxjs/add/operator/publish");
31939 var Edge_1 = require("../Edge");
31940 var Error_1 = require("../Error");
31941 var Graph_1 = require("../Graph");
31945 * @classdesc Represents a graph of nodes with edges.
31947 var Graph = (function () {
31949 * Create a new graph instance.
31951 * @param {APIv3} [apiV3] - API instance for retrieving data.
31952 * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival.
31953 * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations.
31954 * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations.
31955 * @param {FilterCreator} [filterCreator] - Instance for filter creation.
31956 * @param {IGraphConfiguration} [configuration] - Configuration struct.
31958 function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator, configuration) {
31959 this._apiV3 = apiV3;
31960 this._cachedNodes = {};
31961 this._cachedNodeTiles = {};
31962 this._cachedSpatialEdges = {};
31963 this._cachedTiles = {};
31964 this._cachingFill$ = {};
31965 this._cachingFull$ = {};
31966 this._cachingSequences$ = {};
31967 this._cachingSpatialArea$ = {};
31968 this._cachingTiles$ = {};
31969 this._changed$ = new Subject_1.Subject();
31970 this._defaultAlt = 2;
31971 this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator();
31972 this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator();
31973 this._filter = this._filterCreator.createFilter(undefined);
31974 this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator();
31975 this._configuration = configuration != null ?
31979 maxUnusedNodes: 100,
31980 maxUnusedTiles: 20,
31983 this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lat", ".lon", ".lat", ".lon"]);
31984 this._nodeIndexTiles = {};
31985 this._nodeToTile = {};
31986 this._preStored = {};
31987 this._requiredNodeTiles = {};
31988 this._requiredSpatialArea = {};
31989 this._sequences = {};
31990 this._tilePrecision = 7;
31991 this._tileThreshold = 20;
31993 Object.defineProperty(Graph.prototype, "changed$", {
31997 * @returns {Observable<Graph>} Observable emitting
31998 * the graph every time it has changed.
32001 return this._changed$;
32007 * Retrieve and cache node fill properties.
32009 * @param {string} key - Key of node to fill.
32010 * @returns {Observable<Graph>} Observable emitting the graph
32011 * when the node has been updated.
32012 * @throws {GraphMapillaryError} When the operation is not valid on the
32015 Graph.prototype.cacheFill$ = function (key) {
32017 if (key in this._cachingFull$) {
32018 throw new Error_1.GraphMapillaryError("Cannot fill node while caching full (" + key + ").");
32020 if (!this.hasNode(key)) {
32021 throw new Error_1.GraphMapillaryError("Cannot fill node that does not exist in graph (" + key + ").");
32023 if (key in this._cachingFill$) {
32024 return this._cachingFill$[key];
32026 var node = this.getNode(key);
32028 throw new Error_1.GraphMapillaryError("Cannot fill node that is already full (" + key + ").");
32030 this._cachingFill$[key] = this._apiV3.imageByKeyFill$([key])
32031 .do(function (imageByKeyFill) {
32033 _this._makeFull(node, imageByKeyFill[key]);
32035 delete _this._cachingFill$[key];
32037 .map(function (imageByKeyFill) {
32040 .finally(function () {
32041 if (key in _this._cachingFill$) {
32042 delete _this._cachingFill$[key];
32044 _this._changed$.next(_this);
32048 return this._cachingFill$[key];
32051 * Retrieve and cache full node properties.
32053 * @param {string} key - Key of node to fill.
32054 * @returns {Observable<Graph>} Observable emitting the graph
32055 * when the node has been updated.
32056 * @throws {GraphMapillaryError} When the operation is not valid on the
32059 Graph.prototype.cacheFull$ = function (key) {
32061 if (key in this._cachingFull$) {
32062 return this._cachingFull$[key];
32064 if (this.hasNode(key)) {
32065 throw new Error_1.GraphMapillaryError("Cannot cache full node that already exist in graph (" + key + ").");
32067 this._cachingFull$[key] = this._apiV3.imageByKeyFull$([key])
32068 .do(function (imageByKeyFull) {
32069 var fn = imageByKeyFull[key];
32070 if (_this.hasNode(key)) {
32071 var node = _this.getNode(key);
32073 _this._makeFull(node, fn);
32077 if (fn.sequence == null || fn.sequence.key == null) {
32078 throw new Error_1.GraphMapillaryError("Node has no sequence (" + key + ").");
32080 var node = new Graph_1.Node(fn);
32081 _this._makeFull(node, fn);
32082 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
32083 _this._preStore(h, node);
32084 _this._setNode(node);
32085 delete _this._cachingFull$[key];
32088 .map(function (imageByKeyFull) {
32091 .finally(function () {
32092 if (key in _this._cachingFull$) {
32093 delete _this._cachingFull$[key];
32095 _this._changed$.next(_this);
32099 return this._cachingFull$[key];
32102 * Retrieve and cache a node sequence.
32104 * @param {string} key - Key of node for which to retrieve sequence.
32105 * @returns {Observable<Graph>} Observable emitting the graph
32106 * when the sequence has been retrieved.
32107 * @throws {GraphMapillaryError} When the operation is not valid on the
32110 Graph.prototype.cacheNodeSequence$ = function (key) {
32111 if (!this.hasNode(key)) {
32112 throw new Error_1.GraphMapillaryError("Cannot cache sequence edges of node that does not exist in graph (" + key + ").");
32114 var node = this.getNode(key);
32115 if (node.sequenceKey in this._sequences) {
32116 throw new Error_1.GraphMapillaryError("Sequence already cached (" + key + "), (" + node.sequenceKey + ").");
32118 return this._cacheSequence$(node.sequenceKey);
32121 * Retrieve and cache a sequence.
32123 * @param {string} sequenceKey - Key of sequence to cache.
32124 * @returns {Observable<Graph>} Observable emitting the graph
32125 * when the sequence has been retrieved.
32126 * @throws {GraphMapillaryError} When the operation is not valid on the
32129 Graph.prototype.cacheSequence$ = function (sequenceKey) {
32130 if (sequenceKey in this._sequences) {
32131 throw new Error_1.GraphMapillaryError("Sequence already cached (" + sequenceKey + ")");
32133 return this._cacheSequence$(sequenceKey);
32136 * Cache sequence edges for a node.
32138 * @param {string} key - Key of node.
32139 * @throws {GraphMapillaryError} When the operation is not valid on the
32142 Graph.prototype.cacheSequenceEdges = function (key) {
32143 var node = this.getNode(key);
32144 if (!(node.sequenceKey in this._sequences)) {
32145 throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")");
32147 var sequence = this._sequences[node.sequenceKey].sequence;
32148 var edges = this._edgeCalculator.computeSequenceEdges(node, sequence);
32149 node.cacheSequenceEdges(edges);
32152 * Retrieve and cache full nodes for a node spatial area.
32154 * @param {string} key - Key of node for which to retrieve sequence.
32155 * @returns {Observable<Graph>} Observable emitting the graph
32156 * when the nodes in the spatial area has been made full.
32157 * @throws {GraphMapillaryError} When the operation is not valid on the
32160 Graph.prototype.cacheSpatialArea$ = function (key) {
32162 if (!this.hasNode(key)) {
32163 throw new Error_1.GraphMapillaryError("Cannot cache spatial area of node that does not exist in graph (" + key + ").");
32165 if (key in this._cachedSpatialEdges) {
32166 throw new Error_1.GraphMapillaryError("Node already spatially cached (" + key + ").");
32168 if (!(key in this._requiredSpatialArea)) {
32169 throw new Error_1.GraphMapillaryError("Spatial area not determined (" + key + ").");
32171 var spatialArea = this._requiredSpatialArea[key];
32172 if (Object.keys(spatialArea.cacheNodes).length === 0) {
32173 throw new Error_1.GraphMapillaryError("Spatial nodes already cached (" + key + ").");
32175 if (key in this._cachingSpatialArea$) {
32176 return this._cachingSpatialArea$[key];
32179 while (spatialArea.cacheKeys.length > 0) {
32180 batches.push(spatialArea.cacheKeys.splice(0, 200));
32182 var batchesToCache = batches.length;
32183 var spatialNodes$ = [];
32184 var _loop_1 = function (batch) {
32185 var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch)
32186 .do(function (imageByKeyFill) {
32187 for (var fillKey in imageByKeyFill) {
32188 if (!imageByKeyFill.hasOwnProperty(fillKey)) {
32191 var spatialNode = spatialArea.cacheNodes[fillKey];
32192 if (spatialNode.full) {
32193 delete spatialArea.cacheNodes[fillKey];
32196 var fillNode = imageByKeyFill[fillKey];
32197 _this._makeFull(spatialNode, fillNode);
32198 delete spatialArea.cacheNodes[fillKey];
32200 if (--batchesToCache === 0) {
32201 delete _this._cachingSpatialArea$[key];
32204 .map(function (imageByKeyFill) {
32207 .catch(function (error) {
32208 for (var _i = 0, batch_1 = batch; _i < batch_1.length; _i++) {
32209 var batchKey = batch_1[_i];
32210 if (batchKey in spatialArea.all) {
32211 delete spatialArea.all[batchKey];
32213 if (batchKey in spatialArea.cacheNodes) {
32214 delete spatialArea.cacheNodes[batchKey];
32217 if (--batchesToCache === 0) {
32218 delete _this._cachingSpatialArea$[key];
32222 .finally(function () {
32223 if (Object.keys(spatialArea.cacheNodes).length === 0) {
32224 _this._changed$.next(_this);
32229 spatialNodes$.push(spatialNodeBatch$);
32232 for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {
32233 var batch = batches_1[_i];
32236 this._cachingSpatialArea$[key] = spatialNodes$;
32237 return spatialNodes$;
32240 * Cache spatial edges for a node.
32242 * @param {string} key - Key of node.
32243 * @throws {GraphMapillaryError} When the operation is not valid on the
32246 Graph.prototype.cacheSpatialEdges = function (key) {
32247 if (key in this._cachedSpatialEdges) {
32248 throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ").");
32250 var node = this.getNode(key);
32251 var sequence = this._sequences[node.sequenceKey].sequence;
32252 var fallbackKeys = [];
32253 var prevKey = sequence.findPrevKey(node.key);
32254 if (prevKey != null) {
32255 fallbackKeys.push(prevKey);
32257 var nextKey = sequence.findNextKey(node.key);
32258 if (nextKey != null) {
32259 fallbackKeys.push(nextKey);
32261 var allSpatialNodes = this._requiredSpatialArea[key].all;
32262 var potentialNodes = [];
32263 var filter = this._filter;
32264 for (var spatialNodeKey in allSpatialNodes) {
32265 if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) {
32268 var spatialNode = allSpatialNodes[spatialNodeKey];
32269 if (filter(spatialNode)) {
32270 potentialNodes.push(spatialNode);
32273 var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys);
32274 var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey);
32275 edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges));
32276 edges = edges.concat(this._edgeCalculator.computePanoEdges(node, potentialEdges));
32277 edges = edges.concat(this._edgeCalculator.computePerspectiveToPanoEdges(node, potentialEdges));
32278 edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges));
32279 node.cacheSpatialEdges(edges);
32280 this._cachedSpatialEdges[key] = node;
32281 delete this._requiredSpatialArea[key];
32282 delete this._cachedNodeTiles[key];
32285 * Retrieve and cache geohash tiles for a node.
32287 * @param {string} key - Key of node for which to retrieve tiles.
32288 * @returns {Observable<Graph>} Observable emitting the graph
32289 * when the tiles required for the node has been cached.
32290 * @throws {GraphMapillaryError} When the operation is not valid on the
32293 Graph.prototype.cacheTiles$ = function (key) {
32295 if (key in this._cachedNodeTiles) {
32296 throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
32298 if (key in this._cachedSpatialEdges) {
32299 throw new Error_1.GraphMapillaryError("Spatial edges already cached so tiles considered cached (" + key + ").");
32301 if (!(key in this._requiredNodeTiles)) {
32302 throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ").");
32304 var nodeTiles = this._requiredNodeTiles[key];
32305 if (nodeTiles.cache.length === 0 &&
32306 nodeTiles.caching.length === 0) {
32307 throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
32309 if (!this.hasNode(key)) {
32310 throw new Error_1.GraphMapillaryError("Cannot cache tiles of node that does not exist in graph (" + key + ").");
32312 var hs = nodeTiles.cache.slice();
32313 nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs);
32314 nodeTiles.cache = [];
32315 var cacheTiles$ = [];
32316 var _loop_2 = function (h) {
32317 var cacheTile$ = null;
32318 if (h in this_2._cachingTiles$) {
32319 cacheTile$ = this_2._cachingTiles$[h];
32322 cacheTile$ = this_2._apiV3.imagesByH$([h])
32323 .do(function (imagesByH) {
32324 var coreNodes = imagesByH[h];
32325 if (h in _this._cachedTiles) {
32328 _this._nodeIndexTiles[h] = [];
32329 _this._cachedTiles[h] = { accessed: new Date().getTime(), nodes: [] };
32330 var hCache = _this._cachedTiles[h].nodes;
32331 var preStored = _this._removeFromPreStore(h);
32332 for (var index in coreNodes) {
32333 if (!coreNodes.hasOwnProperty(index)) {
32336 var coreNode = coreNodes[index];
32337 if (coreNode == null) {
32340 if (coreNode.sequence == null ||
32341 coreNode.sequence.key == null) {
32342 console.warn("Sequence missing, discarding (" + coreNode.key + ")");
32345 if (preStored != null && coreNode.key in preStored) {
32346 var node_1 = preStored[coreNode.key];
32347 delete preStored[coreNode.key];
32348 hCache.push(node_1);
32349 var nodeIndexItem_1 = {
32350 lat: node_1.latLon.lat,
32351 lon: node_1.latLon.lon,
32354 _this._nodeIndex.insert(nodeIndexItem_1);
32355 _this._nodeIndexTiles[h].push(nodeIndexItem_1);
32356 _this._nodeToTile[node_1.key] = h;
32359 var node = new Graph_1.Node(coreNode);
32361 var nodeIndexItem = {
32362 lat: node.latLon.lat,
32363 lon: node.latLon.lon,
32366 _this._nodeIndex.insert(nodeIndexItem);
32367 _this._nodeIndexTiles[h].push(nodeIndexItem);
32368 _this._nodeToTile[node.key] = h;
32369 _this._setNode(node);
32371 delete _this._cachingTiles$[h];
32373 .map(function (imagesByH) {
32376 .catch(function (error) {
32377 delete _this._cachingTiles$[h];
32382 this_2._cachingTiles$[h] = cacheTile$;
32384 cacheTiles$.push(cacheTile$
32385 .do(function (graph) {
32386 var index = nodeTiles.caching.indexOf(h);
32388 nodeTiles.caching.splice(index, 1);
32390 if (nodeTiles.caching.length === 0 &&
32391 nodeTiles.cache.length === 0) {
32392 delete _this._requiredNodeTiles[key];
32393 _this._cachedNodeTiles[key] = true;
32396 .catch(function (error) {
32397 var index = nodeTiles.caching.indexOf(h);
32399 nodeTiles.caching.splice(index, 1);
32401 if (nodeTiles.caching.length === 0 &&
32402 nodeTiles.cache.length === 0) {
32403 delete _this._requiredNodeTiles[key];
32404 _this._cachedNodeTiles[key] = true;
32408 .finally(function () {
32409 _this._changed$.next(_this);
32415 for (var _i = 0, _a = nodeTiles.caching; _i < _a.length; _i++) {
32419 return cacheTiles$;
32422 * Initialize the cache for a node.
32424 * @param {string} key - Key of node.
32425 * @throws {GraphMapillaryError} When the operation is not valid on the
32428 Graph.prototype.initializeCache = function (key) {
32429 if (key in this._cachedNodes) {
32430 throw new Error_1.GraphMapillaryError("Node already in cache (" + key + ").");
32432 var node = this.getNode(key);
32433 node.initializeCache(new Graph_1.NodeCache());
32434 var accessed = new Date().getTime();
32435 this._cachedNodes[key] = { accessed: accessed, node: node };
32436 this._updateCachedTileAccess(key, accessed);
32439 * Get a value indicating if the graph is fill caching a node.
32441 * @param {string} key - Key of node.
32442 * @returns {boolean} Value indicating if the node is being fill cached.
32444 Graph.prototype.isCachingFill = function (key) {
32445 return key in this._cachingFill$;
32448 * Get a value indicating if the graph is fully caching a node.
32450 * @param {string} key - Key of node.
32451 * @returns {boolean} Value indicating if the node is being fully cached.
32453 Graph.prototype.isCachingFull = function (key) {
32454 return key in this._cachingFull$;
32457 * Get a value indicating if the graph is caching a sequence of a node.
32459 * @param {string} key - Key of node.
32460 * @returns {boolean} Value indicating if the sequence of a node is
32463 Graph.prototype.isCachingNodeSequence = function (key) {
32464 var node = this.getNode(key);
32465 return node.sequenceKey in this._cachingSequences$;
32468 * Get a value indicating if the graph is caching a sequence.
32470 * @param {string} sequenceKey - Key of sequence.
32471 * @returns {boolean} Value indicating if the sequence is
32474 Graph.prototype.isCachingSequence = function (sequenceKey) {
32475 return sequenceKey in this._cachingSequences$;
32478 * Get a value indicating if the graph is caching the tiles
32479 * required for calculating spatial edges of a node.
32481 * @param {string} key - Key of node.
32482 * @returns {boolean} Value indicating if the tiles of
32483 * a node are being cached.
32485 Graph.prototype.isCachingTiles = function (key) {
32486 return key in this._requiredNodeTiles &&
32487 this._requiredNodeTiles[key].cache.length === 0 &&
32488 this._requiredNodeTiles[key].caching.length > 0;
32491 * Get a value indicating if the cache has been initialized
32494 * @param {string} key - Key of node.
32495 * @returns {boolean} Value indicating if the cache has been
32496 * initialized for a node.
32498 Graph.prototype.hasInitializedCache = function (key) {
32499 return key in this._cachedNodes;
32502 * Get a value indicating if a node exist in the graph.
32504 * @param {string} key - Key of node.
32505 * @returns {boolean} Value indicating if a node exist in the graph.
32507 Graph.prototype.hasNode = function (key) {
32508 var accessed = new Date().getTime();
32509 this._updateCachedNodeAccess(key, accessed);
32510 this._updateCachedTileAccess(key, accessed);
32511 return key in this._nodes;
32514 * Get a value indicating if a node sequence exist in the graph.
32516 * @param {string} key - Key of node.
32517 * @returns {boolean} Value indicating if a node sequence exist
32520 Graph.prototype.hasNodeSequence = function (key) {
32521 var node = this.getNode(key);
32522 var sequenceKey = node.sequenceKey;
32523 var hasNodeSequence = sequenceKey in this._sequences;
32524 if (hasNodeSequence) {
32525 this._sequences[sequenceKey].accessed = new Date().getTime();
32527 return hasNodeSequence;
32530 * Get a value indicating if a sequence exist in the graph.
32532 * @param {string} sequenceKey - Key of sequence.
32533 * @returns {boolean} Value indicating if a sequence exist
32536 Graph.prototype.hasSequence = function (sequenceKey) {
32537 var hasSequence = sequenceKey in this._sequences;
32539 this._sequences[sequenceKey].accessed = new Date().getTime();
32541 return hasSequence;
32544 * Get a value indicating if the graph has fully cached
32545 * all nodes in the spatial area of a node.
32547 * @param {string} key - Key of node.
32548 * @returns {boolean} Value indicating if the spatial area
32549 * of a node has been cached.
32551 Graph.prototype.hasSpatialArea = function (key) {
32552 if (!this.hasNode(key)) {
32553 throw new Error_1.GraphMapillaryError("Spatial area nodes cannot be determined if node not in graph (" + key + ").");
32555 if (key in this._cachedSpatialEdges) {
32558 if (key in this._requiredSpatialArea) {
32559 return Object.keys(this._requiredSpatialArea[key].cacheNodes).length === 0;
32561 var node = this.getNode(key);
32562 var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold);
32563 var spatialItems = this._nodeIndex.search({
32569 var spatialNodes = {
32574 for (var _i = 0, spatialItems_1 = spatialItems; _i < spatialItems_1.length; _i++) {
32575 var spatialItem = spatialItems_1[_i];
32576 spatialNodes.all[spatialItem.node.key] = spatialItem.node;
32577 if (!spatialItem.node.full) {
32578 spatialNodes.cacheKeys.push(spatialItem.node.key);
32579 spatialNodes.cacheNodes[spatialItem.node.key] = spatialItem.node;
32582 this._requiredSpatialArea[key] = spatialNodes;
32583 return spatialNodes.cacheKeys.length === 0;
32586 * Get a value indicating if the graph has a tiles required
32589 * @param {string} key - Key of node.
32590 * @returns {boolean} Value indicating if the the tiles required
32591 * by a node has been cached.
32593 Graph.prototype.hasTiles = function (key) {
32595 if (key in this._cachedNodeTiles) {
32598 if (key in this._cachedSpatialEdges) {
32601 if (!this.hasNode(key)) {
32602 throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ").");
32604 var nodeTiles = { cache: [], caching: [] };
32605 if (!(key in this._requiredNodeTiles)) {
32606 var node = this.getNode(key);
32607 nodeTiles.cache = this._graphCalculator
32608 .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold)
32609 .filter(function (h) {
32610 return !(h in _this._cachedTiles);
32612 if (nodeTiles.cache.length > 0) {
32613 this._requiredNodeTiles[key] = nodeTiles;
32617 nodeTiles = this._requiredNodeTiles[key];
32619 return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0;
32624 * @param {string} key - Key of node.
32625 * @returns {Node} Retrieved node.
32627 Graph.prototype.getNode = function (key) {
32628 var accessed = new Date().getTime();
32629 this._updateCachedNodeAccess(key, accessed);
32630 this._updateCachedTileAccess(key, accessed);
32631 return this._nodes[key];
32636 * @param {string} sequenceKey - Key of sequence.
32637 * @returns {Node} Retrieved sequence.
32639 Graph.prototype.getSequence = function (sequenceKey) {
32640 var sequenceAccess = this._sequences[sequenceKey];
32641 sequenceAccess.accessed = new Date().getTime();
32642 return sequenceAccess.sequence;
32645 * Reset all spatial edges of the graph nodes.
32647 Graph.prototype.resetSpatialEdges = function () {
32648 var cachedKeys = Object.keys(this._cachedSpatialEdges);
32649 for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) {
32650 var cachedKey = cachedKeys_1[_i];
32651 var node = this._cachedSpatialEdges[cachedKey];
32652 node.resetSpatialEdges();
32653 delete this._cachedSpatialEdges[cachedKey];
32657 * Reset the complete graph but keep the nodes corresponding
32658 * to the supplied keys. All other nodes will be disposed.
32660 * @param {Array<string>} keepKeys - Keys for nodes to keep
32661 * in graph after reset.
32663 Graph.prototype.reset = function (keepKeys) {
32665 for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) {
32666 var key = keepKeys_1[_i];
32667 if (!this.hasNode(key)) {
32668 throw new Error("Node does not exist " + key);
32670 var node = this.getNode(key);
32671 node.resetSequenceEdges();
32672 node.resetSpatialEdges();
32675 for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) {
32676 var cachedKey = _b[_a];
32677 if (keepKeys.indexOf(cachedKey) !== -1) {
32680 this._cachedNodes[cachedKey].node.dispose();
32681 delete this._cachedNodes[cachedKey];
32683 this._cachedNodeTiles = {};
32684 this._cachedSpatialEdges = {};
32685 this._cachedTiles = {};
32686 this._cachingFill$ = {};
32687 this._cachingFull$ = {};
32688 this._cachingSequences$ = {};
32689 this._cachingSpatialArea$ = {};
32690 this._cachingTiles$ = {};
32692 this._nodeToTile = {};
32693 this._preStored = {};
32694 for (var _c = 0, nodes_1 = nodes; _c < nodes_1.length; _c++) {
32695 var node = nodes_1[_c];
32696 this._nodes[node.key] = node;
32697 var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision);
32698 this._preStore(h, node);
32700 this._requiredNodeTiles = {};
32701 this._requiredSpatialArea = {};
32702 this._sequences = {};
32703 this._nodeIndexTiles = {};
32704 this._nodeIndex.clear();
32707 * Set the spatial node filter.
32709 * @param {FilterExpression} filter - Filter expression to be applied
32710 * when calculating spatial edges.
32712 Graph.prototype.setFilter = function (filter) {
32713 this._filter = this._filterCreator.createFilter(filter);
32716 * Uncache the graph according to the graph configuration.
32718 * @description Uncaches unused tiles, unused nodes and
32719 * sequences according to the numbers specified in the
32720 * graph configuration. Sequences does not have a direct
32721 * reference to either tiles or nodes and may be uncached
32722 * even if they are related to the nodes that should be kept.
32724 * @param {Array<string>} keepKeys - Keys of nodes to keep in
32725 * graph unrelated to last access. Tiles related to those keys
32726 * will also be kept in graph.
32728 Graph.prototype.uncache = function (keepKeys) {
32729 var keysInUse = {};
32730 this._addNewKeys(keysInUse, this._cachingFull$);
32731 this._addNewKeys(keysInUse, this._cachingFill$);
32732 this._addNewKeys(keysInUse, this._cachingTiles$);
32733 this._addNewKeys(keysInUse, this._cachingSpatialArea$);
32734 this._addNewKeys(keysInUse, this._requiredNodeTiles);
32735 this._addNewKeys(keysInUse, this._requiredSpatialArea);
32736 for (var _i = 0, keepKeys_2 = keepKeys; _i < keepKeys_2.length; _i++) {
32737 var key = keepKeys_2[_i];
32738 if (key in keysInUse) {
32741 keysInUse[key] = true;
32744 for (var key in keysInUse) {
32745 if (!keysInUse.hasOwnProperty(key)) {
32748 var node = this._nodes[key];
32749 var nodeHs = this._graphCalculator.encodeHs(node.latLon);
32750 for (var _a = 0, nodeHs_1 = nodeHs; _a < nodeHs_1.length; _a++) {
32751 var nodeH = nodeHs_1[_a];
32752 if (!(nodeH in keepHs)) {
32753 keepHs[nodeH] = true;
32757 var potentialHs = [];
32758 for (var h in this._cachedTiles) {
32759 if (!this._cachedTiles.hasOwnProperty(h) || h in keepHs) {
32762 potentialHs.push([h, this._cachedTiles[h]]);
32764 var uncacheHs = potentialHs
32765 .sort(function (h1, h2) {
32766 return h2[1].accessed - h1[1].accessed;
32768 .slice(this._configuration.maxUnusedTiles)
32769 .map(function (h) {
32772 for (var _b = 0, uncacheHs_1 = uncacheHs; _b < uncacheHs_1.length; _b++) {
32773 var uncacheH = uncacheHs_1[_b];
32774 this._uncacheTile(uncacheH);
32776 var potentialNodes = [];
32777 for (var key in this._cachedNodes) {
32778 if (!this._cachedNodes.hasOwnProperty(key) || key in keysInUse) {
32781 potentialNodes.push(this._cachedNodes[key]);
32783 var uncacheNodes = potentialNodes
32784 .sort(function (n1, n2) {
32785 return n2.accessed - n1.accessed;
32787 .slice(this._configuration.maxUnusedNodes);
32788 for (var _c = 0, uncacheNodes_1 = uncacheNodes; _c < uncacheNodes_1.length; _c++) {
32789 var nodeAccess = uncacheNodes_1[_c];
32790 nodeAccess.node.uncache();
32791 var key = nodeAccess.node.key;
32792 delete this._cachedNodes[key];
32793 if (key in this._cachedNodeTiles) {
32794 delete this._cachedNodeTiles[key];
32796 if (key in this._cachedSpatialEdges) {
32797 delete this._cachedSpatialEdges[key];
32800 var potentialSequences = [];
32801 for (var sequenceKey in this._sequences) {
32802 if (!this._sequences.hasOwnProperty(sequenceKey) ||
32803 sequenceKey in this._cachingSequences$) {
32806 potentialSequences.push(this._sequences[sequenceKey]);
32808 var uncacheSequences = potentialSequences
32809 .sort(function (s1, s2) {
32810 return s2.accessed - s1.accessed;
32812 .slice(this._configuration.maxSequences);
32813 for (var _d = 0, uncacheSequences_1 = uncacheSequences; _d < uncacheSequences_1.length; _d++) {
32814 var sequenceAccess = uncacheSequences_1[_d];
32815 var sequenceKey = sequenceAccess.sequence.key;
32816 delete this._sequences[sequenceKey];
32817 sequenceAccess.sequence.dispose();
32820 Graph.prototype._addNewKeys = function (keys, dict) {
32821 for (var key in dict) {
32822 if (!dict.hasOwnProperty(key) || !this.hasNode(key)) {
32825 if (!(key in keys)) {
32830 Graph.prototype._cacheSequence$ = function (sequenceKey) {
32832 if (sequenceKey in this._cachingSequences$) {
32833 return this._cachingSequences$[sequenceKey];
32835 this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey])
32836 .do(function (sequenceByKey) {
32837 if (!(sequenceKey in _this._sequences)) {
32838 _this._sequences[sequenceKey] = {
32839 accessed: new Date().getTime(),
32840 sequence: new Graph_1.Sequence(sequenceByKey[sequenceKey]),
32843 delete _this._cachingSequences$[sequenceKey];
32845 .map(function (sequenceByKey) {
32848 .finally(function () {
32849 if (sequenceKey in _this._cachingSequences$) {
32850 delete _this._cachingSequences$[sequenceKey];
32852 _this._changed$.next(_this);
32856 return this._cachingSequences$[sequenceKey];
32858 Graph.prototype._makeFull = function (node, fillNode) {
32859 if (fillNode.calt == null) {
32860 fillNode.calt = this._defaultAlt;
32862 if (fillNode.c_rotation == null) {
32863 fillNode.c_rotation = this._graphCalculator.rotationFromCompass(fillNode.ca, fillNode.orientation);
32865 node.makeFull(fillNode);
32867 Graph.prototype._preStore = function (h, node) {
32868 if (!(h in this._preStored)) {
32869 this._preStored[h] = {};
32871 this._preStored[h][node.key] = node;
32873 Graph.prototype._removeFromPreStore = function (h) {
32874 var preStored = null;
32875 if (h in this._preStored) {
32876 preStored = this._preStored[h];
32877 delete this._preStored[h];
32881 Graph.prototype._setNode = function (node) {
32882 var key = node.key;
32883 if (this.hasNode(key)) {
32884 throw new Error_1.GraphMapillaryError("Node already exist (" + key + ").");
32886 this._nodes[key] = node;
32888 Graph.prototype._uncacheTile = function (h) {
32889 for (var _i = 0, _a = this._cachedTiles[h].nodes; _i < _a.length; _i++) {
32891 var key = node.key;
32892 delete this._nodes[key];
32893 delete this._nodeToTile[key];
32894 if (key in this._cachedNodes) {
32895 delete this._cachedNodes[key];
32897 if (key in this._cachedNodeTiles) {
32898 delete this._cachedNodeTiles[key];
32900 if (key in this._cachedSpatialEdges) {
32901 delete this._cachedSpatialEdges[key];
32905 for (var _b = 0, _c = this._nodeIndexTiles[h]; _b < _c.length; _b++) {
32906 var nodeIndexItem = _c[_b];
32907 this._nodeIndex.remove(nodeIndexItem);
32909 delete this._nodeIndexTiles[h];
32910 delete this._cachedTiles[h];
32912 Graph.prototype._updateCachedTileAccess = function (key, accessed) {
32913 if (key in this._nodeToTile) {
32914 this._cachedTiles[this._nodeToTile[key]].accessed = accessed;
32917 Graph.prototype._updateCachedNodeAccess = function (key, accessed) {
32918 if (key in this._cachedNodes) {
32919 this._cachedNodes[key].accessed = accessed;
32924 exports.Graph = Graph;
32925 exports.default = Graph;
32927 },{"../Edge":227,"../Error":228,"../Graph":230,"rbush":25,"rxjs/Subject":34,"rxjs/add/observable/from":41,"rxjs/add/operator/catch":52,"rxjs/add/operator/do":59,"rxjs/add/operator/finally":62,"rxjs/add/operator/map":65,"rxjs/add/operator/publish":71}],312:[function(require,module,exports){
32929 /// <reference path="../../typings/index.d.ts" />
32930 Object.defineProperty(exports, "__esModule", { value: true });
32931 var geohash = require("latlon-geohash");
32932 var THREE = require("three");
32933 var Geo_1 = require("../Geo");
32934 var GeoHashDirections = (function () {
32935 function GeoHashDirections() {
32937 return GeoHashDirections;
32939 GeoHashDirections.n = "n";
32940 GeoHashDirections.nw = "nw";
32941 GeoHashDirections.w = "w";
32942 GeoHashDirections.sw = "sw";
32943 GeoHashDirections.s = "s";
32944 GeoHashDirections.se = "se";
32945 GeoHashDirections.e = "e";
32946 GeoHashDirections.ne = "ne";
32948 * @class GraphCalculator
32950 * @classdesc Represents a calculator for graph entities.
32952 var GraphCalculator = (function () {
32954 * Create a new graph calculator instance.
32956 * @param {GeoCoords} geoCoords - Geo coords instance.
32958 function GraphCalculator(geoCoords) {
32959 this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords();
32962 * Encode the geohash tile for geodetic coordinates.
32964 * @param {ILatLon} latlon - Latitude and longitude to encode.
32965 * @param {number} precision - Precision of the encoding.
32967 * @returns {string} The geohash tile for the lat, lon and precision.
32969 GraphCalculator.prototype.encodeH = function (latLon, precision) {
32970 if (precision === void 0) { precision = 7; }
32971 return geohash.encode(latLon.lat, latLon.lon, precision);
32974 * Encode the geohash tiles within a threshold from a position
32975 * using Manhattan distance.
32977 * @param {ILatLon} latlon - Latitude and longitude to encode.
32978 * @param {number} precision - Precision of the encoding.
32979 * @param {number} threshold - Threshold of the encoding in meters.
32981 * @returns {string} The geohash tiles reachable within the threshold.
32983 GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) {
32984 if (precision === void 0) { precision = 7; }
32985 if (threshold === void 0) { threshold = 20; }
32986 var h = geohash.encode(latLon.lat, latLon.lon, precision);
32987 var bounds = geohash.bounds(h);
32988 var ne = bounds.ne;
32989 var sw = bounds.sw;
32990 var neighbours = geohash.neighbours(h);
32991 var bl = [0, 0, 0];
32992 var tr = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, sw.lat, sw.lon, 0);
32993 var position = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, sw.lat, sw.lon, 0);
32994 var left = position[0] - bl[0];
32995 var right = tr[0] - position[0];
32996 var bottom = position[1] - bl[1];
32997 var top = tr[1] - position[1];
32998 var l = left < threshold;
32999 var r = right < threshold;
33000 var b = bottom < threshold;
33001 var t = top < threshold;
33004 hs.push(neighbours[GeoHashDirections.n]);
33007 hs.push(neighbours[GeoHashDirections.nw]);
33010 hs.push(neighbours[GeoHashDirections.w]);
33013 hs.push(neighbours[GeoHashDirections.sw]);
33016 hs.push(neighbours[GeoHashDirections.s]);
33019 hs.push(neighbours[GeoHashDirections.se]);
33022 hs.push(neighbours[GeoHashDirections.e]);
33025 hs.push(neighbours[GeoHashDirections.ne]);
33030 * Get the bounding box corners for a circle with radius of a threshold
33031 * with center in a geodetic position.
33033 * @param {ILatLon} latlon - Latitude and longitude to encode.
33034 * @param {number} threshold - Threshold distance from the position in meters.
33036 * @returns {Array<ILatLon>} The south west and north east corners of the
33039 GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) {
33040 var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0);
33041 var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0);
33043 { lat: bl[0], lon: bl[1] },
33044 { lat: tr[0], lon: tr[1] },
33048 * Convert a compass angle to an angle axis rotation vector.
33050 * @param {number} compassAngle - The compass angle in degrees.
33051 * @param {number} orientation - The orientation of the original image.
33053 * @returns {Array<number>} Angle axis rotation vector.
33055 GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) {
33059 switch (orientation) {
33078 var rz = new THREE.Matrix4().makeRotationZ(z);
33079 var euler = new THREE.Euler(x, y, compassAngle * Math.PI / 180, "XYZ");
33080 var re = new THREE.Matrix4().makeRotationFromEuler(euler);
33081 var rotation = new THREE.Vector4().setAxisAngleFromRotationMatrix(re.multiply(rz));
33082 return rotation.multiplyScalar(rotation.w).toArray().slice(0, 3);
33084 return GraphCalculator;
33086 exports.GraphCalculator = GraphCalculator;
33087 exports.default = GraphCalculator;
33089 },{"../Geo":229,"latlon-geohash":21,"three":176}],313:[function(require,module,exports){
33091 Object.defineProperty(exports, "__esModule", { value: true });
33092 var Observable_1 = require("rxjs/Observable");
33093 var Subject_1 = require("rxjs/Subject");
33094 require("rxjs/add/operator/catch");
33095 require("rxjs/add/operator/concat");
33096 require("rxjs/add/operator/do");
33097 require("rxjs/add/operator/expand");
33098 require("rxjs/add/operator/finally");
33099 require("rxjs/add/operator/first");
33100 require("rxjs/add/operator/last");
33101 require("rxjs/add/operator/map");
33102 require("rxjs/add/operator/mergeMap");
33103 require("rxjs/add/operator/publishReplay");
33105 * @class GraphService
33107 * @classdesc Represents a service for graph operations.
33109 var GraphService = (function () {
33111 * Create a new graph service instance.
33113 * @param {Graph} graph - Graph instance to be operated on.
33115 function GraphService(graph, imageLoadingService) {
33116 this._graph$ = Observable_1.Observable
33118 .concat(graph.changed$)
33121 this._graph$.subscribe(function () { });
33122 this._imageLoadingService = imageLoadingService;
33123 this._firstGraphSubjects$ = [];
33124 this._initializeCacheSubscriptions = [];
33125 this._sequenceSubscriptions = [];
33126 this._spatialSubscriptions = [];
33129 * Cache a node in the graph and retrieve it.
33131 * @description When called, the full properties of
33132 * the node are retrieved and the node cache is initialized.
33133 * After that the node assets are cached and the node
33134 * is emitted to the observable when.
33135 * In parallel to caching the node assets, the sequence and
33136 * spatial edges of the node are cached. For this, the sequence
33137 * of the node and the required tiles and spatial nodes are
33138 * retrieved. The sequence and spatial edges may be set before
33139 * or after the node is returned.
33141 * @param {string} key - Key of the node to cache.
33142 * @return {Observable<Node>} Observable emitting a single item,
33143 * the node, when it has been retrieved and its assets are cached.
33144 * @throws {Error} Propagates any IO node caching errors to the caller.
33146 GraphService.prototype.cacheNode$ = function (key) {
33148 var firstGraphSubject$ = new Subject_1.Subject();
33149 this._firstGraphSubjects$.push(firstGraphSubject$);
33150 var firstGraph$ = firstGraphSubject$
33153 var node$ = firstGraph$
33154 .map(function (graph) {
33155 return graph.getNode(key);
33157 .mergeMap(function (node) {
33158 return node.assetsCached ?
33159 Observable_1.Observable.of(node) :
33160 node.cacheAssets$();
33164 node$.subscribe(function (node) {
33165 _this._imageLoadingService.loadnode$.next(node);
33166 }, function (error) {
33167 console.error("Failed to cache node (" + key + ")", error);
33169 var initializeCacheSubscription = this._graph$
33171 .mergeMap(function (graph) {
33172 if (graph.isCachingFull(key) || !graph.hasNode(key)) {
33173 return graph.cacheFull$(key);
33175 if (graph.isCachingFill(key) || !graph.getNode(key).full) {
33176 return graph.cacheFill$(key);
33178 return Observable_1.Observable.of(graph);
33180 .do(function (graph) {
33181 if (!graph.hasInitializedCache(key)) {
33182 graph.initializeCache(key);
33185 .finally(function () {
33186 if (initializeCacheSubscription == null) {
33189 _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions);
33190 _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$);
33192 .subscribe(function (graph) {
33193 firstGraphSubject$.next(graph);
33194 firstGraphSubject$.complete();
33195 }, function (error) {
33196 firstGraphSubject$.error(error);
33198 if (!initializeCacheSubscription.closed) {
33199 this._initializeCacheSubscriptions.push(initializeCacheSubscription);
33201 var sequenceSubscription = firstGraph$
33202 .mergeMap(function (graph) {
33203 if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) {
33204 return graph.cacheNodeSequence$(key);
33206 return Observable_1.Observable.of(graph);
33208 .do(function (graph) {
33209 if (!graph.getNode(key).sequenceEdges.cached) {
33210 graph.cacheSequenceEdges(key);
33213 .finally(function () {
33214 if (sequenceSubscription == null) {
33217 _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions);
33219 .subscribe(function (graph) { return; }, function (error) {
33220 console.error("Failed to cache sequence edges (" + key + ").", error);
33222 if (!sequenceSubscription.closed) {
33223 this._sequenceSubscriptions.push(sequenceSubscription);
33225 var spatialSubscription = firstGraph$
33226 .expand(function (graph) {
33227 if (graph.hasTiles(key)) {
33228 return Observable_1.Observable.empty();
33230 return Observable_1.Observable
33231 .from(graph.cacheTiles$(key))
33232 .mergeMap(function (graph$) {
33234 .mergeMap(function (g) {
33235 if (g.isCachingTiles(key)) {
33236 return Observable_1.Observable.empty();
33238 return Observable_1.Observable.of(g);
33240 .catch(function (error, caught$) {
33241 console.error("Failed to cache tile data (" + key + ").", error);
33242 return Observable_1.Observable.empty();
33247 .mergeMap(function (graph) {
33248 if (graph.hasSpatialArea(key)) {
33249 return Observable_1.Observable.of(graph);
33251 return Observable_1.Observable
33252 .from(graph.cacheSpatialArea$(key))
33253 .mergeMap(function (graph$) {
33255 .catch(function (error, caught$) {
33256 console.error("Failed to cache spatial nodes (" + key + ").", error);
33257 return Observable_1.Observable.empty();
33262 .mergeMap(function (graph) {
33263 return graph.hasNodeSequence(key) ?
33264 Observable_1.Observable.of(graph) :
33265 graph.cacheNodeSequence$(key);
33267 .do(function (graph) {
33268 if (!graph.getNode(key).spatialEdges.cached) {
33269 graph.cacheSpatialEdges(key);
33272 .finally(function () {
33273 if (spatialSubscription == null) {
33276 _this._removeFromArray(spatialSubscription, _this._spatialSubscriptions);
33278 .subscribe(function (graph) { return; }, function (error) {
33279 console.error("Failed to cache spatial edges (" + key + ").", error);
33281 if (!spatialSubscription.closed) {
33282 this._spatialSubscriptions.push(spatialSubscription);
33285 .first(function (node) {
33286 return node.assetsCached;
33290 * Cache a sequence in the graph and retrieve it.
33292 * @param {string} sequenceKey - Sequence key.
33293 * @returns {Observable<Sequence>} Observable emitting a single item,
33294 * the sequence, when it has been retrieved and its assets are cached.
33295 * @throws {Error} Propagates any IO node caching errors to the caller.
33297 GraphService.prototype.cacheSequence$ = function (sequenceKey) {
33298 return this._graph$
33300 .mergeMap(function (graph) {
33301 if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
33302 return graph.cacheSequence$(sequenceKey);
33304 return Observable_1.Observable.of(graph);
33306 .map(function (graph) {
33307 return graph.getSequence(sequenceKey);
33311 * Set a spatial edge filter on the graph.
33313 * @description Resets the spatial edges of all cached nodes.
33315 * @param {FilterExpression} filter - Filter expression to be applied.
33316 * @return {Observable<Graph>} Observable emitting a single item,
33317 * the graph, when the spatial edges have been reset.
33319 GraphService.prototype.setFilter$ = function (filter) {
33320 this._resetSubscriptions(this._spatialSubscriptions);
33321 return this._graph$
33323 .do(function (graph) {
33324 graph.resetSpatialEdges();
33325 graph.setFilter(filter);
33331 * @description Resets the graph but keeps the nodes of the
33334 * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
33335 * @return {Observable<Node>} Observable emitting a single item,
33336 * the graph, when it has been reset.
33338 GraphService.prototype.reset$ = function (keepKeys) {
33339 this._abortSubjects(this._firstGraphSubjects$);
33340 this._resetSubscriptions(this._initializeCacheSubscriptions);
33341 this._resetSubscriptions(this._sequenceSubscriptions);
33342 this._resetSubscriptions(this._spatialSubscriptions);
33343 return this._graph$
33345 .do(function (graph) {
33346 graph.reset(keepKeys);
33350 * Uncache the graph.
33352 * @description Uncaches the graph by removing tiles, nodes and
33353 * sequences. Keeps the nodes of the supplied keys and the tiles
33354 * related to those nodes.
33356 * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
33357 * @return {Observable<Graph>} Observable emitting a single item,
33358 * the graph, when the graph has been uncached.
33360 GraphService.prototype.uncache$ = function (keepKeys) {
33361 return this._graph$
33363 .do(function (graph) {
33364 graph.uncache(keepKeys);
33367 GraphService.prototype._abortSubjects = function (subjects) {
33368 for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) {
33369 var subject = _a[_i];
33370 this._removeFromArray(subject, subjects);
33371 subject.error(new Error("Cache node request was aborted."));
33374 GraphService.prototype._removeFromArray = function (object, objects) {
33375 var index = objects.indexOf(object);
33376 if (index !== -1) {
33377 objects.splice(index, 1);
33380 GraphService.prototype._resetSubscriptions = function (subscriptions) {
33381 for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) {
33382 var subscription = _a[_i];
33383 this._removeFromArray(subscription, subscriptions);
33384 if (!subscription.closed) {
33385 subscription.unsubscribe();
33389 return GraphService;
33391 exports.GraphService = GraphService;
33392 exports.default = GraphService;
33394 },{"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/operator/catch":52,"rxjs/add/operator/concat":54,"rxjs/add/operator/do":59,"rxjs/add/operator/expand":60,"rxjs/add/operator/finally":62,"rxjs/add/operator/first":63,"rxjs/add/operator/last":64,"rxjs/add/operator/map":65,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/publishReplay":72}],314:[function(require,module,exports){
33396 /// <reference path="../../typings/index.d.ts" />
33397 Object.defineProperty(exports, "__esModule", { value: true });
33398 var Subject_1 = require("rxjs/Subject");
33399 var ImageLoadingService = (function () {
33400 function ImageLoadingService() {
33401 this._loadnode$ = new Subject_1.Subject();
33402 this._loadstatus$ = this._loadnode$
33403 .scan(function (nodes, node) {
33404 nodes[node.key] = node.loadStatus;
33409 this._loadstatus$.subscribe(function () { });
33411 Object.defineProperty(ImageLoadingService.prototype, "loadnode$", {
33413 return this._loadnode$;
33418 Object.defineProperty(ImageLoadingService.prototype, "loadstatus$", {
33420 return this._loadstatus$;
33425 return ImageLoadingService;
33427 exports.ImageLoadingService = ImageLoadingService;
33429 },{"rxjs/Subject":34}],315:[function(require,module,exports){
33431 /// <reference path="../../typings/index.d.ts" />
33432 Object.defineProperty(exports, "__esModule", { value: true });
33433 var Pbf = require("pbf");
33434 var MeshReader = (function () {
33435 function MeshReader() {
33437 MeshReader.read = function (buffer) {
33438 var pbf = new Pbf(buffer);
33439 return pbf.readFields(MeshReader._readMeshField, { faces: [], vertices: [] });
33441 MeshReader._readMeshField = function (tag, mesh, pbf) {
33443 mesh.vertices.push(pbf.readFloat());
33445 else if (tag === 2) {
33446 mesh.faces.push(pbf.readVarint());
33451 exports.MeshReader = MeshReader;
33453 },{"pbf":23}],316:[function(require,module,exports){
33455 Object.defineProperty(exports, "__esModule", { value: true });
33456 require("rxjs/add/observable/combineLatest");
33457 require("rxjs/add/operator/map");
33461 * @classdesc Represents a node in the navigation graph.
33463 * Explanation of position and bearing properties:
33465 * When images are uploaded they will have GPS information in the EXIF, this is what
33466 * is called `originalLatLon`(@link Node#originalLatLon).
33468 * When Structure from Motions has been run for a node a `computedLatLon` that
33469 * differs from the `originalLatLon` will be created. It is different because
33470 * GPS positions are not very exact and SfM aligns the camera positions according
33471 * to the 3D reconstruction (@link Node#computedLatLon).
33473 * At last there exist a `latLon` property which evaluates to
33474 * the `computedLatLon` from SfM if it exists but falls back
33475 * to the `originalLatLon` from the EXIF GPS otherwise (@link Node#latlon).
33477 * Everything that is done in in the Viewer is based on the SfM positions,
33478 * i.e. `computedLatLon`. That is why the smooth transitions go in the right
33479 * direction (nd not in strange directions because of bad GPS).
33481 * E.g. when placing a marker in the Viewer it is relative to the SfM
33482 * position i.e. the `computedLatLon`.
33484 * The same concept as above also applies to the compass angle (or bearing) properties
33485 * `originalCa`, `computedCa` and `ca`.
33487 var Node = (function () {
33489 * Create a new node instance.
33491 * @description Nodes are always created internally by the library.
33492 * Nodes can not be added to the library through any API method.
33494 * @param {ICoreNode} coreNode - Raw core node data.
33496 function Node(core) {
33497 this._cache = null;
33501 Object.defineProperty(Node.prototype, "assetsCached", {
33503 * Get assets cached.
33505 * @description The assets that need to be cached for this property
33506 * to report true are the following: fill properties, image and mesh.
33507 * The library ensures that the current node will always have the
33510 * @returns {boolean} Value indicating whether all assets have been
33514 return this._core != null &&
33515 this._fill != null &&
33516 this._cache != null &&
33517 this._cache.image != null &&
33518 this._cache.mesh != null;
33523 Object.defineProperty(Node.prototype, "alt", {
33527 * @description If SfM has not been run the computed altitude is
33528 * set to a default value of two meters.
33530 * @returns {number} Altitude, in meters.
33533 return this._fill.calt;
33538 Object.defineProperty(Node.prototype, "ca", {
33542 * @description If the SfM computed compass angle exists it will
33543 * be returned, otherwise the original EXIF compass angle.
33545 * @returns {number} Compass angle, measured in degrees.
33548 return this._fill.cca != null ? this._fill.cca : this._fill.ca;
33553 Object.defineProperty(Node.prototype, "capturedAt", {
33557 * @returns {number} Timestamp when the image was captured.
33560 return this._fill.captured_at;
33565 Object.defineProperty(Node.prototype, "computedCA", {
33569 * @description Will not be set if SfM has not been run.
33571 * @returns {number} SfM computed compass angle, measured in degrees.
33574 return this._fill.cca;
33579 Object.defineProperty(Node.prototype, "computedLatLon", {
33581 * Get computedLatLon.
33583 * @description Will not be set if SfM has not been run.
33585 * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum,
33586 * measured in degrees.
33589 return this._core.cl;
33594 Object.defineProperty(Node.prototype, "focal", {
33598 * @description Will not be set if SfM has not been run.
33600 * @returns {number} SfM computed focal length.
33603 return this._fill.cfocal;
33608 Object.defineProperty(Node.prototype, "full", {
33612 * @description The library ensures that the current node will
33615 * @returns {boolean} Value indicating whether the node has all
33616 * properties filled.
33619 return this._fill != null;
33624 Object.defineProperty(Node.prototype, "fullPano", {
33628 * @returns {boolean} Value indicating whether the node is a complete
33632 return this._fill.gpano != null &&
33633 this._fill.gpano.CroppedAreaLeftPixels === 0 &&
33634 this._fill.gpano.CroppedAreaTopPixels === 0 &&
33635 this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels &&
33636 this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels;
33641 Object.defineProperty(Node.prototype, "gpano", {
33645 * @description Will not be set for non panoramic images.
33647 * @returns {IGPano} Panorama information for panorama images.
33650 return this._fill.gpano;
33655 Object.defineProperty(Node.prototype, "height", {
33659 * @returns {number} Height of original image, not adjusted
33663 return this._fill.height;
33668 Object.defineProperty(Node.prototype, "image", {
33672 * @description The image will always be set on the current node.
33674 * @returns {HTMLImageElement} Cached image element of the node.
33677 return this._cache.image;
33682 Object.defineProperty(Node.prototype, "key", {
33686 * @returns {string} Unique key of the node.
33689 return this._core.key;
33694 Object.defineProperty(Node.prototype, "latLon", {
33698 * @description If the SfM computed latitude longitude exist
33699 * it will be returned, otherwise the original EXIF latitude
33702 * @returns {ILatLon} Latitude longitude in WGS84 datum,
33703 * measured in degrees.
33706 return this._core.cl != null ? this._core.cl : this._core.l;
33711 Object.defineProperty(Node.prototype, "loadStatus", {
33715 * @returns {ILoadStatus} Value indicating the load status
33716 * of the mesh and image.
33719 return this._cache.loadStatus;
33724 Object.defineProperty(Node.prototype, "merged", {
33728 * @returns {boolean} Value indicating whether SfM has been
33729 * run on the node and the node has been merged into a
33730 * connected component.
33733 return this._fill != null &&
33734 this._fill.merge_version != null &&
33735 this._fill.merge_version > 0;
33740 Object.defineProperty(Node.prototype, "mergeCC", {
33744 * @description Will not be set if SfM has not yet been run on
33747 * @returns {number} SfM connected component key to which
33751 return this._fill.merge_cc;
33756 Object.defineProperty(Node.prototype, "mergeVersion", {
33758 * Get mergeVersion.
33760 * @returns {number} Version for which SfM was run and image was merged.
33763 return this._fill.merge_version;
33768 Object.defineProperty(Node.prototype, "mesh", {
33772 * @description The mesh will always be set on the current node.
33774 * @returns {IMesh} SfM triangulated mesh of reconstructed
33775 * atomic 3D points.
33778 return this._cache.mesh;
33783 Object.defineProperty(Node.prototype, "orientation", {
33787 * @returns {number} EXIF orientation of original image.
33790 return this._fill.orientation;
33795 Object.defineProperty(Node.prototype, "originalCA", {
33799 * @returns {number} Original EXIF compass angle, measured in
33803 return this._fill.ca;
33808 Object.defineProperty(Node.prototype, "originalLatLon", {
33810 * Get originalLatLon.
33812 * @returns {ILatLon} Original EXIF latitude longitude in
33813 * WGS84 datum, measured in degrees.
33816 return this._core.l;
33821 Object.defineProperty(Node.prototype, "pano", {
33825 * @returns {boolean} Value indicating whether the node is a panorama.
33826 * It could be a cropped or full panorama.
33829 return this._fill.gpano != null &&
33830 this._fill.gpano.FullPanoWidthPixels != null;
33835 Object.defineProperty(Node.prototype, "projectKey", {
33839 * @returns {string} Unique key of the project to which
33840 * the node belongs.
33843 return this._fill.project != null ?
33844 this._fill.project.key :
33850 Object.defineProperty(Node.prototype, "rotation", {
33854 * @description Will not be set if SfM has not been run.
33856 * @returns {Array<number>} Rotation vector in angle axis representation.
33859 return this._fill.c_rotation;
33864 Object.defineProperty(Node.prototype, "scale", {
33868 * @description Will not be set if SfM has not been run.
33870 * @returns {number} Scale of atomic reconstruction.
33873 return this._fill.atomic_scale;
33878 Object.defineProperty(Node.prototype, "sequenceKey", {
33882 * @returns {string} Unique key of the sequence to which
33883 * the node belongs.
33886 return this._core.sequence.key;
33891 Object.defineProperty(Node.prototype, "sequenceEdges", {
33893 * Get sequenceEdges.
33895 * @returns {IEdgeStatus} Value describing the status of the
33899 return this._cache.sequenceEdges;
33904 Object.defineProperty(Node.prototype, "sequenceEdges$", {
33906 * Get sequenceEdges$.
33908 * @returns {Observable<IEdgeStatus>} Observable emitting
33909 * values describing the status of the sequence edges.
33912 return this._cache.sequenceEdges$;
33917 Object.defineProperty(Node.prototype, "spatialEdges", {
33919 * Get spatialEdges.
33921 * @returns {IEdgeStatus} Value describing the status of the
33925 return this._cache.spatialEdges;
33930 Object.defineProperty(Node.prototype, "spatialEdges$", {
33932 * Get spatialEdges$.
33934 * @returns {Observable<IEdgeStatus>} Observable emitting
33935 * values describing the status of the spatial edges.
33938 return this._cache.spatialEdges$;
33943 Object.defineProperty(Node.prototype, "userKey", {
33947 * @returns {string} Unique key of the user who uploaded
33951 return this._fill.user.key;
33956 Object.defineProperty(Node.prototype, "username", {
33960 * @returns {string} Username of the user who uploaded
33964 return this._fill.user.username;
33969 Object.defineProperty(Node.prototype, "width", {
33973 * @returns {number} Width of original image, not
33974 * adjusted for orientation.
33977 return this._fill.width;
33983 * Cache the image and mesh assets.
33985 * @description The assets are always cached internally by the
33986 * library prior to setting a node as the current node.
33988 * @returns {Observable<Node>} Observable emitting this node whenever the
33989 * load status has changed and when the mesh or image has been fully loaded.
33991 Node.prototype.cacheAssets$ = function () {
33993 return this._cache.cacheAssets$(this.key, this.pano, this.merged)
33994 .map(function (cache) {
33998 Node.prototype.cacheImage$ = function (imageSize) {
34000 return this._cache.cacheImage$(this.key, imageSize)
34001 .map(function (cache) {
34006 * Cache the sequence edges.
34008 * @description The sequence edges are cached asynchronously
34009 * internally by the library.
34011 * @param {Array<IEdge>} edges - Sequence edges to cache.
34013 Node.prototype.cacheSequenceEdges = function (edges) {
34014 this._cache.cacheSequenceEdges(edges);
34017 * Cache the spatial edges.
34019 * @description The spatial edges are cached asynchronously
34020 * internally by the library.
34022 * @param {Array<IEdge>} edges - Spatial edges to cache.
34024 Node.prototype.cacheSpatialEdges = function (edges) {
34025 this._cache.cacheSpatialEdges(edges);
34028 * Dispose the node.
34030 * @description Disposes all cached assets.
34032 Node.prototype.dispose = function () {
34033 if (this._cache != null) {
34034 this._cache.dispose();
34035 this._cache = null;
34041 * Initialize the node cache.
34043 * @description The node cache is initialized internally by
34046 * @param {NodeCache} cache - The node cache to set as cache.
34048 Node.prototype.initializeCache = function (cache) {
34049 if (this._cache != null) {
34050 throw new Error("Node cache already initialized (" + this.key + ").");
34052 this._cache = cache;
34055 * Fill the node with all properties.
34057 * @description The node is filled internally by
34060 * @param {IFillNode} fill - The fill node struct.
34062 Node.prototype.makeFull = function (fill) {
34063 if (fill == null) {
34064 throw new Error("Fill can not be null.");
34069 * Reset the sequence edges.
34071 Node.prototype.resetSequenceEdges = function () {
34072 this._cache.resetSequenceEdges();
34075 * Reset the spatial edges.
34077 Node.prototype.resetSpatialEdges = function () {
34078 this._cache.resetSpatialEdges();
34081 * Clears the image and mesh assets, aborts
34082 * any outstanding requests and resets edges.
34084 Node.prototype.uncache = function () {
34085 if (this._cache == null) {
34088 this._cache.dispose();
34089 this._cache = null;
34093 exports.Node = Node;
34094 exports.default = Node;
34096 },{"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/map":65}],317:[function(require,module,exports){
34097 (function (Buffer){
34099 Object.defineProperty(exports, "__esModule", { value: true });
34100 var Subject_1 = require("rxjs/Subject");
34101 var Observable_1 = require("rxjs/Observable");
34102 require("rxjs/add/observable/combineLatest");
34103 require("rxjs/add/operator/publishReplay");
34104 var Graph_1 = require("../Graph");
34105 var Utils_1 = require("../Utils");
34109 * @classdesc Represents the cached properties of a node.
34111 var NodeCache = (function () {
34113 * Create a new node cache instance.
34115 function NodeCache() {
34116 this._disposed = false;
34117 this._image = null;
34118 this._loadStatus = { loaded: 0, total: 0 };
34120 this._sequenceEdges = { cached: false, edges: [] };
34121 this._spatialEdges = { cached: false, edges: [] };
34122 this._sequenceEdgesChanged$ = new Subject_1.Subject();
34123 this._sequenceEdges$ = this._sequenceEdgesChanged$
34124 .startWith(this._sequenceEdges)
34127 this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(function () { });
34128 this._spatialEdgesChanged$ = new Subject_1.Subject();
34129 this._spatialEdges$ = this._spatialEdgesChanged$
34130 .startWith(this._spatialEdges)
34133 this._spatialEdgesSubscription = this._spatialEdges$.subscribe(function () { });
34134 this._cachingAssets$ = null;
34136 Object.defineProperty(NodeCache.prototype, "image", {
34140 * @description Will not be set when assets have not been cached
34141 * or when the object has been disposed.
34143 * @returns {HTMLImageElement} Cached image element of the node.
34146 return this._image;
34151 Object.defineProperty(NodeCache.prototype, "loadStatus", {
34155 * @returns {ILoadStatus} Value indicating the load status
34156 * of the mesh and image.
34159 return this._loadStatus;
34164 Object.defineProperty(NodeCache.prototype, "mesh", {
34168 * @description Will not be set when assets have not been cached
34169 * or when the object has been disposed.
34171 * @returns {IMesh} SfM triangulated mesh of reconstructed
34172 * atomic 3D points.
34180 Object.defineProperty(NodeCache.prototype, "sequenceEdges", {
34182 * Get sequenceEdges.
34184 * @returns {IEdgeStatus} Value describing the status of the
34188 return this._sequenceEdges;
34193 Object.defineProperty(NodeCache.prototype, "sequenceEdges$", {
34195 * Get sequenceEdges$.
34197 * @returns {Observable<IEdgeStatus>} Observable emitting
34198 * values describing the status of the sequence edges.
34201 return this._sequenceEdges$;
34206 Object.defineProperty(NodeCache.prototype, "spatialEdges", {
34208 * Get spatialEdges.
34210 * @returns {IEdgeStatus} Value describing the status of the
34214 return this._spatialEdges;
34219 Object.defineProperty(NodeCache.prototype, "spatialEdges$", {
34221 * Get spatialEdges$.
34223 * @returns {Observable<IEdgeStatus>} Observable emitting
34224 * values describing the status of the spatial edges.
34227 return this._spatialEdges$;
34233 * Cache the image and mesh assets.
34235 * @param {string} key - Key of the node to cache.
34236 * @param {boolean} pano - Value indicating whether node is a panorama.
34237 * @param {boolean} merged - Value indicating whether node is merged.
34238 * @returns {Observable<NodeCache>} Observable emitting this node
34239 * cache whenever the load status has changed and when the mesh or image
34240 * has been fully loaded.
34242 NodeCache.prototype.cacheAssets$ = function (key, pano, merged) {
34244 if (this._cachingAssets$ != null) {
34245 return this._cachingAssets$;
34247 var imageSize = pano ?
34248 Utils_1.Settings.basePanoramaSize :
34249 Utils_1.Settings.baseImageSize;
34250 this._cachingAssets$ = Observable_1.Observable
34251 .combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged), function (imageStatus, meshStatus) {
34252 _this._loadStatus.loaded = 0;
34253 _this._loadStatus.total = 0;
34255 _this._mesh = meshStatus.object;
34256 _this._loadStatus.loaded += meshStatus.loaded.loaded;
34257 _this._loadStatus.total += meshStatus.loaded.total;
34260 _this._image = imageStatus.object;
34261 _this._loadStatus.loaded += imageStatus.loaded.loaded;
34262 _this._loadStatus.total += imageStatus.loaded.total;
34266 .finally(function () {
34267 _this._cachingAssets$ = null;
34271 return this._cachingAssets$;
34274 * Cache an image with a higher resolution than the current one.
34276 * @param {string} key - Key of the node to cache.
34277 * @param {ImageSize} imageSize - The size to cache.
34278 * @returns {Observable<NodeCache>} Observable emitting a single item,
34279 * the node cache, when the image has been cached. If supplied image
34280 * size is not larger than the current image size the node cache is
34281 * returned immediately.
34283 NodeCache.prototype.cacheImage$ = function (key, imageSize) {
34285 if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) {
34286 return Observable_1.Observable.of(this);
34288 return this._cacheImage$(key, imageSize)
34289 .first(function (status) {
34290 return status.object != null;
34292 .do(function (status) {
34293 _this._disposeImage();
34294 _this._image = status.object;
34296 .map(function (imageStatus) {
34301 * Cache the sequence edges.
34303 * @param {Array<IEdge>} edges - Sequence edges to cache.
34305 NodeCache.prototype.cacheSequenceEdges = function (edges) {
34306 this._sequenceEdges = { cached: true, edges: edges };
34307 this._sequenceEdgesChanged$.next(this._sequenceEdges);
34310 * Cache the spatial edges.
34312 * @param {Array<IEdge>} edges - Spatial edges to cache.
34314 NodeCache.prototype.cacheSpatialEdges = function (edges) {
34315 this._spatialEdges = { cached: true, edges: edges };
34316 this._spatialEdgesChanged$.next(this._spatialEdges);
34319 * Dispose the node cache.
34321 * @description Disposes all cached assets and unsubscribes to
34324 NodeCache.prototype.dispose = function () {
34325 this._sequenceEdgesSubscription.unsubscribe();
34326 this._spatialEdgesSubscription.unsubscribe();
34327 this._disposeImage();
34329 this._loadStatus.loaded = 0;
34330 this._loadStatus.total = 0;
34331 this._sequenceEdges = { cached: false, edges: [] };
34332 this._spatialEdges = { cached: false, edges: [] };
34333 this._sequenceEdgesChanged$.next(this._sequenceEdges);
34334 this._spatialEdgesChanged$.next(this._spatialEdges);
34335 this._disposed = true;
34336 if (this._imageRequest != null) {
34337 this._imageRequest.abort();
34339 if (this._meshRequest != null) {
34340 this._meshRequest.abort();
34344 * Reset the sequence edges.
34346 NodeCache.prototype.resetSequenceEdges = function () {
34347 this._sequenceEdges = { cached: false, edges: [] };
34348 this._sequenceEdgesChanged$.next(this._sequenceEdges);
34351 * Reset the spatial edges.
34353 NodeCache.prototype.resetSpatialEdges = function () {
34354 this._spatialEdges = { cached: false, edges: [] };
34355 this._spatialEdgesChanged$.next(this._spatialEdges);
34360 * @param {string} key - Key of the node to cache.
34361 * @param {boolean} pano - Value indicating whether node is a panorama.
34362 * @returns {Observable<ILoadStatusObject<HTMLImageElement>>} Observable
34363 * emitting a load status object every time the load status changes
34364 * and completes when the image is fully loaded.
34366 NodeCache.prototype._cacheImage$ = function (key, imageSize) {
34368 return Observable_1.Observable.create(function (subscriber) {
34369 var xmlHTTP = new XMLHttpRequest();
34370 xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize), true);
34371 xmlHTTP.responseType = "arraybuffer";
34372 xmlHTTP.timeout = 15000;
34373 xmlHTTP.onload = function (pe) {
34374 if (xmlHTTP.status !== 200) {
34375 _this._imageRequest = null;
34376 subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
34379 var image = new Image();
34380 image.crossOrigin = "Anonymous";
34381 image.onload = function (e) {
34382 _this._imageRequest = null;
34383 if (_this._disposed) {
34384 window.URL.revokeObjectURL(image.src);
34385 subscriber.error(new Error("Image load was aborted (" + key + ")"));
34388 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
34389 subscriber.complete();
34391 image.onerror = function (error) {
34392 _this._imageRequest = null;
34393 subscriber.error(new Error("Failed to load image (" + key + ")"));
34395 var blob = new Blob([xmlHTTP.response]);
34396 image.src = window.URL.createObjectURL(blob);
34398 xmlHTTP.onprogress = function (pe) {
34399 if (_this._disposed) {
34402 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
34404 xmlHTTP.onerror = function (error) {
34405 _this._imageRequest = null;
34406 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
34408 xmlHTTP.ontimeout = function (e) {
34409 _this._imageRequest = null;
34410 subscriber.error(new Error("Image request timed out (" + key + ")"));
34412 xmlHTTP.onabort = function (event) {
34413 _this._imageRequest = null;
34414 subscriber.error(new Error("Image request was aborted (" + key + ")"));
34416 _this._imageRequest = xmlHTTP;
34417 xmlHTTP.send(null);
34423 * @param {string} key - Key of the node to cache.
34424 * @param {boolean} merged - Value indicating whether node is merged.
34425 * @returns {Observable<ILoadStatusObject<IMesh>>} Observable emitting
34426 * a load status object every time the load status changes and completes
34427 * when the mesh is fully loaded.
34429 NodeCache.prototype._cacheMesh$ = function (key, merged) {
34431 return Observable_1.Observable.create(function (subscriber) {
34433 subscriber.next(_this._createEmptyMeshLoadStatus());
34434 subscriber.complete();
34437 var xmlHTTP = new XMLHttpRequest();
34438 xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true);
34439 xmlHTTP.responseType = "arraybuffer";
34440 xmlHTTP.timeout = 15000;
34441 xmlHTTP.onload = function (pe) {
34442 _this._meshRequest = null;
34443 if (_this._disposed) {
34446 var mesh = xmlHTTP.status === 200 ?
34447 Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) :
34448 { faces: [], vertices: [] };
34449 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: mesh });
34450 subscriber.complete();
34452 xmlHTTP.onprogress = function (pe) {
34453 if (_this._disposed) {
34456 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
34458 xmlHTTP.onerror = function (e) {
34459 _this._meshRequest = null;
34460 console.error("Failed to cache mesh (" + key + ")");
34461 subscriber.next(_this._createEmptyMeshLoadStatus());
34462 subscriber.complete();
34464 xmlHTTP.ontimeout = function (e) {
34465 _this._meshRequest = null;
34466 console.error("Mesh request timed out (" + key + ")");
34467 subscriber.next(_this._createEmptyMeshLoadStatus());
34468 subscriber.complete();
34470 xmlHTTP.onabort = function (e) {
34471 _this._meshRequest = null;
34472 subscriber.error(new Error("Mesh request was aborted (" + key + ")"));
34474 _this._meshRequest = xmlHTTP;
34475 xmlHTTP.send(null);
34479 * Create a load status object with an empty mesh.
34481 * @returns {ILoadStatusObject<IMesh>} Load status object
34484 NodeCache.prototype._createEmptyMeshLoadStatus = function () {
34486 loaded: { loaded: 0, total: 0 },
34487 object: { faces: [], vertices: [] },
34490 NodeCache.prototype._disposeImage = function () {
34491 if (this._image != null) {
34492 window.URL.revokeObjectURL(this._image.src);
34494 this._image = null;
34498 exports.NodeCache = NodeCache;
34499 exports.default = NodeCache;
34501 }).call(this,require("buffer").Buffer)
34503 },{"../Graph":230,"../Utils":235,"buffer":7,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/publishReplay":72}],318:[function(require,module,exports){
34505 /// <reference path="../../typings/index.d.ts" />
34506 Object.defineProperty(exports, "__esModule", { value: true });
34507 var _ = require("underscore");
34511 * @classdesc Represents a sequence of ordered nodes.
34513 var Sequence = (function () {
34515 * Create a new sequene instance.
34517 * @param {ISequence} sequence - Raw sequence data.
34519 function Sequence(sequence) {
34520 this._key = sequence.key;
34521 this._keys = sequence.keys;
34523 Object.defineProperty(Sequence.prototype, "key", {
34527 * @returns {string} Unique sequence key.
34535 Object.defineProperty(Sequence.prototype, "keys", {
34539 * @returns {Array<string>} Array of ordered node keys in the sequence.
34548 * Dispose the sequence.
34550 * @description Disposes all cached assets.
34552 Sequence.prototype.dispose = function () {
34557 * Find the next node key in the sequence with respect to
34558 * the provided node key.
34560 * @param {string} key - Reference node key.
34561 * @returns {string} Next key in sequence if it exists, null otherwise.
34563 Sequence.prototype.findNextKey = function (key) {
34564 var i = _.indexOf(this._keys, key);
34565 if ((i + 1) >= this._keys.length || i === -1) {
34569 return this._keys[i + 1];
34573 * Find the previous node key in the sequence with respect to
34574 * the provided node key.
34576 * @param {string} key - Reference node key.
34577 * @returns {string} Previous key in sequence if it exists, null otherwise.
34579 Sequence.prototype.findPrevKey = function (key) {
34580 var i = _.indexOf(this._keys, key);
34581 if (i === 0 || i === -1) {
34585 return this._keys[i - 1];
34590 exports.Sequence = Sequence;
34591 exports.default = Sequence;
34593 },{"underscore":178}],319:[function(require,module,exports){
34595 /// <reference path="../../../typings/index.d.ts" />
34596 Object.defineProperty(exports, "__esModule", { value: true });
34597 var THREE = require("three");
34598 var Edge_1 = require("../../Edge");
34599 var Error_1 = require("../../Error");
34600 var Geo_1 = require("../../Geo");
34602 * @class EdgeCalculator
34604 * @classdesc Represents a class for calculating node edges.
34606 var EdgeCalculator = (function () {
34608 * Create a new edge calculator instance.
34610 * @param {EdgeCalculatorSettings} settings - Settings struct.
34611 * @param {EdgeCalculatorDirections} directions - Directions struct.
34612 * @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
34614 function EdgeCalculator(settings, directions, coefficients) {
34615 this._spatial = new Geo_1.Spatial();
34616 this._geoCoords = new Geo_1.GeoCoords();
34617 this._settings = settings != null ? settings : new Edge_1.EdgeCalculatorSettings();
34618 this._directions = directions != null ? directions : new Edge_1.EdgeCalculatorDirections();
34619 this._coefficients = coefficients != null ? coefficients : new Edge_1.EdgeCalculatorCoefficients();
34622 * Returns the potential edges to destination nodes for a set
34623 * of nodes with respect to a source node.
34625 * @param {Node} node - Source node.
34626 * @param {Array<Node>} nodes - Potential destination nodes.
34627 * @param {Array<string>} fallbackKeys - Keys for destination nodes that should
34628 * be returned even if they do not meet the criteria for a potential edge.
34629 * @throws {ArgumentMapillaryError} If node is not full.
34631 EdgeCalculator.prototype.getPotentialEdges = function (node, potentialNodes, fallbackKeys) {
34633 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
34635 if (!node.merged) {
34638 var currentDirection = this._spatial.viewingDirection(node.rotation);
34639 var currentVerticalDirection = this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
34640 var potentialEdges = [];
34641 for (var _i = 0, potentialNodes_1 = potentialNodes; _i < potentialNodes_1.length; _i++) {
34642 var potential = potentialNodes_1[_i];
34643 if (!potential.merged ||
34644 potential.key === node.key) {
34647 var enu = this._geoCoords.geodeticToEnu(potential.latLon.lat, potential.latLon.lon, potential.alt, node.latLon.lat, node.latLon.lon, node.alt);
34648 var motion = new THREE.Vector3(enu[0], enu[1], enu[2]);
34649 var distance = motion.length();
34650 if (distance > this._settings.maxDistance &&
34651 fallbackKeys.indexOf(potential.key) < 0) {
34654 var motionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, motion.x, motion.y);
34655 var verticalMotion = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
34656 var direction = this._spatial.viewingDirection(potential.rotation);
34657 var directionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
34658 var verticalDirection = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
34659 var verticalDirectionChange = verticalDirection - currentVerticalDirection;
34660 var rotation = this._spatial.relativeRotationAngle(node.rotation, potential.rotation);
34661 var worldMotionAzimuth = this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
34662 var sameSequence = potential.sequenceKey != null &&
34663 node.sequenceKey != null &&
34664 potential.sequenceKey === node.sequenceKey;
34665 var sameMergeCC = (potential.mergeCC == null && node.mergeCC == null) ||
34666 potential.mergeCC === node.mergeCC;
34667 var sameUser = potential.userKey === node.userKey;
34668 var potentialEdge = {
34669 capturedAt: potential.capturedAt,
34670 directionChange: directionChange,
34671 distance: distance,
34672 fullPano: potential.fullPano,
34673 key: potential.key,
34674 motionChange: motionChange,
34675 rotation: rotation,
34676 sameMergeCC: sameMergeCC,
34677 sameSequence: sameSequence,
34678 sameUser: sameUser,
34679 sequenceKey: potential.sequenceKey,
34680 verticalDirectionChange: verticalDirectionChange,
34681 verticalMotion: verticalMotion,
34682 worldMotionAzimuth: worldMotionAzimuth,
34684 potentialEdges.push(potentialEdge);
34686 return potentialEdges;
34689 * Computes the sequence edges for a node.
34691 * @param {Node} node - Source node.
34692 * @throws {ArgumentMapillaryError} If node is not full.
34694 EdgeCalculator.prototype.computeSequenceEdges = function (node, sequence) {
34696 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
34698 if (node.sequenceKey !== sequence.key) {
34699 throw new Error_1.ArgumentMapillaryError("Node and sequence does not correspond.");
34702 var nextKey = sequence.findNextKey(node.key);
34703 if (nextKey != null) {
34706 direction: Edge_1.EdgeDirection.Next,
34707 worldMotionAzimuth: Number.NaN,
34713 var prevKey = sequence.findPrevKey(node.key);
34714 if (prevKey != null) {
34717 direction: Edge_1.EdgeDirection.Prev,
34718 worldMotionAzimuth: Number.NaN,
34727 * Computes the similar edges for a node.
34729 * @description Similar edges for perspective images and cropped panoramas
34730 * look roughly in the same direction and are positioned closed to the node.
34731 * Similar edges for full panoramas only target other full panoramas.
34733 * @param {Node} node - Source node.
34734 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
34735 * @throws {ArgumentMapillaryError} If node is not full.
34737 EdgeCalculator.prototype.computeSimilarEdges = function (node, potentialEdges) {
34740 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
34742 var nodeFullPano = node.fullPano;
34743 var sequenceGroups = {};
34744 for (var _i = 0, potentialEdges_1 = potentialEdges; _i < potentialEdges_1.length; _i++) {
34745 var potentialEdge = potentialEdges_1[_i];
34746 if (potentialEdge.sequenceKey == null) {
34749 if (potentialEdge.sameSequence ||
34750 !potentialEdge.sameMergeCC) {
34753 if (nodeFullPano) {
34754 if (!potentialEdge.fullPano) {
34759 if (!potentialEdge.fullPano &&
34760 Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
34764 if (potentialEdge.distance > this._settings.similarMaxDistance) {
34767 if (potentialEdge.sameUser &&
34768 Math.abs(potentialEdge.capturedAt - node.capturedAt) <
34769 this._settings.similarMinTimeDifference) {
34772 if (sequenceGroups[potentialEdge.sequenceKey] == null) {
34773 sequenceGroups[potentialEdge.sequenceKey] = [];
34775 sequenceGroups[potentialEdge.sequenceKey].push(potentialEdge);
34777 var similarEdges = [];
34778 var calculateScore = node.fullPano ?
34779 function (potentialEdge) {
34780 return potentialEdge.distance;
34782 function (potentialEdge) {
34783 return _this._coefficients.similarDistance * potentialEdge.distance +
34784 _this._coefficients.similarRotation * potentialEdge.rotation;
34786 for (var sequenceKey in sequenceGroups) {
34787 if (!sequenceGroups.hasOwnProperty(sequenceKey)) {
34790 var lowestScore = Number.MAX_VALUE;
34791 var similarEdge = null;
34792 for (var _a = 0, _b = sequenceGroups[sequenceKey]; _a < _b.length; _a++) {
34793 var potentialEdge = _b[_a];
34794 var score = calculateScore(potentialEdge);
34795 if (score < lowestScore) {
34796 lowestScore = score;
34797 similarEdge = potentialEdge;
34800 if (similarEdge == null) {
34803 similarEdges.push(similarEdge);
34805 return similarEdges
34806 .map(function (potentialEdge) {
34809 direction: Edge_1.EdgeDirection.Similar,
34810 worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
34813 to: potentialEdge.key,
34818 * Computes the step edges for a perspective node.
34820 * @param {Node} node - Source node.
34821 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
34822 * @param {string} prevKey - Key of previous node in sequence.
34823 * @param {string} prevKey - Key of next node in sequence.
34824 * @throws {ArgumentMapillaryError} If node is not full.
34826 EdgeCalculator.prototype.computeStepEdges = function (node, potentialEdges, prevKey, nextKey) {
34828 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
34831 if (node.fullPano) {
34834 for (var k in this._directions.steps) {
34835 if (!this._directions.steps.hasOwnProperty(k)) {
34838 var step = this._directions.steps[k];
34839 var lowestScore = Number.MAX_VALUE;
34841 var fallback = null;
34842 for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) {
34843 var potential = potentialEdges_2[_i];
34844 if (potential.fullPano) {
34847 if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
34850 var motionDifference = this._spatial.angleDifference(step.motionChange, potential.motionChange);
34851 var directionMotionDifference = this._spatial.angleDifference(potential.directionChange, motionDifference);
34852 var drift = Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
34853 if (Math.abs(drift) > this._settings.stepMaxDrift) {
34856 var potentialKey = potential.key;
34857 if (step.useFallback && (potentialKey === prevKey || potentialKey === nextKey)) {
34858 fallback = potential;
34860 if (potential.distance > this._settings.stepMaxDistance) {
34863 motionDifference = Math.sqrt(motionDifference * motionDifference +
34864 potential.verticalMotion * potential.verticalMotion);
34865 var score = this._coefficients.stepPreferredDistance *
34866 Math.abs(potential.distance - this._settings.stepPreferredDistance) /
34867 this._settings.stepMaxDistance +
34868 this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
34869 this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
34870 this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
34871 this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
34872 if (score < lowestScore) {
34873 lowestScore = score;
34877 edge = edge == null ? fallback : edge;
34878 if (edge != null) {
34881 direction: step.direction,
34882 worldMotionAzimuth: edge.worldMotionAzimuth,
34892 * Computes the turn edges for a perspective node.
34894 * @param {Node} node - Source node.
34895 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
34896 * @throws {ArgumentMapillaryError} If node is not full.
34898 EdgeCalculator.prototype.computeTurnEdges = function (node, potentialEdges) {
34900 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
34903 if (node.fullPano) {
34906 for (var k in this._directions.turns) {
34907 if (!this._directions.turns.hasOwnProperty(k)) {
34910 var turn = this._directions.turns[k];
34911 var lowestScore = Number.MAX_VALUE;
34913 for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) {
34914 var potential = potentialEdges_3[_i];
34915 if (potential.fullPano) {
34918 if (potential.distance > this._settings.turnMaxDistance) {
34921 var rig = turn.direction !== Edge_1.EdgeDirection.TurnU &&
34922 potential.distance < this._settings.turnMaxRigDistance &&
34923 Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
34924 var directionDifference = this._spatial.angleDifference(turn.directionChange, potential.directionChange);
34925 var score = void 0;
34927 potential.directionChange * turn.directionChange > 0 &&
34928 Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
34929 score = -Math.PI / 2 + Math.abs(potential.directionChange);
34932 if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
34935 var motionDifference = turn.motionChange ?
34936 this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
34937 motionDifference = Math.sqrt(motionDifference * motionDifference +
34938 potential.verticalMotion * potential.verticalMotion);
34940 this._coefficients.turnDistance * potential.distance /
34941 this._settings.turnMaxDistance +
34942 this._coefficients.turnMotion * motionDifference / Math.PI +
34943 this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
34944 this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
34946 if (score < lowestScore) {
34947 lowestScore = score;
34951 if (edge != null) {
34954 direction: turn.direction,
34955 worldMotionAzimuth: edge.worldMotionAzimuth,
34965 * Computes the pano edges for a perspective node.
34967 * @param {Node} node - Source node.
34968 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
34969 * @throws {ArgumentMapillaryError} If node is not full.
34971 EdgeCalculator.prototype.computePerspectiveToPanoEdges = function (node, potentialEdges) {
34973 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
34975 if (node.fullPano) {
34978 var lowestScore = Number.MAX_VALUE;
34980 for (var _i = 0, potentialEdges_4 = potentialEdges; _i < potentialEdges_4.length; _i++) {
34981 var potential = potentialEdges_4[_i];
34982 if (!potential.fullPano) {
34985 var score = this._coefficients.panoPreferredDistance *
34986 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
34987 this._settings.panoMaxDistance +
34988 this._coefficients.panoMotion * Math.abs(potential.motionChange) / Math.PI +
34989 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
34990 if (score < lowestScore) {
34991 lowestScore = score;
34995 if (edge == null) {
35001 direction: Edge_1.EdgeDirection.Pano,
35002 worldMotionAzimuth: edge.worldMotionAzimuth,
35010 * Computes the pano and step edges for a pano node.
35012 * @param {Node} node - Source node.
35013 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
35014 * @throws {ArgumentMapillaryError} If node is not full.
35016 EdgeCalculator.prototype.computePanoEdges = function (node, potentialEdges) {
35018 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
35020 if (!node.fullPano) {
35023 var panoEdges = [];
35024 var potentialPanos = [];
35025 var potentialSteps = [];
35026 for (var _i = 0, potentialEdges_5 = potentialEdges; _i < potentialEdges_5.length; _i++) {
35027 var potential = potentialEdges_5[_i];
35028 if (potential.distance > this._settings.panoMaxDistance) {
35031 if (potential.fullPano) {
35032 if (potential.distance < this._settings.panoMinDistance) {
35035 potentialPanos.push(potential);
35038 for (var k in this._directions.panos) {
35039 if (!this._directions.panos.hasOwnProperty(k)) {
35042 var pano = this._directions.panos[k];
35043 var turn = this._spatial.angleDifference(potential.directionChange, potential.motionChange);
35044 var turnChange = this._spatial.angleDifference(pano.directionChange, turn);
35045 if (Math.abs(turnChange) > this._settings.panoMaxStepTurnChange) {
35048 potentialSteps.push([pano.direction, potential]);
35049 // break if step direction found
35054 var maxRotationDifference = Math.PI / this._settings.panoMaxItems;
35055 var occupiedAngles = [];
35056 var stepAngles = [];
35057 for (var index = 0; index < this._settings.panoMaxItems; index++) {
35058 var rotation = index / this._settings.panoMaxItems * 2 * Math.PI;
35059 var lowestScore = Number.MAX_VALUE;
35061 for (var _a = 0, potentialPanos_1 = potentialPanos; _a < potentialPanos_1.length; _a++) {
35062 var potential = potentialPanos_1[_a];
35063 var motionDifference = this._spatial.angleDifference(rotation, potential.motionChange);
35064 if (Math.abs(motionDifference) > maxRotationDifference) {
35067 var occupiedDifference = Number.MAX_VALUE;
35068 for (var _b = 0, occupiedAngles_1 = occupiedAngles; _b < occupiedAngles_1.length; _b++) {
35069 var occupiedAngle = occupiedAngles_1[_b];
35070 var difference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
35071 if (difference < occupiedDifference) {
35072 occupiedDifference = difference;
35075 if (occupiedDifference <= maxRotationDifference) {
35078 var score = this._coefficients.panoPreferredDistance *
35079 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
35080 this._settings.panoMaxDistance +
35081 this._coefficients.panoMotion * Math.abs(motionDifference) / maxRotationDifference +
35082 this._coefficients.panoSequencePenalty * (potential.sameSequence ? 0 : 1) +
35083 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
35084 if (score < lowestScore) {
35085 lowestScore = score;
35089 if (edge != null) {
35090 occupiedAngles.push(edge.motionChange);
35093 direction: Edge_1.EdgeDirection.Pano,
35094 worldMotionAzimuth: edge.worldMotionAzimuth,
35101 stepAngles.push(rotation);
35104 var occupiedStepAngles = {};
35105 occupiedStepAngles[Edge_1.EdgeDirection.Pano] = occupiedAngles;
35106 occupiedStepAngles[Edge_1.EdgeDirection.StepForward] = [];
35107 occupiedStepAngles[Edge_1.EdgeDirection.StepLeft] = [];
35108 occupiedStepAngles[Edge_1.EdgeDirection.StepBackward] = [];
35109 occupiedStepAngles[Edge_1.EdgeDirection.StepRight] = [];
35110 for (var _c = 0, stepAngles_1 = stepAngles; _c < stepAngles_1.length; _c++) {
35111 var stepAngle = stepAngles_1[_c];
35112 var occupations = [];
35113 for (var k in this._directions.panos) {
35114 if (!this._directions.panos.hasOwnProperty(k)) {
35117 var pano = this._directions.panos[k];
35118 var allOccupiedAngles = occupiedStepAngles[Edge_1.EdgeDirection.Pano]
35119 .concat(occupiedStepAngles[pano.direction])
35120 .concat(occupiedStepAngles[pano.prev])
35121 .concat(occupiedStepAngles[pano.next]);
35122 var lowestScore = Number.MAX_VALUE;
35124 for (var _d = 0, potentialSteps_1 = potentialSteps; _d < potentialSteps_1.length; _d++) {
35125 var potential = potentialSteps_1[_d];
35126 if (potential[0] !== pano.direction) {
35129 var motionChange = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
35130 if (Math.abs(motionChange) > maxRotationDifference) {
35133 var minOccupiedDifference = Number.MAX_VALUE;
35134 for (var _e = 0, allOccupiedAngles_1 = allOccupiedAngles; _e < allOccupiedAngles_1.length; _e++) {
35135 var occupiedAngle = allOccupiedAngles_1[_e];
35136 var occupiedDifference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
35137 if (occupiedDifference < minOccupiedDifference) {
35138 minOccupiedDifference = occupiedDifference;
35141 if (minOccupiedDifference <= maxRotationDifference) {
35144 var score = this._coefficients.panoPreferredDistance *
35145 Math.abs(potential[1].distance - this._settings.panoPreferredDistance) /
35146 this._settings.panoMaxDistance +
35147 this._coefficients.panoMotion * Math.abs(motionChange) / maxRotationDifference +
35148 this._coefficients.panoMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
35149 if (score < lowestScore) {
35150 lowestScore = score;
35154 if (edge != null) {
35155 occupations.push(edge);
35158 direction: edge[0],
35159 worldMotionAzimuth: edge[1].worldMotionAzimuth,
35166 for (var _f = 0, occupations_1 = occupations; _f < occupations_1.length; _f++) {
35167 var occupation = occupations_1[_f];
35168 occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
35173 return EdgeCalculator;
35175 exports.EdgeCalculator = EdgeCalculator;
35176 exports.default = EdgeCalculator;
35178 },{"../../Edge":227,"../../Error":228,"../../Geo":229,"three":176}],320:[function(require,module,exports){
35180 Object.defineProperty(exports, "__esModule", { value: true });
35181 var EdgeCalculatorCoefficients = (function () {
35182 function EdgeCalculatorCoefficients() {
35183 this.panoPreferredDistance = 2;
35184 this.panoMotion = 2;
35185 this.panoSequencePenalty = 1;
35186 this.panoMergeCCPenalty = 4;
35187 this.stepPreferredDistance = 4;
35188 this.stepMotion = 3;
35189 this.stepRotation = 4;
35190 this.stepSequencePenalty = 2;
35191 this.stepMergeCCPenalty = 6;
35192 this.similarDistance = 2;
35193 this.similarRotation = 3;
35194 this.turnDistance = 4;
35195 this.turnMotion = 2;
35196 this.turnSequencePenalty = 1;
35197 this.turnMergeCCPenalty = 4;
35199 return EdgeCalculatorCoefficients;
35201 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients;
35202 exports.default = EdgeCalculatorCoefficients;
35204 },{}],321:[function(require,module,exports){
35206 Object.defineProperty(exports, "__esModule", { value: true });
35207 var Edge_1 = require("../../Edge");
35208 var EdgeCalculatorDirections = (function () {
35209 function EdgeCalculatorDirections() {
35213 this.steps[Edge_1.EdgeDirection.StepForward] = {
35214 direction: Edge_1.EdgeDirection.StepForward,
35218 this.steps[Edge_1.EdgeDirection.StepBackward] = {
35219 direction: Edge_1.EdgeDirection.StepBackward,
35220 motionChange: Math.PI,
35223 this.steps[Edge_1.EdgeDirection.StepLeft] = {
35224 direction: Edge_1.EdgeDirection.StepLeft,
35225 motionChange: Math.PI / 2,
35226 useFallback: false,
35228 this.steps[Edge_1.EdgeDirection.StepRight] = {
35229 direction: Edge_1.EdgeDirection.StepRight,
35230 motionChange: -Math.PI / 2,
35231 useFallback: false,
35233 this.turns[Edge_1.EdgeDirection.TurnLeft] = {
35234 direction: Edge_1.EdgeDirection.TurnLeft,
35235 directionChange: Math.PI / 2,
35236 motionChange: Math.PI / 4,
35238 this.turns[Edge_1.EdgeDirection.TurnRight] = {
35239 direction: Edge_1.EdgeDirection.TurnRight,
35240 directionChange: -Math.PI / 2,
35241 motionChange: -Math.PI / 4,
35243 this.turns[Edge_1.EdgeDirection.TurnU] = {
35244 direction: Edge_1.EdgeDirection.TurnU,
35245 directionChange: Math.PI,
35246 motionChange: null,
35248 this.panos[Edge_1.EdgeDirection.StepForward] = {
35249 direction: Edge_1.EdgeDirection.StepForward,
35250 directionChange: 0,
35251 next: Edge_1.EdgeDirection.StepLeft,
35252 prev: Edge_1.EdgeDirection.StepRight,
35254 this.panos[Edge_1.EdgeDirection.StepBackward] = {
35255 direction: Edge_1.EdgeDirection.StepBackward,
35256 directionChange: Math.PI,
35257 next: Edge_1.EdgeDirection.StepRight,
35258 prev: Edge_1.EdgeDirection.StepLeft,
35260 this.panos[Edge_1.EdgeDirection.StepLeft] = {
35261 direction: Edge_1.EdgeDirection.StepLeft,
35262 directionChange: Math.PI / 2,
35263 next: Edge_1.EdgeDirection.StepBackward,
35264 prev: Edge_1.EdgeDirection.StepForward,
35266 this.panos[Edge_1.EdgeDirection.StepRight] = {
35267 direction: Edge_1.EdgeDirection.StepRight,
35268 directionChange: -Math.PI / 2,
35269 next: Edge_1.EdgeDirection.StepForward,
35270 prev: Edge_1.EdgeDirection.StepBackward,
35273 return EdgeCalculatorDirections;
35275 exports.EdgeCalculatorDirections = EdgeCalculatorDirections;
35277 },{"../../Edge":227}],322:[function(require,module,exports){
35279 Object.defineProperty(exports, "__esModule", { value: true });
35280 var EdgeCalculatorSettings = (function () {
35281 function EdgeCalculatorSettings() {
35282 this.panoMinDistance = 0.1;
35283 this.panoMaxDistance = 20;
35284 this.panoPreferredDistance = 5;
35285 this.panoMaxItems = 4;
35286 this.panoMaxStepTurnChange = Math.PI / 8;
35287 this.rotationMaxDistance = this.turnMaxRigDistance;
35288 this.rotationMaxDirectionChange = Math.PI / 6;
35289 this.rotationMaxVerticalDirectionChange = Math.PI / 8;
35290 this.similarMaxDirectionChange = Math.PI / 8;
35291 this.similarMaxDistance = 12;
35292 this.similarMinTimeDifference = 12 * 3600 * 1000;
35293 this.stepMaxDistance = 20;
35294 this.stepMaxDirectionChange = Math.PI / 6;
35295 this.stepMaxDrift = Math.PI / 6;
35296 this.stepPreferredDistance = 4;
35297 this.turnMaxDistance = 15;
35298 this.turnMaxDirectionChange = 2 * Math.PI / 9;
35299 this.turnMaxRigDistance = 0.65;
35300 this.turnMinRigDirectionChange = Math.PI / 6;
35302 Object.defineProperty(EdgeCalculatorSettings.prototype, "maxDistance", {
35304 return Math.max(this.panoMaxDistance, this.similarMaxDistance, this.stepMaxDistance, this.turnMaxDistance);
35309 return EdgeCalculatorSettings;
35311 exports.EdgeCalculatorSettings = EdgeCalculatorSettings;
35312 exports.default = EdgeCalculatorSettings;
35314 },{}],323:[function(require,module,exports){
35316 Object.defineProperty(exports, "__esModule", { value: true });
35318 * Enumeration for edge directions
35321 * @description Directions for edges in node graph describing
35322 * sequence, spatial and node type relations between nodes.
35325 (function (EdgeDirection) {
35327 * Next node in the sequence.
35329 EdgeDirection[EdgeDirection["Next"] = 0] = "Next";
35331 * Previous node in the sequence.
35333 EdgeDirection[EdgeDirection["Prev"] = 1] = "Prev";
35335 * Step to the left keeping viewing direction.
35337 EdgeDirection[EdgeDirection["StepLeft"] = 2] = "StepLeft";
35339 * Step to the right keeping viewing direction.
35341 EdgeDirection[EdgeDirection["StepRight"] = 3] = "StepRight";
35343 * Step forward keeping viewing direction.
35345 EdgeDirection[EdgeDirection["StepForward"] = 4] = "StepForward";
35347 * Step backward keeping viewing direction.
35349 EdgeDirection[EdgeDirection["StepBackward"] = 5] = "StepBackward";
35351 * Turn 90 degrees counter clockwise.
35353 EdgeDirection[EdgeDirection["TurnLeft"] = 6] = "TurnLeft";
35355 * Turn 90 degrees clockwise.
35357 EdgeDirection[EdgeDirection["TurnRight"] = 7] = "TurnRight";
35359 * Turn 180 degrees.
35361 EdgeDirection[EdgeDirection["TurnU"] = 8] = "TurnU";
35363 * Panorama in general direction.
35365 EdgeDirection[EdgeDirection["Pano"] = 9] = "Pano";
35367 * Looking in roughly the same direction at rougly the same position.
35369 EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar";
35370 })(EdgeDirection = exports.EdgeDirection || (exports.EdgeDirection = {}));
35372 },{}],324:[function(require,module,exports){
35374 /// <reference path="../../typings/index.d.ts" />
35375 Object.defineProperty(exports, "__esModule", { value: true });
35376 var _ = require("underscore");
35377 var vd = require("virtual-dom");
35378 var Subject_1 = require("rxjs/Subject");
35379 require("rxjs/add/operator/combineLatest");
35380 require("rxjs/add/operator/distinctUntilChanged");
35381 require("rxjs/add/operator/filter");
35382 require("rxjs/add/operator/map");
35383 require("rxjs/add/operator/pluck");
35384 require("rxjs/add/operator/scan");
35385 var Render_1 = require("../Render");
35386 var DOMRenderer = (function () {
35387 function DOMRenderer(element, renderService, currentFrame$) {
35388 this._adaptiveOperation$ = new Subject_1.Subject();
35389 this._render$ = new Subject_1.Subject();
35390 this._renderAdaptive$ = new Subject_1.Subject();
35391 this._renderService = renderService;
35392 this._currentFrame$ = currentFrame$;
35393 var rootNode = vd.create(vd.h("div.domRenderer", []));
35394 element.appendChild(rootNode);
35395 this._offset$ = this._adaptiveOperation$
35396 .scan(function (adaptive, operation) {
35397 return operation(adaptive);
35399 elementHeight: element.offsetHeight,
35400 elementWidth: element.offsetWidth,
35402 renderMode: Render_1.RenderMode.Fill,
35404 .filter(function (adaptive) {
35405 return adaptive.imageAspect > 0 && adaptive.elementWidth > 0 && adaptive.elementHeight > 0;
35407 .map(function (adaptive) {
35408 var elementAspect = adaptive.elementWidth / adaptive.elementHeight;
35409 var ratio = adaptive.imageAspect / elementAspect;
35410 var verticalOffset = 0;
35411 var horizontalOffset = 0;
35412 if (adaptive.renderMode === Render_1.RenderMode.Letterbox) {
35413 if (adaptive.imageAspect > elementAspect) {
35414 verticalOffset = adaptive.elementHeight * (1 - 1 / ratio) / 2;
35417 horizontalOffset = adaptive.elementWidth * (1 - ratio) / 2;
35421 if (adaptive.imageAspect > elementAspect) {
35422 horizontalOffset = -adaptive.elementWidth * (ratio - 1) / 2;
35425 verticalOffset = -adaptive.elementHeight * (1 / ratio - 1) / 2;
35429 bottom: verticalOffset,
35430 left: horizontalOffset,
35431 right: horizontalOffset,
35432 top: verticalOffset,
35435 this._currentFrame$
35436 .filter(function (frame) {
35437 return frame.state.currentNode != null;
35439 .distinctUntilChanged(function (k1, k2) {
35441 }, function (frame) {
35442 return frame.state.currentNode.key;
35444 .map(function (frame) {
35445 return frame.state.currentTransform.basicAspect;
35447 .map(function (aspect) {
35448 return function (adaptive) {
35449 adaptive.imageAspect = aspect;
35453 .subscribe(this._adaptiveOperation$);
35454 this._renderAdaptive$
35455 .scan(function (vNodeHashes, vNodeHash) {
35456 if (vNodeHash.vnode == null) {
35457 delete vNodeHashes[vNodeHash.name];
35460 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
35462 return vNodeHashes;
35464 .combineLatest(this._offset$)
35465 .map(function (vo) {
35466 var vNodes = _.values(vo[0]);
35467 var offset = vo[1];
35470 bottom: offset.bottom + "px",
35471 left: offset.left + "px",
35472 "pointer-events": "none",
35473 position: "absolute",
35474 right: offset.right + "px",
35475 top: offset.top + "px",
35479 name: "adaptiveDomRenderer",
35480 vnode: vd.h("div.adaptiveDomRenderer", properties, vNodes),
35483 .subscribe(this._render$);
35484 this._vNode$ = this._render$
35485 .scan(function (vNodeHashes, vNodeHash) {
35486 if (vNodeHash.vnode == null) {
35487 delete vNodeHashes[vNodeHash.name];
35490 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
35492 return vNodeHashes;
35494 .map(function (vNodeHashes) {
35495 var vNodes = _.values(vNodeHashes);
35496 return vd.h("div.domRenderer", vNodes);
35498 this._vPatch$ = this._vNode$
35499 .scan(function (nodePatch, vNode) {
35500 nodePatch.vpatch = vd.diff(nodePatch.vnode, vNode);
35501 nodePatch.vnode = vNode;
35503 }, { vnode: vd.h("div.domRenderer", []), vpatch: null })
35505 this._element$ = this._vPatch$
35506 .scan(function (oldElement, vPatch) {
35507 return vd.patch(oldElement, vPatch);
35511 this._element$.subscribe(function () { });
35512 this._renderService.size$
35513 .map(function (size) {
35514 return function (adaptive) {
35515 adaptive.elementWidth = size.width;
35516 adaptive.elementHeight = size.height;
35520 .subscribe(this._adaptiveOperation$);
35521 this._renderService.renderMode$
35522 .map(function (renderMode) {
35523 return function (adaptive) {
35524 adaptive.renderMode = renderMode;
35528 .subscribe(this._adaptiveOperation$);
35530 Object.defineProperty(DOMRenderer.prototype, "element$", {
35532 return this._element$;
35537 Object.defineProperty(DOMRenderer.prototype, "render$", {
35539 return this._render$;
35544 Object.defineProperty(DOMRenderer.prototype, "renderAdaptive$", {
35546 return this._renderAdaptive$;
35551 DOMRenderer.prototype.clear = function (name) {
35552 this._renderAdaptive$.next({ name: name, vnode: null });
35553 this._render$.next({ name: name, vnode: null });
35555 return DOMRenderer;
35557 exports.DOMRenderer = DOMRenderer;
35558 exports.default = DOMRenderer;
35560 },{"../Render":232,"rxjs/Subject":34,"rxjs/add/operator/combineLatest":53,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/pluck":70,"rxjs/add/operator/scan":73,"underscore":178,"virtual-dom":182}],325:[function(require,module,exports){
35562 Object.defineProperty(exports, "__esModule", { value: true });
35564 (function (GLRenderStage) {
35565 GLRenderStage[GLRenderStage["Background"] = 0] = "Background";
35566 GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground";
35567 })(GLRenderStage = exports.GLRenderStage || (exports.GLRenderStage = {}));
35568 exports.default = GLRenderStage;
35570 },{}],326:[function(require,module,exports){
35572 /// <reference path="../../typings/index.d.ts" />
35573 Object.defineProperty(exports, "__esModule", { value: true });
35574 var THREE = require("three");
35575 var Observable_1 = require("rxjs/Observable");
35576 var Subject_1 = require("rxjs/Subject");
35577 require("rxjs/add/observable/combineLatest");
35578 require("rxjs/add/operator/distinctUntilChanged");
35579 require("rxjs/add/operator/filter");
35580 require("rxjs/add/operator/first");
35581 require("rxjs/add/operator/map");
35582 require("rxjs/add/operator/merge");
35583 require("rxjs/add/operator/mergeMap");
35584 require("rxjs/add/operator/scan");
35585 require("rxjs/add/operator/share");
35586 require("rxjs/add/operator/startWith");
35587 var Render_1 = require("../Render");
35588 var GLRenderer = (function () {
35589 function GLRenderer(canvasContainer, renderService) {
35591 this._renderFrame$ = new Subject_1.Subject();
35592 this._renderCameraOperation$ = new Subject_1.Subject();
35593 this._render$ = new Subject_1.Subject();
35594 this._clear$ = new Subject_1.Subject();
35595 this._renderOperation$ = new Subject_1.Subject();
35596 this._rendererOperation$ = new Subject_1.Subject();
35597 this._eraserOperation$ = new Subject_1.Subject();
35598 this._renderService = renderService;
35599 this._renderer$ = this._rendererOperation$
35600 .scan(function (renderer, operation) {
35601 return operation(renderer);
35602 }, { needsRender: false, renderer: null });
35603 this._renderCollection$ = this._renderOperation$
35604 .scan(function (hashes, operation) {
35605 return operation(hashes);
35608 this._renderCamera$ = this._renderCameraOperation$
35609 .scan(function (rc, operation) {
35610 return operation(rc);
35611 }, { frameId: -1, needsRender: false, perspective: null });
35612 this._eraser$ = this._eraserOperation$
35613 .startWith(function (eraser) {
35616 .scan(function (eraser, operation) {
35617 return operation(eraser);
35618 }, { needsRender: false });
35619 Observable_1.Observable
35620 .combineLatest([this._renderer$, this._renderCollection$, this._renderCamera$, this._eraser$], function (renderer, hashes, rc, eraser) {
35621 var renders = Object.keys(hashes)
35622 .map(function (key) {
35623 return hashes[key];
35625 return { camera: rc, eraser: eraser, renderer: renderer, renders: renders };
35627 .filter(function (co) {
35628 var needsRender = co.renderer.needsRender ||
35629 co.camera.needsRender ||
35630 co.eraser.needsRender;
35631 var frameId = co.camera.frameId;
35632 for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
35633 var render = _a[_i];
35634 if (render.frameId !== frameId) {
35637 needsRender = needsRender || render.needsRender;
35639 return needsRender;
35641 .distinctUntilChanged(function (n1, n2) {
35644 return co.eraser.needsRender ? -1 : co.camera.frameId;
35646 .subscribe(function (co) {
35647 co.renderer.needsRender = false;
35648 co.camera.needsRender = false;
35649 co.eraser.needsRender = false;
35650 var perspectiveCamera = co.camera.perspective;
35651 var backgroundRenders = [];
35652 var foregroundRenders = [];
35653 for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
35654 var render = _a[_i];
35655 if (render.stage === Render_1.GLRenderStage.Background) {
35656 backgroundRenders.push(render.render);
35658 else if (render.stage === Render_1.GLRenderStage.Foreground) {
35659 foregroundRenders.push(render.render);
35662 var renderer = co.renderer.renderer;
35664 for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) {
35665 var render = backgroundRenders_1[_b];
35666 render(perspectiveCamera, renderer);
35668 renderer.clearDepth();
35669 for (var _c = 0, foregroundRenders_1 = foregroundRenders; _c < foregroundRenders_1.length; _c++) {
35670 var render = foregroundRenders_1[_c];
35671 render(perspectiveCamera, renderer);
35675 .map(function (rc) {
35676 return function (irc) {
35677 irc.frameId = rc.frameId;
35678 irc.perspective = rc.perspective;
35679 if (rc.changed === true) {
35680 irc.needsRender = true;
35685 .subscribe(this._renderCameraOperation$);
35686 this._renderFrameSubscribe();
35687 var renderHash$ = this._render$
35688 .map(function (hash) {
35689 return function (hashes) {
35690 hashes[hash.name] = hash.render;
35694 var clearHash$ = this._clear$
35695 .map(function (name) {
35696 return function (hashes) {
35697 delete hashes[name];
35701 Observable_1.Observable
35702 .merge(renderHash$, clearHash$)
35703 .subscribe(this._renderOperation$);
35704 this._webGLRenderer$ = this._render$
35706 .map(function (hash) {
35707 var element = renderService.element;
35708 var webGLRenderer = new THREE.WebGLRenderer();
35709 webGLRenderer.setPixelRatio(window.devicePixelRatio);
35710 webGLRenderer.setSize(element.offsetWidth, element.offsetHeight);
35711 webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0);
35712 webGLRenderer.autoClear = false;
35713 webGLRenderer.domElement.style.position = "absolute";
35714 canvasContainer.appendChild(webGLRenderer.domElement);
35715 return webGLRenderer;
35719 this._webGLRenderer$.subscribe(function () { });
35720 var createRenderer$ = this._webGLRenderer$
35722 .map(function (webGLRenderer) {
35723 return function (renderer) {
35724 renderer.needsRender = true;
35725 renderer.renderer = webGLRenderer;
35729 var resizeRenderer$ = this._renderService.size$
35730 .map(function (size) {
35731 return function (renderer) {
35732 if (renderer.renderer == null) {
35735 renderer.renderer.setSize(size.width, size.height);
35736 renderer.needsRender = true;
35740 var clearRenderer$ = this._clear$
35741 .map(function (name) {
35742 return function (renderer) {
35743 if (renderer.renderer == null) {
35746 renderer.needsRender = true;
35750 Observable_1.Observable
35751 .merge(createRenderer$, resizeRenderer$, clearRenderer$)
35752 .subscribe(this._rendererOperation$);
35753 var renderCollectionEmpty$ = this._renderCollection$
35754 .filter(function (hashes) {
35755 return Object.keys(hashes).length === 0;
35758 renderCollectionEmpty$
35759 .subscribe(function (hashes) {
35760 if (_this._renderFrameSubscription == null) {
35763 _this._renderFrameSubscription.unsubscribe();
35764 _this._renderFrameSubscription = null;
35765 _this._renderFrameSubscribe();
35767 renderCollectionEmpty$
35768 .map(function (hashes) {
35769 return function (eraser) {
35770 eraser.needsRender = true;
35774 .subscribe(this._eraserOperation$);
35776 Object.defineProperty(GLRenderer.prototype, "render$", {
35778 return this._render$;
35783 Object.defineProperty(GLRenderer.prototype, "webGLRenderer$", {
35785 return this._webGLRenderer$;
35790 GLRenderer.prototype.clear = function (name) {
35791 this._clear$.next(name);
35793 GLRenderer.prototype._renderFrameSubscribe = function () {
35797 .map(function (renderHash) {
35798 return function (irc) {
35799 irc.needsRender = true;
35803 .subscribe(function (operation) {
35804 _this._renderCameraOperation$.next(operation);
35806 this._renderFrameSubscription = this._render$
35808 .mergeMap(function (hash) {
35809 return _this._renderService.renderCameraFrame$;
35811 .subscribe(this._renderFrame$);
35815 exports.GLRenderer = GLRenderer;
35816 exports.default = GLRenderer;
35818 },{"../Render":232,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/scan":73,"rxjs/add/operator/share":74,"rxjs/add/operator/startWith":78,"three":176}],327:[function(require,module,exports){
35820 /// <reference path="../../typings/index.d.ts" />
35821 Object.defineProperty(exports, "__esModule", { value: true });
35822 var THREE = require("three");
35823 var Geo_1 = require("../Geo");
35824 var Render_1 = require("../Render");
35825 var RenderCamera = (function () {
35826 function RenderCamera(elementWidth, elementHeight, renderMode) {
35829 this._frameId = -1;
35830 this._changed = false;
35831 this._changedForFrame = -1;
35832 this.currentAspect = 1;
35833 this.currentPano = false;
35834 this.previousAspect = 1;
35835 this.previousPano = false;
35836 this.renderMode = renderMode;
35837 this._spatial = new Geo_1.Spatial();
35838 this._camera = new Geo_1.Camera();
35839 var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
35840 this._perspective = new THREE.PerspectiveCamera(50, perspectiveCameraAspect, 0.4, 10000);
35841 this._perspective.matrixAutoUpdate = false;
35842 this._rotation = { phi: 0, theta: 0 };
35844 Object.defineProperty(RenderCamera.prototype, "camera", {
35846 return this._camera;
35851 Object.defineProperty(RenderCamera.prototype, "changed", {
35853 return this.frameId === this._changedForFrame;
35858 Object.defineProperty(RenderCamera.prototype, "frameId", {
35860 return this._frameId;
35862 set: function (value) {
35863 this._frameId = value;
35864 if (this._changed) {
35865 this._changed = false;
35866 this._changedForFrame = value;
35872 Object.defineProperty(RenderCamera.prototype, "perspective", {
35874 return this._perspective;
35879 Object.defineProperty(RenderCamera.prototype, "rotation", {
35881 return this._rotation;
35886 RenderCamera.prototype.updateAspect = function (elementWidth, elementHeight) {
35887 var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
35888 this._perspective.aspect = perspectiveCameraAspect;
35889 this._changed = true;
35891 RenderCamera.prototype.updateProjection = function () {
35892 var currentAspect = this._getAspect(this.currentAspect, this.currentPano, this.perspective.aspect);
35893 var previousAspect = this._getAspect(this.previousAspect, this.previousPano, this.perspective.aspect);
35894 var aspect = (1 - this.alpha) * previousAspect + this.alpha * currentAspect;
35895 var verticalFov = this._getVerticalFov(aspect, this._camera.focal, this.zoom);
35896 this._perspective.fov = verticalFov;
35897 this._perspective.updateProjectionMatrix();
35898 this._changed = true;
35900 RenderCamera.prototype.updatePerspective = function (camera) {
35901 this._perspective.up.copy(camera.up);
35902 this._perspective.position.copy(camera.position);
35903 this._perspective.lookAt(camera.lookat);
35904 this._perspective.updateMatrix();
35905 this._perspective.updateMatrixWorld(false);
35906 this._perspective.matrixWorldInverse.getInverse(this._perspective.matrixWorld);
35907 this._changed = true;
35909 RenderCamera.prototype.updateRotation = function (camera) {
35910 this._rotation = this._getRotation(camera);
35912 RenderCamera.prototype._getVerticalFov = function (aspect, focal, zoom) {
35913 return 2 * Math.atan(0.5 / (Math.pow(2, zoom) * aspect * focal)) * 180 / Math.PI;
35915 RenderCamera.prototype._getAspect = function (nodeAspect, pano, perspectiveCameraAspect) {
35919 var coeff = Math.max(1, 1 / nodeAspect);
35920 var usePerspective = this.renderMode === Render_1.RenderMode.Letterbox ?
35921 nodeAspect > perspectiveCameraAspect :
35922 nodeAspect < perspectiveCameraAspect;
35923 var aspect = usePerspective ?
35924 coeff * perspectiveCameraAspect :
35925 coeff * nodeAspect;
35928 RenderCamera.prototype._getPerspectiveCameraAspect = function (elementWidth, elementHeight) {
35929 return elementWidth === 0 ? 0 : elementWidth / elementHeight;
35931 RenderCamera.prototype._getRotation = function (camera) {
35932 var direction = camera.lookat.clone().sub(camera.position);
35933 var up = camera.up.clone();
35934 var upProjection = direction.clone().dot(up);
35935 var planeProjection = direction.clone().sub(up.clone().multiplyScalar(upProjection));
35936 var phi = Math.atan2(planeProjection.y, planeProjection.x);
35937 var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
35938 return { phi: phi, theta: theta };
35940 return RenderCamera;
35942 exports.RenderCamera = RenderCamera;
35943 exports.default = RenderCamera;
35945 },{"../Geo":229,"../Render":232,"three":176}],328:[function(require,module,exports){
35947 Object.defineProperty(exports, "__esModule", { value: true });
35949 * Enumeration for render mode
35952 * @description Modes for specifying how rendering is done
35953 * in the viewer. All modes preserves the original aspect
35954 * ratio of the images.
35957 (function (RenderMode) {
35959 * Displays all content within the viewer.
35961 * @description Black bars shown on both
35962 * sides of the content. Bars are shown
35963 * either below and above or to the left
35964 * and right of the content depending on
35965 * the aspect ratio relation between the
35966 * image and the viewer.
35968 RenderMode[RenderMode["Letterbox"] = 0] = "Letterbox";
35970 * Fills the viewer by cropping content.
35972 * @description Cropping is done either
35973 * in horizontal or vertical direction
35974 * depending on the aspect ratio relation
35975 * between the image and the viewer.
35977 RenderMode[RenderMode["Fill"] = 1] = "Fill";
35978 })(RenderMode = exports.RenderMode || (exports.RenderMode = {}));
35979 exports.default = RenderMode;
35981 },{}],329:[function(require,module,exports){
35983 /// <reference path="../../typings/index.d.ts" />
35984 Object.defineProperty(exports, "__esModule", { value: true });
35985 var Subject_1 = require("rxjs/Subject");
35986 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
35987 require("rxjs/add/observable/combineLatest");
35988 require("rxjs/add/operator/do");
35989 require("rxjs/add/operator/filter");
35990 require("rxjs/add/operator/map");
35991 require("rxjs/add/operator/publishReplay");
35992 require("rxjs/add/operator/scan");
35993 require("rxjs/add/operator/skip");
35994 require("rxjs/add/operator/startWith");
35995 require("rxjs/add/operator/withLatestFrom");
35996 var Geo_1 = require("../Geo");
35997 var Render_1 = require("../Render");
35998 var RenderService = (function () {
35999 function RenderService(element, currentFrame$, renderMode) {
36001 this._element = element;
36002 this._currentFrame$ = currentFrame$;
36003 this._spatial = new Geo_1.Spatial();
36004 renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill;
36005 this._resize$ = new Subject_1.Subject();
36006 this._renderCameraOperation$ = new Subject_1.Subject();
36008 new BehaviorSubject_1.BehaviorSubject({
36009 height: this._element.offsetHeight,
36010 width: this._element.offsetWidth,
36014 return { height: _this._element.offsetHeight, width: _this._element.offsetWidth };
36016 .subscribe(this._size$);
36017 this._renderMode$ = new BehaviorSubject_1.BehaviorSubject(renderMode);
36018 this._renderCameraHolder$ = this._renderCameraOperation$
36019 .startWith(function (rc) {
36022 .scan(function (rc, operation) {
36023 return operation(rc);
36024 }, new Render_1.RenderCamera(this._element.offsetWidth, this._element.offsetHeight, renderMode))
36027 this._renderCameraFrame$ = this._currentFrame$
36028 .withLatestFrom(this._renderCameraHolder$, function (frame, renderCamera) {
36029 return [frame, renderCamera];
36031 .do(function (args) {
36032 var frame = args[0];
36034 var camera = frame.state.camera;
36035 if (rc.alpha !== frame.state.alpha ||
36036 rc.zoom !== frame.state.zoom ||
36037 rc.camera.diff(camera) > 1e-9) {
36038 var currentTransform = frame.state.currentTransform;
36039 var previousTransform = frame.state.previousTransform != null ?
36040 frame.state.previousTransform :
36041 frame.state.currentTransform;
36042 var previousNode = frame.state.previousNode != null ?
36043 frame.state.previousNode :
36044 frame.state.currentNode;
36045 rc.currentAspect = currentTransform.basicAspect;
36046 rc.currentPano = frame.state.currentNode.pano;
36047 rc.previousAspect = previousTransform.basicAspect;
36048 rc.previousPano = previousNode.pano;
36049 rc.alpha = frame.state.alpha;
36050 rc.zoom = frame.state.zoom;
36051 rc.camera.copy(camera);
36052 rc.updatePerspective(camera);
36053 rc.updateRotation(camera);
36054 rc.updateProjection();
36056 rc.frameId = frame.id;
36058 .map(function (args) {
36063 this._renderCamera$ = this._renderCameraFrame$
36064 .filter(function (rc) {
36069 this._bearing$ = this._renderCamera$
36070 .map(function (renderCamera) {
36071 var bearing = _this._spatial.radToDeg(_this._spatial.azimuthalToBearing(renderCamera.rotation.phi));
36072 return _this._spatial.wrap(bearing, 0, 360);
36078 .map(function (size) {
36079 return function (rc) {
36080 rc.updateAspect(size.width, size.height);
36081 rc.updateProjection();
36085 .subscribe(this._renderCameraOperation$);
36088 .map(function (rm) {
36089 return function (rc) {
36090 rc.renderMode = rm;
36091 rc.updateProjection();
36095 .subscribe(this._renderCameraOperation$);
36096 this._bearing$.subscribe(function () { });
36097 this._renderCameraHolder$.subscribe(function () { });
36098 this._size$.subscribe(function () { });
36099 this._renderMode$.subscribe(function () { });
36100 this._renderCamera$.subscribe(function () { });
36101 this._renderCameraFrame$.subscribe(function () { });
36103 Object.defineProperty(RenderService.prototype, "bearing$", {
36105 return this._bearing$;
36110 Object.defineProperty(RenderService.prototype, "element", {
36112 return this._element;
36117 Object.defineProperty(RenderService.prototype, "resize$", {
36119 return this._resize$;
36124 Object.defineProperty(RenderService.prototype, "size$", {
36126 return this._size$;
36131 Object.defineProperty(RenderService.prototype, "renderMode$", {
36133 return this._renderMode$;
36138 Object.defineProperty(RenderService.prototype, "renderCameraFrame$", {
36140 return this._renderCameraFrame$;
36145 Object.defineProperty(RenderService.prototype, "renderCamera$", {
36147 return this._renderCamera$;
36152 return RenderService;
36154 exports.RenderService = RenderService;
36155 exports.default = RenderService;
36157 },{"../Geo":229,"../Render":232,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/do":59,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73,"rxjs/add/operator/skip":75,"rxjs/add/operator/startWith":78,"rxjs/add/operator/withLatestFrom":83}],330:[function(require,module,exports){
36159 Object.defineProperty(exports, "__esModule", { value: true });
36161 (function (State) {
36162 State[State["Traversing"] = 0] = "Traversing";
36163 State[State["Waiting"] = 1] = "Waiting";
36164 })(State = exports.State || (exports.State = {}));
36165 exports.default = State;
36167 },{}],331:[function(require,module,exports){
36169 Object.defineProperty(exports, "__esModule", { value: true });
36170 var State_1 = require("../State");
36171 var Geo_1 = require("../Geo");
36172 var StateContext = (function () {
36173 function StateContext() {
36174 this._state = new State_1.TraversingState({
36176 camera: new Geo_1.Camera(),
36178 reference: { alt: 0, lat: 0, lon: 0 },
36183 StateContext.prototype.traverse = function () {
36184 this._state = this._state.traverse();
36186 StateContext.prototype.wait = function () {
36187 this._state = this._state.wait();
36189 Object.defineProperty(StateContext.prototype, "state", {
36191 if (this._state instanceof State_1.TraversingState) {
36192 return State_1.State.Traversing;
36194 else if (this._state instanceof State_1.WaitingState) {
36195 return State_1.State.Waiting;
36197 throw new Error("Invalid state");
36202 Object.defineProperty(StateContext.prototype, "reference", {
36204 return this._state.reference;
36209 Object.defineProperty(StateContext.prototype, "alpha", {
36211 return this._state.alpha;
36216 Object.defineProperty(StateContext.prototype, "camera", {
36218 return this._state.camera;
36223 Object.defineProperty(StateContext.prototype, "zoom", {
36225 return this._state.zoom;
36230 Object.defineProperty(StateContext.prototype, "currentNode", {
36232 return this._state.currentNode;
36237 Object.defineProperty(StateContext.prototype, "previousNode", {
36239 return this._state.previousNode;
36244 Object.defineProperty(StateContext.prototype, "currentCamera", {
36246 return this._state.currentCamera;
36251 Object.defineProperty(StateContext.prototype, "currentTransform", {
36253 return this._state.currentTransform;
36258 Object.defineProperty(StateContext.prototype, "previousTransform", {
36260 return this._state.previousTransform;
36265 Object.defineProperty(StateContext.prototype, "trajectory", {
36267 return this._state.trajectory;
36272 Object.defineProperty(StateContext.prototype, "currentIndex", {
36274 return this._state.currentIndex;
36279 Object.defineProperty(StateContext.prototype, "lastNode", {
36281 return this._state.trajectory[this._state.trajectory.length - 1];
36286 Object.defineProperty(StateContext.prototype, "nodesAhead", {
36288 return this._state.trajectory.length - 1 - this._state.currentIndex;
36293 Object.defineProperty(StateContext.prototype, "motionless", {
36295 return this._state.motionless;
36300 StateContext.prototype.getCenter = function () {
36301 return this._state.getCenter();
36303 StateContext.prototype.setCenter = function (center) {
36304 this._state.setCenter(center);
36306 StateContext.prototype.setZoom = function (zoom) {
36307 this._state.setZoom(zoom);
36309 StateContext.prototype.update = function (fps) {
36310 this._state.update(fps);
36312 StateContext.prototype.append = function (nodes) {
36313 this._state.append(nodes);
36315 StateContext.prototype.prepend = function (nodes) {
36316 this._state.prepend(nodes);
36318 StateContext.prototype.remove = function (n) {
36319 this._state.remove(n);
36321 StateContext.prototype.clear = function () {
36322 this._state.clear();
36324 StateContext.prototype.clearPrior = function () {
36325 this._state.clearPrior();
36327 StateContext.prototype.cut = function () {
36330 StateContext.prototype.set = function (nodes) {
36331 this._state.set(nodes);
36333 StateContext.prototype.rotate = function (delta) {
36334 this._state.rotate(delta);
36336 StateContext.prototype.rotateBasic = function (basicRotation) {
36337 this._state.rotateBasic(basicRotation);
36339 StateContext.prototype.rotateBasicUnbounded = function (basicRotation) {
36340 this._state.rotateBasicUnbounded(basicRotation);
36342 StateContext.prototype.rotateToBasic = function (basic) {
36343 this._state.rotateToBasic(basic);
36345 StateContext.prototype.move = function (delta) {
36346 this._state.move(delta);
36348 StateContext.prototype.moveTo = function (delta) {
36349 this._state.moveTo(delta);
36351 StateContext.prototype.zoomIn = function (delta, reference) {
36352 this._state.zoomIn(delta, reference);
36354 return StateContext;
36356 exports.StateContext = StateContext;
36358 },{"../Geo":229,"../State":233}],332:[function(require,module,exports){
36360 Object.defineProperty(exports, "__esModule", { value: true });
36361 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
36362 var Subject_1 = require("rxjs/Subject");
36363 var AnimationFrame_1 = require("rxjs/util/AnimationFrame");
36364 require("rxjs/add/operator/bufferCount");
36365 require("rxjs/add/operator/distinctUntilChanged");
36366 require("rxjs/add/operator/do");
36367 require("rxjs/add/operator/filter");
36368 require("rxjs/add/operator/first");
36369 require("rxjs/add/operator/map");
36370 require("rxjs/add/operator/pairwise");
36371 require("rxjs/add/operator/publishReplay");
36372 require("rxjs/add/operator/scan");
36373 require("rxjs/add/operator/startWith");
36374 require("rxjs/add/operator/switchMap");
36375 require("rxjs/add/operator/withLatestFrom");
36376 var State_1 = require("../State");
36377 var StateService = (function () {
36378 function StateService() {
36380 this._appendNode$ = new Subject_1.Subject();
36381 this._start$ = new Subject_1.Subject();
36382 this._frame$ = new Subject_1.Subject();
36383 this._fpsSampleRate = 30;
36384 this._contextOperation$ = new BehaviorSubject_1.BehaviorSubject(function (context) {
36387 this._context$ = this._contextOperation$
36388 .scan(function (context, operation) {
36389 return operation(context);
36390 }, new State_1.StateContext())
36393 this._state$ = this._context$
36394 .map(function (context) {
36395 return context.state;
36397 .distinctUntilChanged()
36400 this._fps$ = this._start$
36401 .switchMap(function () {
36402 return _this._frame$
36403 .bufferCount(1, _this._fpsSampleRate)
36404 .map(function (frameIds) {
36405 return new Date().getTime();
36408 .map(function (times) {
36409 return Math.max(20, 1000 * _this._fpsSampleRate / (times[1] - times[0]));
36414 this._currentState$ = this._frame$
36415 .withLatestFrom(this._fps$, this._context$, function (frameId, fps, context) {
36416 return [frameId, fps, context];
36418 .filter(function (fc) {
36419 return fc[2].currentNode != null;
36421 .do(function (fc) {
36422 fc[2].update(fc[1]);
36424 .map(function (fc) {
36425 return { fps: fc[1], id: fc[0], state: fc[2] };
36428 this._lastState$ = this._currentState$
36431 var nodeChanged$ = this._currentState$
36432 .distinctUntilChanged(undefined, function (f) {
36433 return f.state.currentNode.key;
36437 var nodeChangedSubject$ = new Subject_1.Subject();
36439 .subscribe(nodeChangedSubject$);
36440 this._currentKey$ = new BehaviorSubject_1.BehaviorSubject(null);
36441 nodeChangedSubject$
36442 .map(function (f) {
36443 return f.state.currentNode.key;
36445 .subscribe(this._currentKey$);
36446 this._currentNode$ = nodeChangedSubject$
36447 .map(function (f) {
36448 return f.state.currentNode;
36452 this._currentCamera$ = nodeChangedSubject$
36453 .map(function (f) {
36454 return f.state.currentCamera;
36458 this._currentTransform$ = nodeChangedSubject$
36459 .map(function (f) {
36460 return f.state.currentTransform;
36464 this._reference$ = nodeChangedSubject$
36465 .map(function (f) {
36466 return f.state.reference;
36468 .distinctUntilChanged(function (r1, r2) {
36469 return r1.lat === r2.lat && r1.lon === r2.lon;
36470 }, function (reference) {
36471 return { lat: reference.lat, lon: reference.lon };
36475 this._currentNodeExternal$ = nodeChanged$
36476 .map(function (f) {
36477 return f.state.currentNode;
36482 .map(function (node) {
36483 return function (context) {
36484 context.append([node]);
36488 .subscribe(this._contextOperation$);
36489 this._inMotionOperation$ = new Subject_1.Subject();
36491 .map(function (frame) {
36494 .subscribe(this._inMotionOperation$);
36495 this._inMotionOperation$
36496 .distinctUntilChanged()
36497 .filter(function (moving) {
36500 .switchMap(function (moving) {
36501 return _this._currentState$
36502 .filter(function (frame) {
36503 return frame.state.nodesAhead === 0;
36505 .map(function (frame) {
36506 return [frame.state.camera.clone(), frame.state.zoom];
36509 .map(function (pair) {
36510 var c1 = pair[0][0];
36511 var c2 = pair[1][0];
36512 var z1 = pair[0][1];
36513 var z2 = pair[1][1];
36514 return c1.diff(c2) > 1e-5 || Math.abs(z1 - z2) > 1e-5;
36516 .first(function (changed) {
36520 .subscribe(this._inMotionOperation$);
36521 this._inMotion$ = this._inMotionOperation$
36522 .distinctUntilChanged()
36525 this._inTranslationOperation$ = new Subject_1.Subject();
36527 .map(function (frame) {
36530 .subscribe(this._inTranslationOperation$);
36531 this._inTranslationOperation$
36532 .distinctUntilChanged()
36533 .filter(function (inTranslation) {
36534 return inTranslation;
36536 .switchMap(function (inTranslation) {
36537 return _this._currentState$
36538 .filter(function (frame) {
36539 return frame.state.nodesAhead === 0;
36541 .map(function (frame) {
36542 return frame.state.camera.position.clone();
36545 .map(function (pair) {
36546 return pair[0].distanceToSquared(pair[1]) !== 0;
36548 .first(function (changed) {
36552 .subscribe(this._inTranslationOperation$);
36553 this._inTranslation$ = this._inTranslationOperation$
36554 .distinctUntilChanged()
36557 this._state$.subscribe(function () { });
36558 this._currentNode$.subscribe(function () { });
36559 this._currentCamera$.subscribe(function () { });
36560 this._currentTransform$.subscribe(function () { });
36561 this._reference$.subscribe(function () { });
36562 this._currentNodeExternal$.subscribe(function () { });
36563 this._lastState$.subscribe(function () { });
36564 this._inMotion$.subscribe(function () { });
36565 this._inTranslation$.subscribe(function () { });
36566 this._frameId = null;
36567 this._frameGenerator = new AnimationFrame_1.RequestAnimationFrameDefinition(window);
36569 Object.defineProperty(StateService.prototype, "currentState$", {
36571 return this._currentState$;
36576 Object.defineProperty(StateService.prototype, "currentNode$", {
36578 return this._currentNode$;
36583 Object.defineProperty(StateService.prototype, "currentKey$", {
36585 return this._currentKey$;
36590 Object.defineProperty(StateService.prototype, "currentNodeExternal$", {
36592 return this._currentNodeExternal$;
36597 Object.defineProperty(StateService.prototype, "currentCamera$", {
36599 return this._currentCamera$;
36604 Object.defineProperty(StateService.prototype, "currentTransform$", {
36606 return this._currentTransform$;
36611 Object.defineProperty(StateService.prototype, "state$", {
36613 return this._state$;
36618 Object.defineProperty(StateService.prototype, "reference$", {
36620 return this._reference$;
36625 Object.defineProperty(StateService.prototype, "inMotion$", {
36627 return this._inMotion$;
36632 Object.defineProperty(StateService.prototype, "inTranslation$", {
36634 return this._inTranslation$;
36639 Object.defineProperty(StateService.prototype, "appendNode$", {
36641 return this._appendNode$;
36646 StateService.prototype.traverse = function () {
36647 this._inMotionOperation$.next(true);
36648 this._invokeContextOperation(function (context) { context.traverse(); });
36650 StateService.prototype.wait = function () {
36651 this._invokeContextOperation(function (context) { context.wait(); });
36653 StateService.prototype.appendNodes = function (nodes) {
36654 this._invokeContextOperation(function (context) { context.append(nodes); });
36656 StateService.prototype.prependNodes = function (nodes) {
36657 this._invokeContextOperation(function (context) { context.prepend(nodes); });
36659 StateService.prototype.removeNodes = function (n) {
36660 this._invokeContextOperation(function (context) { context.remove(n); });
36662 StateService.prototype.clearNodes = function () {
36663 this._invokeContextOperation(function (context) { context.clear(); });
36665 StateService.prototype.clearPriorNodes = function () {
36666 this._invokeContextOperation(function (context) { context.clearPrior(); });
36668 StateService.prototype.cutNodes = function () {
36669 this._invokeContextOperation(function (context) { context.cut(); });
36671 StateService.prototype.setNodes = function (nodes) {
36672 this._invokeContextOperation(function (context) { context.set(nodes); });
36674 StateService.prototype.rotate = function (delta) {
36675 this._inMotionOperation$.next(true);
36676 this._invokeContextOperation(function (context) { context.rotate(delta); });
36678 StateService.prototype.rotateBasic = function (basicRotation) {
36679 this._inMotionOperation$.next(true);
36680 this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); });
36682 StateService.prototype.rotateBasicUnbounded = function (basicRotation) {
36683 this._inMotionOperation$.next(true);
36684 this._invokeContextOperation(function (context) { context.rotateBasicUnbounded(basicRotation); });
36686 StateService.prototype.rotateToBasic = function (basic) {
36687 this._inMotionOperation$.next(true);
36688 this._invokeContextOperation(function (context) { context.rotateToBasic(basic); });
36690 StateService.prototype.move = function (delta) {
36691 this._inMotionOperation$.next(true);
36692 this._invokeContextOperation(function (context) { context.move(delta); });
36694 StateService.prototype.moveTo = function (position) {
36695 this._inMotionOperation$.next(true);
36696 this._invokeContextOperation(function (context) { context.moveTo(position); });
36699 * Change zoom level while keeping the reference point position approximately static.
36701 * @parameter {number} delta - Change in zoom level.
36702 * @parameter {Array<number>} reference - Reference point in basic coordinates.
36704 StateService.prototype.zoomIn = function (delta, reference) {
36705 this._inMotionOperation$.next(true);
36706 this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); });
36708 StateService.prototype.getCenter = function () {
36709 return this._lastState$
36711 .map(function (frame) {
36712 return frame.state.getCenter();
36715 StateService.prototype.getZoom = function () {
36716 return this._lastState$
36718 .map(function (frame) {
36719 return frame.state.zoom;
36722 StateService.prototype.setCenter = function (center) {
36723 this._inMotionOperation$.next(true);
36724 this._invokeContextOperation(function (context) { context.setCenter(center); });
36726 StateService.prototype.setZoom = function (zoom) {
36727 this._inMotionOperation$.next(true);
36728 this._invokeContextOperation(function (context) { context.setZoom(zoom); });
36730 StateService.prototype.start = function () {
36731 if (this._frameId == null) {
36732 this._start$.next(null);
36733 this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
36734 this._frame$.next(this._frameId);
36737 StateService.prototype.stop = function () {
36738 if (this._frameId != null) {
36739 this._frameGenerator.cancelAnimationFrame(this._frameId);
36740 this._frameId = null;
36743 StateService.prototype._invokeContextOperation = function (action) {
36744 this._contextOperation$
36745 .next(function (context) {
36750 StateService.prototype._frame = function (time) {
36751 this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
36752 this._frame$.next(this._frameId);
36754 return StateService;
36756 exports.StateService = StateService;
36758 },{"../State":233,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/add/operator/bufferCount":50,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/do":59,"rxjs/add/operator/filter":61,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/pairwise":69,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73,"rxjs/add/operator/startWith":78,"rxjs/add/operator/switchMap":79,"rxjs/add/operator/withLatestFrom":83,"rxjs/util/AnimationFrame":157}],333:[function(require,module,exports){
36760 /// <reference path="../../../typings/index.d.ts" />
36761 Object.defineProperty(exports, "__esModule", { value: true });
36762 var Error_1 = require("../../Error");
36763 var Geo_1 = require("../../Geo");
36764 var StateBase = (function () {
36765 function StateBase(state) {
36766 this._spatial = new Geo_1.Spatial();
36767 this._geoCoords = new Geo_1.GeoCoords();
36768 this._referenceThreshold = 0.01;
36769 this._reference = state.reference;
36770 this._alpha = state.alpha;
36771 this._camera = state.camera.clone();
36772 this._zoom = state.zoom;
36773 this._currentIndex = state.currentIndex;
36774 this._trajectory = state.trajectory.slice();
36775 this._trajectoryTransforms = [];
36776 this._trajectoryCameras = [];
36777 for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) {
36779 var translation = this._nodeToTranslation(node);
36780 var transform = new Geo_1.Transform(node, node.image, translation);
36781 this._trajectoryTransforms.push(transform);
36782 this._trajectoryCameras.push(new Geo_1.Camera(transform));
36784 this._currentNode = this._trajectory.length > 0 ?
36785 this._trajectory[this._currentIndex] :
36787 this._previousNode = this._trajectory.length > 1 && this.currentIndex > 0 ?
36788 this._trajectory[this._currentIndex - 1] :
36790 this._currentCamera = this._trajectoryCameras.length > 0 ?
36791 this._trajectoryCameras[this._currentIndex].clone() :
36792 new Geo_1.Camera();
36793 this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
36794 this._trajectoryCameras[this._currentIndex - 1].clone() :
36795 this._currentCamera.clone();
36797 Object.defineProperty(StateBase.prototype, "reference", {
36799 return this._reference;
36804 Object.defineProperty(StateBase.prototype, "alpha", {
36806 return this._getAlpha();
36811 Object.defineProperty(StateBase.prototype, "camera", {
36813 return this._camera;
36818 Object.defineProperty(StateBase.prototype, "zoom", {
36825 Object.defineProperty(StateBase.prototype, "trajectory", {
36827 return this._trajectory;
36832 Object.defineProperty(StateBase.prototype, "currentIndex", {
36834 return this._currentIndex;
36839 Object.defineProperty(StateBase.prototype, "currentNode", {
36841 return this._currentNode;
36846 Object.defineProperty(StateBase.prototype, "previousNode", {
36848 return this._previousNode;
36853 Object.defineProperty(StateBase.prototype, "currentCamera", {
36855 return this._currentCamera;
36860 Object.defineProperty(StateBase.prototype, "currentTransform", {
36862 return this._trajectoryTransforms.length > 0 ?
36863 this._trajectoryTransforms[this.currentIndex] : null;
36868 Object.defineProperty(StateBase.prototype, "previousTransform", {
36870 return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
36871 this._trajectoryTransforms[this.currentIndex - 1] : null;
36876 Object.defineProperty(StateBase.prototype, "motionless", {
36878 return this._motionless;
36883 StateBase.prototype.append = function (nodes) {
36884 if (nodes.length < 1) {
36885 throw Error("Trajectory can not be empty");
36887 if (this._currentIndex < 0) {
36891 this._trajectory = this._trajectory.concat(nodes);
36892 this._appendToTrajectories(nodes);
36895 StateBase.prototype.prepend = function (nodes) {
36896 if (nodes.length < 1) {
36897 throw Error("Trajectory can not be empty");
36899 this._trajectory = nodes.slice().concat(this._trajectory);
36900 this._currentIndex += nodes.length;
36901 this._setCurrentNode();
36902 var referenceReset = this._setReference(this._currentNode);
36903 if (referenceReset) {
36904 this._setTrajectories();
36907 this._prependToTrajectories(nodes);
36909 this._setCurrentCamera();
36911 StateBase.prototype.remove = function (n) {
36913 throw Error("n must be a positive integer");
36915 if (this._currentIndex - 1 < n) {
36916 throw Error("Current and previous nodes can not be removed");
36918 for (var i = 0; i < n; i++) {
36919 this._trajectory.shift();
36920 this._trajectoryTransforms.shift();
36921 this._trajectoryCameras.shift();
36922 this._currentIndex--;
36924 this._setCurrentNode();
36926 StateBase.prototype.clearPrior = function () {
36927 if (this._currentIndex > 0) {
36928 this.remove(this._currentIndex - 1);
36931 StateBase.prototype.clear = function () {
36933 if (this._currentIndex > 0) {
36934 this.remove(this._currentIndex - 1);
36937 StateBase.prototype.cut = function () {
36938 while (this._trajectory.length - 1 > this._currentIndex) {
36939 this._trajectory.pop();
36940 this._trajectoryTransforms.pop();
36941 this._trajectoryCameras.pop();
36944 StateBase.prototype.set = function (nodes) {
36945 this._setTrajectory(nodes);
36946 this._setCurrentNode();
36947 this._setReference(this._currentNode);
36948 this._setTrajectories();
36949 this._setCurrentCamera();
36951 StateBase.prototype.getCenter = function () {
36952 return this._currentNode != null ?
36953 this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
36956 StateBase.prototype._setCurrent = function () {
36957 this._setCurrentNode();
36958 var referenceReset = this._setReference(this._currentNode);
36959 if (referenceReset) {
36960 this._setTrajectories();
36962 this._setCurrentCamera();
36964 StateBase.prototype._setCurrentCamera = function () {
36965 this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
36966 this._previousCamera = this._currentIndex > 0 ?
36967 this._trajectoryCameras[this._currentIndex - 1].clone() :
36968 this._currentCamera.clone();
36970 StateBase.prototype._motionlessTransition = function () {
36971 var nodesSet = this._currentNode != null && this._previousNode != null;
36972 return nodesSet && !(this._currentNode.merged &&
36973 this._previousNode.merged &&
36974 this._withinOriginalDistance() &&
36975 this._sameConnectedComponent());
36977 StateBase.prototype._setReference = function (node) {
36978 // do not reset reference if node is within threshold distance
36979 if (Math.abs(node.latLon.lat - this.reference.lat) < this._referenceThreshold &&
36980 Math.abs(node.latLon.lon - this.reference.lon) < this._referenceThreshold) {
36983 // do not reset reference if previous node exist and transition is with motion
36984 if (this._previousNode != null && !this._motionlessTransition()) {
36987 this._reference.lat = node.latLon.lat;
36988 this._reference.lon = node.latLon.lon;
36989 this._reference.alt = node.alt;
36992 StateBase.prototype._setCurrentNode = function () {
36993 this._currentNode = this._trajectory.length > 0 ?
36994 this._trajectory[this._currentIndex] :
36996 this._previousNode = this._currentIndex > 0 ?
36997 this._trajectory[this._currentIndex - 1] :
37000 StateBase.prototype._setTrajectory = function (nodes) {
37001 if (nodes.length < 1) {
37002 throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty");
37004 if (this._currentNode != null) {
37005 this._trajectory = [this._currentNode].concat(nodes);
37006 this._currentIndex = 1;
37009 this._trajectory = nodes.slice();
37010 this._currentIndex = 0;
37013 StateBase.prototype._setTrajectories = function () {
37014 this._trajectoryTransforms.length = 0;
37015 this._trajectoryCameras.length = 0;
37016 this._appendToTrajectories(this._trajectory);
37018 StateBase.prototype._appendToTrajectories = function (nodes) {
37019 for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
37020 var node = nodes_1[_i];
37021 if (!node.assetsCached) {
37022 throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory");
37024 var translation = this._nodeToTranslation(node);
37025 var transform = new Geo_1.Transform(node, node.image, translation);
37026 this._trajectoryTransforms.push(transform);
37027 this._trajectoryCameras.push(new Geo_1.Camera(transform));
37030 StateBase.prototype._prependToTrajectories = function (nodes) {
37031 for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) {
37033 if (!node.assetsCached) {
37034 throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory");
37036 var translation = this._nodeToTranslation(node);
37037 var transform = new Geo_1.Transform(node, node.image, translation);
37038 this._trajectoryTransforms.unshift(transform);
37039 this._trajectoryCameras.unshift(new Geo_1.Camera(transform));
37042 StateBase.prototype._nodeToTranslation = function (node) {
37043 var C = this._geoCoords.geodeticToEnu(node.latLon.lat, node.latLon.lon, node.alt, this._reference.lat, this._reference.lon, this._reference.alt);
37044 var RC = this._spatial.rotate(C, node.rotation);
37045 return [-RC.x, -RC.y, -RC.z];
37047 StateBase.prototype._sameConnectedComponent = function () {
37048 var current = this._currentNode;
37049 var previous = this._previousNode;
37051 !current.mergeCC ||
37053 !previous.mergeCC) {
37056 return current.mergeCC === previous.mergeCC;
37058 StateBase.prototype._withinOriginalDistance = function () {
37059 var current = this._currentNode;
37060 var previous = this._previousNode;
37061 if (!current || !previous) {
37064 // 50 km/h moves 28m in 2s
37065 var distance = this._spatial.distanceFromLatLon(current.originalLatLon.lat, current.originalLatLon.lon, previous.originalLatLon.lat, previous.originalLatLon.lon);
37066 return distance < 25;
37070 exports.StateBase = StateBase;
37072 },{"../../Error":228,"../../Geo":229}],334:[function(require,module,exports){
37074 /// <reference path="../../../typings/index.d.ts" />
37075 var __extends = (this && this.__extends) || (function () {
37076 var extendStatics = Object.setPrototypeOf ||
37077 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
37078 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
37079 return function (d, b) {
37080 extendStatics(d, b);
37081 function __() { this.constructor = d; }
37082 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
37085 Object.defineProperty(exports, "__esModule", { value: true });
37086 var THREE = require("three");
37087 var UnitBezier = require("@mapbox/unitbezier");
37088 var State_1 = require("../../State");
37089 var RotationDelta = (function () {
37090 function RotationDelta(phi, theta) {
37092 this._theta = theta;
37094 Object.defineProperty(RotationDelta.prototype, "phi", {
37098 set: function (value) {
37104 Object.defineProperty(RotationDelta.prototype, "theta", {
37106 return this._theta;
37108 set: function (value) {
37109 this._theta = value;
37114 Object.defineProperty(RotationDelta.prototype, "isZero", {
37116 return this._phi === 0 && this._theta === 0;
37121 RotationDelta.prototype.copy = function (delta) {
37122 this._phi = delta.phi;
37123 this._theta = delta.theta;
37125 RotationDelta.prototype.lerp = function (other, alpha) {
37126 this._phi = (1 - alpha) * this._phi + alpha * other.phi;
37127 this._theta = (1 - alpha) * this._theta + alpha * other.theta;
37129 RotationDelta.prototype.multiply = function (value) {
37130 this._phi *= value;
37131 this._theta *= value;
37133 RotationDelta.prototype.threshold = function (value) {
37134 this._phi = Math.abs(this._phi) > value ? this._phi : 0;
37135 this._theta = Math.abs(this._theta) > value ? this._theta : 0;
37137 RotationDelta.prototype.lengthSquared = function () {
37138 return this._phi * this._phi + this._theta * this._theta;
37140 RotationDelta.prototype.reset = function () {
37144 return RotationDelta;
37146 var TraversingState = (function (_super) {
37147 __extends(TraversingState, _super);
37148 function TraversingState(state) {
37149 var _this = _super.call(this, state) || this;
37150 _this._adjustCameras();
37151 _this._motionless = _this._motionlessTransition();
37152 _this._baseAlpha = _this._alpha;
37153 _this._animationSpeed = 0.025;
37154 _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
37155 _this._useBezier = false;
37156 _this._rotationDelta = new RotationDelta(0, 0);
37157 _this._requestedRotationDelta = null;
37158 _this._basicRotation = [0, 0];
37159 _this._requestedBasicRotation = null;
37160 _this._requestedBasicRotationUnbounded = null;
37161 _this._rotationAcceleration = 0.86;
37162 _this._rotationIncreaseAlpha = 0.97;
37163 _this._rotationDecreaseAlpha = 0.9;
37164 _this._rotationThreshold = 1e-3;
37165 _this._unboundedRotationAlpha = 0.8;
37166 _this._desiredZoom = state.zoom;
37167 _this._minZoom = 0;
37168 _this._maxZoom = 3;
37169 _this._lookatDepth = 10;
37170 _this._desiredLookat = null;
37171 _this._desiredCenter = null;
37174 TraversingState.prototype.traverse = function () {
37175 throw new Error("Not implemented");
37177 TraversingState.prototype.wait = function () {
37178 return new State_1.WaitingState(this);
37180 TraversingState.prototype.append = function (nodes) {
37181 var emptyTrajectory = this._trajectory.length === 0;
37182 if (emptyTrajectory) {
37183 this._resetTransition();
37185 _super.prototype.append.call(this, nodes);
37186 if (emptyTrajectory) {
37187 this._setDesiredCenter();
37188 this._setDesiredZoom();
37191 TraversingState.prototype.prepend = function (nodes) {
37192 var emptyTrajectory = this._trajectory.length === 0;
37193 if (emptyTrajectory) {
37194 this._resetTransition();
37196 _super.prototype.prepend.call(this, nodes);
37197 if (emptyTrajectory) {
37198 this._setDesiredCenter();
37199 this._setDesiredZoom();
37202 TraversingState.prototype.set = function (nodes) {
37203 _super.prototype.set.call(this, nodes);
37204 this._desiredLookat = null;
37205 this._resetTransition();
37206 this._clearRotation();
37207 this._setDesiredCenter();
37208 this._setDesiredZoom();
37209 if (this._trajectory.length < 3) {
37210 this._useBezier = true;
37213 TraversingState.prototype.move = function (delta) {
37214 throw new Error("Not implemented");
37216 TraversingState.prototype.moveTo = function (delta) {
37217 throw new Error("Not implemented");
37219 TraversingState.prototype.rotate = function (rotationDelta) {
37220 if (this._currentNode == null) {
37223 this._desiredZoom = this._zoom;
37224 this._desiredLookat = null;
37225 this._requestedBasicRotation = null;
37226 if (this._requestedRotationDelta != null) {
37227 this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi;
37228 this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta;
37231 this._requestedRotationDelta = new RotationDelta(rotationDelta.phi, rotationDelta.theta);
37234 TraversingState.prototype.rotateBasic = function (basicRotation) {
37235 if (this._currentNode == null) {
37238 this._desiredZoom = this._zoom;
37239 this._desiredLookat = null;
37240 this._requestedRotationDelta = null;
37241 if (this._requestedBasicRotation != null) {
37242 this._requestedBasicRotation[0] += basicRotation[0];
37243 this._requestedBasicRotation[1] += basicRotation[1];
37244 var threshold = 0.05 / Math.pow(2, this._zoom);
37245 this._requestedBasicRotation[0] =
37246 this._spatial.clamp(this._requestedBasicRotation[0], -threshold, threshold);
37247 this._requestedBasicRotation[1] =
37248 this._spatial.clamp(this._requestedBasicRotation[1], -threshold, threshold);
37251 this._requestedBasicRotation = basicRotation.slice();
37254 TraversingState.prototype.rotateBasicUnbounded = function (basicRotation) {
37255 if (this._currentNode == null) {
37258 if (this._requestedBasicRotationUnbounded != null) {
37259 this._requestedBasicRotationUnbounded[0] += basicRotation[0];
37260 this._requestedBasicRotationUnbounded[1] += basicRotation[1];
37263 this._requestedBasicRotationUnbounded = basicRotation.slice();
37266 TraversingState.prototype.rotateToBasic = function (basic) {
37267 if (this._currentNode == null) {
37270 this._desiredZoom = this._zoom;
37271 this._desiredLookat = null;
37272 basic[0] = this._spatial.clamp(basic[0], 0, 1);
37273 basic[1] = this._spatial.clamp(basic[1], 0, 1);
37274 var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth);
37275 this._currentCamera.lookat.fromArray(lookat);
37277 TraversingState.prototype.zoomIn = function (delta, reference) {
37278 if (this._currentNode == null) {
37281 this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta));
37282 var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray());
37283 var currentCenterX = currentCenter[0];
37284 var currentCenterY = currentCenter[1];
37285 var zoom0 = Math.pow(2, this._zoom);
37286 var zoom1 = Math.pow(2, this._desiredZoom);
37287 var refX = reference[0];
37288 var refY = reference[1];
37289 if (this.currentTransform.gpano != null &&
37290 this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
37291 if (refX - currentCenterX > 0.5) {
37294 else if (currentCenterX - refX > 0.5) {
37298 var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX);
37299 var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY);
37300 var gpano = this.currentTransform.gpano;
37301 if (this._currentNode.fullPano) {
37302 newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
37303 newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95);
37305 else if (gpano != null &&
37306 this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
37307 newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
37308 newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1);
37311 newCenterX = this._spatial.clamp(newCenterX, 0, 1);
37312 newCenterY = this._spatial.clamp(newCenterY, 0, 1);
37314 this._desiredLookat = new THREE.Vector3()
37315 .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth));
37317 TraversingState.prototype.setCenter = function (center) {
37318 this._desiredLookat = null;
37319 this._requestedRotationDelta = null;
37320 this._requestedBasicRotation = null;
37321 this._desiredZoom = this._zoom;
37323 this._spatial.clamp(center[0], 0, 1),
37324 this._spatial.clamp(center[1], 0, 1),
37326 if (this._currentNode == null) {
37327 this._desiredCenter = clamped;
37330 this._desiredCenter = null;
37331 var currentLookat = new THREE.Vector3()
37332 .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth));
37333 var previousTransform = this.previousTransform != null ?
37334 this.previousTransform :
37335 this.currentTransform;
37336 var previousLookat = new THREE.Vector3()
37337 .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth));
37338 this._currentCamera.lookat.copy(currentLookat);
37339 this._previousCamera.lookat.copy(previousLookat);
37341 TraversingState.prototype.setZoom = function (zoom) {
37342 this._desiredLookat = null;
37343 this._requestedRotationDelta = null;
37344 this._requestedBasicRotation = null;
37345 this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom);
37346 this._desiredZoom = this._zoom;
37348 TraversingState.prototype.update = function (fps) {
37349 if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) {
37350 this._currentIndex += 1;
37351 this._useBezier = this._trajectory.length < 3 &&
37352 this._currentIndex + 1 === this._trajectory.length;
37353 this._setCurrent();
37354 this._resetTransition();
37355 this._clearRotation();
37356 this._desiredZoom = this._currentNode.fullPano ? this._zoom : 0;
37357 this._desiredLookat = null;
37359 var animationSpeed = this._animationSpeed * (60 / fps);
37360 this._baseAlpha = Math.min(1, this._baseAlpha + animationSpeed);
37361 if (this._useBezier) {
37362 this._alpha = this._unitBezier.solve(this._baseAlpha);
37365 this._alpha = this._baseAlpha;
37367 this._updateRotation();
37368 if (!this._rotationDelta.isZero) {
37369 this._applyRotation(this._previousCamera);
37370 this._applyRotation(this._currentCamera);
37372 this._updateRotationBasic();
37373 if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
37374 this._applyRotationBasic();
37376 this._updateZoom(animationSpeed);
37377 this._updateLookat(animationSpeed);
37378 this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
37380 TraversingState.prototype._getAlpha = function () {
37381 return this._motionless ? Math.ceil(this._alpha) : this._alpha;
37383 TraversingState.prototype._setCurrentCamera = function () {
37384 _super.prototype._setCurrentCamera.call(this);
37385 this._adjustCameras();
37387 TraversingState.prototype._adjustCameras = function () {
37388 if (this._previousNode == null) {
37391 var lookat = this._camera.lookat.clone().sub(this._camera.position);
37392 this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
37393 if (this._currentNode.fullPano) {
37394 this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
37397 TraversingState.prototype._resetTransition = function () {
37399 this._baseAlpha = 0;
37400 this._motionless = this._motionlessTransition();
37402 TraversingState.prototype._applyRotation = function (camera) {
37403 if (camera == null) {
37406 var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
37407 var qInverse = q.clone().inverse();
37408 var offset = new THREE.Vector3();
37409 offset.copy(camera.lookat).sub(camera.position);
37410 offset.applyQuaternion(q);
37411 var length = offset.length();
37412 var phi = Math.atan2(offset.y, offset.x);
37413 phi += this._rotationDelta.phi;
37414 var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
37415 theta += this._rotationDelta.theta;
37416 theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
37417 offset.x = Math.sin(theta) * Math.cos(phi);
37418 offset.y = Math.sin(theta) * Math.sin(phi);
37419 offset.z = Math.cos(theta);
37420 offset.applyQuaternion(qInverse);
37421 camera.lookat.copy(camera.position).add(offset.multiplyScalar(length));
37423 TraversingState.prototype._applyRotationBasic = function () {
37424 var currentNode = this._currentNode;
37425 var previousNode = this._previousNode != null ?
37426 this.previousNode :
37428 var currentCamera = this._currentCamera;
37429 var previousCamera = this._previousCamera;
37430 var currentTransform = this.currentTransform;
37431 var previousTransform = this.previousTransform != null ?
37432 this.previousTransform :
37433 this.currentTransform;
37434 var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray());
37435 var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray());
37436 var currentGPano = currentTransform.gpano;
37437 var previousGPano = previousTransform.gpano;
37438 if (currentNode.fullPano) {
37439 currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1);
37440 currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0.05, 0.95);
37442 else if (currentGPano != null &&
37443 currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) {
37444 currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1);
37445 currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
37448 currentBasic[0] = this._spatial.clamp(currentBasic[0] + this._basicRotation[0], 0, 1);
37449 currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
37451 if (previousNode.fullPano) {
37452 previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1);
37453 previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0.05, 0.95);
37455 else if (previousGPano != null &&
37456 previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) {
37457 previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1);
37458 previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0, 1);
37461 previousBasic[0] = this._spatial.clamp(previousBasic[0] + this._basicRotation[0], 0, 1);
37462 previousBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
37464 var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth);
37465 currentCamera.lookat.fromArray(currentLookat);
37466 var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth);
37467 previousCamera.lookat.fromArray(previousLookat);
37469 TraversingState.prototype._updateZoom = function (animationSpeed) {
37470 var diff = this._desiredZoom - this._zoom;
37471 var sign = diff > 0 ? 1 : diff < 0 ? -1 : 0;
37475 else if (Math.abs(diff) < 2e-3) {
37476 this._zoom = this._desiredZoom;
37477 if (this._desiredLookat != null) {
37478 this._desiredLookat = null;
37482 this._zoom += sign * Math.max(Math.abs(5 * animationSpeed * diff), 2e-3);
37485 TraversingState.prototype._updateLookat = function (animationSpeed) {
37486 if (this._desiredLookat === null) {
37489 var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat);
37490 if (Math.abs(diff) < 1e-6) {
37491 this._currentCamera.lookat.copy(this._desiredLookat);
37492 this._desiredLookat = null;
37495 this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed);
37498 TraversingState.prototype._updateRotation = function () {
37499 if (this._requestedRotationDelta != null) {
37500 var length_1 = this._rotationDelta.lengthSquared();
37501 var requestedLength = this._requestedRotationDelta.lengthSquared();
37502 if (requestedLength > length_1) {
37503 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha);
37506 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha);
37508 this._requestedRotationDelta = null;
37511 if (this._rotationDelta.isZero) {
37514 this._rotationDelta.multiply(this._rotationAcceleration);
37515 this._rotationDelta.threshold(this._rotationThreshold);
37517 TraversingState.prototype._updateRotationBasic = function () {
37518 if (this._requestedBasicRotation != null) {
37519 var x = this._basicRotation[0];
37520 var y = this._basicRotation[1];
37521 var reqX = this._requestedBasicRotation[0];
37522 var reqY = this._requestedBasicRotation[1];
37523 if (Math.abs(reqX) > Math.abs(x)) {
37524 this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX;
37527 this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX;
37529 if (Math.abs(reqY) > Math.abs(y)) {
37530 this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY;
37533 this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY;
37535 this._requestedBasicRotation = null;
37538 if (this._requestedBasicRotationUnbounded != null) {
37539 var reqX = this._requestedBasicRotationUnbounded[0];
37540 var reqY = this._requestedBasicRotationUnbounded[1];
37541 if (Math.abs(reqX) > 0) {
37542 this._basicRotation[0] = (1 - this._unboundedRotationAlpha) * this._basicRotation[0] + this._unboundedRotationAlpha * reqX;
37544 if (Math.abs(reqY) > 0) {
37545 this._basicRotation[1] = (1 - this._unboundedRotationAlpha) * this._basicRotation[1] + this._unboundedRotationAlpha * reqY;
37547 if (this._desiredLookat != null) {
37548 var desiredBasicLookat = this.currentTransform.projectBasic(this._desiredLookat.toArray());
37549 desiredBasicLookat[0] += reqX;
37550 desiredBasicLookat[1] += reqY;
37551 this._desiredLookat = new THREE.Vector3()
37552 .fromArray(this.currentTransform.unprojectBasic(desiredBasicLookat, this._lookatDepth));
37554 this._requestedBasicRotationUnbounded = null;
37556 if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) {
37559 this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0];
37560 this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1];
37561 if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) &&
37562 Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) {
37563 this._basicRotation = [0, 0];
37566 TraversingState.prototype._clearRotation = function () {
37567 if (this._currentNode.fullPano) {
37570 if (this._requestedRotationDelta != null) {
37571 this._requestedRotationDelta = null;
37573 if (!this._rotationDelta.isZero) {
37574 this._rotationDelta.reset();
37576 if (this._requestedBasicRotation != null) {
37577 this._requestedBasicRotation = null;
37579 if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) {
37580 this._basicRotation = [0, 0];
37583 TraversingState.prototype._setDesiredCenter = function () {
37584 if (this._desiredCenter == null) {
37587 var lookatDirection = new THREE.Vector3()
37588 .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth))
37589 .sub(this._currentCamera.position);
37590 this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection));
37591 this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection));
37592 this._desiredCenter = null;
37594 TraversingState.prototype._setDesiredZoom = function () {
37595 this._desiredZoom =
37596 this._currentNode.fullPano || this._previousNode == null ?
37599 return TraversingState;
37600 }(State_1.StateBase));
37601 exports.TraversingState = TraversingState;
37603 },{"../../State":233,"@mapbox/unitbezier":2,"three":176}],335:[function(require,module,exports){
37605 var __extends = (this && this.__extends) || (function () {
37606 var extendStatics = Object.setPrototypeOf ||
37607 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
37608 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
37609 return function (d, b) {
37610 extendStatics(d, b);
37611 function __() { this.constructor = d; }
37612 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
37615 Object.defineProperty(exports, "__esModule", { value: true });
37616 var State_1 = require("../../State");
37617 var WaitingState = (function (_super) {
37618 __extends(WaitingState, _super);
37619 function WaitingState(state) {
37620 var _this = _super.call(this, state) || this;
37621 _this._adjustCameras();
37622 _this._motionless = _this._motionlessTransition();
37625 WaitingState.prototype.traverse = function () {
37626 return new State_1.TraversingState(this);
37628 WaitingState.prototype.wait = function () {
37629 throw new Error("Not implemented");
37631 WaitingState.prototype.prepend = function (nodes) {
37632 _super.prototype.prepend.call(this, nodes);
37633 this._motionless = this._motionlessTransition();
37635 WaitingState.prototype.set = function (nodes) {
37636 _super.prototype.set.call(this, nodes);
37637 this._motionless = this._motionlessTransition();
37639 WaitingState.prototype.rotate = function (delta) { return; };
37640 WaitingState.prototype.rotateBasic = function (basicRotation) { return; };
37641 WaitingState.prototype.rotateBasicUnbounded = function (basicRotation) { return; };
37642 WaitingState.prototype.rotateToBasic = function (basic) { return; };
37643 WaitingState.prototype.zoomIn = function (delta, reference) { return; };
37644 WaitingState.prototype.move = function (delta) {
37645 this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
37647 WaitingState.prototype.moveTo = function (position) {
37648 this._alpha = Math.max(0, Math.min(1, position));
37650 WaitingState.prototype.update = function (fps) {
37651 this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
37653 WaitingState.prototype.setCenter = function (center) { return; };
37654 WaitingState.prototype.setZoom = function (zoom) { return; };
37655 WaitingState.prototype._getAlpha = function () {
37656 return this._motionless ? Math.round(this._alpha) : this._alpha;
37658 WaitingState.prototype._setCurrentCamera = function () {
37659 _super.prototype._setCurrentCamera.call(this);
37660 this._adjustCameras();
37662 WaitingState.prototype._adjustCameras = function () {
37663 if (this._previousNode == null) {
37666 if (this._currentNode.fullPano) {
37667 var lookat = this._camera.lookat.clone().sub(this._camera.position);
37668 this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
37670 if (this._previousNode.fullPano) {
37671 var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
37672 this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
37675 return WaitingState;
37676 }(State_1.StateBase));
37677 exports.WaitingState = WaitingState;
37679 },{"../../State":233}],336:[function(require,module,exports){
37681 Object.defineProperty(exports, "__esModule", { value: true });
37682 var Observable_1 = require("rxjs/Observable");
37684 * @class ImageTileLoader
37686 * @classdesc Represents a loader of image tiles.
37688 var ImageTileLoader = (function () {
37690 * Create a new node image tile loader instance.
37692 * @param {string} scheme - The URI scheme.
37693 * @param {string} host - The URI host.
37694 * @param {string} [origin] - The origin query param.
37696 function ImageTileLoader(scheme, host, origin) {
37697 this._scheme = scheme;
37699 this._origin = origin != null ? "?origin=" + origin : "";
37702 * Retrieve an image tile.
37704 * @description Retrieve an image tile by specifying the area
37705 * as well as the scaled size.
37707 * @param {string} identifier - The identifier of the image.
37708 * @param {number} x - The top left x pixel coordinate for the tile
37709 * in the original image.
37710 * @param {number} y - The top left y pixel coordinate for the tile
37711 * in the original image.
37712 * @param {number} w - The pixel width of the tile in the original image.
37713 * @param {number} h - The pixel height of the tile in the original image.
37714 * @param {number} scaledW - The scaled width of the returned tile.
37715 * @param {number} scaledH - The scaled height of the returned tile.
37717 ImageTileLoader.prototype.getTile = function (identifier, x, y, w, h, scaledW, scaledH) {
37718 var characteristics = "/" + identifier + "/" + x + "," + y + "," + w + "," + h + "/" + scaledW + "," + scaledH + "/0/default.jpg";
37719 var url = this._scheme +
37724 var xmlHTTP = null;
37725 return [Observable_1.Observable.create(function (subscriber) {
37726 xmlHTTP = new XMLHttpRequest();
37727 xmlHTTP.open("GET", url, true);
37728 xmlHTTP.responseType = "arraybuffer";
37729 xmlHTTP.timeout = 15000;
37730 xmlHTTP.onload = function (event) {
37731 if (xmlHTTP.status !== 200) {
37732 subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + "). " +
37733 ("Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)));
37736 var image = new Image();
37737 image.crossOrigin = "Anonymous";
37738 image.onload = function (e) {
37739 subscriber.next(image);
37740 subscriber.complete();
37742 image.onerror = function (error) {
37743 subscriber.error(new Error("Failed to load tile image (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
37745 var blob = new Blob([xmlHTTP.response]);
37746 image.src = window.URL.createObjectURL(blob);
37748 xmlHTTP.onerror = function (error) {
37749 subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
37751 xmlHTTP.ontimeout = function (error) {
37752 subscriber.error(new Error("Tile request timed out (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
37754 xmlHTTP.onabort = function (event) {
37755 subscriber.error(new Error("Tile request was aborted (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
37757 xmlHTTP.send(null);
37760 if (xmlHTTP != null) {
37766 return ImageTileLoader;
37768 exports.ImageTileLoader = ImageTileLoader;
37769 exports.default = ImageTileLoader;
37771 },{"rxjs/Observable":29}],337:[function(require,module,exports){
37773 Object.defineProperty(exports, "__esModule", { value: true });
37775 * @class ImageTileStore
37777 * @classdesc Represents a store for image tiles.
37779 var ImageTileStore = (function () {
37781 * Create a new node image tile store instance.
37783 function ImageTileStore() {
37787 * Add an image tile to the store.
37789 * @param {HTMLImageElement} image - The image tile.
37790 * @param {string} key - The identifier for the tile.
37791 * @param {number} level - The level of the tile.
37793 ImageTileStore.prototype.addImage = function (image, key, level) {
37794 if (!(level in this._images)) {
37795 this._images[level] = {};
37797 this._images[level][key] = image;
37800 * Dispose the store.
37802 * @description Disposes all cached assets.
37804 ImageTileStore.prototype.dispose = function () {
37805 for (var _i = 0, _a = Object.keys(this._images); _i < _a.length; _i++) {
37806 var level = _a[_i];
37807 var levelImages = this._images[level];
37808 for (var _b = 0, _c = Object.keys(levelImages); _b < _c.length; _b++) {
37810 window.URL.revokeObjectURL(levelImages[key].src);
37811 delete levelImages[key];
37813 delete this._images[level];
37817 * Get an image tile from the store.
37819 * @param {string} key - The identifier for the tile.
37820 * @param {number} level - The level of the tile.
37822 ImageTileStore.prototype.getImage = function (key, level) {
37823 return this._images[level][key];
37826 * Check if an image tile exist in the store.
37828 * @param {string} key - The identifier for the tile.
37829 * @param {number} level - The level of the tile.
37831 ImageTileStore.prototype.hasImage = function (key, level) {
37832 return level in this._images && key in this._images[level];
37834 return ImageTileStore;
37836 exports.ImageTileStore = ImageTileStore;
37837 exports.default = ImageTileStore;
37839 },{}],338:[function(require,module,exports){
37841 /// <reference path="../../typings/index.d.ts" />
37842 Object.defineProperty(exports, "__esModule", { value: true });
37843 var Geo_1 = require("../Geo");
37845 * @class RegionOfInterestCalculator
37847 * @classdesc Represents a calculator for regions of interest.
37849 var RegionOfInterestCalculator = (function () {
37850 function RegionOfInterestCalculator() {
37851 this._viewportCoords = new Geo_1.ViewportCoords();
37854 * Compute a region of interest based on the current render camera
37855 * and the viewport size.
37857 * @param {RenderCamera} renderCamera - Render camera used for unprojections.
37858 * @param {ISize} size - Viewport size in pixels.
37859 * @param {Transform} transform - Transform used for projections.
37861 * @returns {IRegionOfInterest} A region of interest.
37863 RegionOfInterestCalculator.prototype.computeRegionOfInterest = function (renderCamera, size, transform) {
37864 var viewportBoundaryPoints = this._viewportBoundaryPoints(4);
37865 var bbox = this._viewportPointsBoundingBox(viewportBoundaryPoints, renderCamera, transform);
37866 this._clipBoundingBox(bbox);
37867 var viewportPixelWidth = 2 / size.width;
37868 var viewportPixelHeight = 2 / size.height;
37869 var centralViewportPixel = [
37870 [-0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
37871 [0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
37872 [0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
37873 [-0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
37875 var cpbox = this._viewportPointsBoundingBox(centralViewportPixel, renderCamera, transform);
37878 pixelHeight: cpbox.maxY - cpbox.minY,
37879 pixelWidth: cpbox.maxX - cpbox.minX + (cpbox.minX < cpbox.maxX ? 0 : 1),
37882 RegionOfInterestCalculator.prototype._viewportBoundaryPoints = function (pointsPerSide) {
37884 var os = [[-1, 1], [1, 1], [1, -1], [-1, -1]];
37885 var ds = [[2, 0], [0, -2], [-2, 0], [0, 2]];
37886 for (var side = 0; side < 4; ++side) {
37889 for (var i = 0; i < pointsPerSide; ++i) {
37890 points.push([o[0] + d[0] * i / pointsPerSide,
37891 o[1] + d[1] * i / pointsPerSide]);
37896 RegionOfInterestCalculator.prototype._viewportPointsBoundingBox = function (viewportPoints, renderCamera, transform) {
37898 var basicPoints = viewportPoints
37899 .map(function (point) {
37900 return _this._viewportCoords
37901 .viewportToBasic(point[0], point[1], transform, renderCamera.perspective);
37903 if (transform.gpano != null) {
37904 return this._boundingBoxPano(basicPoints);
37907 return this._boundingBox(basicPoints);
37910 RegionOfInterestCalculator.prototype._boundingBox = function (points) {
37912 maxX: Number.NEGATIVE_INFINITY,
37913 maxY: Number.NEGATIVE_INFINITY,
37914 minX: Number.POSITIVE_INFINITY,
37915 minY: Number.POSITIVE_INFINITY,
37917 for (var i = 0; i < points.length; ++i) {
37918 bbox.minX = Math.min(bbox.minX, points[i][0]);
37919 bbox.maxX = Math.max(bbox.maxX, points[i][0]);
37920 bbox.minY = Math.min(bbox.minY, points[i][1]);
37921 bbox.maxY = Math.max(bbox.maxY, points[i][1]);
37925 RegionOfInterestCalculator.prototype._boundingBoxPano = function (points) {
37929 for (var i = 0; i < points.length; ++i) {
37930 xs.push(points[i][0]);
37931 ys.push(points[i][1]);
37933 xs.sort(function (a, b) { return _this._sign(a - b); });
37934 ys.sort(function (a, b) { return _this._sign(a - b); });
37935 var intervalX = this._intervalPano(xs);
37937 maxX: intervalX[1],
37938 maxY: ys[ys.length - 1],
37939 minX: intervalX[0],
37944 * Find the max interval between consecutive numbers.
37945 * Assumes numbers are between 0 and 1, sorted and that
37946 * x is equivalent to x + 1.
37948 RegionOfInterestCalculator.prototype._intervalPano = function (xs) {
37951 for (var i = 0; i < xs.length - 1; ++i) {
37952 var dx = xs[i + 1] - xs[i];
37958 var loopdx = xs[0] + 1 - xs[xs.length - 1];
37959 if (loopdx > maxdx) {
37960 return [xs[0], xs[xs.length - 1]];
37963 return [xs[maxi + 1], xs[maxi]];
37966 RegionOfInterestCalculator.prototype._clipBoundingBox = function (bbox) {
37967 bbox.minX = Math.max(0, Math.min(1, bbox.minX));
37968 bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
37969 bbox.minY = Math.max(0, Math.min(1, bbox.minY));
37970 bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
37972 RegionOfInterestCalculator.prototype._sign = function (n) {
37973 return n > 0 ? 1 : n < 0 ? -1 : 0;
37975 return RegionOfInterestCalculator;
37977 exports.RegionOfInterestCalculator = RegionOfInterestCalculator;
37978 exports.default = RegionOfInterestCalculator;
37980 },{"../Geo":229}],339:[function(require,module,exports){
37982 /// <reference path="../../typings/index.d.ts" />
37983 Object.defineProperty(exports, "__esModule", { value: true });
37984 var THREE = require("three");
37985 var Subject_1 = require("rxjs/Subject");
37987 * @class TextureProvider
37989 * @classdesc Represents a provider of textures.
37991 var TextureProvider = (function () {
37993 * Create a new node texture provider instance.
37995 * @param {string} key - The identifier of the image for which to request tiles.
37996 * @param {number} width - The full width of the original image.
37997 * @param {number} height - The full height of the original image.
37998 * @param {number} tileSize - The size used when requesting tiles.
37999 * @param {HTMLImageElement} background - Image to use as background.
38000 * @param {ImageTileLoader} imageTileLoader - Loader for retrieving tiles.
38001 * @param {ImageTileStore} imageTileStore - Store for saving tiles.
38002 * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture.
38004 function TextureProvider(key, width, height, tileSize, background, imageTileLoader, imageTileStore, renderer) {
38005 this._disposed = false;
38007 if (width <= 0 || height <= 0) {
38008 console.warn("Original image size (" + width + ", " + height + ") is invalid (" + key + "). Tiles will not be loaded.");
38010 this._width = width;
38011 this._height = height;
38012 this._maxLevel = Math.ceil(Math.log(Math.max(height, width)) / Math.log(2));
38013 this._currentLevel = -1;
38014 this._tileSize = tileSize;
38015 this._updated$ = new Subject_1.Subject();
38016 this._createdSubject$ = new Subject_1.Subject();
38017 this._created$ = this._createdSubject$
38020 this._createdSubscription = this._created$.subscribe(function () { });
38021 this._hasSubject$ = new Subject_1.Subject();
38022 this._has$ = this._hasSubject$
38026 this._hasSubscription = this._has$.subscribe(function () { });
38027 this._abortFunctions = [];
38028 this._tileSubscriptions = {};
38029 this._renderedCurrentLevelTiles = {};
38030 this._renderedTiles = {};
38031 this._background = background;
38032 this._camera = null;
38033 this._imageTileLoader = imageTileLoader;
38034 this._imageTileStore = imageTileStore;
38035 this._renderer = renderer;
38036 this._renderTarget = null;
38039 Object.defineProperty(TextureProvider.prototype, "disposed", {
38043 * @returns {boolean} Value indicating whether provider has
38047 return this._disposed;
38052 Object.defineProperty(TextureProvider.prototype, "hasTexture$", {
38056 * @returns {Observable<boolean>} Observable emitting
38057 * values indicating when the existance of a texture
38066 Object.defineProperty(TextureProvider.prototype, "key", {
38070 * @returns {boolean} The identifier of the image for
38071 * which to render textures.
38079 Object.defineProperty(TextureProvider.prototype, "textureUpdated$", {
38081 * Get textureUpdated$.
38083 * @returns {Observable<boolean>} Observable emitting
38084 * values when an existing texture has been updated.
38087 return this._updated$;
38092 Object.defineProperty(TextureProvider.prototype, "textureCreated$", {
38094 * Get textureCreated$.
38096 * @returns {Observable<boolean>} Observable emitting
38097 * values when a new texture has been created.
38100 return this._created$;
38106 * Abort all outstanding image tile requests.
38108 TextureProvider.prototype.abort = function () {
38109 for (var key in this._tileSubscriptions) {
38110 if (!this._tileSubscriptions.hasOwnProperty(key)) {
38113 this._tileSubscriptions[key].unsubscribe();
38115 this._tileSubscriptions = {};
38116 for (var _i = 0, _a = this._abortFunctions; _i < _a.length; _i++) {
38117 var abort = _a[_i];
38120 this._abortFunctions = [];
38123 * Dispose the provider.
38125 * @description Disposes all cached assets and
38126 * aborts all outstanding image tile requests.
38128 TextureProvider.prototype.dispose = function () {
38129 if (this._disposed) {
38130 console.warn("Texture already disposed (" + this._key + ")");
38134 if (this._renderTarget != null) {
38135 this._renderTarget.dispose();
38136 this._renderTarget = null;
38138 this._imageTileStore.dispose();
38139 this._imageTileStore = null;
38140 this._background = null;
38141 this._camera = null;
38142 this._imageTileLoader = null;
38143 this._renderer = null;
38145 this._createdSubscription.unsubscribe();
38146 this._hasSubscription.unsubscribe();
38147 this._disposed = true;
38150 * Set the region of interest.
38152 * @description When the region of interest is set the
38153 * the tile level is determined and tiles for the region
38154 * are fetched from the store or the loader and renderedLevel
38157 * @param {IRegionOfInterest} roi - Spatial edges to cache.
38159 TextureProvider.prototype.setRegionOfInterest = function (roi) {
38160 if (this._width <= 0 || this._height <= 0) {
38164 var width = 1 / this._roi.pixelWidth;
38165 var height = 1 / this._roi.pixelHeight;
38166 var size = Math.max(height, width);
38167 var currentLevel = Math.max(0, Math.min(this._maxLevel, Math.round(Math.log(size) / Math.log(2) + 0.25)));
38168 if (currentLevel !== this._currentLevel) {
38170 this._currentLevel = currentLevel;
38171 if (!(this._currentLevel in this._renderedTiles)) {
38172 this._renderedTiles[this._currentLevel] = [];
38174 this._renderedCurrentLevelTiles = {};
38175 for (var _i = 0, _a = this._renderedTiles[this._currentLevel]; _i < _a.length; _i++) {
38177 this._renderedCurrentLevelTiles[this._tileKey(tile)] = true;
38180 var topLeft = this._getTileCoords([this._roi.bbox.minX, this._roi.bbox.minY]);
38181 var bottomRight = this._getTileCoords([this._roi.bbox.maxX, this._roi.bbox.maxY]);
38182 var tiles = this._getTiles(topLeft, bottomRight);
38183 if (this._camera == null) {
38184 this._camera = new THREE.OrthographicCamera(-this._width / 2, this._width / 2, this._height / 2, -this._height / 2, -1, 1);
38185 this._camera.position.z = 1;
38186 var gl = this._renderer.getContext();
38187 var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
38188 var backgroundSize = Math.max(this._width, this._height);
38189 var scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize;
38190 var targetWidth = Math.floor(scale * this._width);
38191 var targetHeight = Math.floor(scale * this._height);
38192 this._renderTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, {
38193 depthBuffer: false,
38194 format: THREE.RGBFormat,
38195 magFilter: THREE.LinearFilter,
38196 minFilter: THREE.LinearFilter,
38197 stencilBuffer: false,
38199 this._renderToTarget(0, 0, this._width, this._height, this._background);
38200 this._createdSubject$.next(this._renderTarget.texture);
38201 this._hasSubject$.next(true);
38203 this._fetchTiles(tiles);
38206 * Update the image used as background for the texture.
38208 * @param {HTMLImageElement} background - The background image.
38210 TextureProvider.prototype.updateBackground = function (background) {
38211 this._background = background;
38214 * Retrieve an image tile.
38216 * @description Retrieve an image tile and render it to the
38217 * texture. Add the tile to the store and emit to the updated
38220 * @param {Array<number>} tile - The tile coordinates.
38221 * @param {number} level - The tile level.
38222 * @param {number} x - The top left x pixel coordinate of the tile.
38223 * @param {number} y - The top left y pixel coordinate of the tile.
38224 * @param {number} w - The pixel width of the tile.
38225 * @param {number} h - The pixel height of the tile.
38226 * @param {number} scaledW - The scaled width of the returned tile.
38227 * @param {number} scaledH - The scaled height of the returned tile.
38229 TextureProvider.prototype._fetchTile = function (tile, level, x, y, w, h, scaledX, scaledY) {
38231 var getTile = this._imageTileLoader.getTile(this._key, x, y, w, h, scaledX, scaledY);
38232 var tile$ = getTile[0];
38233 var abort = getTile[1];
38234 this._abortFunctions.push(abort);
38235 var tileKey = this._tileKey(tile);
38236 var subscription = tile$
38237 .subscribe(function (image) {
38238 _this._renderToTarget(x, y, w, h, image);
38239 _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
38240 _this._removeFromArray(abort, _this._abortFunctions);
38241 _this._setTileRendered(tile, _this._currentLevel);
38242 _this._imageTileStore.addImage(image, tileKey, level);
38243 _this._updated$.next(true);
38244 }, function (error) {
38245 _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
38246 _this._removeFromArray(abort, _this._abortFunctions);
38247 console.error(error);
38249 if (!subscription.closed) {
38250 this._tileSubscriptions[tileKey] = subscription;
38254 * Retrieve image tiles.
38256 * @description Retrieve a image tiles and render them to the
38257 * texture. Retrieve from store if it exists, otherwise Retrieve
38260 * @param {Array<Array<number>>} tiles - Array of tile coordinates to
38263 TextureProvider.prototype._fetchTiles = function (tiles) {
38264 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
38265 for (var _i = 0, tiles_1 = tiles; _i < tiles_1.length; _i++) {
38266 var tile = tiles_1[_i];
38267 var tileKey = this._tileKey(tile);
38268 if (tileKey in this._renderedCurrentLevelTiles ||
38269 tileKey in this._tileSubscriptions) {
38272 var tileX = tileSize * tile[0];
38273 var tileY = tileSize * tile[1];
38274 var tileWidth = tileX + tileSize > this._width ? this._width - tileX : tileSize;
38275 var tileHeight = tileY + tileSize > this._height ? this._height - tileY : tileSize;
38276 if (this._imageTileStore.hasImage(tileKey, this._currentLevel)) {
38277 this._renderToTarget(tileX, tileY, tileWidth, tileHeight, this._imageTileStore.getImage(tileKey, this._currentLevel));
38278 this._setTileRendered(tile, this._currentLevel);
38279 this._updated$.next(true);
38282 var scaledX = Math.floor(tileWidth / tileSize * this._tileSize);
38283 var scaledY = Math.floor(tileHeight / tileSize * this._tileSize);
38284 this._fetchTile(tile, this._currentLevel, tileX, tileY, tileWidth, tileHeight, scaledX, scaledY);
38288 * Get tile coordinates for a point using the current level.
38290 * @param {Array<number>} point - Point in basic coordinates.
38292 * @returns {Array<number>} x and y tile coodinates.
38294 TextureProvider.prototype._getTileCoords = function (point) {
38295 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
38296 var maxX = Math.ceil(this._width / tileSize) - 1;
38297 var maxY = Math.ceil(this._height / tileSize) - 1;
38299 Math.min(Math.floor(this._width * point[0] / tileSize), maxX),
38300 Math.min(Math.floor(this._height * point[1] / tileSize), maxY),
38304 * Get tile coordinates for all tiles contained in a bounding
38307 * @param {Array<number>} topLeft - Top left tile coordinate of bounding box.
38308 * @param {Array<number>} bottomRight - Bottom right tile coordinate of bounding box.
38310 * @returns {Array<Array<number>>} Array of x, y tile coodinates.
38312 TextureProvider.prototype._getTiles = function (topLeft, bottomRight) {
38314 if (topLeft[0] > bottomRight[0]) {
38315 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
38316 var maxX = Math.ceil(this._width / tileSize) - 1;
38317 for (var x = topLeft[0]; x <= maxX; x++) {
38320 for (var x = 0; x <= bottomRight[0]; x++) {
38325 for (var x = topLeft[0]; x <= bottomRight[0]; x++) {
38330 for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
38332 for (var y = topLeft[1]; y <= bottomRight[1]; y++) {
38333 tiles.push([x, y]);
38339 * Remove an item from an array if it exists in array.
38341 * @param {T} item - Item to remove.
38342 * @param {Array<T>} array - Array from which item should be removed.
38344 TextureProvider.prototype._removeFromArray = function (item, array) {
38345 var index = array.indexOf(item);
38346 if (index !== -1) {
38347 array.splice(index, 1);
38351 * Remove an item from a dictionary.
38353 * @param {string} key - Key of the item to remove.
38354 * @param {Object} dict - Dictionary from which item should be removed.
38356 TextureProvider.prototype._removeFromDictionary = function (key, dict) {
38362 * Render an image tile to the target texture.
38364 * @param {number} x - The top left x pixel coordinate of the tile.
38365 * @param {number} y - The top left y pixel coordinate of the tile.
38366 * @param {number} w - The pixel width of the tile.
38367 * @param {number} h - The pixel height of the tile.
38368 * @param {HTMLImageElement} background - The image tile to render.
38370 TextureProvider.prototype._renderToTarget = function (x, y, w, h, image) {
38371 var texture = new THREE.Texture(image);
38372 texture.minFilter = THREE.LinearFilter;
38373 texture.needsUpdate = true;
38374 var geometry = new THREE.PlaneGeometry(w, h);
38375 var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide });
38376 var mesh = new THREE.Mesh(geometry, material);
38377 mesh.position.x = -this._width / 2 + x + w / 2;
38378 mesh.position.y = this._height / 2 - y - h / 2;
38379 var scene = new THREE.Scene();
38381 this._renderer.render(scene, this._camera, this._renderTarget);
38382 this._renderer.setRenderTarget(undefined);
38383 scene.remove(mesh);
38384 geometry.dispose();
38385 material.dispose();
38389 * Mark a tile as rendered.
38391 * @description Clears tiles marked as rendered in other
38392 * levels of the tile pyramid if they were rendered on
38393 * top of or below the tile.
38395 * @param {Arrary<number>} tile - The tile coordinates.
38396 * @param {number} level - Tile level of the tile coordinates.
38398 TextureProvider.prototype._setTileRendered = function (tile, level) {
38399 var otherLevels = Object.keys(this._renderedTiles)
38400 .map(function (key) {
38401 return parseInt(key, 10);
38403 .filter(function (renderedLevel) {
38404 return renderedLevel !== level;
38406 for (var _i = 0, otherLevels_1 = otherLevels; _i < otherLevels_1.length; _i++) {
38407 var otherLevel = otherLevels_1[_i];
38408 var scale = Math.pow(2, otherLevel - level);
38409 if (otherLevel < level) {
38410 var x = Math.floor(scale * tile[0]);
38411 var y = Math.floor(scale * tile[1]);
38412 for (var _a = 0, _b = this._renderedTiles[otherLevel].slice(); _a < _b.length; _a++) {
38413 var otherTile = _b[_a];
38414 if (otherTile[0] === x && otherTile[1] === y) {
38415 var index = this._renderedTiles[otherLevel].indexOf(otherTile);
38416 this._renderedTiles[otherLevel].splice(index, 1);
38421 var startX = scale * tile[0];
38422 var endX = startX + scale - 1;
38423 var startY = scale * tile[1];
38424 var endY = startY + scale - 1;
38425 for (var _c = 0, _d = this._renderedTiles[otherLevel].slice(); _c < _d.length; _c++) {
38426 var otherTile = _d[_c];
38427 if (otherTile[0] >= startX && otherTile[0] <= endX &&
38428 otherTile[1] >= startY && otherTile[1] <= endY) {
38429 var index = this._renderedTiles[otherLevel].indexOf(otherTile);
38430 this._renderedTiles[otherLevel].splice(index, 1);
38434 if (this._renderedTiles[otherLevel].length === 0) {
38435 delete this._renderedTiles[otherLevel];
38438 this._renderedTiles[level].push(tile);
38439 this._renderedCurrentLevelTiles[this._tileKey(tile)] = true;
38442 * Create a tile key from a tile coordinates.
38444 * @description Tile keys are used as a hash for
38445 * storing the tile in a dictionary.
38447 * @param {Arrary<number>} tile - The tile coordinates.
38449 TextureProvider.prototype._tileKey = function (tile) {
38450 return tile[0] + "-" + tile[1];
38452 return TextureProvider;
38454 exports.TextureProvider = TextureProvider;
38455 exports.default = TextureProvider;
38457 },{"rxjs/Subject":34,"three":176}],340:[function(require,module,exports){
38459 Object.defineProperty(exports, "__esModule", { value: true });
38460 var EventEmitter = (function () {
38461 function EventEmitter() {
38465 * Subscribe to an event by its name.
38466 * @param {string }eventType - The name of the event to subscribe to.
38467 * @param {any} fn - The handler called when the event occurs.
38469 EventEmitter.prototype.on = function (eventType, fn) {
38470 this._events[eventType] = this._events[eventType] || [];
38471 this._events[eventType].push(fn);
38475 * Unsubscribe from an event by its name.
38476 * @param {string} eventType - The name of the event to subscribe to.
38477 * @param {any} fn - The handler to remove.
38479 EventEmitter.prototype.off = function (eventType, fn) {
38484 if (!this._listens(eventType)) {
38485 var idx = this._events[eventType].indexOf(fn);
38487 this._events[eventType].splice(idx, 1);
38489 if (this._events[eventType].length) {
38490 delete this._events[eventType];
38494 delete this._events[eventType];
38498 EventEmitter.prototype.fire = function (eventType, data) {
38499 if (!this._listens(eventType)) {
38502 for (var _i = 0, _a = this._events[eventType]; _i < _a.length; _i++) {
38504 fn.call(this, data);
38508 EventEmitter.prototype._listens = function (eventType) {
38509 return !!(this._events && this._events[eventType]);
38511 return EventEmitter;
38513 exports.EventEmitter = EventEmitter;
38514 exports.default = EventEmitter;
38516 },{}],341:[function(require,module,exports){
38518 Object.defineProperty(exports, "__esModule", { value: true });
38519 var Viewer_1 = require("../Viewer");
38520 var Settings = (function () {
38521 function Settings() {
38523 Settings.setOptions = function (options) {
38524 Settings._baseImageSize = options.baseImageSize != null ?
38525 options.baseImageSize :
38526 Viewer_1.ImageSize.Size640;
38527 Settings._basePanoramaSize = options.basePanoramaSize != null ?
38528 options.basePanoramaSize :
38529 Viewer_1.ImageSize.Size2048;
38530 Settings._maxImageSize = options.maxImageSize != null ?
38531 options.maxImageSize :
38532 Viewer_1.ImageSize.Size2048;
38534 Object.defineProperty(Settings, "baseImageSize", {
38536 return Settings._baseImageSize;
38541 Object.defineProperty(Settings, "basePanoramaSize", {
38543 return Settings._basePanoramaSize;
38548 Object.defineProperty(Settings, "maxImageSize", {
38550 return Settings._maxImageSize;
38557 exports.Settings = Settings;
38558 exports.default = Settings;
38560 },{"../Viewer":236}],342:[function(require,module,exports){
38562 Object.defineProperty(exports, "__esModule", { value: true });
38563 var Urls = (function () {
38566 Object.defineProperty(Urls, "tileScheme", {
38573 Object.defineProperty(Urls, "tileDomain", {
38575 return "d2qb1440i7l50o.cloudfront.net";
38580 Object.defineProperty(Urls, "origin", {
38582 return "mapillary.webgl";
38587 Urls.thumbnail = function (key, size) {
38588 return "https://d1cuyjsrcm0gby.cloudfront.net/" + key + "/thumb-" + size + ".jpg?origin=" + this.origin;
38590 Urls.falcorModel = function (clientId) {
38591 return "https://a.mapillary.com/v3/model.json?client_id=" + clientId;
38593 Urls.protoMesh = function (key) {
38594 return "https://d1brzeo354iq2l.cloudfront.net/v2/mesh/" + key;
38598 exports.Urls = Urls;
38599 exports.default = Urls;
38601 },{}],343:[function(require,module,exports){
38603 Object.defineProperty(exports, "__esModule", { value: true });
38605 * Enumeration for alignments
38610 (function (Alignment) {
38614 Alignment[Alignment["Bottom"] = 0] = "Bottom";
38616 * Align to bottom left
38618 Alignment[Alignment["BottomLeft"] = 1] = "BottomLeft";
38620 * Align to bottom right
38622 Alignment[Alignment["BottomRight"] = 2] = "BottomRight";
38626 Alignment[Alignment["Center"] = 3] = "Center";
38630 Alignment[Alignment["Left"] = 4] = "Left";
38634 Alignment[Alignment["Right"] = 5] = "Right";
38638 Alignment[Alignment["Top"] = 6] = "Top";
38640 * Align to top left
38642 Alignment[Alignment["TopLeft"] = 7] = "TopLeft";
38644 * Align to top right
38646 Alignment[Alignment["TopRight"] = 8] = "TopRight";
38647 })(Alignment = exports.Alignment || (exports.Alignment = {}));
38648 exports.default = Alignment;
38650 },{}],344:[function(require,module,exports){
38652 Object.defineProperty(exports, "__esModule", { value: true });
38653 require("rxjs/add/operator/bufferCount");
38654 require("rxjs/add/operator/delay");
38655 require("rxjs/add/operator/distinctUntilChanged");
38656 require("rxjs/add/operator/map");
38657 require("rxjs/add/operator/switchMap");
38658 var CacheService = (function () {
38659 function CacheService(graphService, stateService) {
38660 this._graphService = graphService;
38661 this._stateService = stateService;
38662 this._started = false;
38664 Object.defineProperty(CacheService.prototype, "started", {
38666 return this._started;
38671 CacheService.prototype.start = function () {
38673 if (this._started) {
38676 this._uncacheSubscription = this._stateService.currentState$
38677 .distinctUntilChanged(undefined, function (frame) {
38678 return frame.state.currentNode.key;
38680 .map(function (frame) {
38681 return frame.state.trajectory
38682 .map(function (n) {
38687 .switchMap(function (keepKeysBuffer) {
38688 var keepKeys = keepKeysBuffer[0];
38689 return _this._graphService.uncache$(keepKeys);
38691 .subscribe(function () { });
38692 this._started = true;
38694 CacheService.prototype.stop = function () {
38695 if (!this._started) {
38698 this._uncacheSubscription.unsubscribe();
38699 this._uncacheSubscription = null;
38700 this._started = false;
38702 return CacheService;
38704 exports.CacheService = CacheService;
38705 exports.default = CacheService;
38707 },{"rxjs/add/operator/bufferCount":50,"rxjs/add/operator/delay":56,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"rxjs/add/operator/switchMap":79}],345:[function(require,module,exports){
38709 Object.defineProperty(exports, "__esModule", { value: true });
38710 var Component_1 = require("../Component");
38711 var ComponentController = (function () {
38712 function ComponentController(container, navigator, observer, key, options) {
38714 this._container = container;
38715 this._observer = observer;
38716 this._navigator = navigator;
38717 this._options = options != null ? options : {};
38719 this._componentService = new Component_1.ComponentService(this._container, this._navigator);
38720 this._coverComponent = this._componentService.getCover();
38721 this._initializeComponents();
38723 this._initilizeCoverComponent();
38724 this._subscribeCoverComponent();
38727 this._navigator.movedToKey$
38728 .first(function (k) {
38731 .subscribe(function (k) {
38733 _this._componentService.deactivateCover();
38734 _this._coverComponent.configure({ key: _this._key, loading: false, visible: false });
38735 _this._subscribeCoverComponent();
38736 _this._navigator.stateService.start();
38737 _this._observer.startEmit();
38741 ComponentController.prototype.get = function (name) {
38742 return this._componentService.get(name);
38744 ComponentController.prototype.activate = function (name) {
38745 this._componentService.activate(name);
38747 ComponentController.prototype.activateCover = function () {
38748 this._coverComponent.configure({ loading: false, visible: true });
38750 ComponentController.prototype.deactivate = function (name) {
38751 this._componentService.deactivate(name);
38753 ComponentController.prototype.deactivateCover = function () {
38754 this._coverComponent.configure({ loading: true, visible: true });
38756 ComponentController.prototype.resize = function () {
38757 this._componentService.resize();
38759 ComponentController.prototype._initializeComponents = function () {
38760 var options = this._options;
38761 this._uFalse(options.background, "background");
38762 this._uFalse(options.debug, "debug");
38763 this._uFalse(options.image, "image");
38764 this._uFalse(options.marker, "marker");
38765 this._uFalse(options.navigation, "navigation");
38766 this._uFalse(options.popup, "popup");
38767 this._uFalse(options.route, "route");
38768 this._uFalse(options.slider, "slider");
38769 this._uFalse(options.tag, "tag");
38770 this._uTrue(options.attribution, "attribution");
38771 this._uTrue(options.bearing, "bearing");
38772 this._uTrue(options.cache, "cache");
38773 this._uTrue(options.direction, "direction");
38774 this._uTrue(options.imagePlane, "imagePlane");
38775 this._uTrue(options.keyboard, "keyboard");
38776 this._uTrue(options.loading, "loading");
38777 this._uTrue(options.mouse, "mouse");
38778 this._uTrue(options.sequence, "sequence");
38779 this._uTrue(options.stats, "stats");
38781 ComponentController.prototype._initilizeCoverComponent = function () {
38782 var options = this._options;
38783 this._coverComponent.configure({ key: this._key });
38784 if (options.cover === undefined || options.cover) {
38785 this.activateCover();
38788 this.deactivateCover();
38791 ComponentController.prototype._subscribeCoverComponent = function () {
38793 this._coverComponent.configuration$.subscribe(function (conf) {
38794 if (conf.loading) {
38795 _this._navigator.stateService.currentKey$
38797 .switchMap(function (key) {
38798 return key == null || key !== conf.key ?
38799 _this._navigator.moveToKey$(conf.key) :
38800 _this._navigator.stateService.currentNode$
38803 .subscribe(function (node) {
38804 _this._navigator.stateService.start();
38805 _this._observer.startEmit();
38806 _this._coverComponent.configure({ loading: false, visible: false });
38807 _this._componentService.deactivateCover();
38808 }, function (error) {
38809 console.error("Failed to deactivate cover.", error);
38810 _this._coverComponent.configure({ loading: false, visible: true });
38813 else if (conf.visible) {
38814 _this._observer.stopEmit();
38815 _this._navigator.stateService.stop();
38816 _this._componentService.activateCover();
38820 ComponentController.prototype._uFalse = function (option, name) {
38821 if (option === undefined) {
38822 this._componentService.deactivate(name);
38825 if (typeof option === "boolean") {
38827 this._componentService.activate(name);
38830 this._componentService.deactivate(name);
38834 this._componentService.configure(name, option);
38835 this._componentService.activate(name);
38837 ComponentController.prototype._uTrue = function (option, name) {
38838 if (option === undefined) {
38839 this._componentService.activate(name);
38842 if (typeof option === "boolean") {
38844 this._componentService.activate(name);
38847 this._componentService.deactivate(name);
38851 this._componentService.configure(name, option);
38852 this._componentService.activate(name);
38854 return ComponentController;
38856 exports.ComponentController = ComponentController;
38858 },{"../Component":226}],346:[function(require,module,exports){
38860 Object.defineProperty(exports, "__esModule", { value: true });
38861 var Render_1 = require("../Render");
38862 var Viewer_1 = require("../Viewer");
38863 var Container = (function () {
38864 function Container(id, stateService, options) {
38866 this._container = document.getElementById(id);
38867 if (!this._container) {
38868 throw new Error("Container '" + id + "' not found.");
38870 this._container.classList.add("mapillary-js");
38871 this._canvasContainer = document.createElement("div");
38872 this._canvasContainer.className = "mapillary-js-interactive";
38873 this._domContainer = document.createElement("div");
38874 this._domContainer.className = "mapillary-js-dom";
38875 this._container.appendChild(this._canvasContainer);
38876 this._container.appendChild(this._domContainer);
38877 this.renderService = new Render_1.RenderService(this._container, stateService.currentState$, options.renderMode);
38878 this.glRenderer = new Render_1.GLRenderer(this._canvasContainer, this.renderService);
38879 this.domRenderer = new Render_1.DOMRenderer(this._domContainer, this.renderService, stateService.currentState$);
38880 this.mouseService = new Viewer_1.MouseService(this._canvasContainer, this._domContainer);
38881 this.touchService = new Viewer_1.TouchService(this._canvasContainer, this._domContainer);
38882 this.spriteService = new Viewer_1.SpriteService(options.sprite);
38884 Object.defineProperty(Container.prototype, "element", {
38886 return this._container;
38891 Object.defineProperty(Container.prototype, "canvasContainer", {
38893 return this.canvasContainer;
38900 exports.Container = Container;
38901 exports.default = Container;
38903 },{"../Render":232,"../Viewer":236}],347:[function(require,module,exports){
38905 Object.defineProperty(exports, "__esModule", { value: true });
38907 * Enumeration for image sizes
38910 * @description Image sizes in pixels for the long side of the image.
38913 (function (ImageSize) {
38915 * 320 pixels image size
38917 ImageSize[ImageSize["Size320"] = 320] = "Size320";
38919 * 640 pixels image size
38921 ImageSize[ImageSize["Size640"] = 640] = "Size640";
38923 * 1024 pixels image size
38925 ImageSize[ImageSize["Size1024"] = 1024] = "Size1024";
38927 * 2048 pixels image size
38929 ImageSize[ImageSize["Size2048"] = 2048] = "Size2048";
38930 })(ImageSize = exports.ImageSize || (exports.ImageSize = {}));
38932 },{}],348:[function(require,module,exports){
38934 /// <reference path="../../typings/index.d.ts" />
38935 Object.defineProperty(exports, "__esModule", { value: true });
38936 var _ = require("underscore");
38937 var Subject_1 = require("rxjs/Subject");
38938 require("rxjs/add/operator/debounceTime");
38939 require("rxjs/add/operator/distinctUntilChanged");
38940 require("rxjs/add/operator/map");
38941 require("rxjs/add/operator/publishReplay");
38942 require("rxjs/add/operator/scan");
38943 require("rxjs/add/operator/startWith");
38944 var LoadingService = (function () {
38945 function LoadingService() {
38946 this._loadersSubject$ = new Subject_1.Subject();
38947 this._loaders$ = this._loadersSubject$
38948 .scan(function (loaders, loader) {
38949 if (loader.task !== undefined) {
38950 loaders[loader.task] = loader.loading;
38958 Object.defineProperty(LoadingService.prototype, "loading$", {
38960 return this._loaders$
38961 .map(function (loaders) {
38962 return _.reduce(loaders, function (loader, acc) {
38963 return (loader || acc);
38967 .distinctUntilChanged();
38972 LoadingService.prototype.taskLoading$ = function (task) {
38973 return this._loaders$
38974 .map(function (loaders) {
38975 return !!loaders[task];
38978 .distinctUntilChanged();
38980 LoadingService.prototype.startLoading = function (task) {
38981 this._loadersSubject$.next({ loading: true, task: task });
38983 LoadingService.prototype.stopLoading = function (task) {
38984 this._loadersSubject$.next({ loading: false, task: task });
38986 return LoadingService;
38988 exports.LoadingService = LoadingService;
38989 exports.default = LoadingService;
38991 },{"rxjs/Subject":34,"rxjs/add/operator/debounceTime":55,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73,"rxjs/add/operator/startWith":78,"underscore":178}],349:[function(require,module,exports){
38993 Object.defineProperty(exports, "__esModule", { value: true });
38994 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
38995 var Observable_1 = require("rxjs/Observable");
38996 var Subject_1 = require("rxjs/Subject");
38997 require("rxjs/add/observable/fromEvent");
38998 require("rxjs/add/operator/distinctUntilChanged");
38999 require("rxjs/add/operator/filter");
39000 require("rxjs/add/operator/map");
39001 require("rxjs/add/operator/merge");
39002 require("rxjs/add/operator/mergeMap");
39003 require("rxjs/add/operator/publishReplay");
39004 require("rxjs/add/operator/scan");
39005 require("rxjs/add/operator/switchMap");
39006 require("rxjs/add/operator/withLatestFrom");
39007 var Geo_1 = require("../Geo");
39008 var MouseService = (function () {
39009 function MouseService(canvasContainer, domContainer, viewportCoords) {
39011 this._canvasContainer = canvasContainer;
39012 this._domContainer = domContainer;
39013 this._viewportCoords = viewportCoords != null ? viewportCoords : new Geo_1.ViewportCoords();
39014 this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
39015 this._active$ = this._activeSubject$
39016 .distinctUntilChanged()
39019 this._claimMouse$ = new Subject_1.Subject();
39020 this._documentMouseMove$ = Observable_1.Observable.fromEvent(document, "mousemove");
39021 this._documentMouseUp$ = Observable_1.Observable.fromEvent(document, "mouseup");
39022 this._mouseDown$ = Observable_1.Observable.fromEvent(canvasContainer, "mousedown");
39023 this._mouseLeave$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseleave");
39024 this._mouseMove$ = Observable_1.Observable.fromEvent(canvasContainer, "mousemove");
39025 this._mouseUp$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseup");
39026 this._mouseOut$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseout");
39027 this._mouseOver$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseover");
39028 this._domMouseDown$ = Observable_1.Observable.fromEvent(domContainer, "mousedown");
39029 this._domMouseMove$ = Observable_1.Observable.fromEvent(domContainer, "mousemove");
39030 Observable_1.Observable
39031 .merge(this._domMouseDown$, this._domMouseMove$)
39032 .subscribe(function (event) {
39033 event.preventDefault();
39035 this._click$ = Observable_1.Observable.fromEvent(canvasContainer, "click");
39036 this._dblClick$ = Observable_1.Observable.fromEvent(canvasContainer, "dblclick");
39038 .subscribe(function (event) {
39039 event.preventDefault();
39041 this._contextMenu$ = Observable_1.Observable.fromEvent(canvasContainer, "contextmenu");
39043 .subscribe(function (event) {
39044 event.preventDefault();
39046 this._mouseWheel$ = Observable_1.Observable
39047 .merge(Observable_1.Observable.fromEvent(canvasContainer, "wheel"), Observable_1.Observable.fromEvent(domContainer, "wheel"));
39048 this._consistentContextMenu$ = Observable_1.Observable
39049 .merge(this._mouseDown$, this._mouseMove$, this._mouseOut$, this._mouseUp$, this._contextMenu$)
39051 .filter(function (events) {
39052 // fire context menu on mouse up both on mac and windows
39053 return events[0].type === "mousedown" &&
39054 events[1].type === "contextmenu" &&
39055 events[2].type === "mouseup";
39057 .map(function (events) {
39061 var dragStop$ = Observable_1.Observable
39062 .merge(Observable_1.Observable.fromEvent(window, "blur"), this._documentMouseUp$
39063 .filter(function (e) {
39064 return e.button === 0;
39067 var leftButtonDown$ = this._mouseDown$
39068 .filter(function (e) {
39069 return e.button === 0;
39072 this._mouseDragStart$ = leftButtonDown$
39073 .mergeMap(function (e) {
39074 return _this._documentMouseMove$
39075 .takeUntil(dragStop$)
39078 this._mouseDrag$ = leftButtonDown$
39079 .mergeMap(function (e) {
39080 return _this._documentMouseMove$
39082 .takeUntil(dragStop$);
39084 this._mouseDragEnd$ = this._mouseDragStart$
39085 .mergeMap(function (e) {
39086 return dragStop$.first();
39088 var containerLeftButtonDown$ = this._domMouseDown$
39089 .filter(function (e) {
39090 return e.button === 0;
39093 this._domMouseDragStart$ = containerLeftButtonDown$
39094 .mergeMap(function (e) {
39095 return _this._documentMouseMove$
39096 .takeUntil(dragStop$)
39099 this._domMouseDrag$ = containerLeftButtonDown$
39100 .mergeMap(function (e) {
39101 return _this._documentMouseMove$
39103 .takeUntil(dragStop$);
39105 this._domMouseDragEnd$ = this._domMouseDragStart$
39106 .mergeMap(function (e) {
39107 return dragStop$.first();
39109 this._staticClick$ = this._mouseDown$
39110 .switchMap(function (e) {
39111 return _this._click$
39112 .takeUntil(_this._mouseMove$)
39115 this._mouseOwner$ = this._claimMouse$
39116 .scan(function (claims, mouseClaim) {
39117 if (mouseClaim.zindex == null) {
39118 delete claims[mouseClaim.name];
39121 claims[mouseClaim.name] = mouseClaim.zindex;
39125 .map(function (claims) {
39128 for (var name_1 in claims) {
39129 if (claims.hasOwnProperty(name_1)) {
39130 if (claims[name_1] > curZ) {
39131 curZ = claims[name_1];
39140 this._mouseOwner$.subscribe(function () { });
39142 Object.defineProperty(MouseService.prototype, "active$", {
39144 return this._active$;
39149 Object.defineProperty(MouseService.prototype, "activate$", {
39151 return this._activeSubject$;
39156 Object.defineProperty(MouseService.prototype, "documentMouseMove$", {
39158 return this._documentMouseMove$;
39163 Object.defineProperty(MouseService.prototype, "documentMouseUp$", {
39165 return this._documentMouseUp$;
39170 Object.defineProperty(MouseService.prototype, "domMouseDragStart$", {
39172 return this._domMouseDragStart$;
39177 Object.defineProperty(MouseService.prototype, "domMouseDrag$", {
39179 return this._domMouseDrag$;
39184 Object.defineProperty(MouseService.prototype, "domMouseDragEnd$", {
39186 return this._domMouseDragEnd$;
39191 Object.defineProperty(MouseService.prototype, "domMouseDown$", {
39193 return this._domMouseDown$;
39198 Object.defineProperty(MouseService.prototype, "domMouseMove$", {
39200 return this._domMouseMove$;
39205 Object.defineProperty(MouseService.prototype, "mouseOwner$", {
39207 return this._mouseOwner$;
39212 Object.defineProperty(MouseService.prototype, "mouseDown$", {
39214 return this._mouseDown$;
39219 Object.defineProperty(MouseService.prototype, "mouseMove$", {
39221 return this._mouseMove$;
39226 Object.defineProperty(MouseService.prototype, "mouseLeave$", {
39228 return this._mouseLeave$;
39233 Object.defineProperty(MouseService.prototype, "mouseOut$", {
39235 return this._mouseOut$;
39240 Object.defineProperty(MouseService.prototype, "mouseOver$", {
39242 return this._mouseOver$;
39247 Object.defineProperty(MouseService.prototype, "mouseUp$", {
39249 return this._mouseUp$;
39254 Object.defineProperty(MouseService.prototype, "click$", {
39256 return this._click$;
39261 Object.defineProperty(MouseService.prototype, "dblClick$", {
39263 return this._dblClick$;
39268 Object.defineProperty(MouseService.prototype, "contextMenu$", {
39270 return this._consistentContextMenu$;
39275 Object.defineProperty(MouseService.prototype, "mouseWheel$", {
39277 return this._mouseWheel$;
39282 Object.defineProperty(MouseService.prototype, "mouseDragStart$", {
39284 return this._mouseDragStart$;
39289 Object.defineProperty(MouseService.prototype, "mouseDrag$", {
39291 return this._mouseDrag$;
39296 Object.defineProperty(MouseService.prototype, "mouseDragEnd$", {
39298 return this._mouseDragEnd$;
39303 Object.defineProperty(MouseService.prototype, "staticClick$", {
39305 return this._staticClick$;
39310 MouseService.prototype.claimMouse = function (name, zindex) {
39311 this._claimMouse$.next({ name: name, zindex: zindex });
39313 MouseService.prototype.unclaimMouse = function (name) {
39314 this._claimMouse$.next({ name: name, zindex: null });
39316 MouseService.prototype.filtered$ = function (name, observable$) {
39318 .withLatestFrom(this.mouseOwner$, function (event, owner) {
39319 return [event, owner];
39321 .filter(function (eo) {
39322 return eo[1] === name;
39324 .map(function (eo) {
39328 return MouseService;
39330 exports.MouseService = MouseService;
39331 exports.default = MouseService;
39333 },{"../Geo":229,"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/fromEvent":42,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/mergeMap":68,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73,"rxjs/add/operator/switchMap":79,"rxjs/add/operator/withLatestFrom":83}],350:[function(require,module,exports){
39335 /// <reference path="../../typings/index.d.ts" />
39336 Object.defineProperty(exports, "__esModule", { value: true });
39337 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
39338 var Observable_1 = require("rxjs/Observable");
39339 require("rxjs/add/observable/throw");
39340 require("rxjs/add/operator/do");
39341 require("rxjs/add/operator/finally");
39342 require("rxjs/add/operator/first");
39343 require("rxjs/add/operator/map");
39344 require("rxjs/add/operator/mergeMap");
39345 var API_1 = require("../API");
39346 var Graph_1 = require("../Graph");
39347 var Edge_1 = require("../Edge");
39348 var State_1 = require("../State");
39349 var Viewer_1 = require("../Viewer");
39350 var Navigator = (function () {
39351 function Navigator(clientId, token, apiV3, graphService, imageLoadingService, loadingService, stateService, cacheService) {
39352 this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token);
39353 this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService();
39354 this._graphService = graphService != null ?
39356 new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService);
39357 this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService();
39358 this._loadingName = "navigator";
39359 this._stateService = stateService != null ? stateService : new State_1.StateService();
39360 this._cacheService = cacheService != null ?
39362 new Viewer_1.CacheService(this._graphService, this._stateService);
39363 this._cacheService.start();
39364 this._keyRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
39365 this._movedToKey$ = new BehaviorSubject_1.BehaviorSubject(null);
39366 this._dirRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
39367 this._latLonRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
39369 Object.defineProperty(Navigator.prototype, "apiV3", {
39371 return this._apiV3;
39376 Object.defineProperty(Navigator.prototype, "graphService", {
39378 return this._graphService;
39383 Object.defineProperty(Navigator.prototype, "imageLoadingService", {
39385 return this._imageLoadingService;
39390 Object.defineProperty(Navigator.prototype, "keyRequested$", {
39392 return this._keyRequested$;
39397 Object.defineProperty(Navigator.prototype, "loadingService", {
39399 return this._loadingService;
39404 Object.defineProperty(Navigator.prototype, "movedToKey$", {
39406 return this._movedToKey$;
39411 Object.defineProperty(Navigator.prototype, "stateService", {
39413 return this._stateService;
39418 Navigator.prototype.moveToKey$ = function (key) {
39420 this.loadingService.startLoading(this._loadingName);
39421 this._keyRequested$.next(key);
39422 return this._graphService.cacheNode$(key)
39423 .do(function (node) {
39424 _this.stateService.setNodes([node]);
39425 _this._movedToKey$.next(node.key);
39427 .finally(function () {
39428 _this.loadingService.stopLoading(_this._loadingName);
39431 Navigator.prototype.moveDir$ = function (direction) {
39433 this.loadingService.startLoading(this._loadingName);
39434 this._dirRequested$.next(direction);
39435 return this.stateService.currentNode$
39437 .mergeMap(function (node) {
39438 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
39439 node.sequenceEdges$ :
39440 node.spatialEdges$)
39442 .map(function (status) {
39443 for (var _i = 0, _a = status.edges; _i < _a.length; _i++) {
39445 if (edge.data.direction === direction) {
39452 .mergeMap(function (directionKey) {
39453 if (directionKey == null) {
39454 _this.loadingService.stopLoading(_this._loadingName);
39455 return Observable_1.Observable
39456 .throw(new Error("Direction (" + direction + ") does not exist for current node."));
39458 return _this.moveToKey$(directionKey);
39461 Navigator.prototype.moveCloseTo$ = function (lat, lon) {
39463 this.loadingService.startLoading(this._loadingName);
39464 this._latLonRequested$.next({ lat: lat, lon: lon });
39465 return this.apiV3.imageCloseTo$(lat, lon)
39466 .mergeMap(function (fullNode) {
39467 if (fullNode == null) {
39468 _this.loadingService.stopLoading(_this._loadingName);
39469 return Observable_1.Observable
39470 .throw(new Error("No image found close to lat " + lat + ", lon " + lon + "."));
39472 return _this.moveToKey$(fullNode.key);
39475 Navigator.prototype.setFilter$ = function (filter) {
39477 this._stateService.clearNodes();
39478 return this._movedToKey$
39480 .mergeMap(function (key) {
39482 return _this._trajectoryKeys$()
39483 .mergeMap(function (keys) {
39484 return _this._graphService.setFilter$(filter)
39485 .mergeMap(function (graph) {
39486 return _this._cacheKeys$(keys);
39491 return _this._keyRequested$
39492 .mergeMap(function (requestedKey) {
39493 if (requestedKey != null) {
39494 return _this._graphService.setFilter$(filter)
39495 .mergeMap(function (graph) {
39496 return _this._graphService.cacheNode$(requestedKey);
39499 return _this._graphService.setFilter$(filter)
39500 .map(function (graph) {
39505 .map(function (node) {
39509 Navigator.prototype.setToken$ = function (token) {
39511 this._stateService.clearNodes();
39512 return this._movedToKey$
39514 .do(function (key) {
39515 _this._apiV3.setToken(token);
39517 .mergeMap(function (key) {
39518 return key == null ?
39519 _this._graphService.reset$([])
39520 .map(function (graph) {
39523 _this._trajectoryKeys$()
39524 .mergeMap(function (keys) {
39525 return _this._graphService.reset$(keys)
39526 .mergeMap(function (graph) {
39527 return _this._cacheKeys$(keys);
39531 .map(function (node) {
39536 Navigator.prototype._cacheKeys$ = function (keys) {
39538 var cacheNodes$ = keys
39539 .map(function (key) {
39540 return _this._graphService.cacheNode$(key);
39542 return Observable_1.Observable
39546 Navigator.prototype._trajectoryKeys$ = function () {
39547 return this._stateService.currentState$
39549 .map(function (frame) {
39550 return frame.state.trajectory
39551 .map(function (node) {
39558 exports.Navigator = Navigator;
39559 exports.default = Navigator;
39561 },{"../API":225,"../Edge":227,"../Graph":230,"../State":233,"../Viewer":236,"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/add/observable/throw":46,"rxjs/add/operator/do":59,"rxjs/add/operator/finally":62,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"rxjs/add/operator/mergeMap":68}],351:[function(require,module,exports){
39563 Object.defineProperty(exports, "__esModule", { value: true });
39564 var Observable_1 = require("rxjs/Observable");
39565 require("rxjs/add/observable/combineLatest");
39566 require("rxjs/add/operator/distinctUntilChanged");
39567 require("rxjs/add/operator/map");
39568 require("rxjs/add/operator/throttleTime");
39569 var Viewer_1 = require("../Viewer");
39570 var Observer = (function () {
39571 function Observer(eventEmitter, navigator, container) {
39573 this._container = container;
39574 this._eventEmitter = eventEmitter;
39575 this._navigator = navigator;
39576 this._projection = new Viewer_1.Projection();
39577 this._started = false;
39578 // loading should always emit, also when cover is activated
39579 this._navigator.loadingService.loading$
39580 .subscribe(function (loading) {
39581 _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading);
39584 Object.defineProperty(Observer.prototype, "started", {
39586 return this._started;
39591 Observer.prototype.projectBasic$ = function (basicPoint) {
39593 return Observable_1.Observable
39594 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
39596 .map(function (_a) {
39597 var render = _a[0], transform = _a[1];
39598 var canvasPoint = _this._projection.basicToCanvas(basicPoint, _this._container.element, render, transform);
39599 return [Math.round(canvasPoint[0]), Math.round(canvasPoint[1])];
39602 Observer.prototype.startEmit = function () {
39604 if (this._started) {
39607 this._started = true;
39608 this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$
39609 .subscribe(function (node) {
39610 _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node);
39612 this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$
39613 .switchMap(function (node) {
39614 return node.sequenceEdges$;
39616 .subscribe(function (status) {
39617 _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status);
39619 this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$
39620 .switchMap(function (node) {
39621 return node.spatialEdges$;
39623 .subscribe(function (status) {
39624 _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status);
39626 this._moveSubscription = Observable_1.Observable
39627 .combineLatest(this._navigator.stateService.inMotion$, this._container.mouseService.active$, this._container.touchService.active$)
39628 .map(function (values) {
39629 return values[0] || values[1] || values[2];
39631 .distinctUntilChanged()
39632 .subscribe(function (started) {
39634 _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null);
39637 _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null);
39640 this._bearingSubscription = this._container.renderService.bearing$
39642 .distinctUntilChanged(function (b1, b2) {
39643 return Math.abs(b2 - b1) < 1;
39645 .subscribe(function (bearing) {
39646 _this._eventEmitter.fire(Viewer_1.Viewer.bearingchanged, bearing);
39648 var mouseMove$ = this._container.mouseService.active$
39649 .switchMap(function (active) {
39651 Observable_1.Observable.empty() :
39652 _this._container.mouseService.mouseMove$;
39654 this._viewerMouseEventSubscription = Observable_1.Observable
39655 .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$))
39656 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
39657 .map(function (_a) {
39658 var _b = _a[0], type = _b[0], event = _b[1], render = _a[1], reference = _a[2], transform = _a[3];
39659 var unprojection = _this._projection.eventToUnprojection(event, _this._container.element, render, reference, transform);
39661 basicPoint: unprojection.basicPoint,
39662 latLon: unprojection.latLon,
39663 originalEvent: event,
39664 pixelPoint: unprojection.pixelPoint,
39665 target: _this._eventEmitter,
39669 .subscribe(function (event) {
39670 _this._eventEmitter.fire(event.type, event);
39673 Observer.prototype.stopEmit = function () {
39674 if (!this.started) {
39677 this._started = false;
39678 this._bearingSubscription.unsubscribe();
39679 this._currentNodeSubscription.unsubscribe();
39680 this._moveSubscription.unsubscribe();
39681 this._sequenceEdgesSubscription.unsubscribe();
39682 this._spatialEdgesSubscription.unsubscribe();
39683 this._viewerMouseEventSubscription.unsubscribe();
39684 this._bearingSubscription = null;
39685 this._currentNodeSubscription = null;
39686 this._moveSubscription = null;
39687 this._sequenceEdgesSubscription = null;
39688 this._spatialEdgesSubscription = null;
39689 this._viewerMouseEventSubscription = null;
39691 Observer.prototype.unproject$ = function (canvasPoint) {
39693 return Observable_1.Observable
39694 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
39696 .map(function (_a) {
39697 var render = _a[0], reference = _a[1], transform = _a[2];
39698 var unprojection = _this._projection.canvasToUnprojection(canvasPoint, _this._container.element, render, reference, transform);
39699 return unprojection.latLon;
39702 Observer.prototype.unprojectBasic$ = function (canvasPoint) {
39704 return Observable_1.Observable
39705 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
39707 .map(function (_a) {
39708 var render = _a[0], transform = _a[1];
39709 return _this._projection.canvasToBasic(canvasPoint, _this._container.element, render, transform);
39712 Observer.prototype._mapMouseEvent$ = function (type, mouseEvent$) {
39713 return mouseEvent$.map(function (event) {
39714 return [type, event];
39719 exports.Observer = Observer;
39720 exports.default = Observer;
39722 },{"../Viewer":236,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"rxjs/add/operator/throttleTime":82}],352:[function(require,module,exports){
39724 /// <reference path="../../typings/index.d.ts" />
39725 Object.defineProperty(exports, "__esModule", { value: true });
39726 var THREE = require("three");
39727 var Geo_1 = require("../Geo");
39728 var Projection = (function () {
39729 function Projection(geoCoords, viewportCoords) {
39730 this._geoCoords = !!geoCoords ? geoCoords : new Geo_1.GeoCoords();
39731 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
39733 Projection.prototype.basicToCanvas = function (basicPoint, container, render, transform) {
39734 return this._viewportCoords
39735 .basicToCanvas(basicPoint[0], basicPoint[1], container, transform, render.perspective);
39737 Projection.prototype.canvasToBasic = function (canvasPoint, container, render, transform) {
39738 var basicPoint = this._viewportCoords
39739 .canvasToBasic(canvasPoint[0], canvasPoint[1], container, transform, render.perspective);
39740 if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
39745 Projection.prototype.eventToUnprojection = function (event, container, render, reference, transform) {
39746 var pixelPoint = this._viewportCoords.canvasPosition(event, container);
39747 return this.canvasToUnprojection(pixelPoint, container, render, reference, transform);
39749 Projection.prototype.canvasToUnprojection = function (canvasPoint, container, render, reference, transform) {
39750 var canvasX = canvasPoint[0];
39751 var canvasY = canvasPoint[1];
39752 var _a = this._viewportCoords.canvasToViewport(canvasX, canvasY, container), viewportX = _a[0], viewportY = _a[1];
39753 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
39754 .unproject(render.perspective);
39755 var basicPoint = transform.projectBasic(point3d.toArray());
39756 if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
39759 var direction3d = point3d.clone().sub(render.camera.position).normalize();
39760 var dist = -2 / direction3d.z;
39762 if (dist > 0 && dist < 100 && !!basicPoint) {
39763 var point = direction3d.clone().multiplyScalar(dist).add(render.camera.position);
39764 var latLonArray = this._geoCoords
39765 .enuToGeodetic(point.x, point.y, point.z, reference.lat, reference.lon, reference.alt)
39767 latLon = { lat: latLonArray[0], lon: latLonArray[1] };
39769 var unprojection = {
39770 basicPoint: basicPoint,
39772 pixelPoint: [canvasX, canvasY],
39774 return unprojection;
39778 exports.Projection = Projection;
39779 exports.default = Projection;
39781 },{"../Geo":229,"three":176}],353:[function(require,module,exports){
39783 /// <reference path="../../typings/index.d.ts" />
39784 Object.defineProperty(exports, "__esModule", { value: true });
39785 var THREE = require("three");
39786 var vd = require("virtual-dom");
39787 var Subject_1 = require("rxjs/Subject");
39788 require("rxjs/add/operator/publishReplay");
39789 require("rxjs/add/operator/scan");
39790 require("rxjs/add/operator/startWith");
39791 var Viewer_1 = require("../Viewer");
39792 var SpriteAtlas = (function () {
39793 function SpriteAtlas() {
39795 Object.defineProperty(SpriteAtlas.prototype, "json", {
39796 set: function (value) {
39797 this._json = value;
39802 Object.defineProperty(SpriteAtlas.prototype, "image", {
39803 set: function (value) {
39804 this._image = value;
39805 this._texture = new THREE.Texture(this._image);
39806 this._texture.minFilter = THREE.NearestFilter;
39811 Object.defineProperty(SpriteAtlas.prototype, "loaded", {
39813 return !!(this._image && this._json);
39818 SpriteAtlas.prototype.getGLSprite = function (name) {
39819 if (!this.loaded) {
39820 throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
39822 var definition = this._json[name];
39824 console.warn("Sprite with key" + name + "does not exist in sprite definition.");
39825 return new THREE.Object3D();
39827 var texture = this._texture.clone();
39828 texture.needsUpdate = true;
39829 var width = this._image.width;
39830 var height = this._image.height;
39831 texture.offset.x = definition.x / width;
39832 texture.offset.y = (height - definition.y - definition.height) / height;
39833 texture.repeat.x = definition.width / width;
39834 texture.repeat.y = definition.height / height;
39835 var material = new THREE.SpriteMaterial({ map: texture });
39836 return new THREE.Sprite(material);
39838 SpriteAtlas.prototype.getDOMSprite = function (name, float) {
39839 if (!this.loaded) {
39840 throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
39842 if (float == null) {
39843 float = Viewer_1.Alignment.Center;
39845 var definition = this._json[name];
39847 console.warn("Sprite with key" + name + "does not exist in sprite definition.");
39848 return vd.h("div", {}, []);
39850 var clipTop = definition.y;
39851 var clipRigth = definition.x + definition.width;
39852 var clipBottom = definition.y + definition.height;
39853 var clipLeft = definition.x;
39854 var left = -definition.x;
39855 var top = -definition.y;
39856 var height = this._image.height;
39857 var width = this._image.width;
39859 case Viewer_1.Alignment.Bottom:
39860 case Viewer_1.Alignment.Center:
39861 case Viewer_1.Alignment.Top:
39862 left -= definition.width / 2;
39864 case Viewer_1.Alignment.BottomLeft:
39865 case Viewer_1.Alignment.Left:
39866 case Viewer_1.Alignment.TopLeft:
39867 left -= definition.width;
39869 case Viewer_1.Alignment.BottomRight:
39870 case Viewer_1.Alignment.Right:
39871 case Viewer_1.Alignment.BottomRight:
39876 case Viewer_1.Alignment.Center:
39877 case Viewer_1.Alignment.Left:
39878 case Viewer_1.Alignment.Right:
39879 top -= definition.height / 2;
39881 case Viewer_1.Alignment.Top:
39882 case Viewer_1.Alignment.TopLeft:
39883 case Viewer_1.Alignment.TopRight:
39884 top -= definition.height;
39886 case Viewer_1.Alignment.Bottom:
39887 case Viewer_1.Alignment.BottomLeft:
39888 case Viewer_1.Alignment.BottomRight:
39892 var pixelRatioInverse = 1 / definition.pixelRatio;
39893 clipTop *= pixelRatioInverse;
39894 clipRigth *= pixelRatioInverse;
39895 clipBottom *= pixelRatioInverse;
39896 clipLeft *= pixelRatioInverse;
39897 left *= pixelRatioInverse;
39898 top *= pixelRatioInverse;
39899 height *= pixelRatioInverse;
39900 width *= pixelRatioInverse;
39902 src: this._image.src,
39904 clip: "rect(" + clipTop + "px, " + clipRigth + "px, " + clipBottom + "px, " + clipLeft + "px)",
39905 height: height + "px",
39907 position: "absolute",
39909 width: width + "px",
39912 return vd.h("img", properties, []);
39914 return SpriteAtlas;
39916 var SpriteService = (function () {
39917 function SpriteService(sprite) {
39919 this._retina = window.devicePixelRatio > 1;
39920 this._spriteAtlasOperation$ = new Subject_1.Subject();
39921 this._spriteAtlas$ = this._spriteAtlasOperation$
39922 .startWith(function (atlas) {
39925 .scan(function (atlas, operation) {
39926 return operation(atlas);
39927 }, new SpriteAtlas())
39930 this._spriteAtlas$.subscribe(function () { });
39931 if (sprite == null) {
39934 var format = this._retina ? "@2x" : "";
39935 var imageXmlHTTP = new XMLHttpRequest();
39936 imageXmlHTTP.open("GET", sprite + format + ".png", true);
39937 imageXmlHTTP.responseType = "arraybuffer";
39938 imageXmlHTTP.onload = function () {
39939 var image = new Image();
39940 image.onload = function () {
39941 _this._spriteAtlasOperation$.next(function (atlas) {
39942 atlas.image = image;
39946 var blob = new Blob([imageXmlHTTP.response]);
39947 image.src = window.URL.createObjectURL(blob);
39949 imageXmlHTTP.onerror = function (error) {
39950 console.error(new Error("Failed to fetch sprite sheet (" + sprite + format + ".png)"));
39952 imageXmlHTTP.send();
39953 var jsonXmlHTTP = new XMLHttpRequest();
39954 jsonXmlHTTP.open("GET", sprite + format + ".json", true);
39955 jsonXmlHTTP.responseType = "text";
39956 jsonXmlHTTP.onload = function () {
39957 var json = JSON.parse(jsonXmlHTTP.response);
39958 _this._spriteAtlasOperation$.next(function (atlas) {
39963 jsonXmlHTTP.onerror = function (error) {
39964 console.error(new Error("Failed to fetch sheet (" + sprite + format + ".json)"));
39966 jsonXmlHTTP.send();
39968 Object.defineProperty(SpriteService.prototype, "spriteAtlas$", {
39970 return this._spriteAtlas$;
39975 return SpriteService;
39977 exports.SpriteService = SpriteService;
39978 exports.default = SpriteService;
39980 },{"../Viewer":236,"rxjs/Subject":34,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73,"rxjs/add/operator/startWith":78,"three":176,"virtual-dom":182}],354:[function(require,module,exports){
39982 Object.defineProperty(exports, "__esModule", { value: true });
39983 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
39984 var Observable_1 = require("rxjs/Observable");
39985 var Subject_1 = require("rxjs/Subject");
39986 require("rxjs/add/observable/timer");
39987 require("rxjs/add/operator/bufferWhen");
39988 require("rxjs/add/operator/filter");
39989 require("rxjs/add/operator/map");
39990 require("rxjs/add/operator/merge");
39991 require("rxjs/add/operator/scan");
39992 require("rxjs/add/operator/switchMap");
39993 var TouchService = (function () {
39994 function TouchService(canvasContainer, domContainer) {
39996 this._canvasContainer = canvasContainer;
39997 this._domContainer = domContainer;
39998 this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
39999 this._active$ = this._activeSubject$
40000 .distinctUntilChanged()
40003 Observable_1.Observable.fromEvent(domContainer, "touchmove")
40004 .subscribe(function (event) {
40005 event.preventDefault();
40007 this._touchStart$ = Observable_1.Observable.fromEvent(canvasContainer, "touchstart");
40008 this._touchMove$ = Observable_1.Observable.fromEvent(canvasContainer, "touchmove");
40009 this._touchEnd$ = Observable_1.Observable.fromEvent(canvasContainer, "touchend");
40010 this._touchCancel$ = Observable_1.Observable.fromEvent(canvasContainer, "touchcancel");
40011 var tapStart$ = this._touchStart$
40012 .filter(function (te) {
40013 return te.touches.length === 1 && te.targetTouches.length === 1;
40016 this._doubleTap$ = tapStart$
40017 .bufferWhen(function () {
40020 .switchMap(function (event) {
40021 return Observable_1.Observable
40027 .filter(function (events) {
40028 return events.length === 2;
40030 .map(function (events) {
40031 return events[events.length - 1];
40035 .subscribe(function (event) {
40036 event.preventDefault();
40038 this._singleTouchMove$ = this._touchMove$
40039 .filter(function (te) {
40040 return te.touches.length === 1 && te.targetTouches.length === 1;
40043 var singleTouchStart$ = Observable_1.Observable
40044 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
40045 .filter(function (te) {
40046 return te.touches.length === 1 && te.targetTouches.length === 1;
40048 var multipleTouchStart$ = Observable_1.Observable
40049 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
40050 .filter(function (te) {
40051 return te.touches.length >= 1;
40053 var touchStop$ = Observable_1.Observable
40054 .merge(this._touchEnd$, this._touchCancel$)
40055 .filter(function (te) {
40056 return te.touches.length === 0;
40058 this._singleTouchDragStart$ = singleTouchStart$
40059 .mergeMap(function (e) {
40060 return _this._singleTouchMove$
40061 .takeUntil(Observable_1.Observable.merge(touchStop$, multipleTouchStart$))
40064 this._singleTouchDragEnd$ = singleTouchStart$
40065 .mergeMap(function (e) {
40066 return Observable_1.Observable
40067 .merge(touchStop$, multipleTouchStart$)
40070 this._singleTouchDrag$ = singleTouchStart$
40071 .switchMap(function (te) {
40072 return _this._singleTouchMove$
40074 .takeUntil(Observable_1.Observable
40075 .merge(multipleTouchStart$, touchStop$));
40077 var touchesChanged$ = Observable_1.Observable
40078 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$);
40079 this._pinchStart$ = touchesChanged$
40080 .filter(function (te) {
40081 return te.touches.length === 2 && te.targetTouches.length === 2;
40083 this._pinchEnd$ = touchesChanged$
40084 .filter(function (te) {
40085 return te.touches.length !== 2 || te.targetTouches.length !== 2;
40087 this._pinchOperation$ = new Subject_1.Subject();
40088 this._pinch$ = this._pinchOperation$
40089 .scan(function (pinch, operation) {
40090 return operation(pinch);
40100 originalEvent: null,
40109 .filter(function (te) {
40110 return te.touches.length === 2 && te.targetTouches.length === 2;
40112 .map(function (te) {
40113 return function (previous) {
40114 var touch1 = te.touches[0];
40115 var touch2 = te.touches[1];
40116 var minX = Math.min(touch1.clientX, touch2.clientX);
40117 var maxX = Math.max(touch1.clientX, touch2.clientX);
40118 var minY = Math.min(touch1.clientY, touch2.clientY);
40119 var maxY = Math.max(touch1.clientY, touch2.clientY);
40120 var centerClientX = minX + (maxX - minX) / 2;
40121 var centerClientY = minY + (maxY - minY) / 2;
40122 var centerPageX = centerClientX + touch1.pageX - touch1.clientX;
40123 var centerPageY = centerClientY + touch1.pageY - touch1.clientY;
40124 var centerScreenX = centerClientX + touch1.screenX - touch1.clientX;
40125 var centerScreenY = centerClientY + touch1.screenY - touch1.clientY;
40126 var distanceX = Math.abs(touch1.clientX - touch2.clientX);
40127 var distanceY = Math.abs(touch1.clientY - touch2.clientY);
40128 var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
40129 var distanceChange = distance - previous.distance;
40130 var changeX = distanceX - previous.distanceX;
40131 var changeY = distanceY - previous.distanceY;
40135 clientX: centerClientX,
40136 clientY: centerClientY,
40137 distance: distance,
40138 distanceChange: distanceChange,
40139 distanceX: distanceX,
40140 distanceY: distanceY,
40142 pageX: centerPageX,
40143 pageY: centerPageY,
40144 screenX: centerScreenX,
40145 screenY: centerScreenY,
40152 .subscribe(this._pinchOperation$);
40153 this._pinchChange$ = this._pinchStart$
40154 .switchMap(function (te) {
40155 return _this._pinch$
40157 .takeUntil(_this._pinchEnd$);
40160 Object.defineProperty(TouchService.prototype, "active$", {
40162 return this._active$;
40167 Object.defineProperty(TouchService.prototype, "activate$", {
40169 return this._activeSubject$;
40174 Object.defineProperty(TouchService.prototype, "doubleTap$", {
40176 return this._doubleTap$;
40181 Object.defineProperty(TouchService.prototype, "touchStart$", {
40183 return this._touchStart$;
40188 Object.defineProperty(TouchService.prototype, "touchMove$", {
40190 return this._touchMove$;
40195 Object.defineProperty(TouchService.prototype, "touchEnd$", {
40197 return this._touchEnd$;
40202 Object.defineProperty(TouchService.prototype, "touchCancel$", {
40204 return this._touchCancel$;
40209 Object.defineProperty(TouchService.prototype, "singleTouchDragStart$", {
40211 return this._singleTouchDragStart$;
40216 Object.defineProperty(TouchService.prototype, "singleTouchDrag$", {
40218 return this._singleTouchDrag$;
40223 Object.defineProperty(TouchService.prototype, "singleTouchDragEnd$", {
40225 return this._singleTouchDragEnd$;
40230 Object.defineProperty(TouchService.prototype, "pinch$", {
40232 return this._pinchChange$;
40237 Object.defineProperty(TouchService.prototype, "pinchStart$", {
40239 return this._pinchStart$;
40244 Object.defineProperty(TouchService.prototype, "pinchEnd$", {
40246 return this._pinchEnd$;
40251 return TouchService;
40253 exports.TouchService = TouchService;
40255 },{"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/timer":47,"rxjs/add/operator/bufferWhen":51,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/merge":66,"rxjs/add/operator/scan":73,"rxjs/add/operator/switchMap":79}],355:[function(require,module,exports){
40257 /// <reference path="../../typings/index.d.ts" />
40258 var __extends = (this && this.__extends) || (function () {
40259 var extendStatics = Object.setPrototypeOf ||
40260 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
40261 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
40262 return function (d, b) {
40263 extendStatics(d, b);
40264 function __() { this.constructor = d; }
40265 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40268 Object.defineProperty(exports, "__esModule", { value: true });
40269 var when = require("when");
40270 var Viewer_1 = require("../Viewer");
40271 var Utils_1 = require("../Utils");
40275 * @classdesc The Viewer object represents the navigable photo viewer.
40276 * Create a Viewer by specifying a container, client ID, photo key and
40277 * other options. The viewer exposes methods and events for programmatic
40280 * The viewer works with a few different coordinate systems.
40282 * Container pixel coordinates
40284 * Pixel coordinates are coordinates on the viewer container. The origin is
40285 * in the top left corner of the container. The axes are
40286 * directed according to the following for a viewer container with a width
40287 * of 640 pixels and height of 480 pixels.
40291 * +------------------------>
40296 * (0, 480) (640, 480)
40299 * Basic image coordinates
40301 * Basic image coordinates represents points in the original image adjusted for
40302 * orientation. They range from 0 to 1 on both axes. The origin is in the top left
40303 * corner of the image and the axes are directed
40304 * according to the following for all image types.
40308 * +------------------------>
40316 * For every camera viewing direction it is possible to convert between these
40317 * two coordinate systems for the current node. The image can be panned and
40318 * zoomed independently of the size of the viewer container resulting in
40319 * different conversion results for different viewing directions.
40321 var Viewer = (function (_super) {
40322 __extends(Viewer, _super);
40324 * Create a new viewer instance.
40326 * @param {string} id - Required `id` of a DOM element which will
40327 * be transformed into the viewer.
40328 * @param {string} clientId - Required `Mapillary API ClientID`. Can
40329 * be obtained from https://www.mapillary.com/app/settings/developers.
40330 * @param {string} [key] - Optional `photoId` to start from, can be any
40331 * Mapillary photo, if null no image is loaded.
40332 * @param {IViewerOptions} [options] - Optional configuration object
40333 * specifing Viewer's initial setup.
40334 * @param {string} [token] - Optional bearer token for API requests of
40335 * protected resources.
40339 * var viewer = new Mapillary.Viewer("<element-id>", "<client-id>", "<my key>");
40342 function Viewer(id, clientId, key, options, token) {
40343 var _this = _super.call(this) || this;
40344 options = options != null ? options : {};
40345 Utils_1.Settings.setOptions(options);
40346 _this._navigator = new Viewer_1.Navigator(clientId, token);
40347 _this._container = new Viewer_1.Container(id, _this._navigator.stateService, options);
40348 _this._observer = new Viewer_1.Observer(_this, _this._navigator, _this._container);
40349 _this._componentController = new Viewer_1.ComponentController(_this._container, _this._navigator, _this._observer, key, options.component);
40353 * Activate a component.
40355 * @param {string} name - Name of the component which will become active.
40359 * viewer.activateComponent("marker");
40362 Viewer.prototype.activateComponent = function (name) {
40363 this._componentController.activate(name);
40366 * Activate the cover (deactivates all other components).
40368 Viewer.prototype.activateCover = function () {
40369 this._componentController.activateCover();
40372 * Deactivate a component.
40374 * @param {string} name - Name of component which become inactive.
40378 * viewer.deactivateComponent("mouse");
40381 Viewer.prototype.deactivateComponent = function (name) {
40382 this._componentController.deactivate(name);
40385 * Deactivate the cover (activates all components marked as active).
40387 Viewer.prototype.deactivateCover = function () {
40388 this._componentController.deactivateCover();
40391 * Get the bearing of the current viewer camera.
40393 * @description The bearing depends on how the camera
40394 * is currently rotated and does not correspond
40395 * to the compass angle of the current node if the view
40398 * Bearing is measured in degrees clockwise with respect to
40401 * @returns {Promise<number>} Promise to the bearing
40402 * of the current viewer camera.
40406 * viewer.getBearing().then((b) => { console.log(b); });
40409 Viewer.prototype.getBearing = function () {
40411 return when.promise(function (resolve, reject) {
40412 _this._container.renderService.bearing$
40414 .subscribe(function (bearing) {
40416 }, function (error) {
40422 * Get the basic coordinates of the current photo that is
40423 * at the center of the viewport.
40425 * @description Basic coordinates are 2D coordinates on the [0, 1] interval
40426 * and have the origin point, (0, 0), at the top left corner and the
40427 * maximum value, (1, 1), at the bottom right corner of the original
40430 * @returns {Promise<number[]>} Promise to the basic coordinates
40431 * of the current photo at the center for the viewport.
40435 * viewer.getCenter().then((c) => { console.log(c); });
40438 Viewer.prototype.getCenter = function () {
40440 return when.promise(function (resolve, reject) {
40441 _this._navigator.stateService.getCenter()
40442 .subscribe(function (center) {
40444 }, function (error) {
40452 * @param {string} name - Name of component.
40453 * @returns {Component} The requested component.
40457 * var mouseComponent = viewer.getComponent("mouse");
40460 Viewer.prototype.getComponent = function (name) {
40461 return this._componentController.get(name);
40464 * Returns the viewer's containing HTML element.
40466 * @returns {HTMLElement} The viewer's container.
40468 Viewer.prototype.getContainer = function () {
40469 return this._container.element;
40472 * Get the photo's current zoom level.
40474 * @returns {Promise<number>} Promise to the viewers's current
40479 * viewer.getZoom().then((z) => { console.log(z); });
40482 Viewer.prototype.getZoom = function () {
40484 return when.promise(function (resolve, reject) {
40485 _this._navigator.stateService.getZoom()
40486 .subscribe(function (zoom) {
40488 }, function (error) {
40494 * Move close to given latitude and longitude.
40496 * @description Because the method propagates IO errors, these potential errors
40497 * need to be handled by the method caller (see example).
40499 * @param {Number} lat - Latitude, in degrees.
40500 * @param {Number} lon - Longitude, in degrees.
40501 * @returns {Promise<Node>} Promise to the node that was navigated to.
40502 * @throws {Error} If no nodes exist close to provided latitude
40504 * @throws {Error} Propagates any IO errors to the caller.
40508 * viewer.moveCloseTo(0, 0).then(
40509 * (n) => { console.log(n); },
40510 * (e) => { console.error(e); });
40513 Viewer.prototype.moveCloseTo = function (lat, lon) {
40515 return when.promise(function (resolve, reject) {
40516 _this._navigator.moveCloseTo$(lat, lon).subscribe(function (node) {
40518 }, function (error) {
40524 * Navigate in a given direction.
40526 * @description This method has to be called through EdgeDirection enumeration as in the example.
40528 * @param {EdgeDirection} dir - Direction in which which to move.
40529 * @returns {Promise<Node>} Promise to the node that was navigated to.
40530 * @throws {Error} If the current node does not have the edge direction
40531 * or the edges has not yet been cached.
40532 * @throws {Error} Propagates any IO errors to the caller.
40536 * viewer.moveDir(Mapillary.EdgeDirection.Next).then(
40537 * (n) => { console.log(n); },
40538 * (e) => { console.error(e); });
40541 Viewer.prototype.moveDir = function (dir) {
40543 return when.promise(function (resolve, reject) {
40544 _this._navigator.moveDir$(dir).subscribe(function (node) {
40546 }, function (error) {
40552 * Navigate to a given photo key.
40554 * @param {string} key - A valid Mapillary photo key.
40555 * @returns {Promise<Node>} Promise to the node that was navigated to.
40556 * @throws {Error} Propagates any IO errors to the caller.
40560 * viewer.moveToKey("<my key>").then(
40561 * (n) => { console.log(n); },
40562 * (e) => { console.error(e); });
40565 Viewer.prototype.moveToKey = function (key) {
40567 return when.promise(function (resolve, reject) {
40568 _this._navigator.moveToKey$(key).subscribe(function (node) {
40570 }, function (error) {
40576 * Project basic image coordinates for the current node to canvas pixel
40579 * @description The basic image coordinates may not always correspond to a
40580 * pixel point that lies in the visible area of the viewer container.
40582 * @param {Array<number>} basicPoint - Basic images coordinates to project.
40583 * @returns {Promise<ILatLon>} Promise to the pixel coordinates corresponding
40584 * to the basic image point.
40588 * viewer.projectFromBasic([0.3, 0.7])
40589 * .then((pixelPoint) => { console.log(pixelPoint); });
40592 Viewer.prototype.projectFromBasic = function (basicPoint) {
40594 return when.promise(function (resolve, reject) {
40595 _this._observer.projectBasic$(basicPoint)
40596 .subscribe(function (pixelPoint) {
40597 resolve(pixelPoint);
40598 }, function (error) {
40604 * Detect the viewer's new width and height and resize it.
40606 * @description The components will also detect the viewer's
40607 * new size and resize their rendered elements if needed.
40614 Viewer.prototype.resize = function () {
40615 this._container.renderService.resize$.next(null);
40616 this._componentController.resize();
40619 * Set a bearer token for authenticated API requests of
40620 * protected resources.
40622 * @description When the supplied token is null or undefined,
40623 * any previously set bearer token will be cleared and the
40624 * viewer will make unauthenticated requests.
40626 * Calling setAuthToken aborts all outstanding move requests.
40627 * The promises of those move requests will be rejected and
40628 * the rejections need to be caught.
40630 * @param {string} [token] token - Bearer token.
40631 * @returns {Promise<void>} Promise that resolves after token
40636 * viewer.setAuthToken("<my token>")
40637 * .then(() => { console.log("token set"); });
40640 Viewer.prototype.setAuthToken = function (token) {
40642 return when.promise(function (resolve, reject) {
40643 _this._navigator.setToken$(token)
40644 .subscribe(function () {
40645 resolve(undefined);
40646 }, function (error) {
40652 * Set the basic coordinates of the current photo to be in the
40653 * center of the viewport.
40655 * @description Basic coordinates are 2D coordinates on the [0, 1] interval
40656 * and has the origin point, (0, 0), at the top left corner and the
40657 * maximum value, (1, 1), at the bottom right corner of the original
40660 * @param {number[]} The basic coordinates of the current
40661 * photo to be at the center for the viewport.
40665 * viewer.setCenter([0.5, 0.5]);
40668 Viewer.prototype.setCenter = function (center) {
40669 this._navigator.stateService.setCenter(center);
40672 * Set the filter selecting nodes to use when calculating
40673 * the spatial edges.
40675 * @description The following filter types are supported:
40679 * `["==", key, value]` equality: `node[key] = value`
40681 * `["!=", key, value]` inequality: `node[key] ≠ value`
40683 * `["<", key, value]` less than: `node[key] < value`
40685 * `["<=", key, value]` less than or equal: `node[key] ≤ value`
40687 * `[">", key, value]` greater than: `node[key] > value`
40689 * `[">=", key, value]` greater than or equal: `node[key] ≥ value`
40693 * `["in", key, v0, ..., vn]` set inclusion: `node[key] ∈ {v0, ..., vn}`
40695 * `["!in", key, v0, ..., vn]` set exclusion: `node[key] ∉ {v0, ..., vn}`
40699 * `["all", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`
40701 * A key must be a string that identifies a node property name. A value must be
40702 * a string, number, or boolean. Strictly-typed comparisons are used. The values
40703 * `f0, ..., fn` of the combining filter must be filter expressions.
40705 * Clear the filter by setting it to null or empty array.
40707 * @param {FilterExpression} filter - The filter expression.
40708 * @returns {Promise<void>} Promise that resolves after filter is applied.
40712 * viewer.setFilter(["==", "sequenceKey", "<my sequence key>"]);
40715 Viewer.prototype.setFilter = function (filter) {
40717 return when.promise(function (resolve, reject) {
40718 _this._navigator.setFilter$(filter)
40719 .subscribe(function () {
40720 resolve(undefined);
40721 }, function (error) {
40727 * Set the viewer's render mode.
40729 * @param {RenderMode} renderMode - Render mode.
40733 * viewer.setRenderMode(Mapillary.RenderMode.Letterbox);
40736 Viewer.prototype.setRenderMode = function (renderMode) {
40737 this._container.renderService.renderMode$.next(renderMode);
40740 * Set the photo's current zoom level.
40742 * @description Possible zoom level values are on the [0, 3] interval.
40743 * Zero means zooming out to fit the photo to the view whereas three
40744 * shows the highest level of detail.
40746 * @param {number} The photo's current zoom level.
40750 * viewer.setZoom(2);
40753 Viewer.prototype.setZoom = function (zoom) {
40754 this._navigator.stateService.setZoom(zoom);
40757 * Unproject canvas pixel coordinates to an ILatLon representing geographical
40760 * @description The pixel point may not always correspond to geographical
40761 * coordinates. In the case of no correspondence the returned value will
40764 * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
40765 * @returns {Promise<ILatLon>} Promise to the latLon corresponding to the pixel point.
40769 * viewer.unproject([100, 100])
40770 * .then((latLon) => { console.log(latLon); });
40773 Viewer.prototype.unproject = function (pixelPoint) {
40775 return when.promise(function (resolve, reject) {
40776 _this._observer.unproject$(pixelPoint)
40777 .subscribe(function (latLon) {
40779 }, function (error) {
40785 * Unproject canvas pixel coordinates to basic image coordinates for the
40788 * @description The pixel point may not always correspond to basic image
40789 * coordinates. In the case of no correspondence the returned value will
40792 * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
40793 * @returns {Promise<ILatLon>} Promise to the basic coordinates corresponding
40794 * to the pixel point.
40798 * viewer.unprojectToBasic([100, 100])
40799 * .then((basicPoint) => { console.log(basicPoint); });
40802 Viewer.prototype.unprojectToBasic = function (pixelPoint) {
40804 return when.promise(function (resolve, reject) {
40805 _this._observer.unprojectBasic$(pixelPoint)
40806 .subscribe(function (basicPoint) {
40807 resolve(basicPoint);
40808 }, function (error) {
40814 }(Utils_1.EventEmitter));
40816 * Fired when the viewing direction of the camera changes.
40818 * @type {number} bearing - Value indicating the current bearing
40819 * measured in degrees clockwise with respect to north.
40821 Viewer.bearingchanged = "bearingchanged";
40823 * Fired when a pointing device (usually a mouse) is pressed and released at
40824 * the same point in the viewer.
40826 * @type {IViewerMouseEvent} event - Viewer mouse event data.
40828 Viewer.click = "click";
40830 * Fired when the right button of the mouse is clicked within the viewer.
40832 * @type {IViewerMouseEvent} event - Viewer mouse event data.
40834 Viewer.contextmenu = "contextmenu";
40836 * Fired when a pointing device (usually a mouse) is clicked twice at
40837 * the same point in the viewer.
40839 * @type {IViewerMouseEvent} event - Viewer mouse event data.
40841 Viewer.dblclick = "dblclick";
40843 * Fired when the viewer is loading more data.
40845 * @type {boolean} loading - Value indicating whether the viewer is loading.
40847 Viewer.loadingchanged = "loadingchanged";
40849 * Fired when a pointing device (usually a mouse) is pressed within the viewer.
40851 * @type {IViewerMouseEvent} event - Viewer mouse event data.
40853 Viewer.mousedown = "mousedown";
40855 * Fired when a pointing device (usually a mouse) is moved within the viewer.
40856 * @description Will not fire when the mouse is actively used, e.g. for drag pan.
40858 * @type {IViewerMouseEvent} event - Viewer mouse event data.
40860 Viewer.mousemove = "mousemove";
40862 * Fired when a pointing device (usually a mouse) leaves the viewer's canvas.
40864 * @type {IViewerMouseEvent} event - Viewer mouse event data.
40866 Viewer.mouseout = "mouseout";
40868 * Fired when a pointing device (usually a mouse) is moved onto the viewer's canvas.
40870 * @type {IViewerMouseEvent} event - Viewer mouse event data.
40872 Viewer.mouseover = "mouseover";
40874 * Fired when a pointing device (usually a mouse) is released within the viewer.
40876 * @type {IViewerMouseEvent} event - Viewer mouse event data.
40878 Viewer.mouseup = "mouseup";
40880 * Fired when the viewer motion stops and it is in a fixed
40881 * position with a fixed point of view.
40884 Viewer.moveend = "moveend";
40886 * Fired when the motion from one view to another start,
40887 * either by changing the position (e.g. when changing node) or
40888 * when changing point of view (e.g. by interaction such as pan and zoom).
40891 Viewer.movestart = "movestart";
40893 * Fired every time the viewer navigates to a new node.
40895 * @type {Node} node - Current node.
40897 Viewer.nodechanged = "nodechanged";
40899 * Fired every time the sequence edges of the current node changes.
40901 * @type {IEdgeStatus} status - The edge status object.
40903 Viewer.sequenceedgeschanged = "sequenceedgeschanged";
40905 * Fired every time the spatial edges of the current node changes.
40907 * @type {IEdgeStatus} status - The edge status object.
40909 Viewer.spatialedgeschanged = "spatialedgeschanged";
40910 exports.Viewer = Viewer;
40912 },{"../Utils":235,"../Viewer":236,"when":223}]},{},[231])(231)
40914 //# sourceMappingURL=mapillary.js.map