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 exports.byteLength = byteLength
5 exports.toByteArray = toByteArray
6 exports.fromByteArray = fromByteArray
10 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
12 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
13 for (var i = 0, len = code.length; i < len; ++i) {
15 revLookup[code.charCodeAt(i)] = i
18 revLookup['-'.charCodeAt(0)] = 62
19 revLookup['_'.charCodeAt(0)] = 63
21 function placeHoldersCount (b64) {
24 throw new Error('Invalid string. Length must be a multiple of 4')
27 // the number of equal signs (place holders)
28 // if there are two placeholders, than the two characters before it
30 // if there is only one, then the three characters before it represent 2 bytes
31 // this is just a cheap hack to not do indexOf twice
32 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
35 function byteLength (b64) {
36 // base64 is 4/3 + up to two characters of the original data
37 return b64.length * 3 / 4 - placeHoldersCount(b64)
40 function toByteArray (b64) {
41 var i, j, l, tmp, placeHolders, arr
43 placeHolders = placeHoldersCount(b64)
45 arr = new Arr(len * 3 / 4 - placeHolders)
47 // if there are placeholders, only get up to the last complete 4 chars
48 l = placeHolders > 0 ? len - 4 : len
52 for (i = 0, j = 0; i < l; i += 4, j += 3) {
53 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
54 arr[L++] = (tmp >> 16) & 0xFF
55 arr[L++] = (tmp >> 8) & 0xFF
59 if (placeHolders === 2) {
60 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
62 } else if (placeHolders === 1) {
63 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
64 arr[L++] = (tmp >> 8) & 0xFF
71 function tripletToBase64 (num) {
72 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
75 function encodeChunk (uint8, start, end) {
78 for (var i = start; i < end; i += 3) {
79 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
80 output.push(tripletToBase64(tmp))
82 return output.join('')
85 function fromByteArray (uint8) {
87 var len = uint8.length
88 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
91 var maxChunkLength = 16383 // must be multiple of 3
93 // go through the array every three bytes, we'll deal with trailing stuff later
94 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
95 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
98 // pad the end with zeros, but make sure to not forget the extra bytes
99 if (extraBytes === 1) {
101 output += lookup[tmp >> 2]
102 output += lookup[(tmp << 4) & 0x3F]
104 } else if (extraBytes === 2) {
105 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
106 output += lookup[tmp >> 10]
107 output += lookup[(tmp >> 4) & 0x3F]
108 output += lookup[(tmp << 2) & 0x3F]
114 return parts.join('')
117 },{}],2:[function(require,module,exports){
119 },{}],3:[function(require,module,exports){
121 * Cross-Browser Split 1.1.1
122 * Copyright 2007-2012 Steven Levithan <stevenlevithan.com>
123 * Available under the MIT License
124 * ECMAScript compliant, uniform cross-browser split method
128 * Splits a string into an array of strings using a regex or string separator. Matches of the
129 * separator are not included in the result array. However, if `separator` is a regex that contains
130 * capturing groups, backreferences are spliced into the result each time `separator` is matched.
131 * Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably
133 * @param {String} str String to split.
134 * @param {RegExp|String} separator Regex or string to use for separating the string.
135 * @param {Number} [limit] Maximum number of items to include in the result array.
136 * @returns {Array} Array of substrings.
140 * split('a b c d', ' ');
141 * // -> ['a', 'b', 'c', 'd']
144 * split('a b c d', ' ', 2);
147 * // Backreferences in result array
148 * split('..word1 word2..', /([a-z]+)(\d+)/i);
149 * // -> ['..', 'word', '1', ' ', 'word', '2', '..']
151 module.exports = (function split(undef) {
153 var nativeSplit = String.prototype.split,
154 compliantExecNpcg = /()??/.exec("")[1] === undef,
155 // NPCG: nonparticipating capturing group
158 self = function(str, separator, limit) {
159 // If `separator` is not a regex, use `nativeSplit`
160 if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
161 return nativeSplit.call(str, separator, limit);
164 flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6
165 (separator.sticky ? "y" : ""),
168 // Make `global` and avoid `lastIndex` issues by working with a copy
169 separator = new RegExp(separator.source, flags + "g"),
170 separator2, match, lastIndex, lastLength;
171 str += ""; // Type-convert
172 if (!compliantExecNpcg) {
173 // Doesn't need flags gy, but they don't hurt
174 separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
176 /* Values for `limit`, per the spec:
177 * If undefined: 4294967295 // Math.pow(2, 32) - 1
178 * If 0, Infinity, or NaN: 0
179 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
180 * If negative number: 4294967296 - Math.floor(Math.abs(limit))
181 * If other: Type-convert, then use the above rules
183 limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1
184 limit >>> 0; // ToUint32(limit)
185 while (match = separator.exec(str)) {
186 // `separator.lastIndex` is not reliable cross-browser
187 lastIndex = match.index + match[0].length;
188 if (lastIndex > lastLastIndex) {
189 output.push(str.slice(lastLastIndex, match.index));
190 // Fix browsers whose `exec` methods don't consistently return `undefined` for
191 // nonparticipating capturing groups
192 if (!compliantExecNpcg && match.length > 1) {
193 match[0].replace(separator2, function() {
194 for (var i = 1; i < arguments.length - 2; i++) {
195 if (arguments[i] === undef) {
201 if (match.length > 1 && match.index < str.length) {
202 Array.prototype.push.apply(output, match.slice(1));
204 lastLength = match[0].length;
205 lastLastIndex = lastIndex;
206 if (output.length >= limit) {
210 if (separator.lastIndex === match.index) {
211 separator.lastIndex++; // Avoid an infinite loop
214 if (lastLastIndex === str.length) {
215 if (lastLength || !separator.test("")) {
219 output.push(str.slice(lastLastIndex));
221 return output.length > limit ? output.slice(0, limit) : output;
227 },{}],4:[function(require,module,exports){
228 // shim for using process in browser
229 var process = module.exports = {};
231 // cached from whatever global is present so that test runners that stub it
232 // don't break things. But we need to wrap it in a try catch in case it is
233 // wrapped in strict mode code which doesn't define any globals. It's inside a
234 // function because try/catches deoptimize in certain engines.
236 var cachedSetTimeout;
237 var cachedClearTimeout;
239 function defaultSetTimout() {
240 throw new Error('setTimeout has not been defined');
242 function defaultClearTimeout () {
243 throw new Error('clearTimeout has not been defined');
247 if (typeof setTimeout === 'function') {
248 cachedSetTimeout = setTimeout;
250 cachedSetTimeout = defaultSetTimout;
253 cachedSetTimeout = defaultSetTimout;
256 if (typeof clearTimeout === 'function') {
257 cachedClearTimeout = clearTimeout;
259 cachedClearTimeout = defaultClearTimeout;
262 cachedClearTimeout = defaultClearTimeout;
265 function runTimeout(fun) {
266 if (cachedSetTimeout === setTimeout) {
267 //normal enviroments in sane situations
268 return setTimeout(fun, 0);
270 // if setTimeout wasn't available but was latter defined
271 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
272 cachedSetTimeout = setTimeout;
273 return setTimeout(fun, 0);
276 // when when somebody has screwed with setTimeout but no I.E. maddness
277 return cachedSetTimeout(fun, 0);
280 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
281 return cachedSetTimeout.call(null, fun, 0);
283 // 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
284 return cachedSetTimeout.call(this, fun, 0);
290 function runClearTimeout(marker) {
291 if (cachedClearTimeout === clearTimeout) {
292 //normal enviroments in sane situations
293 return clearTimeout(marker);
295 // if clearTimeout wasn't available but was latter defined
296 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
297 cachedClearTimeout = clearTimeout;
298 return clearTimeout(marker);
301 // when when somebody has screwed with setTimeout but no I.E. maddness
302 return cachedClearTimeout(marker);
305 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
306 return cachedClearTimeout.call(null, marker);
308 // 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.
309 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
310 return cachedClearTimeout.call(this, marker);
318 var draining = false;
322 function cleanUpNextTick() {
323 if (!draining || !currentQueue) {
327 if (currentQueue.length) {
328 queue = currentQueue.concat(queue);
337 function drainQueue() {
341 var timeout = runTimeout(cleanUpNextTick);
344 var len = queue.length;
346 currentQueue = queue;
348 while (++queueIndex < len) {
350 currentQueue[queueIndex].run();
358 runClearTimeout(timeout);
361 process.nextTick = function (fun) {
362 var args = new Array(arguments.length - 1);
363 if (arguments.length > 1) {
364 for (var i = 1; i < arguments.length; i++) {
365 args[i - 1] = arguments[i];
368 queue.push(new Item(fun, args));
369 if (queue.length === 1 && !draining) {
370 runTimeout(drainQueue);
374 // v8 likes predictible objects
375 function Item(fun, array) {
379 Item.prototype.run = function () {
380 this.fun.apply(null, this.array);
382 process.title = 'browser';
383 process.browser = true;
386 process.version = ''; // empty string to avoid regexp issues
387 process.versions = {};
392 process.addListener = noop;
395 process.removeListener = noop;
396 process.removeAllListeners = noop;
398 process.prependListener = noop;
399 process.prependOnceListener = noop;
401 process.listeners = function (name) { return [] }
403 process.binding = function (name) {
404 throw new Error('process.binding is not supported');
407 process.cwd = function () { return '/' };
408 process.chdir = function (dir) {
409 throw new Error('process.chdir is not supported');
411 process.umask = function() { return 0; };
413 },{}],5:[function(require,module,exports){
416 * The buffer module from node.js, for the browser.
418 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
421 /* eslint-disable no-proto */
425 var base64 = require('base64-js')
426 var ieee754 = require('ieee754')
427 var isArray = require('isarray')
429 exports.Buffer = Buffer
430 exports.SlowBuffer = SlowBuffer
431 exports.INSPECT_MAX_BYTES = 50
434 * If `Buffer.TYPED_ARRAY_SUPPORT`:
435 * === true Use Uint8Array implementation (fastest)
436 * === false Use Object implementation (most compatible, even IE6)
438 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
439 * Opera 11.6+, iOS 4.2+.
441 * Due to various browser bugs, sometimes the Object implementation will be used even
442 * when the browser supports typed arrays.
446 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
447 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
449 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
451 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
452 * incorrect length in some situations.
454 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
455 * get the Object implementation, which is slower but behaves correctly.
457 Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
458 ? global.TYPED_ARRAY_SUPPORT
459 : typedArraySupport()
462 * Export kMaxLength after typed array support is determined.
464 exports.kMaxLength = kMaxLength()
466 function typedArraySupport () {
468 var arr = new Uint8Array(1)
469 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
470 return arr.foo() === 42 && // typed array instances can be augmented
471 typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
472 arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
478 function kMaxLength () {
479 return Buffer.TYPED_ARRAY_SUPPORT
484 function createBuffer (that, length) {
485 if (kMaxLength() < length) {
486 throw new RangeError('Invalid typed array length')
488 if (Buffer.TYPED_ARRAY_SUPPORT) {
489 // Return an augmented `Uint8Array` instance, for best performance
490 that = new Uint8Array(length)
491 that.__proto__ = Buffer.prototype
493 // Fallback: Return an object instance of the Buffer class
495 that = new Buffer(length)
504 * The Buffer constructor returns instances of `Uint8Array` that have their
505 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
506 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
507 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
508 * returns a single octet.
510 * The `Uint8Array` prototype remains unmodified.
513 function Buffer (arg, encodingOrOffset, length) {
514 if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
515 return new Buffer(arg, encodingOrOffset, length)
519 if (typeof arg === 'number') {
520 if (typeof encodingOrOffset === 'string') {
522 'If encoding is specified then the first argument must be a string'
525 return allocUnsafe(this, arg)
527 return from(this, arg, encodingOrOffset, length)
530 Buffer.poolSize = 8192 // not used by this implementation
532 // TODO: Legacy, not needed anymore. Remove in next major version.
533 Buffer._augment = function (arr) {
534 arr.__proto__ = Buffer.prototype
538 function from (that, value, encodingOrOffset, length) {
539 if (typeof value === 'number') {
540 throw new TypeError('"value" argument must not be a number')
543 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
544 return fromArrayBuffer(that, value, encodingOrOffset, length)
547 if (typeof value === 'string') {
548 return fromString(that, value, encodingOrOffset)
551 return fromObject(that, value)
555 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
556 * if value is a number.
557 * Buffer.from(str[, encoding])
559 * Buffer.from(buffer)
560 * Buffer.from(arrayBuffer[, byteOffset[, length]])
562 Buffer.from = function (value, encodingOrOffset, length) {
563 return from(null, value, encodingOrOffset, length)
566 if (Buffer.TYPED_ARRAY_SUPPORT) {
567 Buffer.prototype.__proto__ = Uint8Array.prototype
568 Buffer.__proto__ = Uint8Array
569 if (typeof Symbol !== 'undefined' && Symbol.species &&
570 Buffer[Symbol.species] === Buffer) {
571 // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
572 Object.defineProperty(Buffer, Symbol.species, {
579 function assertSize (size) {
580 if (typeof size !== 'number') {
581 throw new TypeError('"size" argument must be a number')
582 } else if (size < 0) {
583 throw new RangeError('"size" argument must not be negative')
587 function alloc (that, size, fill, encoding) {
590 return createBuffer(that, size)
592 if (fill !== undefined) {
593 // Only pay attention to encoding if it's a string. This
594 // prevents accidentally sending in a number that would
595 // be interpretted as a start offset.
596 return typeof encoding === 'string'
597 ? createBuffer(that, size).fill(fill, encoding)
598 : createBuffer(that, size).fill(fill)
600 return createBuffer(that, size)
604 * Creates a new filled Buffer instance.
605 * alloc(size[, fill[, encoding]])
607 Buffer.alloc = function (size, fill, encoding) {
608 return alloc(null, size, fill, encoding)
611 function allocUnsafe (that, size) {
613 that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
614 if (!Buffer.TYPED_ARRAY_SUPPORT) {
615 for (var i = 0; i < size; ++i) {
623 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
625 Buffer.allocUnsafe = function (size) {
626 return allocUnsafe(null, size)
629 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
631 Buffer.allocUnsafeSlow = function (size) {
632 return allocUnsafe(null, size)
635 function fromString (that, string, encoding) {
636 if (typeof encoding !== 'string' || encoding === '') {
640 if (!Buffer.isEncoding(encoding)) {
641 throw new TypeError('"encoding" must be a valid string encoding')
644 var length = byteLength(string, encoding) | 0
645 that = createBuffer(that, length)
647 var actual = that.write(string, encoding)
649 if (actual !== length) {
650 // Writing a hex string, for example, that contains invalid characters will
651 // cause everything after the first invalid character to be ignored. (e.g.
652 // 'abxxcd' will be treated as 'ab')
653 that = that.slice(0, actual)
659 function fromArrayLike (that, array) {
660 var length = array.length < 0 ? 0 : checked(array.length) | 0
661 that = createBuffer(that, length)
662 for (var i = 0; i < length; i += 1) {
663 that[i] = array[i] & 255
668 function fromArrayBuffer (that, array, byteOffset, length) {
669 array.byteLength // this throws if `array` is not a valid ArrayBuffer
671 if (byteOffset < 0 || array.byteLength < byteOffset) {
672 throw new RangeError('\'offset\' is out of bounds')
675 if (array.byteLength < byteOffset + (length || 0)) {
676 throw new RangeError('\'length\' is out of bounds')
679 if (byteOffset === undefined && length === undefined) {
680 array = new Uint8Array(array)
681 } else if (length === undefined) {
682 array = new Uint8Array(array, byteOffset)
684 array = new Uint8Array(array, byteOffset, length)
687 if (Buffer.TYPED_ARRAY_SUPPORT) {
688 // Return an augmented `Uint8Array` instance, for best performance
690 that.__proto__ = Buffer.prototype
692 // Fallback: Return an object instance of the Buffer class
693 that = fromArrayLike(that, array)
698 function fromObject (that, obj) {
699 if (Buffer.isBuffer(obj)) {
700 var len = checked(obj.length) | 0
701 that = createBuffer(that, len)
703 if (that.length === 0) {
707 obj.copy(that, 0, 0, len)
712 if ((typeof ArrayBuffer !== 'undefined' &&
713 obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
714 if (typeof obj.length !== 'number' || isnan(obj.length)) {
715 return createBuffer(that, 0)
717 return fromArrayLike(that, obj)
720 if (obj.type === 'Buffer' && isArray(obj.data)) {
721 return fromArrayLike(that, obj.data)
725 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
728 function checked (length) {
729 // Note: cannot use `length < kMaxLength()` here because that fails when
730 // length is NaN (which is otherwise coerced to zero.)
731 if (length >= kMaxLength()) {
732 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
733 'size: 0x' + kMaxLength().toString(16) + ' bytes')
738 function SlowBuffer (length) {
739 if (+length != length) { // eslint-disable-line eqeqeq
742 return Buffer.alloc(+length)
745 Buffer.isBuffer = function isBuffer (b) {
746 return !!(b != null && b._isBuffer)
749 Buffer.compare = function compare (a, b) {
750 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
751 throw new TypeError('Arguments must be Buffers')
754 if (a === b) return 0
759 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
772 Buffer.isEncoding = function isEncoding (encoding) {
773 switch (String(encoding).toLowerCase()) {
791 Buffer.concat = function concat (list, length) {
792 if (!isArray(list)) {
793 throw new TypeError('"list" argument must be an Array of Buffers')
796 if (list.length === 0) {
797 return Buffer.alloc(0)
801 if (length === undefined) {
803 for (i = 0; i < list.length; ++i) {
804 length += list[i].length
808 var buffer = Buffer.allocUnsafe(length)
810 for (i = 0; i < list.length; ++i) {
812 if (!Buffer.isBuffer(buf)) {
813 throw new TypeError('"list" argument must be an Array of Buffers')
815 buf.copy(buffer, pos)
821 function byteLength (string, encoding) {
822 if (Buffer.isBuffer(string)) {
825 if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
826 (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
827 return string.byteLength
829 if (typeof string !== 'string') {
833 var len = string.length
834 if (len === 0) return 0
836 // Use a for loop to avoid recursion
837 var loweredCase = false
847 return utf8ToBytes(string).length
856 return base64ToBytes(string).length
858 if (loweredCase) return utf8ToBytes(string).length // assume utf8
859 encoding = ('' + encoding).toLowerCase()
864 Buffer.byteLength = byteLength
866 function slowToString (encoding, start, end) {
867 var loweredCase = false
869 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
870 // property of a typed array.
872 // This behaves neither like String nor Uint8Array in that we set start/end
873 // to their upper/lower bounds if the value passed is out of range.
874 // undefined is handled specially as per ECMA-262 6th Edition,
875 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
876 if (start === undefined || start < 0) {
879 // Return early if start > this.length. Done here to prevent potential uint32
880 // coercion fail below.
881 if (start > this.length) {
885 if (end === undefined || end > this.length) {
893 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
901 if (!encoding) encoding = 'utf8'
906 return hexSlice(this, start, end)
910 return utf8Slice(this, start, end)
913 return asciiSlice(this, start, end)
917 return latin1Slice(this, start, end)
920 return base64Slice(this, start, end)
926 return utf16leSlice(this, start, end)
929 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
930 encoding = (encoding + '').toLowerCase()
936 // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
938 Buffer.prototype._isBuffer = true
940 function swap (b, n, m) {
946 Buffer.prototype.swap16 = function swap16 () {
947 var len = this.length
949 throw new RangeError('Buffer size must be a multiple of 16-bits')
951 for (var i = 0; i < len; i += 2) {
957 Buffer.prototype.swap32 = function swap32 () {
958 var len = this.length
960 throw new RangeError('Buffer size must be a multiple of 32-bits')
962 for (var i = 0; i < len; i += 4) {
964 swap(this, i + 1, i + 2)
969 Buffer.prototype.swap64 = function swap64 () {
970 var len = this.length
972 throw new RangeError('Buffer size must be a multiple of 64-bits')
974 for (var i = 0; i < len; i += 8) {
976 swap(this, i + 1, i + 6)
977 swap(this, i + 2, i + 5)
978 swap(this, i + 3, i + 4)
983 Buffer.prototype.toString = function toString () {
984 var length = this.length | 0
985 if (length === 0) return ''
986 if (arguments.length === 0) return utf8Slice(this, 0, length)
987 return slowToString.apply(this, arguments)
990 Buffer.prototype.equals = function equals (b) {
991 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
992 if (this === b) return true
993 return Buffer.compare(this, b) === 0
996 Buffer.prototype.inspect = function inspect () {
998 var max = exports.INSPECT_MAX_BYTES
999 if (this.length > 0) {
1000 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
1001 if (this.length > max) str += ' ... '
1003 return '<Buffer ' + str + '>'
1006 Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
1007 if (!Buffer.isBuffer(target)) {
1008 throw new TypeError('Argument must be a Buffer')
1011 if (start === undefined) {
1014 if (end === undefined) {
1015 end = target ? target.length : 0
1017 if (thisStart === undefined) {
1020 if (thisEnd === undefined) {
1021 thisEnd = this.length
1024 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1025 throw new RangeError('out of range index')
1028 if (thisStart >= thisEnd && start >= end) {
1031 if (thisStart >= thisEnd) {
1043 if (this === target) return 0
1045 var x = thisEnd - thisStart
1047 var len = Math.min(x, y)
1049 var thisCopy = this.slice(thisStart, thisEnd)
1050 var targetCopy = target.slice(start, end)
1052 for (var i = 0; i < len; ++i) {
1053 if (thisCopy[i] !== targetCopy[i]) {
1060 if (x < y) return -1
1065 // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
1066 // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
1069 // - buffer - a Buffer to search
1070 // - val - a string, Buffer, or number
1071 // - byteOffset - an index into `buffer`; will be clamped to an int32
1072 // - encoding - an optional encoding, relevant is val is a string
1073 // - dir - true for indexOf, false for lastIndexOf
1074 function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
1075 // Empty buffer means no match
1076 if (buffer.length === 0) return -1
1078 // Normalize byteOffset
1079 if (typeof byteOffset === 'string') {
1080 encoding = byteOffset
1082 } else if (byteOffset > 0x7fffffff) {
1083 byteOffset = 0x7fffffff
1084 } else if (byteOffset < -0x80000000) {
1085 byteOffset = -0x80000000
1087 byteOffset = +byteOffset // Coerce to Number.
1088 if (isNaN(byteOffset)) {
1089 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
1090 byteOffset = dir ? 0 : (buffer.length - 1)
1093 // Normalize byteOffset: negative offsets start from the end of the buffer
1094 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
1095 if (byteOffset >= buffer.length) {
1097 else byteOffset = buffer.length - 1
1098 } else if (byteOffset < 0) {
1099 if (dir) byteOffset = 0
1104 if (typeof val === 'string') {
1105 val = Buffer.from(val, encoding)
1108 // Finally, search either indexOf (if dir is true) or lastIndexOf
1109 if (Buffer.isBuffer(val)) {
1110 // Special case: looking for empty string/buffer always fails
1111 if (val.length === 0) {
1114 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
1115 } else if (typeof val === 'number') {
1116 val = val & 0xFF // Search for a byte value [0-255]
1117 if (Buffer.TYPED_ARRAY_SUPPORT &&
1118 typeof Uint8Array.prototype.indexOf === 'function') {
1120 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1122 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1125 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
1128 throw new TypeError('val must be string, number or Buffer')
1131 function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1133 var arrLength = arr.length
1134 var valLength = val.length
1136 if (encoding !== undefined) {
1137 encoding = String(encoding).toLowerCase()
1138 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1139 encoding === 'utf16le' || encoding === 'utf-16le') {
1140 if (arr.length < 2 || val.length < 2) {
1150 function read (buf, i) {
1151 if (indexSize === 1) {
1154 return buf.readUInt16BE(i * indexSize)
1161 for (i = byteOffset; i < arrLength; i++) {
1162 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1163 if (foundIndex === -1) foundIndex = i
1164 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
1166 if (foundIndex !== -1) i -= i - foundIndex
1171 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1172 for (i = byteOffset; i >= 0; i--) {
1174 for (var j = 0; j < valLength; j++) {
1175 if (read(arr, i + j) !== read(val, j)) {
1187 Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1188 return this.indexOf(val, byteOffset, encoding) !== -1
1191 Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1192 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1195 Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1196 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1199 function hexWrite (buf, string, offset, length) {
1200 offset = Number(offset) || 0
1201 var remaining = buf.length - offset
1205 length = Number(length)
1206 if (length > remaining) {
1211 // must be an even number of digits
1212 var strLen = string.length
1213 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
1215 if (length > strLen / 2) {
1218 for (var i = 0; i < length; ++i) {
1219 var parsed = parseInt(string.substr(i * 2, 2), 16)
1220 if (isNaN(parsed)) return i
1221 buf[offset + i] = parsed
1226 function utf8Write (buf, string, offset, length) {
1227 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1230 function asciiWrite (buf, string, offset, length) {
1231 return blitBuffer(asciiToBytes(string), buf, offset, length)
1234 function latin1Write (buf, string, offset, length) {
1235 return asciiWrite(buf, string, offset, length)
1238 function base64Write (buf, string, offset, length) {
1239 return blitBuffer(base64ToBytes(string), buf, offset, length)
1242 function ucs2Write (buf, string, offset, length) {
1243 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1246 Buffer.prototype.write = function write (string, offset, length, encoding) {
1247 // Buffer#write(string)
1248 if (offset === undefined) {
1250 length = this.length
1252 // Buffer#write(string, encoding)
1253 } else if (length === undefined && typeof offset === 'string') {
1255 length = this.length
1257 // Buffer#write(string, offset[, length][, encoding])
1258 } else if (isFinite(offset)) {
1260 if (isFinite(length)) {
1262 if (encoding === undefined) encoding = 'utf8'
1267 // legacy write(string, encoding, offset, length) - remove in v0.13
1270 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1274 var remaining = this.length - offset
1275 if (length === undefined || length > remaining) length = remaining
1277 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1278 throw new RangeError('Attempt to write outside buffer bounds')
1281 if (!encoding) encoding = 'utf8'
1283 var loweredCase = false
1287 return hexWrite(this, string, offset, length)
1291 return utf8Write(this, string, offset, length)
1294 return asciiWrite(this, string, offset, length)
1298 return latin1Write(this, string, offset, length)
1301 // Warning: maxLength not taken into account in base64Write
1302 return base64Write(this, string, offset, length)
1308 return ucs2Write(this, string, offset, length)
1311 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1312 encoding = ('' + encoding).toLowerCase()
1318 Buffer.prototype.toJSON = function toJSON () {
1321 data: Array.prototype.slice.call(this._arr || this, 0)
1325 function base64Slice (buf, start, end) {
1326 if (start === 0 && end === buf.length) {
1327 return base64.fromByteArray(buf)
1329 return base64.fromByteArray(buf.slice(start, end))
1333 function utf8Slice (buf, start, end) {
1334 end = Math.min(buf.length, end)
1339 var firstByte = buf[i]
1340 var codePoint = null
1341 var bytesPerSequence = (firstByte > 0xEF) ? 4
1342 : (firstByte > 0xDF) ? 3
1343 : (firstByte > 0xBF) ? 2
1346 if (i + bytesPerSequence <= end) {
1347 var secondByte, thirdByte, fourthByte, tempCodePoint
1349 switch (bytesPerSequence) {
1351 if (firstByte < 0x80) {
1352 codePoint = firstByte
1356 secondByte = buf[i + 1]
1357 if ((secondByte & 0xC0) === 0x80) {
1358 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
1359 if (tempCodePoint > 0x7F) {
1360 codePoint = tempCodePoint
1365 secondByte = buf[i + 1]
1366 thirdByte = buf[i + 2]
1367 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1368 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
1369 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1370 codePoint = tempCodePoint
1375 secondByte = buf[i + 1]
1376 thirdByte = buf[i + 2]
1377 fourthByte = buf[i + 3]
1378 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1379 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
1380 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1381 codePoint = tempCodePoint
1387 if (codePoint === null) {
1388 // we did not generate a valid codePoint so insert a
1389 // replacement char (U+FFFD) and advance only 1 byte
1391 bytesPerSequence = 1
1392 } else if (codePoint > 0xFFFF) {
1393 // encode to utf16 (surrogate pair dance)
1394 codePoint -= 0x10000
1395 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1396 codePoint = 0xDC00 | codePoint & 0x3FF
1400 i += bytesPerSequence
1403 return decodeCodePointsArray(res)
1406 // Based on http://stackoverflow.com/a/22747272/680742, the browser with
1407 // the lowest limit is Chrome, with 0x10000 args.
1408 // We go 1 magnitude less, for safety
1409 var MAX_ARGUMENTS_LENGTH = 0x1000
1411 function decodeCodePointsArray (codePoints) {
1412 var len = codePoints.length
1413 if (len <= MAX_ARGUMENTS_LENGTH) {
1414 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1417 // Decode in chunks to avoid "call stack size exceeded".
1421 res += String.fromCharCode.apply(
1423 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1429 function asciiSlice (buf, start, end) {
1431 end = Math.min(buf.length, end)
1433 for (var i = start; i < end; ++i) {
1434 ret += String.fromCharCode(buf[i] & 0x7F)
1439 function latin1Slice (buf, start, end) {
1441 end = Math.min(buf.length, end)
1443 for (var i = start; i < end; ++i) {
1444 ret += String.fromCharCode(buf[i])
1449 function hexSlice (buf, start, end) {
1450 var len = buf.length
1452 if (!start || start < 0) start = 0
1453 if (!end || end < 0 || end > len) end = len
1456 for (var i = start; i < end; ++i) {
1457 out += toHex(buf[i])
1462 function utf16leSlice (buf, start, end) {
1463 var bytes = buf.slice(start, end)
1465 for (var i = 0; i < bytes.length; i += 2) {
1466 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
1471 Buffer.prototype.slice = function slice (start, end) {
1472 var len = this.length
1474 end = end === undefined ? len : ~~end
1478 if (start < 0) start = 0
1479 } else if (start > len) {
1485 if (end < 0) end = 0
1486 } else if (end > len) {
1490 if (end < start) end = start
1493 if (Buffer.TYPED_ARRAY_SUPPORT) {
1494 newBuf = this.subarray(start, end)
1495 newBuf.__proto__ = Buffer.prototype
1497 var sliceLen = end - start
1498 newBuf = new Buffer(sliceLen, undefined)
1499 for (var i = 0; i < sliceLen; ++i) {
1500 newBuf[i] = this[i + start]
1508 * Need to make sure that buffer isn't trying to write out of bounds.
1510 function checkOffset (offset, ext, length) {
1511 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1512 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1515 Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1517 byteLength = byteLength | 0
1518 if (!noAssert) checkOffset(offset, byteLength, this.length)
1520 var val = this[offset]
1523 while (++i < byteLength && (mul *= 0x100)) {
1524 val += this[offset + i] * mul
1530 Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1532 byteLength = byteLength | 0
1534 checkOffset(offset, byteLength, this.length)
1537 var val = this[offset + --byteLength]
1539 while (byteLength > 0 && (mul *= 0x100)) {
1540 val += this[offset + --byteLength] * mul
1546 Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1547 if (!noAssert) checkOffset(offset, 1, this.length)
1551 Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1552 if (!noAssert) checkOffset(offset, 2, this.length)
1553 return this[offset] | (this[offset + 1] << 8)
1556 Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1557 if (!noAssert) checkOffset(offset, 2, this.length)
1558 return (this[offset] << 8) | this[offset + 1]
1561 Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1562 if (!noAssert) checkOffset(offset, 4, this.length)
1564 return ((this[offset]) |
1565 (this[offset + 1] << 8) |
1566 (this[offset + 2] << 16)) +
1567 (this[offset + 3] * 0x1000000)
1570 Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1571 if (!noAssert) checkOffset(offset, 4, this.length)
1573 return (this[offset] * 0x1000000) +
1574 ((this[offset + 1] << 16) |
1575 (this[offset + 2] << 8) |
1579 Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1581 byteLength = byteLength | 0
1582 if (!noAssert) checkOffset(offset, byteLength, this.length)
1584 var val = this[offset]
1587 while (++i < byteLength && (mul *= 0x100)) {
1588 val += this[offset + i] * mul
1592 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1597 Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1599 byteLength = byteLength | 0
1600 if (!noAssert) checkOffset(offset, byteLength, this.length)
1604 var val = this[offset + --i]
1605 while (i > 0 && (mul *= 0x100)) {
1606 val += this[offset + --i] * mul
1610 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1615 Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1616 if (!noAssert) checkOffset(offset, 1, this.length)
1617 if (!(this[offset] & 0x80)) return (this[offset])
1618 return ((0xff - this[offset] + 1) * -1)
1621 Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1622 if (!noAssert) checkOffset(offset, 2, this.length)
1623 var val = this[offset] | (this[offset + 1] << 8)
1624 return (val & 0x8000) ? val | 0xFFFF0000 : val
1627 Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1628 if (!noAssert) checkOffset(offset, 2, this.length)
1629 var val = this[offset + 1] | (this[offset] << 8)
1630 return (val & 0x8000) ? val | 0xFFFF0000 : val
1633 Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1634 if (!noAssert) checkOffset(offset, 4, this.length)
1636 return (this[offset]) |
1637 (this[offset + 1] << 8) |
1638 (this[offset + 2] << 16) |
1639 (this[offset + 3] << 24)
1642 Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1643 if (!noAssert) checkOffset(offset, 4, this.length)
1645 return (this[offset] << 24) |
1646 (this[offset + 1] << 16) |
1647 (this[offset + 2] << 8) |
1651 Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1652 if (!noAssert) checkOffset(offset, 4, this.length)
1653 return ieee754.read(this, offset, true, 23, 4)
1656 Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1657 if (!noAssert) checkOffset(offset, 4, this.length)
1658 return ieee754.read(this, offset, false, 23, 4)
1661 Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1662 if (!noAssert) checkOffset(offset, 8, this.length)
1663 return ieee754.read(this, offset, true, 52, 8)
1666 Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1667 if (!noAssert) checkOffset(offset, 8, this.length)
1668 return ieee754.read(this, offset, false, 52, 8)
1671 function checkInt (buf, value, offset, ext, max, min) {
1672 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1673 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1674 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1677 Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1680 byteLength = byteLength | 0
1682 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1683 checkInt(this, value, offset, byteLength, maxBytes, 0)
1688 this[offset] = value & 0xFF
1689 while (++i < byteLength && (mul *= 0x100)) {
1690 this[offset + i] = (value / mul) & 0xFF
1693 return offset + byteLength
1696 Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1699 byteLength = byteLength | 0
1701 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1702 checkInt(this, value, offset, byteLength, maxBytes, 0)
1705 var i = byteLength - 1
1707 this[offset + i] = value & 0xFF
1708 while (--i >= 0 && (mul *= 0x100)) {
1709 this[offset + i] = (value / mul) & 0xFF
1712 return offset + byteLength
1715 Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1718 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1719 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
1720 this[offset] = (value & 0xff)
1724 function objectWriteUInt16 (buf, value, offset, littleEndian) {
1725 if (value < 0) value = 0xffff + value + 1
1726 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
1727 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
1728 (littleEndian ? i : 1 - i) * 8
1732 Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1735 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1736 if (Buffer.TYPED_ARRAY_SUPPORT) {
1737 this[offset] = (value & 0xff)
1738 this[offset + 1] = (value >>> 8)
1740 objectWriteUInt16(this, value, offset, true)
1745 Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1748 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1749 if (Buffer.TYPED_ARRAY_SUPPORT) {
1750 this[offset] = (value >>> 8)
1751 this[offset + 1] = (value & 0xff)
1753 objectWriteUInt16(this, value, offset, false)
1758 function objectWriteUInt32 (buf, value, offset, littleEndian) {
1759 if (value < 0) value = 0xffffffff + value + 1
1760 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
1761 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
1765 Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1768 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1769 if (Buffer.TYPED_ARRAY_SUPPORT) {
1770 this[offset + 3] = (value >>> 24)
1771 this[offset + 2] = (value >>> 16)
1772 this[offset + 1] = (value >>> 8)
1773 this[offset] = (value & 0xff)
1775 objectWriteUInt32(this, value, offset, true)
1780 Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1783 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1784 if (Buffer.TYPED_ARRAY_SUPPORT) {
1785 this[offset] = (value >>> 24)
1786 this[offset + 1] = (value >>> 16)
1787 this[offset + 2] = (value >>> 8)
1788 this[offset + 3] = (value & 0xff)
1790 objectWriteUInt32(this, value, offset, false)
1795 Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1799 var limit = Math.pow(2, 8 * byteLength - 1)
1801 checkInt(this, value, offset, byteLength, limit - 1, -limit)
1807 this[offset] = value & 0xFF
1808 while (++i < byteLength && (mul *= 0x100)) {
1809 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1812 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1815 return offset + byteLength
1818 Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1822 var limit = Math.pow(2, 8 * byteLength - 1)
1824 checkInt(this, value, offset, byteLength, limit - 1, -limit)
1827 var i = byteLength - 1
1830 this[offset + i] = value & 0xFF
1831 while (--i >= 0 && (mul *= 0x100)) {
1832 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1835 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1838 return offset + byteLength
1841 Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1844 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
1845 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
1846 if (value < 0) value = 0xff + value + 1
1847 this[offset] = (value & 0xff)
1851 Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1854 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1855 if (Buffer.TYPED_ARRAY_SUPPORT) {
1856 this[offset] = (value & 0xff)
1857 this[offset + 1] = (value >>> 8)
1859 objectWriteUInt16(this, value, offset, true)
1864 Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1867 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1868 if (Buffer.TYPED_ARRAY_SUPPORT) {
1869 this[offset] = (value >>> 8)
1870 this[offset + 1] = (value & 0xff)
1872 objectWriteUInt16(this, value, offset, false)
1877 Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1880 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1881 if (Buffer.TYPED_ARRAY_SUPPORT) {
1882 this[offset] = (value & 0xff)
1883 this[offset + 1] = (value >>> 8)
1884 this[offset + 2] = (value >>> 16)
1885 this[offset + 3] = (value >>> 24)
1887 objectWriteUInt32(this, value, offset, true)
1892 Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
1895 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1896 if (value < 0) value = 0xffffffff + value + 1
1897 if (Buffer.TYPED_ARRAY_SUPPORT) {
1898 this[offset] = (value >>> 24)
1899 this[offset + 1] = (value >>> 16)
1900 this[offset + 2] = (value >>> 8)
1901 this[offset + 3] = (value & 0xff)
1903 objectWriteUInt32(this, value, offset, false)
1908 function checkIEEE754 (buf, value, offset, ext, max, min) {
1909 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1910 if (offset < 0) throw new RangeError('Index out of range')
1913 function writeFloat (buf, value, offset, littleEndian, noAssert) {
1915 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
1917 ieee754.write(buf, value, offset, littleEndian, 23, 4)
1921 Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
1922 return writeFloat(this, value, offset, true, noAssert)
1925 Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
1926 return writeFloat(this, value, offset, false, noAssert)
1929 function writeDouble (buf, value, offset, littleEndian, noAssert) {
1931 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
1933 ieee754.write(buf, value, offset, littleEndian, 52, 8)
1937 Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
1938 return writeDouble(this, value, offset, true, noAssert)
1941 Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
1942 return writeDouble(this, value, offset, false, noAssert)
1945 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1946 Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1947 if (!start) start = 0
1948 if (!end && end !== 0) end = this.length
1949 if (targetStart >= target.length) targetStart = target.length
1950 if (!targetStart) targetStart = 0
1951 if (end > 0 && end < start) end = start
1953 // Copy 0 bytes; we're done
1954 if (end === start) return 0
1955 if (target.length === 0 || this.length === 0) return 0
1957 // Fatal error conditions
1958 if (targetStart < 0) {
1959 throw new RangeError('targetStart out of bounds')
1961 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
1962 if (end < 0) throw new RangeError('sourceEnd out of bounds')
1965 if (end > this.length) end = this.length
1966 if (target.length - targetStart < end - start) {
1967 end = target.length - targetStart + start
1970 var len = end - start
1973 if (this === target && start < targetStart && targetStart < end) {
1974 // descending copy from end
1975 for (i = len - 1; i >= 0; --i) {
1976 target[i + targetStart] = this[i + start]
1978 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
1979 // ascending copy from start
1980 for (i = 0; i < len; ++i) {
1981 target[i + targetStart] = this[i + start]
1984 Uint8Array.prototype.set.call(
1986 this.subarray(start, start + len),
1995 // buffer.fill(number[, offset[, end]])
1996 // buffer.fill(buffer[, offset[, end]])
1997 // buffer.fill(string[, offset[, end]][, encoding])
1998 Buffer.prototype.fill = function fill (val, start, end, encoding) {
1999 // Handle string cases:
2000 if (typeof val === 'string') {
2001 if (typeof start === 'string') {
2005 } else if (typeof end === 'string') {
2009 if (val.length === 1) {
2010 var code = val.charCodeAt(0)
2015 if (encoding !== undefined && typeof encoding !== 'string') {
2016 throw new TypeError('encoding must be a string')
2018 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2019 throw new TypeError('Unknown encoding: ' + encoding)
2021 } else if (typeof val === 'number') {
2025 // Invalid ranges are not set to a default, so can range check early.
2026 if (start < 0 || this.length < start || this.length < end) {
2027 throw new RangeError('Out of range index')
2035 end = end === undefined ? this.length : end >>> 0
2040 if (typeof val === 'number') {
2041 for (i = start; i < end; ++i) {
2045 var bytes = Buffer.isBuffer(val)
2047 : utf8ToBytes(new Buffer(val, encoding).toString())
2048 var len = bytes.length
2049 for (i = 0; i < end - start; ++i) {
2050 this[i + start] = bytes[i % len]
2060 var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
2062 function base64clean (str) {
2063 // Node strips out invalid characters like \n and \t from the string, base64-js does not
2064 str = stringtrim(str).replace(INVALID_BASE64_RE, '')
2065 // Node converts strings with length < 2 to ''
2066 if (str.length < 2) return ''
2067 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2068 while (str.length % 4 !== 0) {
2074 function stringtrim (str) {
2075 if (str.trim) return str.trim()
2076 return str.replace(/^\s+|\s+$/g, '')
2079 function toHex (n) {
2080 if (n < 16) return '0' + n.toString(16)
2081 return n.toString(16)
2084 function utf8ToBytes (string, units) {
2085 units = units || Infinity
2087 var length = string.length
2088 var leadSurrogate = null
2091 for (var i = 0; i < length; ++i) {
2092 codePoint = string.charCodeAt(i)
2094 // is surrogate component
2095 if (codePoint > 0xD7FF && codePoint < 0xE000) {
2096 // last char was a lead
2097 if (!leadSurrogate) {
2099 if (codePoint > 0xDBFF) {
2101 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2103 } else if (i + 1 === length) {
2105 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2110 leadSurrogate = codePoint
2116 if (codePoint < 0xDC00) {
2117 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2118 leadSurrogate = codePoint
2122 // valid surrogate pair
2123 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
2124 } else if (leadSurrogate) {
2125 // valid bmp char, but last char was a lead
2126 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2129 leadSurrogate = null
2132 if (codePoint < 0x80) {
2133 if ((units -= 1) < 0) break
2134 bytes.push(codePoint)
2135 } else if (codePoint < 0x800) {
2136 if ((units -= 2) < 0) break
2138 codePoint >> 0x6 | 0xC0,
2139 codePoint & 0x3F | 0x80
2141 } else if (codePoint < 0x10000) {
2142 if ((units -= 3) < 0) break
2144 codePoint >> 0xC | 0xE0,
2145 codePoint >> 0x6 & 0x3F | 0x80,
2146 codePoint & 0x3F | 0x80
2148 } else if (codePoint < 0x110000) {
2149 if ((units -= 4) < 0) break
2151 codePoint >> 0x12 | 0xF0,
2152 codePoint >> 0xC & 0x3F | 0x80,
2153 codePoint >> 0x6 & 0x3F | 0x80,
2154 codePoint & 0x3F | 0x80
2157 throw new Error('Invalid code point')
2164 function asciiToBytes (str) {
2166 for (var i = 0; i < str.length; ++i) {
2167 // Node's code seems to be doing this and not & 0x7F..
2168 byteArray.push(str.charCodeAt(i) & 0xFF)
2173 function utf16leToBytes (str, units) {
2176 for (var i = 0; i < str.length; ++i) {
2177 if ((units -= 2) < 0) break
2179 c = str.charCodeAt(i)
2189 function base64ToBytes (str) {
2190 return base64.toByteArray(base64clean(str))
2193 function blitBuffer (src, dst, offset, length) {
2194 for (var i = 0; i < length; ++i) {
2195 if ((i + offset >= dst.length) || (i >= src.length)) break
2196 dst[i + offset] = src[i]
2201 function isnan (val) {
2202 return val !== val // eslint-disable-line no-self-compare
2205 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
2207 },{"base64-js":1,"ieee754":15,"isarray":19}],6:[function(require,module,exports){
2210 module.exports = earcut;
2212 function earcut(data, holeIndices, dim) {
2216 var hasHoles = holeIndices && holeIndices.length,
2217 outerLen = hasHoles ? holeIndices[0] * dim : data.length,
2218 outerNode = linkedList(data, 0, outerLen, dim, true),
2221 if (!outerNode) return triangles;
2223 var minX, minY, maxX, maxY, x, y, size;
2225 if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
2227 // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
2228 if (data.length > 80 * dim) {
2229 minX = maxX = data[0];
2230 minY = maxY = data[1];
2232 for (var i = dim; i < outerLen; i += dim) {
2235 if (x < minX) minX = x;
2236 if (y < minY) minY = y;
2237 if (x > maxX) maxX = x;
2238 if (y > maxY) maxY = y;
2241 // minX, minY and size are later used to transform coords into integers for z-order calculation
2242 size = Math.max(maxX - minX, maxY - minY);
2245 earcutLinked(outerNode, triangles, dim, minX, minY, size);
2250 // create a circular doubly linked list from polygon points in the specified winding order
2251 function linkedList(data, start, end, dim, clockwise) {
2254 if (clockwise === (signedArea(data, start, end, dim) > 0)) {
2255 for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
2257 for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
2260 if (last && equals(last, last.next)) {
2268 // eliminate colinear or duplicate points
2269 function filterPoints(start, end) {
2270 if (!start) return start;
2271 if (!end) end = start;
2278 if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
2281 if (p === p.next) return null;
2287 } while (again || p !== end);
2292 // main ear slicing loop which triangulates a polygon (given as a linked list)
2293 function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
2296 // interlink polygon nodes in z-order
2297 if (!pass && size) indexCurve(ear, minX, minY, size);
2302 // iterate through ears, slicing them one by one
2303 while (ear.prev !== ear.next) {
2307 if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
2308 // cut off the triangle
2309 triangles.push(prev.i / dim);
2310 triangles.push(ear.i / dim);
2311 triangles.push(next.i / dim);
2315 // skipping the next vertice leads to less sliver triangles
2324 // if we looped through the whole remaining polygon and can't find any more ears
2326 // try filtering points and slicing again
2328 earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
2330 // if this didn't work, try curing all small self-intersections locally
2331 } else if (pass === 1) {
2332 ear = cureLocalIntersections(ear, triangles, dim);
2333 earcutLinked(ear, triangles, dim, minX, minY, size, 2);
2335 // as a last resort, try splitting the remaining polygon into two
2336 } else if (pass === 2) {
2337 splitEarcut(ear, triangles, dim, minX, minY, size);
2345 // check whether a polygon node forms a valid ear with adjacent nodes
2346 function isEar(ear) {
2351 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2353 // now make sure we don't have other points inside the potential ear
2354 var p = ear.next.next;
2356 while (p !== ear.prev) {
2357 if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2358 area(p.prev, p, p.next) >= 0) return false;
2365 function isEarHashed(ear, minX, minY, size) {
2370 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2372 // triangle bbox; min & max are calculated like this for speed
2373 var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
2374 minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
2375 maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
2376 maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
2378 // z-order range for the current triangle bbox;
2379 var minZ = zOrder(minTX, minTY, minX, minY, size),
2380 maxZ = zOrder(maxTX, maxTY, minX, minY, size);
2382 // first look for points inside the triangle in increasing z-order
2385 while (p && p.z <= maxZ) {
2386 if (p !== ear.prev && p !== ear.next &&
2387 pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2388 area(p.prev, p, p.next) >= 0) return false;
2392 // then look for points in decreasing z-order
2395 while (p && p.z >= minZ) {
2396 if (p !== ear.prev && p !== ear.next &&
2397 pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2398 area(p.prev, p, p.next) >= 0) return false;
2405 // go through all polygon nodes and cure small local self-intersections
2406 function cureLocalIntersections(start, triangles, dim) {
2412 if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
2414 triangles.push(a.i / dim);
2415 triangles.push(p.i / dim);
2416 triangles.push(b.i / dim);
2418 // remove two nodes involved
2425 } while (p !== start);
2430 // try splitting polygon into two and triangulate them independently
2431 function splitEarcut(start, triangles, dim, minX, minY, size) {
2432 // look for a valid diagonal that divides the polygon into two
2435 var b = a.next.next;
2436 while (b !== a.prev) {
2437 if (a.i !== b.i && isValidDiagonal(a, b)) {
2438 // split the polygon in two by the diagonal
2439 var c = splitPolygon(a, b);
2441 // filter colinear points around the cuts
2442 a = filterPoints(a, a.next);
2443 c = filterPoints(c, c.next);
2445 // run earcut on each half
2446 earcutLinked(a, triangles, dim, minX, minY, size);
2447 earcutLinked(c, triangles, dim, minX, minY, size);
2453 } while (a !== start);
2456 // link every hole into the outer loop, producing a single-ring polygon without holes
2457 function eliminateHoles(data, holeIndices, outerNode, dim) {
2459 i, len, start, end, list;
2461 for (i = 0, len = holeIndices.length; i < len; i++) {
2462 start = holeIndices[i] * dim;
2463 end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2464 list = linkedList(data, start, end, dim, false);
2465 if (list === list.next) list.steiner = true;
2466 queue.push(getLeftmost(list));
2469 queue.sort(compareX);
2471 // process holes from left to right
2472 for (i = 0; i < queue.length; i++) {
2473 eliminateHole(queue[i], outerNode);
2474 outerNode = filterPoints(outerNode, outerNode.next);
2480 function compareX(a, b) {
2484 // find a bridge between vertices that connects hole with an outer ring and and link it
2485 function eliminateHole(hole, outerNode) {
2486 outerNode = findHoleBridge(hole, outerNode);
2488 var b = splitPolygon(outerNode, hole);
2489 filterPoints(b, b.next);
2493 // David Eberly's algorithm for finding a bridge between hole and outer polygon
2494 function findHoleBridge(hole, outerNode) {
2501 // find a segment intersected by a ray from the hole's leftmost point to the left;
2502 // segment's endpoint with lesser x will be potential connection point
2504 if (hy <= p.y && hy >= p.next.y) {
2505 var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
2506 if (x <= hx && x > qx) {
2509 if (hy === p.y) return p;
2510 if (hy === p.next.y) return p.next;
2512 m = p.x < p.next.x ? p : p.next;
2516 } while (p !== outerNode);
2518 if (!m) return null;
2520 if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
2522 // look for points inside the triangle of hole point, segment intersection and endpoint;
2523 // if there are no points found, we have a valid connection;
2524 // otherwise choose the point of the minimum angle with the ray as connection point
2534 while (p !== stop) {
2535 if (hx >= p.x && p.x >= mx &&
2536 pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
2538 tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
2540 if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
2552 // interlink polygon nodes in z-order
2553 function indexCurve(start, minX, minY, size) {
2556 if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size);
2560 } while (p !== start);
2562 p.prevZ.nextZ = null;
2568 // Simon Tatham's linked list merge sort algorithm
2569 // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
2570 function sortLinked(list) {
2571 var i, p, q, e, tail, numMerges, pSize, qSize,
2584 for (i = 0; i < inSize; i++) {
2592 while (pSize > 0 || (qSize > 0 && q)) {
2598 } else if (qSize === 0 || !q) {
2602 } else if (p.z <= q.z) {
2612 if (tail) tail.nextZ = e;
2625 } while (numMerges > 1);
2630 // z-order of a point given coords and size of the data bounding box
2631 function zOrder(x, y, minX, minY, size) {
2632 // coords are transformed into non-negative 15-bit integer range
2633 x = 32767 * (x - minX) / size;
2634 y = 32767 * (y - minY) / size;
2636 x = (x | (x << 8)) & 0x00FF00FF;
2637 x = (x | (x << 4)) & 0x0F0F0F0F;
2638 x = (x | (x << 2)) & 0x33333333;
2639 x = (x | (x << 1)) & 0x55555555;
2641 y = (y | (y << 8)) & 0x00FF00FF;
2642 y = (y | (y << 4)) & 0x0F0F0F0F;
2643 y = (y | (y << 2)) & 0x33333333;
2644 y = (y | (y << 1)) & 0x55555555;
2646 return x | (y << 1);
2649 // find the leftmost node of a polygon ring
2650 function getLeftmost(start) {
2654 if (p.x < leftmost.x) leftmost = p;
2656 } while (p !== start);
2661 // check if a point lies within a convex triangle
2662 function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
2663 return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
2664 (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
2665 (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
2668 // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
2669 function isValidDiagonal(a, b) {
2670 return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
2671 locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
2674 // signed area of a triangle
2675 function area(p, q, r) {
2676 return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
2679 // check if two points are equal
2680 function equals(p1, p2) {
2681 return p1.x === p2.x && p1.y === p2.y;
2684 // check if two segments intersect
2685 function intersects(p1, q1, p2, q2) {
2686 if ((equals(p1, q1) && equals(p2, q2)) ||
2687 (equals(p1, q2) && equals(p2, q1))) return true;
2688 return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
2689 area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
2692 // check if a polygon diagonal intersects any polygon segments
2693 function intersectsPolygon(a, b) {
2696 if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
2697 intersects(p, p.next, a, b)) return true;
2704 // check if a polygon diagonal is locally inside the polygon
2705 function locallyInside(a, b) {
2706 return area(a.prev, a, a.next) < 0 ?
2707 area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
2708 area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
2711 // check if the middle point of a polygon diagonal is inside the polygon
2712 function middleInside(a, b) {
2715 px = (a.x + b.x) / 2,
2716 py = (a.y + b.y) / 2;
2718 if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
2726 // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
2727 // if one belongs to the outer ring and another to a hole, it merges it into a single ring
2728 function splitPolygon(a, b) {
2729 var a2 = new Node(a.i, a.x, a.y),
2730 b2 = new Node(b.i, b.x, b.y),
2749 // create a node and optionally link it with previous one (in a circular doubly linked list)
2750 function insertNode(i, x, y, last) {
2751 var p = new Node(i, x, y);
2766 function removeNode(p) {
2767 p.next.prev = p.prev;
2768 p.prev.next = p.next;
2770 if (p.prevZ) p.prevZ.nextZ = p.nextZ;
2771 if (p.nextZ) p.nextZ.prevZ = p.prevZ;
2774 function Node(i, x, y) {
2775 // vertice index in coordinates array
2778 // vertex coordinates
2782 // previous and next vertice nodes in a polygon ring
2786 // z-order curve value
2789 // previous and next nodes in z-order
2793 // indicates whether this is a steiner point
2794 this.steiner = false;
2797 // return a percentage difference between the polygon area and its triangulation area;
2798 // used to verify correctness of triangulation
2799 earcut.deviation = function (data, holeIndices, dim, triangles) {
2800 var hasHoles = holeIndices && holeIndices.length;
2801 var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
2803 var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
2805 for (var i = 0, len = holeIndices.length; i < len; i++) {
2806 var start = holeIndices[i] * dim;
2807 var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2808 polygonArea -= Math.abs(signedArea(data, start, end, dim));
2812 var trianglesArea = 0;
2813 for (i = 0; i < triangles.length; i += 3) {
2814 var a = triangles[i] * dim;
2815 var b = triangles[i + 1] * dim;
2816 var c = triangles[i + 2] * dim;
2817 trianglesArea += Math.abs(
2818 (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
2819 (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
2822 return polygonArea === 0 && trianglesArea === 0 ? 0 :
2823 Math.abs((trianglesArea - polygonArea) / polygonArea);
2826 function signedArea(data, start, end, dim) {
2828 for (var i = start, j = end - dim; i < end; i += dim) {
2829 sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
2835 // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
2836 earcut.flatten = function (data) {
2837 var dim = data[0][0].length,
2838 result = {vertices: [], holes: [], dimensions: dim},
2841 for (var i = 0; i < data.length; i++) {
2842 for (var j = 0; j < data[i].length; j++) {
2843 for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
2846 holeIndex += data[i - 1].length;
2847 result.holes.push(holeIndex);
2853 },{}],7:[function(require,module,exports){
2856 var OneVersionConstraint = require('individual/one-version');
2858 var MY_VERSION = '7';
2859 OneVersionConstraint('ev-store', MY_VERSION);
2861 var hashKey = '__EV_STORE_KEY@' + MY_VERSION;
2863 module.exports = EvStore;
2865 function EvStore(elem) {
2866 var hash = elem[hashKey];
2869 hash = elem[hashKey] = {};
2875 },{"individual/one-version":17}],8:[function(require,module,exports){
2877 var request = require('./request');
2878 var buildQueryObject = require('./buildQueryObject');
2879 var isArray = Array.isArray;
2881 function simpleExtend(obj, obj2) {
2883 for (prop in obj2) {
2884 obj[prop] = obj2[prop];
2889 function XMLHttpSource(jsongUrl, config) {
2890 this._jsongUrl = jsongUrl;
2891 if (typeof config === 'number') {
2897 this._config = simpleExtend({
2903 XMLHttpSource.prototype = {
2904 // because javascript
2905 constructor: XMLHttpSource,
2907 * buildQueryObject helper
2909 buildQueryObject: buildQueryObject,
2912 * @inheritDoc DataSource#get
2914 get: function httpSourceGet(pathSet) {
2916 var queryObject = this.buildQueryObject(this._jsongUrl, method, {
2920 var config = simpleExtend(queryObject, this._config);
2921 // pass context for onBeforeRequest callback
2923 return request(method, config, context);
2927 * @inheritDoc DataSource#set
2929 set: function httpSourceSet(jsongEnv) {
2930 var method = 'POST';
2931 var queryObject = this.buildQueryObject(this._jsongUrl, method, {
2932 jsonGraph: jsongEnv,
2935 var config = simpleExtend(queryObject, this._config);
2936 config.headers["Content-Type"] = "application/x-www-form-urlencoded";
2938 // pass context for onBeforeRequest callback
2940 return request(method, config, context);
2945 * @inheritDoc DataSource#call
2947 call: function httpSourceCall(callPath, args, pathSuffix, paths) {
2948 // arguments defaults
2950 pathSuffix = pathSuffix || [];
2951 paths = paths || [];
2953 var method = 'POST';
2955 queryData.push('method=call');
2956 queryData.push('callPath=' + encodeURIComponent(JSON.stringify(callPath)));
2957 queryData.push('arguments=' + encodeURIComponent(JSON.stringify(args)));
2958 queryData.push('pathSuffixes=' + encodeURIComponent(JSON.stringify(pathSuffix)));
2959 queryData.push('paths=' + encodeURIComponent(JSON.stringify(paths)));
2961 var queryObject = this.buildQueryObject(this._jsongUrl, method, queryData.join('&'));
2962 var config = simpleExtend(queryObject, this._config);
2963 config.headers["Content-Type"] = "application/x-www-form-urlencoded";
2965 // pass context for onBeforeRequest callback
2967 return request(method, config, context);
2971 XMLHttpSource.XMLHttpSource = XMLHttpSource;
2972 XMLHttpSource['default'] = XMLHttpSource;
2974 module.exports = XMLHttpSource;
2976 },{"./buildQueryObject":9,"./request":12}],9:[function(require,module,exports){
2978 module.exports = function buildQueryObject(url, method, queryData) {
2981 var data = {url: url};
2982 var isQueryParamUrl = url.indexOf('?') !== -1;
2983 var startUrl = (isQueryParamUrl) ? '&' : '?';
2985 if (typeof queryData === 'string') {
2986 qData.push(queryData);
2989 keys = Object.keys(queryData);
2990 keys.forEach(function (k) {
2991 var value = (typeof queryData[k] === 'object') ? JSON.stringify(queryData[k]) : queryData[k];
2992 qData.push(k + '=' + encodeURIComponent(value));
2996 if (method === 'GET') {
2997 data.url += startUrl + qData.join('&');
2999 data.data = qData.join('&');
3005 },{}],10:[function(require,module,exports){
3008 // Get CORS support even for older IE
3009 module.exports = function getCORSRequest() {
3010 var xhr = new global.XMLHttpRequest();
3011 if ('withCredentials' in xhr) {
3013 } else if (!!global.XDomainRequest) {
3014 return new XDomainRequest();
3016 throw new Error('CORS is not supported by your browser');
3020 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3022 },{}],11:[function(require,module,exports){
3025 module.exports = function getXMLHttpRequest() {
3029 if (global.XMLHttpRequest) {
3030 return new global.XMLHttpRequest();
3033 progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
3034 for (i = 0; i < 3; i++) {
3036 progId = progIds[i];
3037 if (new global.ActiveXObject(progId)) {
3042 return new global.ActiveXObject(progId);
3044 throw new Error('XMLHttpRequest is not supported by your browser');
3049 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3051 },{}],12:[function(require,module,exports){
3053 var getXMLHttpRequest = require('./getXMLHttpRequest');
3054 var getCORSRequest = require('./getCORSRequest');
3055 var hasOwnProp = Object.prototype.hasOwnProperty;
3057 var noop = function() {};
3059 function Observable() {}
3061 Observable.create = function(subscribe) {
3062 var o = new Observable();
3064 o.subscribe = function(onNext, onError, onCompleted) {
3069 if (typeof onNext === 'function') {
3072 onError: (onError || noop),
3073 onCompleted: (onCompleted || noop)
3079 disposable = subscribe(observer);
3081 if (typeof disposable === 'function') {
3093 function request(method, options, context) {
3094 return Observable.create(function requestObserver(observer) {
3097 method: method || 'GET',
3101 responseType: 'json'
3110 for (prop in options) {
3111 if (hasOwnProp.call(options, prop)) {
3112 config[prop] = options[prop];
3116 // Add request with Headers
3117 if (!config.crossDomain && !config.headers['X-Requested-With']) {
3118 config.headers['X-Requested-With'] = 'XMLHttpRequest';
3121 // allow the user to mutate the config open
3122 if (context.onBeforeRequest != null) {
3123 context.onBeforeRequest(config);
3128 xhr = config.crossDomain ? getCORSRequest() : getXMLHttpRequest();
3130 observer.onError(err);
3133 // Takes the url and opens the connection
3135 xhr.open(config.method, config.url, config.async, config.user, config.password);
3137 xhr.open(config.method, config.url, config.async);
3140 // Sets timeout information
3141 xhr.timeout = config.timeout;
3143 // Anything but explicit false results in true.
3144 xhr.withCredentials = config.withCredentials !== false;
3146 // Fills the request headers
3147 headers = config.headers;
3148 for (header in headers) {
3149 if (hasOwnProp.call(headers, header)) {
3150 xhr.setRequestHeader(header, headers[header]);
3154 if (config.responseType) {
3156 xhr.responseType = config.responseType;
3158 // WebKit added support for the json responseType value on 09/03/2013
3159 // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
3160 // known to throw when setting the value "json" as the response type. Other older
3161 // browsers implementing the responseType
3163 // The json response type can be ignored if not supported, because JSON payloads are
3164 // parsed on the client-side regardless.
3165 if (config.responseType !== 'json') {
3171 xhr.onreadystatechange = function onreadystatechange(e) {
3173 if (xhr.readyState === 4) {
3176 onXhrLoad(observer, xhr, e);
3182 xhr.ontimeout = function ontimeout(e) {
3185 onXhrError(observer, xhr, 'timeout error', e);
3190 xhr.send(config.data);
3193 observer.onError(e);
3196 return function dispose() {
3197 // Doesn't work in IE9
3198 if (!isDone && xhr.readyState !== 4) {
3207 * General handling of ultimate failure (after appropriate retries)
3209 function _handleXhrError(observer, textStatus, errorThrown) {
3210 // IE9: cross-domain request may be considered errors
3212 errorThrown = new Error(textStatus);
3215 observer.onError(errorThrown);
3218 function onXhrLoad(observer, xhr, e) {
3223 // If there's no observer, the request has been (or is being) cancelled.
3224 if (xhr && observer) {
3225 responseType = xhr.responseType;
3226 // responseText is the old-school way of retrieving response (supported by IE8 & 9)
3227 // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
3228 responseData = ('response' in xhr) ? xhr.response : xhr.responseText;
3230 // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
3231 var status = (xhr.status === 1223) ? 204 : xhr.status;
3233 if (status >= 200 && status <= 399) {
3235 if (responseType !== 'json') {
3236 responseData = JSON.parse(responseData || '');
3238 if (typeof responseData === 'string') {
3239 responseData = JSON.parse(responseData || '');
3242 _handleXhrError(observer, 'invalid json', e);
3244 observer.onNext(responseData);
3245 observer.onCompleted();
3248 } else if (status === 401 || status === 403 || status === 407) {
3250 return _handleXhrError(observer, responseData);
3252 } else if (status === 410) {
3254 return _handleXhrError(observer, responseData);
3256 } else if (status === 408 || status === 504) {
3258 return _handleXhrError(observer, responseData);
3262 return _handleXhrError(observer, responseData || ('Response code ' + status));
3268 function onXhrError(observer, xhr, status, e) {
3269 _handleXhrError(observer, status || xhr.statusText || 'request error', e);
3272 module.exports = request;
3274 },{"./getCORSRequest":10,"./getXMLHttpRequest":11}],13:[function(require,module,exports){
3276 !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(){
3277 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);
3278 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(){
3279 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(){
3280 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)});
3281 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3283 },{}],14:[function(require,module,exports){
3285 var topLevel = typeof global !== 'undefined' ? global :
3286 typeof window !== 'undefined' ? window : {}
3287 var minDoc = require('min-document');
3291 if (typeof document !== 'undefined') {
3294 doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
3297 doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
3301 module.exports = doccy;
3303 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3305 },{"min-document":2}],15:[function(require,module,exports){
3306 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
3308 var eLen = nBytes * 8 - mLen - 1
3309 var eMax = (1 << eLen) - 1
3310 var eBias = eMax >> 1
3312 var i = isLE ? (nBytes - 1) : 0
3313 var d = isLE ? -1 : 1
3314 var s = buffer[offset + i]
3318 e = s & ((1 << (-nBits)) - 1)
3321 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3323 m = e & ((1 << (-nBits)) - 1)
3326 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3330 } else if (e === eMax) {
3331 return m ? NaN : ((s ? -1 : 1) * Infinity)
3333 m = m + Math.pow(2, mLen)
3336 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
3339 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
3341 var eLen = nBytes * 8 - mLen - 1
3342 var eMax = (1 << eLen) - 1
3343 var eBias = eMax >> 1
3344 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
3345 var i = isLE ? 0 : (nBytes - 1)
3346 var d = isLE ? 1 : -1
3347 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
3349 value = Math.abs(value)
3351 if (isNaN(value) || value === Infinity) {
3352 m = isNaN(value) ? 1 : 0
3355 e = Math.floor(Math.log(value) / Math.LN2)
3356 if (value * (c = Math.pow(2, -e)) < 1) {
3360 if (e + eBias >= 1) {
3363 value += rt * Math.pow(2, 1 - eBias)
3365 if (value * c >= 2) {
3370 if (e + eBias >= eMax) {
3373 } else if (e + eBias >= 1) {
3374 m = (value * c - 1) * Math.pow(2, mLen)
3377 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
3382 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
3386 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
3388 buffer[offset + i - d] |= s * 128
3391 },{}],16:[function(require,module,exports){
3395 /*global window, global*/
3397 var root = typeof window !== 'undefined' ?
3398 window : typeof global !== 'undefined' ?
3401 module.exports = Individual;
3403 function Individual(key, value) {
3413 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3415 },{}],17:[function(require,module,exports){
3418 var Individual = require('./index.js');
3420 module.exports = OneVersion;
3422 function OneVersion(moduleName, version, defaultValue) {
3423 var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName;
3424 var enforceKey = key + '_ENFORCE_SINGLETON';
3426 var versionValue = Individual(enforceKey, version);
3428 if (versionValue !== version) {
3429 throw new Error('Can only have one copy of ' +
3430 moduleName + '.\n' +
3431 'You already have version ' + versionValue +
3433 'This means you cannot install version ' + version);
3436 return Individual(key, defaultValue);
3439 },{"./index.js":16}],18:[function(require,module,exports){
3442 module.exports = function isObject(x) {
3443 return typeof x === "object" && x !== null;
3446 },{}],19:[function(require,module,exports){
3447 var toString = {}.toString;
3449 module.exports = Array.isArray || function (arr) {
3450 return toString.call(arr) == '[object Array]';
3453 },{}],20:[function(require,module,exports){
3454 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3455 /* Geohash encoding/decoding and associated functions (c) Chris Veness 2014-2016 / MIT Licence */
3456 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3462 * Geohash encode, decode, bounds, neighbours.
3468 /* (Geohash-specific) Base32 map */
3469 Geohash.base32 = '0123456789bcdefghjkmnpqrstuvwxyz';
3472 * Encodes latitude/longitude to geohash, either to specified precision or to automatically
3473 * evaluated precision.
3475 * @param {number} lat - Latitude in degrees.
3476 * @param {number} lon - Longitude in degrees.
3477 * @param {number} [precision] - Number of characters in resulting geohash.
3478 * @returns {string} Geohash of supplied latitude/longitude.
3479 * @throws Invalid geohash.
3482 * var geohash = Geohash.encode(52.205, 0.119, 7); // geohash: 'u120fxw'
3484 Geohash.encode = function(lat, lon, precision) {
3486 if (typeof precision == 'undefined') {
3487 // refine geohash until it matches precision of supplied lat/lon
3488 for (var p=1; p<=12; p++) {
3489 var hash = Geohash.encode(lat, lon, p);
3490 var posn = Geohash.decode(hash);
3491 if (posn.lat==lat && posn.lon==lon) return hash;
3493 precision = 12; // set to maximum
3498 precision = Number(precision);
3500 if (isNaN(lat) || isNaN(lon) || isNaN(precision)) throw new Error('Invalid geohash');
3502 var idx = 0; // index into base32 map
3503 var bit = 0; // each char holds 5 bits
3507 var latMin = -90, latMax = 90;
3508 var lonMin = -180, lonMax = 180;
3510 while (geohash.length < precision) {
3512 // bisect E-W longitude
3513 var lonMid = (lonMin + lonMax) / 2;
3514 if (lon >= lonMid) {
3522 // bisect N-S latitude
3523 var latMid = (latMin + latMax) / 2;
3524 if (lat >= latMid) {
3535 // 5 bits gives us a character: append it and start over
3536 geohash += Geohash.base32.charAt(idx);
3547 * Decode geohash to latitude/longitude (location is approximate centre of geohash cell,
3548 * to reasonable precision).
3550 * @param {string} geohash - Geohash string to be converted to latitude/longitude.
3551 * @returns {{lat:number, lon:number}} (Center of) geohashed location.
3552 * @throws Invalid geohash.
3555 * var latlon = Geohash.decode('u120fxw'); // latlon: { lat: 52.205, lon: 0.1188 }
3557 Geohash.decode = function(geohash) {
3559 var bounds = Geohash.bounds(geohash); // <-- the hard work
3560 // now just determine the centre of the cell...
3562 var latMin = bounds.sw.lat, lonMin = bounds.sw.lon;
3563 var latMax = bounds.ne.lat, lonMax = bounds.ne.lon;
3566 var lat = (latMin + latMax)/2;
3567 var lon = (lonMin + lonMax)/2;
3569 // round to close to centre without excessive precision: ⌊2-log10(Δ°)⌋ decimal places
3570 lat = lat.toFixed(Math.floor(2-Math.log(latMax-latMin)/Math.LN10));
3571 lon = lon.toFixed(Math.floor(2-Math.log(lonMax-lonMin)/Math.LN10));
3573 return { lat: Number(lat), lon: Number(lon) };
3578 * Returns SW/NE latitude/longitude bounds of specified geohash.
3580 * @param {string} geohash - Cell that bounds are required of.
3581 * @returns {{sw: {lat: number, lon: number}, ne: {lat: number, lon: number}}}
3582 * @throws Invalid geohash.
3584 Geohash.bounds = function(geohash) {
3585 if (geohash.length === 0) throw new Error('Invalid geohash');
3587 geohash = geohash.toLowerCase();
3590 var latMin = -90, latMax = 90;
3591 var lonMin = -180, lonMax = 180;
3593 for (var i=0; i<geohash.length; i++) {
3594 var chr = geohash.charAt(i);
3595 var idx = Geohash.base32.indexOf(chr);
3596 if (idx == -1) throw new Error('Invalid geohash');
3598 for (var n=4; n>=0; n--) {
3599 var bitN = idx >> n & 1;
3602 var lonMid = (lonMin+lonMax) / 2;
3610 var latMid = (latMin+latMax) / 2;
3622 sw: { lat: latMin, lon: lonMin },
3623 ne: { lat: latMax, lon: lonMax },
3631 * Determines adjacent cell in given direction.
3633 * @param geohash - Cell to which adjacent cell is required.
3634 * @param direction - Direction from geohash (N/S/E/W).
3635 * @returns {string} Geocode of adjacent cell.
3636 * @throws Invalid geohash.
3638 Geohash.adjacent = function(geohash, direction) {
3639 // based on github.com/davetroy/geohash-js
3641 geohash = geohash.toLowerCase();
3642 direction = direction.toLowerCase();
3644 if (geohash.length === 0) throw new Error('Invalid geohash');
3645 if ('nsew'.indexOf(direction) == -1) throw new Error('Invalid direction');
3648 n: [ 'p0r21436x8zb9dcf5h7kjnmqesgutwvy', 'bc01fg45238967deuvhjyznpkmstqrwx' ],
3649 s: [ '14365h7k9dcfesgujnmqp0r2twvyx8zb', '238967debc01fg45kmstqrwxuvhjyznp' ],
3650 e: [ 'bc01fg45238967deuvhjyznpkmstqrwx', 'p0r21436x8zb9dcf5h7kjnmqesgutwvy' ],
3651 w: [ '238967debc01fg45kmstqrwxuvhjyznp', '14365h7k9dcfesgujnmqp0r2twvyx8zb' ],
3654 n: [ 'prxz', 'bcfguvyz' ],
3655 s: [ '028b', '0145hjnp' ],
3656 e: [ 'bcfguvyz', 'prxz' ],
3657 w: [ '0145hjnp', '028b' ],
3660 var lastCh = geohash.slice(-1); // last character of hash
3661 var parent = geohash.slice(0, -1); // hash without last character
3663 var type = geohash.length % 2;
3665 // check for edge-cases which don't share common prefix
3666 if (border[direction][type].indexOf(lastCh) != -1 && parent !== '') {
3667 parent = Geohash.adjacent(parent, direction);
3670 // append letter for direction to parent
3671 return parent + Geohash.base32.charAt(neighbour[direction][type].indexOf(lastCh));
3676 * Returns all 8 adjacent cells to specified geohash.
3678 * @param {string} geohash - Geohash neighbours are required of.
3679 * @returns {{n,ne,e,se,s,sw,w,nw: string}}
3680 * @throws Invalid geohash.
3682 Geohash.neighbours = function(geohash) {
3684 'n': Geohash.adjacent(geohash, 'n'),
3685 'ne': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'e'),
3686 'e': Geohash.adjacent(geohash, 'e'),
3687 'se': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'e'),
3688 's': Geohash.adjacent(geohash, 's'),
3689 'sw': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'w'),
3690 'w': Geohash.adjacent(geohash, 'w'),
3691 'nw': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'w'),
3696 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3697 if (typeof module != 'undefined' && module.exports) module.exports = Geohash; // CommonJS, node.js
3699 },{}],21:[function(require,module,exports){
3700 (function (process){
3701 // Copyright Joyent, Inc. and other Node contributors.
3703 // Permission is hereby granted, free of charge, to any person obtaining a
3704 // copy of this software and associated documentation files (the
3705 // "Software"), to deal in the Software without restriction, including
3706 // without limitation the rights to use, copy, modify, merge, publish,
3707 // distribute, sublicense, and/or sell copies of the Software, and to permit
3708 // persons to whom the Software is furnished to do so, subject to the
3709 // following conditions:
3711 // The above copyright notice and this permission notice shall be included
3712 // in all copies or substantial portions of the Software.
3714 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3715 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3716 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3717 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3718 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3719 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3720 // USE OR OTHER DEALINGS IN THE SOFTWARE.
3722 // resolves . and .. elements in a path array with directory names there
3723 // must be no slashes, empty elements, or device names (c:\) in the array
3724 // (so also no leading and trailing slashes - it does not distinguish
3725 // relative and absolute paths)
3726 function normalizeArray(parts, allowAboveRoot) {
3727 // if the path tries to go above the root, `up` ends up > 0
3729 for (var i = parts.length - 1; i >= 0; i--) {
3730 var last = parts[i];
3733 } else if (last === '..') {
3742 // if the path is allowed to go above the root, restore leading ..s
3743 if (allowAboveRoot) {
3745 parts.unshift('..');
3752 // Split a filename into [root, dir, basename, ext], unix version
3753 // 'root' is just a slash, or nothing.
3755 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
3756 var splitPath = function(filename) {
3757 return splitPathRe.exec(filename).slice(1);
3760 // path.resolve([from ...], to)
3762 exports.resolve = function() {
3763 var resolvedPath = '',
3764 resolvedAbsolute = false;
3766 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
3767 var path = (i >= 0) ? arguments[i] : process.cwd();
3769 // Skip empty and invalid entries
3770 if (typeof path !== 'string') {
3771 throw new TypeError('Arguments to path.resolve must be strings');
3776 resolvedPath = path + '/' + resolvedPath;
3777 resolvedAbsolute = path.charAt(0) === '/';
3780 // At this point the path should be resolved to a full absolute path, but
3781 // handle relative paths to be safe (might happen when process.cwd() fails)
3783 // Normalize the path
3784 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
3786 }), !resolvedAbsolute).join('/');
3788 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
3791 // path.normalize(path)
3793 exports.normalize = function(path) {
3794 var isAbsolute = exports.isAbsolute(path),
3795 trailingSlash = substr(path, -1) === '/';
3797 // Normalize the path
3798 path = normalizeArray(filter(path.split('/'), function(p) {
3800 }), !isAbsolute).join('/');
3802 if (!path && !isAbsolute) {
3805 if (path && trailingSlash) {
3809 return (isAbsolute ? '/' : '') + path;
3813 exports.isAbsolute = function(path) {
3814 return path.charAt(0) === '/';
3818 exports.join = function() {
3819 var paths = Array.prototype.slice.call(arguments, 0);
3820 return exports.normalize(filter(paths, function(p, index) {
3821 if (typeof p !== 'string') {
3822 throw new TypeError('Arguments to path.join must be strings');
3829 // path.relative(from, to)
3831 exports.relative = function(from, to) {
3832 from = exports.resolve(from).substr(1);
3833 to = exports.resolve(to).substr(1);
3835 function trim(arr) {
3837 for (; start < arr.length; start++) {
3838 if (arr[start] !== '') break;
3841 var end = arr.length - 1;
3842 for (; end >= 0; end--) {
3843 if (arr[end] !== '') break;
3846 if (start > end) return [];
3847 return arr.slice(start, end - start + 1);
3850 var fromParts = trim(from.split('/'));
3851 var toParts = trim(to.split('/'));
3853 var length = Math.min(fromParts.length, toParts.length);
3854 var samePartsLength = length;
3855 for (var i = 0; i < length; i++) {
3856 if (fromParts[i] !== toParts[i]) {
3857 samePartsLength = i;
3862 var outputParts = [];
3863 for (var i = samePartsLength; i < fromParts.length; i++) {
3864 outputParts.push('..');
3867 outputParts = outputParts.concat(toParts.slice(samePartsLength));
3869 return outputParts.join('/');
3873 exports.delimiter = ':';
3875 exports.dirname = function(path) {
3876 var result = splitPath(path),
3880 if (!root && !dir) {
3881 // No dirname whatsoever
3886 // It has a dirname, strip trailing slash
3887 dir = dir.substr(0, dir.length - 1);
3894 exports.basename = function(path, ext) {
3895 var f = splitPath(path)[2];
3896 // TODO: make this comparison case-insensitive on windows?
3897 if (ext && f.substr(-1 * ext.length) === ext) {
3898 f = f.substr(0, f.length - ext.length);
3904 exports.extname = function(path) {
3905 return splitPath(path)[3];
3908 function filter (xs, f) {
3909 if (xs.filter) return xs.filter(f);
3911 for (var i = 0; i < xs.length; i++) {
3912 if (f(xs[i], i, xs)) res.push(xs[i]);
3917 // String.prototype.substr - negative index don't work in IE8
3918 var substr = 'ab'.substr(-1) === 'b'
3919 ? function (str, start, len) { return str.substr(start, len) }
3920 : function (str, start, len) {
3921 if (start < 0) start = str.length + start;
3922 return str.substr(start, len);
3926 }).call(this,require('_process'))
3928 },{"_process":4}],22:[function(require,module,exports){
3931 module.exports = Pbf;
3933 var ieee754 = require('ieee754');
3936 this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);
3939 this.length = this.buf.length;
3942 Pbf.Varint = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum
3943 Pbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64
3944 Pbf.Bytes = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields
3945 Pbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32
3947 var SHIFT_LEFT_32 = (1 << 16) * (1 << 16),
3948 SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
3952 destroy: function() {
3956 // === READING =================================================================
3958 readFields: function(readField, result, end) {
3959 end = end || this.length;
3961 while (this.pos < end) {
3962 var val = this.readVarint(),
3964 startPos = this.pos;
3966 this.type = val & 0x7;
3967 readField(tag, result, this);
3969 if (this.pos === startPos) this.skip(val);
3974 readMessage: function(readField, result) {
3975 return this.readFields(readField, result, this.readVarint() + this.pos);
3978 readFixed32: function() {
3979 var val = readUInt32(this.buf, this.pos);
3984 readSFixed32: function() {
3985 var val = readInt32(this.buf, this.pos);
3990 // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)
3992 readFixed64: function() {
3993 var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
3998 readSFixed64: function() {
3999 var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4004 readFloat: function() {
4005 var val = ieee754.read(this.buf, this.pos, true, 23, 4);
4010 readDouble: function() {
4011 var val = ieee754.read(this.buf, this.pos, true, 52, 8);
4016 readVarint: function(isSigned) {
4020 b = buf[this.pos++]; val = b & 0x7f; if (b < 0x80) return val;
4021 b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val;
4022 b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;
4023 b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;
4024 b = buf[this.pos]; val |= (b & 0x0f) << 28;
4026 return readVarintRemainder(val, isSigned, this);
4029 readVarint64: function() { // for compatibility with v2.0.1
4030 return this.readVarint(true);
4033 readSVarint: function() {
4034 var num = this.readVarint();
4035 return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding
4038 readBoolean: function() {
4039 return Boolean(this.readVarint());
4042 readString: function() {
4043 var end = this.readVarint() + this.pos,
4044 str = readUtf8(this.buf, this.pos, end);
4049 readBytes: function() {
4050 var end = this.readVarint() + this.pos,
4051 buffer = this.buf.subarray(this.pos, end);
4056 // verbose for performance reasons; doesn't affect gzipped size
4058 readPackedVarint: function(arr, isSigned) {
4059 var end = readPackedEnd(this);
4061 while (this.pos < end) arr.push(this.readVarint(isSigned));
4064 readPackedSVarint: function(arr) {
4065 var end = readPackedEnd(this);
4067 while (this.pos < end) arr.push(this.readSVarint());
4070 readPackedBoolean: function(arr) {
4071 var end = readPackedEnd(this);
4073 while (this.pos < end) arr.push(this.readBoolean());
4076 readPackedFloat: function(arr) {
4077 var end = readPackedEnd(this);
4079 while (this.pos < end) arr.push(this.readFloat());
4082 readPackedDouble: function(arr) {
4083 var end = readPackedEnd(this);
4085 while (this.pos < end) arr.push(this.readDouble());
4088 readPackedFixed32: function(arr) {
4089 var end = readPackedEnd(this);
4091 while (this.pos < end) arr.push(this.readFixed32());
4094 readPackedSFixed32: function(arr) {
4095 var end = readPackedEnd(this);
4097 while (this.pos < end) arr.push(this.readSFixed32());
4100 readPackedFixed64: function(arr) {
4101 var end = readPackedEnd(this);
4103 while (this.pos < end) arr.push(this.readFixed64());
4106 readPackedSFixed64: function(arr) {
4107 var end = readPackedEnd(this);
4109 while (this.pos < end) arr.push(this.readSFixed64());
4113 skip: function(val) {
4114 var type = val & 0x7;
4115 if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}
4116 else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos;
4117 else if (type === Pbf.Fixed32) this.pos += 4;
4118 else if (type === Pbf.Fixed64) this.pos += 8;
4119 else throw new Error('Unimplemented type: ' + type);
4122 // === WRITING =================================================================
4124 writeTag: function(tag, type) {
4125 this.writeVarint((tag << 3) | type);
4128 realloc: function(min) {
4129 var length = this.length || 16;
4131 while (length < this.pos + min) length *= 2;
4133 if (length !== this.length) {
4134 var buf = new Uint8Array(length);
4137 this.length = length;
4141 finish: function() {
4142 this.length = this.pos;
4144 return this.buf.subarray(0, this.length);
4147 writeFixed32: function(val) {
4149 writeInt32(this.buf, val, this.pos);
4153 writeSFixed32: function(val) {
4155 writeInt32(this.buf, val, this.pos);
4159 writeFixed64: function(val) {
4161 writeInt32(this.buf, val & -1, this.pos);
4162 writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4166 writeSFixed64: function(val) {
4168 writeInt32(this.buf, val & -1, this.pos);
4169 writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4173 writeVarint: function(val) {
4176 if (val > 0xfffffff || val < 0) {
4177 writeBigVarint(val, this);
4183 this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4184 this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4185 this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4186 this.buf[this.pos++] = (val >>> 7) & 0x7f;
4189 writeSVarint: function(val) {
4190 this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
4193 writeBoolean: function(val) {
4194 this.writeVarint(Boolean(val));
4197 writeString: function(str) {
4199 this.realloc(str.length * 4);
4201 this.pos++; // reserve 1 byte for short string length
4203 var startPos = this.pos;
4204 // write the string directly to the buffer and see how much was written
4205 this.pos = writeUtf8(this.buf, str, this.pos);
4206 var len = this.pos - startPos;
4208 if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4210 // finally, write the message length in the reserved place and restore the position
4211 this.pos = startPos - 1;
4212 this.writeVarint(len);
4216 writeFloat: function(val) {
4218 ieee754.write(this.buf, val, this.pos, true, 23, 4);
4222 writeDouble: function(val) {
4224 ieee754.write(this.buf, val, this.pos, true, 52, 8);
4228 writeBytes: function(buffer) {
4229 var len = buffer.length;
4230 this.writeVarint(len);
4232 for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];
4235 writeRawMessage: function(fn, obj) {
4236 this.pos++; // reserve 1 byte for short message length
4238 // write the message directly to the buffer and see how much was written
4239 var startPos = this.pos;
4241 var len = this.pos - startPos;
4243 if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4245 // finally, write the message length in the reserved place and restore the position
4246 this.pos = startPos - 1;
4247 this.writeVarint(len);
4251 writeMessage: function(tag, fn, obj) {
4252 this.writeTag(tag, Pbf.Bytes);
4253 this.writeRawMessage(fn, obj);
4256 writePackedVarint: function(tag, arr) { this.writeMessage(tag, writePackedVarint, arr); },
4257 writePackedSVarint: function(tag, arr) { this.writeMessage(tag, writePackedSVarint, arr); },
4258 writePackedBoolean: function(tag, arr) { this.writeMessage(tag, writePackedBoolean, arr); },
4259 writePackedFloat: function(tag, arr) { this.writeMessage(tag, writePackedFloat, arr); },
4260 writePackedDouble: function(tag, arr) { this.writeMessage(tag, writePackedDouble, arr); },
4261 writePackedFixed32: function(tag, arr) { this.writeMessage(tag, writePackedFixed32, arr); },
4262 writePackedSFixed32: function(tag, arr) { this.writeMessage(tag, writePackedSFixed32, arr); },
4263 writePackedFixed64: function(tag, arr) { this.writeMessage(tag, writePackedFixed64, arr); },
4264 writePackedSFixed64: function(tag, arr) { this.writeMessage(tag, writePackedSFixed64, arr); },
4266 writeBytesField: function(tag, buffer) {
4267 this.writeTag(tag, Pbf.Bytes);
4268 this.writeBytes(buffer);
4270 writeFixed32Field: function(tag, val) {
4271 this.writeTag(tag, Pbf.Fixed32);
4272 this.writeFixed32(val);
4274 writeSFixed32Field: function(tag, val) {
4275 this.writeTag(tag, Pbf.Fixed32);
4276 this.writeSFixed32(val);
4278 writeFixed64Field: function(tag, val) {
4279 this.writeTag(tag, Pbf.Fixed64);
4280 this.writeFixed64(val);
4282 writeSFixed64Field: function(tag, val) {
4283 this.writeTag(tag, Pbf.Fixed64);
4284 this.writeSFixed64(val);
4286 writeVarintField: function(tag, val) {
4287 this.writeTag(tag, Pbf.Varint);
4288 this.writeVarint(val);
4290 writeSVarintField: function(tag, val) {
4291 this.writeTag(tag, Pbf.Varint);
4292 this.writeSVarint(val);
4294 writeStringField: function(tag, str) {
4295 this.writeTag(tag, Pbf.Bytes);
4296 this.writeString(str);
4298 writeFloatField: function(tag, val) {
4299 this.writeTag(tag, Pbf.Fixed32);
4300 this.writeFloat(val);
4302 writeDoubleField: function(tag, val) {
4303 this.writeTag(tag, Pbf.Fixed64);
4304 this.writeDouble(val);
4306 writeBooleanField: function(tag, val) {
4307 this.writeVarintField(tag, Boolean(val));
4311 function readVarintRemainder(l, s, p) {
4315 b = buf[p.pos++]; h = (b & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s);
4316 b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s);
4317 b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);
4318 b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);
4319 b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);
4320 b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);
4322 throw new Error('Expected varint not more than 10 bytes');
4325 function readPackedEnd(pbf) {
4326 return pbf.type === Pbf.Bytes ?
4327 pbf.readVarint() + pbf.pos : pbf.pos + 1;
4330 function toNum(low, high, isSigned) {
4332 return high * 0x100000000 + (low >>> 0);
4335 return ((high >>> 0) * 0x100000000) + (low >>> 0);
4338 function writeBigVarint(val, pbf) {
4342 low = (val % 0x100000000) | 0;
4343 high = (val / 0x100000000) | 0;
4345 low = ~(-val % 0x100000000);
4346 high = ~(-val / 0x100000000);
4348 if (low ^ 0xffffffff) {
4349 low = (low + 1) | 0;
4352 high = (high + 1) | 0;
4356 if (val >= 0x10000000000000000 || val < -0x10000000000000000) {
4357 throw new Error('Given varint doesn\'t fit into 10 bytes');
4362 writeBigVarintLow(low, high, pbf);
4363 writeBigVarintHigh(high, pbf);
4366 function writeBigVarintLow(low, high, pbf) {
4367 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4368 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4369 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4370 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4371 pbf.buf[pbf.pos] = low & 0x7f;
4374 function writeBigVarintHigh(high, pbf) {
4375 var lsb = (high & 0x07) << 4;
4377 pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return;
4378 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4379 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4380 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4381 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4382 pbf.buf[pbf.pos++] = high & 0x7f;
4385 function makeRoomForExtraLength(startPos, len, pbf) {
4388 len <= 0x1fffff ? 2 :
4389 len <= 0xfffffff ? 3 : Math.ceil(Math.log(len) / (Math.LN2 * 7));
4391 // if 1 byte isn't enough for encoding message length, shift the data to the right
4392 pbf.realloc(extraLen);
4393 for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];
4396 function writePackedVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]); }
4397 function writePackedSVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]); }
4398 function writePackedFloat(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]); }
4399 function writePackedDouble(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]); }
4400 function writePackedBoolean(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]); }
4401 function writePackedFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]); }
4402 function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); }
4403 function writePackedFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]); }
4404 function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); }
4406 // Buffer code below from https://github.com/feross/buffer, MIT-licensed
4408 function readUInt32(buf, pos) {
4409 return ((buf[pos]) |
4410 (buf[pos + 1] << 8) |
4411 (buf[pos + 2] << 16)) +
4412 (buf[pos + 3] * 0x1000000);
4415 function writeInt32(buf, val, pos) {
4417 buf[pos + 1] = (val >>> 8);
4418 buf[pos + 2] = (val >>> 16);
4419 buf[pos + 3] = (val >>> 24);
4422 function readInt32(buf, pos) {
4423 return ((buf[pos]) |
4424 (buf[pos + 1] << 8) |
4425 (buf[pos + 2] << 16)) +
4426 (buf[pos + 3] << 24);
4429 function readUtf8(buf, pos, end) {
4435 var c = null; // codepoint
4436 var bytesPerSequence =
4441 if (i + bytesPerSequence > end) break;
4445 if (bytesPerSequence === 1) {
4449 } else if (bytesPerSequence === 2) {
4451 if ((b1 & 0xC0) === 0x80) {
4452 c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);
4457 } else if (bytesPerSequence === 3) {
4460 if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {
4461 c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);
4462 if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {
4466 } else if (bytesPerSequence === 4) {
4470 if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
4471 c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);
4472 if (c <= 0xFFFF || c >= 0x110000) {
4480 bytesPerSequence = 1;
4482 } else if (c > 0xFFFF) {
4484 str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);
4485 c = 0xDC00 | c & 0x3FF;
4488 str += String.fromCharCode(c);
4489 i += bytesPerSequence;
4495 function writeUtf8(buf, str, pos) {
4496 for (var i = 0, c, lead; i < str.length; i++) {
4497 c = str.charCodeAt(i); // code point
4499 if (c > 0xD7FF && c < 0xE000) {
4508 c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;
4512 if (c > 0xDBFF || (i + 1 === str.length)) {
4532 buf[pos++] = c >> 0x6 | 0xC0;
4535 buf[pos++] = c >> 0xC | 0xE0;
4537 buf[pos++] = c >> 0x12 | 0xF0;
4538 buf[pos++] = c >> 0xC & 0x3F | 0x80;
4540 buf[pos++] = c >> 0x6 & 0x3F | 0x80;
4542 buf[pos++] = c & 0x3F | 0x80;
4548 },{"ieee754":15}],23:[function(require,module,exports){
4551 module.exports = partialSort;
4553 // Floyd-Rivest selection algorithm:
4554 // Rearrange items so that all items in the [left, k] range are smaller than all items in (k, right];
4555 // The k-th element will have the (k - left + 1)th smallest value in [left, right]
4557 function partialSort(arr, k, left, right, compare) {
4559 right = right || (arr.length - 1);
4560 compare = compare || defaultCompare;
4562 while (right > left) {
4563 if (right - left > 600) {
4564 var n = right - left + 1;
4565 var m = k - left + 1;
4566 var z = Math.log(n);
4567 var s = 0.5 * Math.exp(2 * z / 3);
4568 var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
4569 var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
4570 var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
4571 partialSort(arr, k, newLeft, newRight, compare);
4579 if (compare(arr[right], t) > 0) swap(arr, left, right);
4585 while (compare(arr[i], t) < 0) i++;
4586 while (compare(arr[j], t) > 0) j--;
4589 if (compare(arr[left], t) === 0) swap(arr, left, j);
4592 swap(arr, j, right);
4595 if (j <= k) left = j + 1;
4596 if (k <= j) right = j - 1;
4600 function swap(arr, i, j) {
4606 function defaultCompare(a, b) {
4607 return a < b ? -1 : a > b ? 1 : 0;
4610 },{}],24:[function(require,module,exports){
4613 module.exports = rbush;
4615 var quickselect = require('quickselect');
4617 function rbush(maxEntries, format) {
4618 if (!(this instanceof rbush)) return new rbush(maxEntries, format);
4620 // max entries in a node is 9 by default; min node fill is 40% for best performance
4621 this._maxEntries = Math.max(4, maxEntries || 9);
4622 this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
4625 this._initFormat(format);
4634 return this._all(this.data, []);
4637 search: function (bbox) {
4639 var node = this.data,
4641 toBBox = this.toBBox;
4643 if (!intersects(bbox, node)) return result;
4645 var nodesToSearch = [],
4646 i, len, child, childBBox;
4649 for (i = 0, len = node.children.length; i < len; i++) {
4651 child = node.children[i];
4652 childBBox = node.leaf ? toBBox(child) : child;
4654 if (intersects(bbox, childBBox)) {
4655 if (node.leaf) result.push(child);
4656 else if (contains(bbox, childBBox)) this._all(child, result);
4657 else nodesToSearch.push(child);
4660 node = nodesToSearch.pop();
4666 collides: function (bbox) {
4668 var node = this.data,
4669 toBBox = this.toBBox;
4671 if (!intersects(bbox, node)) return false;
4673 var nodesToSearch = [],
4674 i, len, child, childBBox;
4677 for (i = 0, len = node.children.length; i < len; i++) {
4679 child = node.children[i];
4680 childBBox = node.leaf ? toBBox(child) : child;
4682 if (intersects(bbox, childBBox)) {
4683 if (node.leaf || contains(bbox, childBBox)) return true;
4684 nodesToSearch.push(child);
4687 node = nodesToSearch.pop();
4693 load: function (data) {
4694 if (!(data && data.length)) return this;
4696 if (data.length < this._minEntries) {
4697 for (var i = 0, len = data.length; i < len; i++) {
4698 this.insert(data[i]);
4703 // recursively build the tree with the given data from stratch using OMT algorithm
4704 var node = this._build(data.slice(), 0, data.length - 1, 0);
4706 if (!this.data.children.length) {
4707 // save as is if tree is empty
4710 } else if (this.data.height === node.height) {
4711 // split root if trees have the same height
4712 this._splitRoot(this.data, node);
4715 if (this.data.height < node.height) {
4716 // swap trees if inserted one is bigger
4717 var tmpNode = this.data;
4722 // insert the small tree into the large tree at appropriate level
4723 this._insert(node, this.data.height - node.height - 1, true);
4729 insert: function (item) {
4730 if (item) this._insert(item, this.data.height - 1);
4734 clear: function () {
4735 this.data = createNode([]);
4739 remove: function (item, equalsFn) {
4740 if (!item) return this;
4742 var node = this.data,
4743 bbox = this.toBBox(item),
4746 i, parent, index, goingUp;
4748 // depth-first iterative tree traversal
4749 while (node || path.length) {
4751 if (!node) { // go up
4753 parent = path[path.length - 1];
4758 if (node.leaf) { // check current node
4759 index = findItem(item, node.children, equalsFn);
4762 // item found, remove the item and condense tree upwards
4763 node.children.splice(index, 1);
4765 this._condense(path);
4770 if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
4775 node = node.children[0];
4777 } else if (parent) { // go right
4779 node = parent.children[i];
4782 } else node = null; // nothing found
4788 toBBox: function (item) { return item; },
4790 compareMinX: compareNodeMinX,
4791 compareMinY: compareNodeMinY,
4793 toJSON: function () { return this.data; },
4795 fromJSON: function (data) {
4800 _all: function (node, result) {
4801 var nodesToSearch = [];
4803 if (node.leaf) result.push.apply(result, node.children);
4804 else nodesToSearch.push.apply(nodesToSearch, node.children);
4806 node = nodesToSearch.pop();
4811 _build: function (items, left, right, height) {
4813 var N = right - left + 1,
4814 M = this._maxEntries,
4818 // reached leaf level; return leaf
4819 node = createNode(items.slice(left, right + 1));
4820 calcBBox(node, this.toBBox);
4825 // target height of the bulk-loaded tree
4826 height = Math.ceil(Math.log(N) / Math.log(M));
4828 // target number of root entries to maximize storage utilization
4829 M = Math.ceil(N / Math.pow(M, height - 1));
4832 node = createNode([]);
4834 node.height = height;
4836 // split the items into M mostly square tiles
4838 var N2 = Math.ceil(N / M),
4839 N1 = N2 * Math.ceil(Math.sqrt(M)),
4840 i, j, right2, right3;
4842 multiSelect(items, left, right, N1, this.compareMinX);
4844 for (i = left; i <= right; i += N1) {
4846 right2 = Math.min(i + N1 - 1, right);
4848 multiSelect(items, i, right2, N2, this.compareMinY);
4850 for (j = i; j <= right2; j += N2) {
4852 right3 = Math.min(j + N2 - 1, right2);
4854 // pack each entry recursively
4855 node.children.push(this._build(items, j, right3, height - 1));
4859 calcBBox(node, this.toBBox);
4864 _chooseSubtree: function (bbox, node, level, path) {
4866 var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
4871 if (node.leaf || path.length - 1 === level) break;
4873 minArea = minEnlargement = Infinity;
4875 for (i = 0, len = node.children.length; i < len; i++) {
4876 child = node.children[i];
4877 area = bboxArea(child);
4878 enlargement = enlargedArea(bbox, child) - area;
4880 // choose entry with the least area enlargement
4881 if (enlargement < minEnlargement) {
4882 minEnlargement = enlargement;
4883 minArea = area < minArea ? area : minArea;
4886 } else if (enlargement === minEnlargement) {
4887 // otherwise choose one with the smallest area
4888 if (area < minArea) {
4895 node = targetNode || node.children[0];
4901 _insert: function (item, level, isNode) {
4903 var toBBox = this.toBBox,
4904 bbox = isNode ? item : toBBox(item),
4907 // find the best node for accommodating the item, saving all nodes along the path too
4908 var node = this._chooseSubtree(bbox, this.data, level, insertPath);
4910 // put the item into the node
4911 node.children.push(item);
4914 // split on node overflow; propagate upwards if necessary
4915 while (level >= 0) {
4916 if (insertPath[level].children.length > this._maxEntries) {
4917 this._split(insertPath, level);
4922 // adjust bboxes along the insertion path
4923 this._adjustParentBBoxes(bbox, insertPath, level);
4926 // split overflowed node into two
4927 _split: function (insertPath, level) {
4929 var node = insertPath[level],
4930 M = node.children.length,
4931 m = this._minEntries;
4933 this._chooseSplitAxis(node, m, M);
4935 var splitIndex = this._chooseSplitIndex(node, m, M);
4937 var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
4938 newNode.height = node.height;
4939 newNode.leaf = node.leaf;
4941 calcBBox(node, this.toBBox);
4942 calcBBox(newNode, this.toBBox);
4944 if (level) insertPath[level - 1].children.push(newNode);
4945 else this._splitRoot(node, newNode);
4948 _splitRoot: function (node, newNode) {
4950 this.data = createNode([node, newNode]);
4951 this.data.height = node.height + 1;
4952 this.data.leaf = false;
4953 calcBBox(this.data, this.toBBox);
4956 _chooseSplitIndex: function (node, m, M) {
4958 var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
4960 minOverlap = minArea = Infinity;
4962 for (i = m; i <= M - m; i++) {
4963 bbox1 = distBBox(node, 0, i, this.toBBox);
4964 bbox2 = distBBox(node, i, M, this.toBBox);
4966 overlap = intersectionArea(bbox1, bbox2);
4967 area = bboxArea(bbox1) + bboxArea(bbox2);
4969 // choose distribution with minimum overlap
4970 if (overlap < minOverlap) {
4971 minOverlap = overlap;
4974 minArea = area < minArea ? area : minArea;
4976 } else if (overlap === minOverlap) {
4977 // otherwise choose distribution with minimum area
4978 if (area < minArea) {
4988 // sorts node children by the best axis for split
4989 _chooseSplitAxis: function (node, m, M) {
4991 var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
4992 compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
4993 xMargin = this._allDistMargin(node, m, M, compareMinX),
4994 yMargin = this._allDistMargin(node, m, M, compareMinY);
4996 // if total distributions margin value is minimal for x, sort by minX,
4997 // otherwise it's already sorted by minY
4998 if (xMargin < yMargin) node.children.sort(compareMinX);
5001 // total margin of all possible split distributions where each node is at least m full
5002 _allDistMargin: function (node, m, M, compare) {
5004 node.children.sort(compare);
5006 var toBBox = this.toBBox,
5007 leftBBox = distBBox(node, 0, m, toBBox),
5008 rightBBox = distBBox(node, M - m, M, toBBox),
5009 margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
5012 for (i = m; i < M - m; i++) {
5013 child = node.children[i];
5014 extend(leftBBox, node.leaf ? toBBox(child) : child);
5015 margin += bboxMargin(leftBBox);
5018 for (i = M - m - 1; i >= m; i--) {
5019 child = node.children[i];
5020 extend(rightBBox, node.leaf ? toBBox(child) : child);
5021 margin += bboxMargin(rightBBox);
5027 _adjustParentBBoxes: function (bbox, path, level) {
5028 // adjust bboxes along the given tree path
5029 for (var i = level; i >= 0; i--) {
5030 extend(path[i], bbox);
5034 _condense: function (path) {
5035 // go through the path, removing empty nodes and updating bboxes
5036 for (var i = path.length - 1, siblings; i >= 0; i--) {
5037 if (path[i].children.length === 0) {
5039 siblings = path[i - 1].children;
5040 siblings.splice(siblings.indexOf(path[i]), 1);
5042 } else this.clear();
5044 } else calcBBox(path[i], this.toBBox);
5048 _initFormat: function (format) {
5049 // data format (minX, minY, maxX, maxY accessors)
5051 // uses eval-type function compilation instead of just accepting a toBBox function
5052 // because the algorithms are very sensitive to sorting functions performance,
5053 // so they should be dead simple and without inner calls
5055 var compareArr = ['return a', ' - b', ';'];
5057 this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
5058 this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
5060 this.toBBox = new Function('a',
5061 'return {minX: a' + format[0] +
5062 ', minY: a' + format[1] +
5063 ', maxX: a' + format[2] +
5064 ', maxY: a' + format[3] + '};');
5068 function findItem(item, items, equalsFn) {
5069 if (!equalsFn) return items.indexOf(item);
5071 for (var i = 0; i < items.length; i++) {
5072 if (equalsFn(item, items[i])) return i;
5077 // calculate node's bbox from bboxes of its children
5078 function calcBBox(node, toBBox) {
5079 distBBox(node, 0, node.children.length, toBBox, node);
5082 // min bounding rectangle of node children from k to p-1
5083 function distBBox(node, k, p, toBBox, destNode) {
5084 if (!destNode) destNode = createNode(null);
5085 destNode.minX = Infinity;
5086 destNode.minY = Infinity;
5087 destNode.maxX = -Infinity;
5088 destNode.maxY = -Infinity;
5090 for (var i = k, child; i < p; i++) {
5091 child = node.children[i];
5092 extend(destNode, node.leaf ? toBBox(child) : child);
5098 function extend(a, b) {
5099 a.minX = Math.min(a.minX, b.minX);
5100 a.minY = Math.min(a.minY, b.minY);
5101 a.maxX = Math.max(a.maxX, b.maxX);
5102 a.maxY = Math.max(a.maxY, b.maxY);
5106 function compareNodeMinX(a, b) { return a.minX - b.minX; }
5107 function compareNodeMinY(a, b) { return a.minY - b.minY; }
5109 function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); }
5110 function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
5112 function enlargedArea(a, b) {
5113 return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
5114 (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
5117 function intersectionArea(a, b) {
5118 var minX = Math.max(a.minX, b.minX),
5119 minY = Math.max(a.minY, b.minY),
5120 maxX = Math.min(a.maxX, b.maxX),
5121 maxY = Math.min(a.maxY, b.maxY);
5123 return Math.max(0, maxX - minX) *
5124 Math.max(0, maxY - minY);
5127 function contains(a, b) {
5128 return a.minX <= b.minX &&
5134 function intersects(a, b) {
5135 return b.minX <= a.maxX &&
5141 function createNode(children) {
5153 // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
5154 // combines selection algorithm with binary divide & conquer approach
5156 function multiSelect(arr, left, right, n, compare) {
5157 var stack = [left, right],
5160 while (stack.length) {
5161 right = stack.pop();
5164 if (right - left <= n) continue;
5166 mid = left + Math.ceil((right - left) / n / 2) * n;
5167 quickselect(arr, mid, left, right, compare);
5169 stack.push(left, mid, mid, right);
5173 },{"quickselect":23}],25:[function(require,module,exports){
5175 var __extends = (this && this.__extends) || function (d, b) {
5176 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5177 function __() { this.constructor = d; }
5178 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5180 var Subject_1 = require('./Subject');
5181 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5183 * @class BehaviorSubject<T>
5185 var BehaviorSubject = (function (_super) {
5186 __extends(BehaviorSubject, _super);
5187 function BehaviorSubject(_value) {
5189 this._value = _value;
5191 Object.defineProperty(BehaviorSubject.prototype, "value", {
5193 return this.getValue();
5198 BehaviorSubject.prototype._subscribe = function (subscriber) {
5199 var subscription = _super.prototype._subscribe.call(this, subscriber);
5200 if (subscription && !subscription.closed) {
5201 subscriber.next(this._value);
5203 return subscription;
5205 BehaviorSubject.prototype.getValue = function () {
5206 if (this.hasError) {
5207 throw this.thrownError;
5209 else if (this.closed) {
5210 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5216 BehaviorSubject.prototype.next = function (value) {
5217 _super.prototype.next.call(this, this._value = value);
5219 return BehaviorSubject;
5220 }(Subject_1.Subject));
5221 exports.BehaviorSubject = BehaviorSubject;
5223 },{"./Subject":33,"./util/ObjectUnsubscribedError":159}],26:[function(require,module,exports){
5225 var __extends = (this && this.__extends) || function (d, b) {
5226 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5227 function __() { this.constructor = d; }
5228 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5230 var Subscriber_1 = require('./Subscriber');
5232 * We need this JSDoc comment for affecting ESDoc.
5234 * @extends {Ignored}
5236 var InnerSubscriber = (function (_super) {
5237 __extends(InnerSubscriber, _super);
5238 function InnerSubscriber(parent, outerValue, outerIndex) {
5240 this.parent = parent;
5241 this.outerValue = outerValue;
5242 this.outerIndex = outerIndex;
5245 InnerSubscriber.prototype._next = function (value) {
5246 this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
5248 InnerSubscriber.prototype._error = function (error) {
5249 this.parent.notifyError(error, this);
5252 InnerSubscriber.prototype._complete = function () {
5253 this.parent.notifyComplete(this);
5256 return InnerSubscriber;
5257 }(Subscriber_1.Subscriber));
5258 exports.InnerSubscriber = InnerSubscriber;
5260 },{"./Subscriber":35}],27:[function(require,module,exports){
5262 var Observable_1 = require('./Observable');
5264 * Represents a push-based event or value that an {@link Observable} can emit.
5265 * This class is particularly useful for operators that manage notifications,
5266 * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and
5267 * others. Besides wrapping the actual delivered value, it also annotates it
5268 * with metadata of, for instance, what type of push message it is (`next`,
5269 * `error`, or `complete`).
5271 * @see {@link materialize}
5272 * @see {@link dematerialize}
5273 * @see {@link observeOn}
5275 * @class Notification<T>
5277 var Notification = (function () {
5278 function Notification(kind, value, error) {
5282 this.hasValue = kind === 'N';
5285 * Delivers to the given `observer` the value wrapped by this Notification.
5286 * @param {Observer} observer
5289 Notification.prototype.observe = function (observer) {
5290 switch (this.kind) {
5292 return observer.next && observer.next(this.value);
5294 return observer.error && observer.error(this.error);
5296 return observer.complete && observer.complete();
5300 * Given some {@link Observer} callbacks, deliver the value represented by the
5301 * current Notification to the correctly corresponding callback.
5302 * @param {function(value: T): void} next An Observer `next` callback.
5303 * @param {function(err: any): void} [error] An Observer `error` callback.
5304 * @param {function(): void} [complete] An Observer `complete` callback.
5307 Notification.prototype.do = function (next, error, complete) {
5308 var kind = this.kind;
5311 return next && next(this.value);
5313 return error && error(this.error);
5315 return complete && complete();
5319 * Takes an Observer or its individual callback functions, and calls `observe`
5320 * or `do` methods accordingly.
5321 * @param {Observer|function(value: T): void} nextOrObserver An Observer or
5322 * the `next` callback.
5323 * @param {function(err: any): void} [error] An Observer `error` callback.
5324 * @param {function(): void} [complete] An Observer `complete` callback.
5327 Notification.prototype.accept = function (nextOrObserver, error, complete) {
5328 if (nextOrObserver && typeof nextOrObserver.next === 'function') {
5329 return this.observe(nextOrObserver);
5332 return this.do(nextOrObserver, error, complete);
5336 * Returns a simple Observable that just delivers the notification represented
5337 * by this Notification instance.
5340 Notification.prototype.toObservable = function () {
5341 var kind = this.kind;
5344 return Observable_1.Observable.of(this.value);
5346 return Observable_1.Observable.throw(this.error);
5348 return Observable_1.Observable.empty();
5350 throw new Error('unexpected notification kind value');
5353 * A shortcut to create a Notification instance of the type `next` from a
5355 * @param {T} value The `next` value.
5356 * @return {Notification<T>} The "next" Notification representing the
5359 Notification.createNext = function (value) {
5360 if (typeof value !== 'undefined') {
5361 return new Notification('N', value);
5363 return this.undefinedValueNotification;
5366 * A shortcut to create a Notification instance of the type `error` from a
5368 * @param {any} [err] The `error` error.
5369 * @return {Notification<T>} The "error" Notification representing the
5372 Notification.createError = function (err) {
5373 return new Notification('E', undefined, err);
5376 * A shortcut to create a Notification instance of the type `complete`.
5377 * @return {Notification<any>} The valueless "complete" Notification.
5379 Notification.createComplete = function () {
5380 return this.completeNotification;
5382 Notification.completeNotification = new Notification('C');
5383 Notification.undefinedValueNotification = new Notification('N', undefined);
5384 return Notification;
5386 exports.Notification = Notification;
5388 },{"./Observable":28}],28:[function(require,module,exports){
5390 var root_1 = require('./util/root');
5391 var toSubscriber_1 = require('./util/toSubscriber');
5392 var observable_1 = require('./symbol/observable');
5394 * A representation of any set of values over any amount of time. This the most basic building block
5397 * @class Observable<T>
5399 var Observable = (function () {
5402 * @param {Function} subscribe the function that is called when the Observable is
5403 * initially subscribed to. This function is given a Subscriber, to which new values
5404 * can be `next`ed, or an `error` method can be called to raise an error, or
5405 * `complete` can be called to notify of a successful completion.
5407 function Observable(subscribe) {
5408 this._isScalar = false;
5410 this._subscribe = subscribe;
5414 * Creates a new Observable, with this Observable as the source, and the passed
5415 * operator defined as the new observable's operator.
5417 * @param {Operator} operator the operator defining the operation to take on the observable
5418 * @return {Observable} a new observable with the Operator applied
5420 Observable.prototype.lift = function (operator) {
5421 var observable = new Observable();
5422 observable.source = this;
5423 observable.operator = operator;
5426 Observable.prototype.subscribe = function (observerOrNext, error, complete) {
5427 var operator = this.operator;
5428 var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
5430 operator.call(sink, this.source);
5433 sink.add(this._trySubscribe(sink));
5435 if (sink.syncErrorThrowable) {
5436 sink.syncErrorThrowable = false;
5437 if (sink.syncErrorThrown) {
5438 throw sink.syncErrorValue;
5443 Observable.prototype._trySubscribe = function (sink) {
5445 return this._subscribe(sink);
5448 sink.syncErrorThrown = true;
5449 sink.syncErrorValue = err;
5455 * @param {Function} next a handler for each value emitted by the observable
5456 * @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
5457 * @return {Promise} a promise that either resolves on observable completion or
5458 * rejects with the handled error
5460 Observable.prototype.forEach = function (next, PromiseCtor) {
5463 if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
5464 PromiseCtor = root_1.root.Rx.config.Promise;
5466 else if (root_1.root.Promise) {
5467 PromiseCtor = root_1.root.Promise;
5471 throw new Error('no Promise impl found');
5473 return new PromiseCtor(function (resolve, reject) {
5474 // Must be declared in a separate statement to avoid a RefernceError when
5475 // accessing subscription below in the closure due to Temporal Dead Zone.
5477 subscription = _this.subscribe(function (value) {
5479 // if there is a subscription, then we can surmise
5480 // the next handling is asynchronous. Any errors thrown
5481 // need to be rejected explicitly and unsubscribe must be
5488 subscription.unsubscribe();
5492 // if there is NO subscription, then we're getting a nexted
5493 // value synchronously during subscription. We can just call it.
5494 // If it errors, Observable's `subscribe` will ensure the
5495 // unsubscription logic is called, then synchronously rethrow the error.
5496 // After that, Promise will trap the error and send it
5497 // down the rejection path.
5500 }, reject, resolve);
5503 Observable.prototype._subscribe = function (subscriber) {
5504 return this.source.subscribe(subscriber);
5507 * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
5508 * @method Symbol.observable
5509 * @return {Observable} this instance of the observable
5511 Observable.prototype[observable_1.observable] = function () {
5514 // HACK: Since TypeScript inherits static properties too, we have to
5515 // fight against TypeScript here so Subject can have a different static create signature
5517 * Creates a new cold Observable by calling the Observable constructor
5521 * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
5522 * @return {Observable} a new cold observable
5524 Observable.create = function (subscribe) {
5525 return new Observable(subscribe);
5529 exports.Observable = Observable;
5531 },{"./symbol/observable":154,"./util/root":171,"./util/toSubscriber":173}],29:[function(require,module,exports){
5535 next: function (value) { },
5536 error: function (err) { throw err; },
5537 complete: function () { }
5540 },{}],30:[function(require,module,exports){
5542 var __extends = (this && this.__extends) || function (d, b) {
5543 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5544 function __() { this.constructor = d; }
5545 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5547 var Subscriber_1 = require('./Subscriber');
5549 * We need this JSDoc comment for affecting ESDoc.
5551 * @extends {Ignored}
5553 var OuterSubscriber = (function (_super) {
5554 __extends(OuterSubscriber, _super);
5555 function OuterSubscriber() {
5556 _super.apply(this, arguments);
5558 OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
5559 this.destination.next(innerValue);
5561 OuterSubscriber.prototype.notifyError = function (error, innerSub) {
5562 this.destination.error(error);
5564 OuterSubscriber.prototype.notifyComplete = function (innerSub) {
5565 this.destination.complete();
5567 return OuterSubscriber;
5568 }(Subscriber_1.Subscriber));
5569 exports.OuterSubscriber = OuterSubscriber;
5571 },{"./Subscriber":35}],31:[function(require,module,exports){
5573 var __extends = (this && this.__extends) || function (d, b) {
5574 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5575 function __() { this.constructor = d; }
5576 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5578 var Subject_1 = require('./Subject');
5579 var queue_1 = require('./scheduler/queue');
5580 var Subscription_1 = require('./Subscription');
5581 var observeOn_1 = require('./operator/observeOn');
5582 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5583 var SubjectSubscription_1 = require('./SubjectSubscription');
5585 * @class ReplaySubject<T>
5587 var ReplaySubject = (function (_super) {
5588 __extends(ReplaySubject, _super);
5589 function ReplaySubject(bufferSize, windowTime, scheduler) {
5590 if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
5591 if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
5593 this.scheduler = scheduler;
5595 this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
5596 this._windowTime = windowTime < 1 ? 1 : windowTime;
5598 ReplaySubject.prototype.next = function (value) {
5599 var now = this._getNow();
5600 this._events.push(new ReplayEvent(now, value));
5601 this._trimBufferThenGetEvents();
5602 _super.prototype.next.call(this, value);
5604 ReplaySubject.prototype._subscribe = function (subscriber) {
5605 var _events = this._trimBufferThenGetEvents();
5606 var scheduler = this.scheduler;
5609 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5611 else if (this.hasError) {
5612 subscription = Subscription_1.Subscription.EMPTY;
5614 else if (this.isStopped) {
5615 subscription = Subscription_1.Subscription.EMPTY;
5618 this.observers.push(subscriber);
5619 subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber);
5622 subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler));
5624 var len = _events.length;
5625 for (var i = 0; i < len && !subscriber.closed; i++) {
5626 subscriber.next(_events[i].value);
5628 if (this.hasError) {
5629 subscriber.error(this.thrownError);
5631 else if (this.isStopped) {
5632 subscriber.complete();
5634 return subscription;
5636 ReplaySubject.prototype._getNow = function () {
5637 return (this.scheduler || queue_1.queue).now();
5639 ReplaySubject.prototype._trimBufferThenGetEvents = function () {
5640 var now = this._getNow();
5641 var _bufferSize = this._bufferSize;
5642 var _windowTime = this._windowTime;
5643 var _events = this._events;
5644 var eventsCount = _events.length;
5645 var spliceCount = 0;
5646 // Trim events that fall out of the time window.
5647 // Start at the front of the list. Break early once
5648 // we encounter an event that falls within the window.
5649 while (spliceCount < eventsCount) {
5650 if ((now - _events[spliceCount].time) < _windowTime) {
5655 if (eventsCount > _bufferSize) {
5656 spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
5658 if (spliceCount > 0) {
5659 _events.splice(0, spliceCount);
5663 return ReplaySubject;
5664 }(Subject_1.Subject));
5665 exports.ReplaySubject = ReplaySubject;
5666 var ReplayEvent = (function () {
5667 function ReplayEvent(time, value) {
5674 },{"./Subject":33,"./SubjectSubscription":34,"./Subscription":36,"./operator/observeOn":128,"./scheduler/queue":152,"./util/ObjectUnsubscribedError":159}],32:[function(require,module,exports){
5677 * An execution context and a data structure to order tasks and schedule their
5678 * execution. Provides a notion of (potentially virtual) time, through the
5679 * `now()` getter method.
5681 * Each unit of work in a Scheduler is called an {@link Action}.
5686 * schedule(work, delay?, state?): Subscription;
5692 var Scheduler = (function () {
5693 function Scheduler(SchedulerAction, now) {
5694 if (now === void 0) { now = Scheduler.now; }
5695 this.SchedulerAction = SchedulerAction;
5699 * Schedules a function, `work`, for execution. May happen at some point in
5700 * the future, according to the `delay` parameter, if specified. May be passed
5701 * some context object, `state`, which will be passed to the `work` function.
5703 * The given arguments will be processed an stored as an Action object in a
5706 * @param {function(state: ?T): ?Subscription} work A function representing a
5707 * task, or some unit of work to be executed by the Scheduler.
5708 * @param {number} [delay] Time to wait before executing the work, where the
5709 * time unit is implicit and defined by the Scheduler itself.
5710 * @param {T} [state] Some contextual data that the `work` function uses when
5711 * called by the Scheduler.
5712 * @return {Subscription} A subscription in order to be able to unsubscribe
5713 * the scheduled work.
5715 Scheduler.prototype.schedule = function (work, delay, state) {
5716 if (delay === void 0) { delay = 0; }
5717 return new this.SchedulerAction(this, work).schedule(state, delay);
5719 Scheduler.now = Date.now ? Date.now : function () { return +new Date(); };
5722 exports.Scheduler = Scheduler;
5724 },{}],33:[function(require,module,exports){
5726 var __extends = (this && this.__extends) || function (d, b) {
5727 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5728 function __() { this.constructor = d; }
5729 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5731 var Observable_1 = require('./Observable');
5732 var Subscriber_1 = require('./Subscriber');
5733 var Subscription_1 = require('./Subscription');
5734 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5735 var SubjectSubscription_1 = require('./SubjectSubscription');
5736 var rxSubscriber_1 = require('./symbol/rxSubscriber');
5738 * @class SubjectSubscriber<T>
5740 var SubjectSubscriber = (function (_super) {
5741 __extends(SubjectSubscriber, _super);
5742 function SubjectSubscriber(destination) {
5743 _super.call(this, destination);
5744 this.destination = destination;
5746 return SubjectSubscriber;
5747 }(Subscriber_1.Subscriber));
5748 exports.SubjectSubscriber = SubjectSubscriber;
5752 var Subject = (function (_super) {
5753 __extends(Subject, _super);
5754 function Subject() {
5756 this.observers = [];
5757 this.closed = false;
5758 this.isStopped = false;
5759 this.hasError = false;
5760 this.thrownError = null;
5762 Subject.prototype[rxSubscriber_1.rxSubscriber] = function () {
5763 return new SubjectSubscriber(this);
5765 Subject.prototype.lift = function (operator) {
5766 var subject = new AnonymousSubject(this, this);
5767 subject.operator = operator;
5770 Subject.prototype.next = function (value) {
5772 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5774 if (!this.isStopped) {
5775 var observers = this.observers;
5776 var len = observers.length;
5777 var copy = observers.slice();
5778 for (var i = 0; i < len; i++) {
5779 copy[i].next(value);
5783 Subject.prototype.error = function (err) {
5785 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5787 this.hasError = true;
5788 this.thrownError = err;
5789 this.isStopped = true;
5790 var observers = this.observers;
5791 var len = observers.length;
5792 var copy = observers.slice();
5793 for (var i = 0; i < len; i++) {
5796 this.observers.length = 0;
5798 Subject.prototype.complete = function () {
5800 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5802 this.isStopped = true;
5803 var observers = this.observers;
5804 var len = observers.length;
5805 var copy = observers.slice();
5806 for (var i = 0; i < len; i++) {
5809 this.observers.length = 0;
5811 Subject.prototype.unsubscribe = function () {
5812 this.isStopped = true;
5814 this.observers = null;
5816 Subject.prototype._trySubscribe = function (subscriber) {
5818 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5821 return _super.prototype._trySubscribe.call(this, subscriber);
5824 Subject.prototype._subscribe = function (subscriber) {
5826 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5828 else if (this.hasError) {
5829 subscriber.error(this.thrownError);
5830 return Subscription_1.Subscription.EMPTY;
5832 else if (this.isStopped) {
5833 subscriber.complete();
5834 return Subscription_1.Subscription.EMPTY;
5837 this.observers.push(subscriber);
5838 return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
5841 Subject.prototype.asObservable = function () {
5842 var observable = new Observable_1.Observable();
5843 observable.source = this;
5846 Subject.create = function (destination, source) {
5847 return new AnonymousSubject(destination, source);
5850 }(Observable_1.Observable));
5851 exports.Subject = Subject;
5853 * @class AnonymousSubject<T>
5855 var AnonymousSubject = (function (_super) {
5856 __extends(AnonymousSubject, _super);
5857 function AnonymousSubject(destination, source) {
5859 this.destination = destination;
5860 this.source = source;
5862 AnonymousSubject.prototype.next = function (value) {
5863 var destination = this.destination;
5864 if (destination && destination.next) {
5865 destination.next(value);
5868 AnonymousSubject.prototype.error = function (err) {
5869 var destination = this.destination;
5870 if (destination && destination.error) {
5871 this.destination.error(err);
5874 AnonymousSubject.prototype.complete = function () {
5875 var destination = this.destination;
5876 if (destination && destination.complete) {
5877 this.destination.complete();
5880 AnonymousSubject.prototype._subscribe = function (subscriber) {
5881 var source = this.source;
5883 return this.source.subscribe(subscriber);
5886 return Subscription_1.Subscription.EMPTY;
5889 return AnonymousSubject;
5891 exports.AnonymousSubject = AnonymousSubject;
5893 },{"./Observable":28,"./SubjectSubscription":34,"./Subscriber":35,"./Subscription":36,"./symbol/rxSubscriber":155,"./util/ObjectUnsubscribedError":159}],34:[function(require,module,exports){
5895 var __extends = (this && this.__extends) || function (d, b) {
5896 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5897 function __() { this.constructor = d; }
5898 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5900 var Subscription_1 = require('./Subscription');
5902 * We need this JSDoc comment for affecting ESDoc.
5904 * @extends {Ignored}
5906 var SubjectSubscription = (function (_super) {
5907 __extends(SubjectSubscription, _super);
5908 function SubjectSubscription(subject, subscriber) {
5910 this.subject = subject;
5911 this.subscriber = subscriber;
5912 this.closed = false;
5914 SubjectSubscription.prototype.unsubscribe = function () {
5919 var subject = this.subject;
5920 var observers = subject.observers;
5921 this.subject = null;
5922 if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
5925 var subscriberIndex = observers.indexOf(this.subscriber);
5926 if (subscriberIndex !== -1) {
5927 observers.splice(subscriberIndex, 1);
5930 return SubjectSubscription;
5931 }(Subscription_1.Subscription));
5932 exports.SubjectSubscription = SubjectSubscription;
5934 },{"./Subscription":36}],35:[function(require,module,exports){
5936 var __extends = (this && this.__extends) || function (d, b) {
5937 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5938 function __() { this.constructor = d; }
5939 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5941 var isFunction_1 = require('./util/isFunction');
5942 var Subscription_1 = require('./Subscription');
5943 var Observer_1 = require('./Observer');
5944 var rxSubscriber_1 = require('./symbol/rxSubscriber');
5946 * Implements the {@link Observer} interface and extends the
5947 * {@link Subscription} class. While the {@link Observer} is the public API for
5948 * consuming the values of an {@link Observable}, all Observers get converted to
5949 * a Subscriber, in order to provide Subscription-like capabilities such as
5950 * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
5951 * implementing operators, but it is rarely used as a public API.
5953 * @class Subscriber<T>
5955 var Subscriber = (function (_super) {
5956 __extends(Subscriber, _super);
5958 * @param {Observer|function(value: T): void} [destinationOrNext] A partially
5959 * defined Observer or a `next` callback function.
5960 * @param {function(e: ?any): void} [error] The `error` callback of an
5962 * @param {function(): void} [complete] The `complete` callback of an
5965 function Subscriber(destinationOrNext, error, complete) {
5967 this.syncErrorValue = null;
5968 this.syncErrorThrown = false;
5969 this.syncErrorThrowable = false;
5970 this.isStopped = false;
5971 switch (arguments.length) {
5973 this.destination = Observer_1.empty;
5976 if (!destinationOrNext) {
5977 this.destination = Observer_1.empty;
5980 if (typeof destinationOrNext === 'object') {
5981 if (destinationOrNext instanceof Subscriber) {
5982 this.destination = destinationOrNext;
5983 this.destination.add(this);
5986 this.syncErrorThrowable = true;
5987 this.destination = new SafeSubscriber(this, destinationOrNext);
5992 this.syncErrorThrowable = true;
5993 this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
5997 Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function () { return this; };
5999 * A static factory for a Subscriber, given a (potentially partial) definition
6001 * @param {function(x: ?T): void} [next] The `next` callback of an Observer.
6002 * @param {function(e: ?any): void} [error] The `error` callback of an
6004 * @param {function(): void} [complete] The `complete` callback of an
6006 * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
6007 * Observer represented by the given arguments.
6009 Subscriber.create = function (next, error, complete) {
6010 var subscriber = new Subscriber(next, error, complete);
6011 subscriber.syncErrorThrowable = false;
6015 * The {@link Observer} callback to receive notifications of type `next` from
6016 * the Observable, with a value. The Observable may call this method 0 or more
6018 * @param {T} [value] The `next` value.
6021 Subscriber.prototype.next = function (value) {
6022 if (!this.isStopped) {
6027 * The {@link Observer} callback to receive notifications of type `error` from
6028 * the Observable, with an attached {@link Error}. Notifies the Observer that
6029 * the Observable has experienced an error condition.
6030 * @param {any} [err] The `error` exception.
6033 Subscriber.prototype.error = function (err) {
6034 if (!this.isStopped) {
6035 this.isStopped = true;
6040 * The {@link Observer} callback to receive a valueless notification of type
6041 * `complete` from the Observable. Notifies the Observer that the Observable
6042 * has finished sending push-based notifications.
6045 Subscriber.prototype.complete = function () {
6046 if (!this.isStopped) {
6047 this.isStopped = true;
6051 Subscriber.prototype.unsubscribe = function () {
6055 this.isStopped = true;
6056 _super.prototype.unsubscribe.call(this);
6058 Subscriber.prototype._next = function (value) {
6059 this.destination.next(value);
6061 Subscriber.prototype._error = function (err) {
6062 this.destination.error(err);
6065 Subscriber.prototype._complete = function () {
6066 this.destination.complete();
6069 Subscriber.prototype._unsubscribeAndRecycle = function () {
6070 var _a = this, _parent = _a._parent, _parents = _a._parents;
6071 this._parent = null;
6072 this._parents = null;
6074 this.closed = false;
6075 this.isStopped = false;
6076 this._parent = _parent;
6077 this._parents = _parents;
6081 }(Subscription_1.Subscription));
6082 exports.Subscriber = Subscriber;
6084 * We need this JSDoc comment for affecting ESDoc.
6086 * @extends {Ignored}
6088 var SafeSubscriber = (function (_super) {
6089 __extends(SafeSubscriber, _super);
6090 function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
6092 this._parentSubscriber = _parentSubscriber;
6095 if (isFunction_1.isFunction(observerOrNext)) {
6096 next = observerOrNext;
6098 else if (observerOrNext) {
6099 next = observerOrNext.next;
6100 error = observerOrNext.error;
6101 complete = observerOrNext.complete;
6102 if (observerOrNext !== Observer_1.empty) {
6103 context = Object.create(observerOrNext);
6104 if (isFunction_1.isFunction(context.unsubscribe)) {
6105 this.add(context.unsubscribe.bind(context));
6107 context.unsubscribe = this.unsubscribe.bind(this);
6110 this._context = context;
6112 this._error = error;
6113 this._complete = complete;
6115 SafeSubscriber.prototype.next = function (value) {
6116 if (!this.isStopped && this._next) {
6117 var _parentSubscriber = this._parentSubscriber;
6118 if (!_parentSubscriber.syncErrorThrowable) {
6119 this.__tryOrUnsub(this._next, value);
6121 else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
6126 SafeSubscriber.prototype.error = function (err) {
6127 if (!this.isStopped) {
6128 var _parentSubscriber = this._parentSubscriber;
6130 if (!_parentSubscriber.syncErrorThrowable) {
6131 this.__tryOrUnsub(this._error, err);
6135 this.__tryOrSetError(_parentSubscriber, this._error, err);
6139 else if (!_parentSubscriber.syncErrorThrowable) {
6144 _parentSubscriber.syncErrorValue = err;
6145 _parentSubscriber.syncErrorThrown = true;
6150 SafeSubscriber.prototype.complete = function () {
6152 if (!this.isStopped) {
6153 var _parentSubscriber = this._parentSubscriber;
6154 if (this._complete) {
6155 var wrappedComplete = function () { return _this._complete.call(_this._context); };
6156 if (!_parentSubscriber.syncErrorThrowable) {
6157 this.__tryOrUnsub(wrappedComplete);
6161 this.__tryOrSetError(_parentSubscriber, wrappedComplete);
6170 SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
6172 fn.call(this._context, value);
6179 SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
6181 fn.call(this._context, value);
6184 parent.syncErrorValue = err;
6185 parent.syncErrorThrown = true;
6190 SafeSubscriber.prototype._unsubscribe = function () {
6191 var _parentSubscriber = this._parentSubscriber;
6192 this._context = null;
6193 this._parentSubscriber = null;
6194 _parentSubscriber.unsubscribe();
6196 return SafeSubscriber;
6199 },{"./Observer":29,"./Subscription":36,"./symbol/rxSubscriber":155,"./util/isFunction":166}],36:[function(require,module,exports){
6201 var isArray_1 = require('./util/isArray');
6202 var isObject_1 = require('./util/isObject');
6203 var isFunction_1 = require('./util/isFunction');
6204 var tryCatch_1 = require('./util/tryCatch');
6205 var errorObject_1 = require('./util/errorObject');
6206 var UnsubscriptionError_1 = require('./util/UnsubscriptionError');
6208 * Represents a disposable resource, such as the execution of an Observable. A
6209 * Subscription has one important method, `unsubscribe`, that takes no argument
6210 * and just disposes the resource held by the subscription.
6212 * Additionally, subscriptions may be grouped together through the `add()`
6213 * method, which will attach a child Subscription to the current Subscription.
6214 * When a Subscription is unsubscribed, all its children (and its grandchildren)
6215 * will be unsubscribed as well.
6217 * @class Subscription
6219 var Subscription = (function () {
6221 * @param {function(): void} [unsubscribe] A function describing how to
6222 * perform the disposal of resources when the `unsubscribe` method is called.
6224 function Subscription(unsubscribe) {
6226 * A flag to indicate whether this Subscription has already been unsubscribed.
6229 this.closed = false;
6230 this._parent = null;
6231 this._parents = null;
6232 this._subscriptions = null;
6234 this._unsubscribe = unsubscribe;
6238 * Disposes the resources held by the subscription. May, for instance, cancel
6239 * an ongoing Observable execution or cancel any other type of work that
6240 * started when the Subscription was created.
6243 Subscription.prototype.unsubscribe = function () {
6244 var hasErrors = false;
6249 var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
6251 this._parent = null;
6252 this._parents = null;
6253 // null out _subscriptions first so any child subscriptions that attempt
6254 // to remove themselves from this subscription will noop
6255 this._subscriptions = null;
6257 var len = _parents ? _parents.length : 0;
6258 // if this._parent is null, then so is this._parents, and we
6259 // don't have to remove ourselves from any parent subscriptions.
6261 _parent.remove(this);
6262 // if this._parents is null or index >= len,
6263 // then _parent is set to null, and the loop exits
6264 _parent = ++index < len && _parents[index] || null;
6266 if (isFunction_1.isFunction(_unsubscribe)) {
6267 var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
6268 if (trial === errorObject_1.errorObject) {
6270 errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ?
6271 flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]);
6274 if (isArray_1.isArray(_subscriptions)) {
6276 len = _subscriptions.length;
6277 while (++index < len) {
6278 var sub = _subscriptions[index];
6279 if (isObject_1.isObject(sub)) {
6280 var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
6281 if (trial === errorObject_1.errorObject) {
6283 errors = errors || [];
6284 var err = errorObject_1.errorObject.e;
6285 if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
6286 errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
6296 throw new UnsubscriptionError_1.UnsubscriptionError(errors);
6300 * Adds a tear down to be called during the unsubscribe() of this
6303 * If the tear down being added is a subscription that is already
6304 * unsubscribed, is the same reference `add` is being called on, or is
6305 * `Subscription.EMPTY`, it will not be added.
6307 * If this subscription is already in an `closed` state, the passed
6308 * tear down logic will be executed immediately.
6310 * @param {TeardownLogic} teardown The additional logic to execute on
6312 * @return {Subscription} Returns the Subscription used or created to be
6313 * added to the inner subscriptions list. This Subscription can be used with
6314 * `remove()` to remove the passed teardown logic from the inner subscriptions
6317 Subscription.prototype.add = function (teardown) {
6318 if (!teardown || (teardown === Subscription.EMPTY)) {
6319 return Subscription.EMPTY;
6321 if (teardown === this) {
6324 var subscription = teardown;
6325 switch (typeof teardown) {
6327 subscription = new Subscription(teardown);
6329 if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
6330 return subscription;
6332 else if (this.closed) {
6333 subscription.unsubscribe();
6334 return subscription;
6336 else if (typeof subscription._addParent !== 'function' /* quack quack */) {
6337 var tmp = subscription;
6338 subscription = new Subscription();
6339 subscription._subscriptions = [tmp];
6343 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
6345 var subscriptions = this._subscriptions || (this._subscriptions = []);
6346 subscriptions.push(subscription);
6347 subscription._addParent(this);
6348 return subscription;
6351 * Removes a Subscription from the internal list of subscriptions that will
6352 * unsubscribe during the unsubscribe process of this Subscription.
6353 * @param {Subscription} subscription The subscription to remove.
6356 Subscription.prototype.remove = function (subscription) {
6357 var subscriptions = this._subscriptions;
6358 if (subscriptions) {
6359 var subscriptionIndex = subscriptions.indexOf(subscription);
6360 if (subscriptionIndex !== -1) {
6361 subscriptions.splice(subscriptionIndex, 1);
6365 Subscription.prototype._addParent = function (parent) {
6366 var _a = this, _parent = _a._parent, _parents = _a._parents;
6367 if (!_parent || _parent === parent) {
6368 // If we don't have a parent, or the new parent is the same as the
6369 // current parent, then set this._parent to the new parent.
6370 this._parent = parent;
6372 else if (!_parents) {
6373 // If there's already one parent, but not multiple, allocate an Array to
6374 // store the rest of the parent Subscriptions.
6375 this._parents = [parent];
6377 else if (_parents.indexOf(parent) === -1) {
6378 // Only add the new parent to the _parents list if it's not already there.
6379 _parents.push(parent);
6382 Subscription.EMPTY = (function (empty) {
6383 empty.closed = true;
6385 }(new Subscription()));
6386 return Subscription;
6388 exports.Subscription = Subscription;
6389 function flattenUnsubscriptionErrors(errors) {
6390 return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []);
6393 },{"./util/UnsubscriptionError":161,"./util/errorObject":162,"./util/isArray":163,"./util/isFunction":166,"./util/isObject":168,"./util/tryCatch":174}],37:[function(require,module,exports){
6395 var Observable_1 = require('../../Observable');
6396 var combineLatest_1 = require('../../observable/combineLatest');
6397 Observable_1.Observable.combineLatest = combineLatest_1.combineLatest;
6399 },{"../../Observable":28,"../../observable/combineLatest":96}],38:[function(require,module,exports){
6401 var Observable_1 = require('../../Observable');
6402 var defer_1 = require('../../observable/defer');
6403 Observable_1.Observable.defer = defer_1.defer;
6405 },{"../../Observable":28,"../../observable/defer":97}],39:[function(require,module,exports){
6407 var Observable_1 = require('../../Observable');
6408 var empty_1 = require('../../observable/empty');
6409 Observable_1.Observable.empty = empty_1.empty;
6411 },{"../../Observable":28,"../../observable/empty":98}],40:[function(require,module,exports){
6413 var Observable_1 = require('../../Observable');
6414 var from_1 = require('../../observable/from');
6415 Observable_1.Observable.from = from_1.from;
6417 },{"../../Observable":28,"../../observable/from":99}],41:[function(require,module,exports){
6419 var Observable_1 = require('../../Observable');
6420 var fromEvent_1 = require('../../observable/fromEvent');
6421 Observable_1.Observable.fromEvent = fromEvent_1.fromEvent;
6423 },{"../../Observable":28,"../../observable/fromEvent":100}],42:[function(require,module,exports){
6425 var Observable_1 = require('../../Observable');
6426 var fromPromise_1 = require('../../observable/fromPromise');
6427 Observable_1.Observable.fromPromise = fromPromise_1.fromPromise;
6429 },{"../../Observable":28,"../../observable/fromPromise":101}],43:[function(require,module,exports){
6431 var Observable_1 = require('../../Observable');
6432 var merge_1 = require('../../observable/merge');
6433 Observable_1.Observable.merge = merge_1.merge;
6435 },{"../../Observable":28,"../../observable/merge":102}],44:[function(require,module,exports){
6437 var Observable_1 = require('../../Observable');
6438 var of_1 = require('../../observable/of');
6439 Observable_1.Observable.of = of_1.of;
6441 },{"../../Observable":28,"../../observable/of":103}],45:[function(require,module,exports){
6443 var Observable_1 = require('../../Observable');
6444 var throw_1 = require('../../observable/throw');
6445 Observable_1.Observable.throw = throw_1._throw;
6447 },{"../../Observable":28,"../../observable/throw":104}],46:[function(require,module,exports){
6449 var Observable_1 = require('../../Observable');
6450 var timer_1 = require('../../observable/timer');
6451 Observable_1.Observable.timer = timer_1.timer;
6453 },{"../../Observable":28,"../../observable/timer":105}],47:[function(require,module,exports){
6455 var Observable_1 = require('../../Observable');
6456 var zip_1 = require('../../observable/zip');
6457 Observable_1.Observable.zip = zip_1.zip;
6459 },{"../../Observable":28,"../../observable/zip":106}],48:[function(require,module,exports){
6461 var Observable_1 = require('../../Observable');
6462 var buffer_1 = require('../../operator/buffer');
6463 Observable_1.Observable.prototype.buffer = buffer_1.buffer;
6465 },{"../../Observable":28,"../../operator/buffer":107}],49:[function(require,module,exports){
6467 var Observable_1 = require('../../Observable');
6468 var bufferCount_1 = require('../../operator/bufferCount');
6469 Observable_1.Observable.prototype.bufferCount = bufferCount_1.bufferCount;
6471 },{"../../Observable":28,"../../operator/bufferCount":108}],50:[function(require,module,exports){
6473 var Observable_1 = require('../../Observable');
6474 var bufferWhen_1 = require('../../operator/bufferWhen');
6475 Observable_1.Observable.prototype.bufferWhen = bufferWhen_1.bufferWhen;
6477 },{"../../Observable":28,"../../operator/bufferWhen":109}],51:[function(require,module,exports){
6479 var Observable_1 = require('../../Observable');
6480 var catch_1 = require('../../operator/catch');
6481 Observable_1.Observable.prototype.catch = catch_1._catch;
6482 Observable_1.Observable.prototype._catch = catch_1._catch;
6484 },{"../../Observable":28,"../../operator/catch":110}],52:[function(require,module,exports){
6486 var Observable_1 = require('../../Observable');
6487 var combineLatest_1 = require('../../operator/combineLatest');
6488 Observable_1.Observable.prototype.combineLatest = combineLatest_1.combineLatest;
6490 },{"../../Observable":28,"../../operator/combineLatest":111}],53:[function(require,module,exports){
6492 var Observable_1 = require('../../Observable');
6493 var concat_1 = require('../../operator/concat');
6494 Observable_1.Observable.prototype.concat = concat_1.concat;
6496 },{"../../Observable":28,"../../operator/concat":112}],54:[function(require,module,exports){
6498 var Observable_1 = require('../../Observable');
6499 var debounceTime_1 = require('../../operator/debounceTime');
6500 Observable_1.Observable.prototype.debounceTime = debounceTime_1.debounceTime;
6502 },{"../../Observable":28,"../../operator/debounceTime":113}],55:[function(require,module,exports){
6504 var Observable_1 = require('../../Observable');
6505 var delay_1 = require('../../operator/delay');
6506 Observable_1.Observable.prototype.delay = delay_1.delay;
6508 },{"../../Observable":28,"../../operator/delay":114}],56:[function(require,module,exports){
6510 var Observable_1 = require('../../Observable');
6511 var distinct_1 = require('../../operator/distinct');
6512 Observable_1.Observable.prototype.distinct = distinct_1.distinct;
6514 },{"../../Observable":28,"../../operator/distinct":115}],57:[function(require,module,exports){
6516 var Observable_1 = require('../../Observable');
6517 var distinctUntilChanged_1 = require('../../operator/distinctUntilChanged');
6518 Observable_1.Observable.prototype.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged;
6520 },{"../../Observable":28,"../../operator/distinctUntilChanged":116}],58:[function(require,module,exports){
6522 var Observable_1 = require('../../Observable');
6523 var do_1 = require('../../operator/do');
6524 Observable_1.Observable.prototype.do = do_1._do;
6525 Observable_1.Observable.prototype._do = do_1._do;
6527 },{"../../Observable":28,"../../operator/do":117}],59:[function(require,module,exports){
6529 var Observable_1 = require('../../Observable');
6530 var expand_1 = require('../../operator/expand');
6531 Observable_1.Observable.prototype.expand = expand_1.expand;
6533 },{"../../Observable":28,"../../operator/expand":118}],60:[function(require,module,exports){
6535 var Observable_1 = require('../../Observable');
6536 var filter_1 = require('../../operator/filter');
6537 Observable_1.Observable.prototype.filter = filter_1.filter;
6539 },{"../../Observable":28,"../../operator/filter":119}],61:[function(require,module,exports){
6541 var Observable_1 = require('../../Observable');
6542 var finally_1 = require('../../operator/finally');
6543 Observable_1.Observable.prototype.finally = finally_1._finally;
6544 Observable_1.Observable.prototype._finally = finally_1._finally;
6546 },{"../../Observable":28,"../../operator/finally":120}],62:[function(require,module,exports){
6548 var Observable_1 = require('../../Observable');
6549 var first_1 = require('../../operator/first');
6550 Observable_1.Observable.prototype.first = first_1.first;
6552 },{"../../Observable":28,"../../operator/first":121}],63:[function(require,module,exports){
6554 var Observable_1 = require('../../Observable');
6555 var last_1 = require('../../operator/last');
6556 Observable_1.Observable.prototype.last = last_1.last;
6558 },{"../../Observable":28,"../../operator/last":122}],64:[function(require,module,exports){
6560 var Observable_1 = require('../../Observable');
6561 var map_1 = require('../../operator/map');
6562 Observable_1.Observable.prototype.map = map_1.map;
6564 },{"../../Observable":28,"../../operator/map":123}],65:[function(require,module,exports){
6566 var Observable_1 = require('../../Observable');
6567 var merge_1 = require('../../operator/merge');
6568 Observable_1.Observable.prototype.merge = merge_1.merge;
6570 },{"../../Observable":28,"../../operator/merge":124}],66:[function(require,module,exports){
6572 var Observable_1 = require('../../Observable');
6573 var mergeAll_1 = require('../../operator/mergeAll');
6574 Observable_1.Observable.prototype.mergeAll = mergeAll_1.mergeAll;
6576 },{"../../Observable":28,"../../operator/mergeAll":125}],67:[function(require,module,exports){
6578 var Observable_1 = require('../../Observable');
6579 var mergeMap_1 = require('../../operator/mergeMap');
6580 Observable_1.Observable.prototype.mergeMap = mergeMap_1.mergeMap;
6581 Observable_1.Observable.prototype.flatMap = mergeMap_1.mergeMap;
6583 },{"../../Observable":28,"../../operator/mergeMap":126}],68:[function(require,module,exports){
6585 var Observable_1 = require('../../Observable');
6586 var pairwise_1 = require('../../operator/pairwise');
6587 Observable_1.Observable.prototype.pairwise = pairwise_1.pairwise;
6589 },{"../../Observable":28,"../../operator/pairwise":129}],69:[function(require,module,exports){
6591 var Observable_1 = require('../../Observable');
6592 var pluck_1 = require('../../operator/pluck');
6593 Observable_1.Observable.prototype.pluck = pluck_1.pluck;
6595 },{"../../Observable":28,"../../operator/pluck":130}],70:[function(require,module,exports){
6597 var Observable_1 = require('../../Observable');
6598 var publish_1 = require('../../operator/publish');
6599 Observable_1.Observable.prototype.publish = publish_1.publish;
6601 },{"../../Observable":28,"../../operator/publish":131}],71:[function(require,module,exports){
6603 var Observable_1 = require('../../Observable');
6604 var publishReplay_1 = require('../../operator/publishReplay');
6605 Observable_1.Observable.prototype.publishReplay = publishReplay_1.publishReplay;
6607 },{"../../Observable":28,"../../operator/publishReplay":132}],72:[function(require,module,exports){
6609 var Observable_1 = require('../../Observable');
6610 var scan_1 = require('../../operator/scan');
6611 Observable_1.Observable.prototype.scan = scan_1.scan;
6613 },{"../../Observable":28,"../../operator/scan":133}],73:[function(require,module,exports){
6615 var Observable_1 = require('../../Observable');
6616 var share_1 = require('../../operator/share');
6617 Observable_1.Observable.prototype.share = share_1.share;
6619 },{"../../Observable":28,"../../operator/share":134}],74:[function(require,module,exports){
6621 var Observable_1 = require('../../Observable');
6622 var skip_1 = require('../../operator/skip');
6623 Observable_1.Observable.prototype.skip = skip_1.skip;
6625 },{"../../Observable":28,"../../operator/skip":135}],75:[function(require,module,exports){
6627 var Observable_1 = require('../../Observable');
6628 var skipUntil_1 = require('../../operator/skipUntil');
6629 Observable_1.Observable.prototype.skipUntil = skipUntil_1.skipUntil;
6631 },{"../../Observable":28,"../../operator/skipUntil":136}],76:[function(require,module,exports){
6633 var Observable_1 = require('../../Observable');
6634 var skipWhile_1 = require('../../operator/skipWhile');
6635 Observable_1.Observable.prototype.skipWhile = skipWhile_1.skipWhile;
6637 },{"../../Observable":28,"../../operator/skipWhile":137}],77:[function(require,module,exports){
6639 var Observable_1 = require('../../Observable');
6640 var startWith_1 = require('../../operator/startWith');
6641 Observable_1.Observable.prototype.startWith = startWith_1.startWith;
6643 },{"../../Observable":28,"../../operator/startWith":138}],78:[function(require,module,exports){
6645 var Observable_1 = require('../../Observable');
6646 var switchMap_1 = require('../../operator/switchMap');
6647 Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap;
6649 },{"../../Observable":28,"../../operator/switchMap":139}],79:[function(require,module,exports){
6651 var Observable_1 = require('../../Observable');
6652 var take_1 = require('../../operator/take');
6653 Observable_1.Observable.prototype.take = take_1.take;
6655 },{"../../Observable":28,"../../operator/take":140}],80:[function(require,module,exports){
6657 var Observable_1 = require('../../Observable');
6658 var takeUntil_1 = require('../../operator/takeUntil');
6659 Observable_1.Observable.prototype.takeUntil = takeUntil_1.takeUntil;
6661 },{"../../Observable":28,"../../operator/takeUntil":141}],81:[function(require,module,exports){
6663 var Observable_1 = require('../../Observable');
6664 var throttleTime_1 = require('../../operator/throttleTime');
6665 Observable_1.Observable.prototype.throttleTime = throttleTime_1.throttleTime;
6667 },{"../../Observable":28,"../../operator/throttleTime":143}],82:[function(require,module,exports){
6669 var Observable_1 = require('../../Observable');
6670 var withLatestFrom_1 = require('../../operator/withLatestFrom');
6671 Observable_1.Observable.prototype.withLatestFrom = withLatestFrom_1.withLatestFrom;
6673 },{"../../Observable":28,"../../operator/withLatestFrom":144}],83:[function(require,module,exports){
6675 var Observable_1 = require('../../Observable');
6676 var zip_1 = require('../../operator/zip');
6677 Observable_1.Observable.prototype.zip = zip_1.zipProto;
6679 },{"../../Observable":28,"../../operator/zip":145}],84:[function(require,module,exports){
6681 var __extends = (this && this.__extends) || function (d, b) {
6682 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6683 function __() { this.constructor = d; }
6684 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6686 var Observable_1 = require('../Observable');
6687 var ScalarObservable_1 = require('./ScalarObservable');
6688 var EmptyObservable_1 = require('./EmptyObservable');
6690 * We need this JSDoc comment for affecting ESDoc.
6691 * @extends {Ignored}
6694 var ArrayLikeObservable = (function (_super) {
6695 __extends(ArrayLikeObservable, _super);
6696 function ArrayLikeObservable(arrayLike, scheduler) {
6698 this.arrayLike = arrayLike;
6699 this.scheduler = scheduler;
6700 if (!scheduler && arrayLike.length === 1) {
6701 this._isScalar = true;
6702 this.value = arrayLike[0];
6705 ArrayLikeObservable.create = function (arrayLike, scheduler) {
6706 var length = arrayLike.length;
6708 return new EmptyObservable_1.EmptyObservable();
6710 else if (length === 1) {
6711 return new ScalarObservable_1.ScalarObservable(arrayLike[0], scheduler);
6714 return new ArrayLikeObservable(arrayLike, scheduler);
6717 ArrayLikeObservable.dispatch = function (state) {
6718 var arrayLike = state.arrayLike, index = state.index, length = state.length, subscriber = state.subscriber;
6719 if (subscriber.closed) {
6722 if (index >= length) {
6723 subscriber.complete();
6726 subscriber.next(arrayLike[index]);
6727 state.index = index + 1;
6728 this.schedule(state);
6730 ArrayLikeObservable.prototype._subscribe = function (subscriber) {
6732 var _a = this, arrayLike = _a.arrayLike, scheduler = _a.scheduler;
6733 var length = arrayLike.length;
6735 return scheduler.schedule(ArrayLikeObservable.dispatch, 0, {
6736 arrayLike: arrayLike, index: index, length: length, subscriber: subscriber
6740 for (var i = 0; i < length && !subscriber.closed; i++) {
6741 subscriber.next(arrayLike[i]);
6743 subscriber.complete();
6746 return ArrayLikeObservable;
6747 }(Observable_1.Observable));
6748 exports.ArrayLikeObservable = ArrayLikeObservable;
6750 },{"../Observable":28,"./EmptyObservable":88,"./ScalarObservable":94}],85:[function(require,module,exports){
6752 var __extends = (this && this.__extends) || function (d, b) {
6753 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6754 function __() { this.constructor = d; }
6755 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6757 var Observable_1 = require('../Observable');
6758 var ScalarObservable_1 = require('./ScalarObservable');
6759 var EmptyObservable_1 = require('./EmptyObservable');
6760 var isScheduler_1 = require('../util/isScheduler');
6762 * We need this JSDoc comment for affecting ESDoc.
6763 * @extends {Ignored}
6766 var ArrayObservable = (function (_super) {
6767 __extends(ArrayObservable, _super);
6768 function ArrayObservable(array, scheduler) {
6771 this.scheduler = scheduler;
6772 if (!scheduler && array.length === 1) {
6773 this._isScalar = true;
6774 this.value = array[0];
6777 ArrayObservable.create = function (array, scheduler) {
6778 return new ArrayObservable(array, scheduler);
6781 * Creates an Observable that emits some values you specify as arguments,
6782 * immediately one after the other, and then emits a complete notification.
6784 * <span class="informal">Emits the arguments you provide, then completes.
6787 * <img src="./img/of.png" width="100%">
6789 * This static operator is useful for creating a simple Observable that only
6790 * emits the arguments given, and the complete notification thereafter. It can
6791 * be used for composing with other Observables, such as with {@link concat}.
6792 * By default, it uses a `null` IScheduler, which means the `next`
6793 * notifications are sent synchronously, although with a different IScheduler
6794 * it is possible to determine when those notifications will be delivered.
6796 * @example <caption>Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second.</caption>
6797 * var numbers = Rx.Observable.of(10, 20, 30);
6798 * var letters = Rx.Observable.of('a', 'b', 'c');
6799 * var interval = Rx.Observable.interval(1000);
6800 * var result = numbers.concat(letters).concat(interval);
6801 * result.subscribe(x => console.log(x));
6803 * @see {@link create}
6804 * @see {@link empty}
6805 * @see {@link never}
6806 * @see {@link throw}
6808 * @param {...T} values Arguments that represent `next` values to be emitted.
6809 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
6810 * the emissions of the `next` notifications.
6811 * @return {Observable<T>} An Observable that emits each given input value.
6816 ArrayObservable.of = function () {
6818 for (var _i = 0; _i < arguments.length; _i++) {
6819 array[_i - 0] = arguments[_i];
6821 var scheduler = array[array.length - 1];
6822 if (isScheduler_1.isScheduler(scheduler)) {
6828 var len = array.length;
6830 return new ArrayObservable(array, scheduler);
6832 else if (len === 1) {
6833 return new ScalarObservable_1.ScalarObservable(array[0], scheduler);
6836 return new EmptyObservable_1.EmptyObservable(scheduler);
6839 ArrayObservable.dispatch = function (state) {
6840 var array = state.array, index = state.index, count = state.count, subscriber = state.subscriber;
6841 if (index >= count) {
6842 subscriber.complete();
6845 subscriber.next(array[index]);
6846 if (subscriber.closed) {
6849 state.index = index + 1;
6850 this.schedule(state);
6852 ArrayObservable.prototype._subscribe = function (subscriber) {
6854 var array = this.array;
6855 var count = array.length;
6856 var scheduler = this.scheduler;
6858 return scheduler.schedule(ArrayObservable.dispatch, 0, {
6859 array: array, index: index, count: count, subscriber: subscriber
6863 for (var i = 0; i < count && !subscriber.closed; i++) {
6864 subscriber.next(array[i]);
6866 subscriber.complete();
6869 return ArrayObservable;
6870 }(Observable_1.Observable));
6871 exports.ArrayObservable = ArrayObservable;
6873 },{"../Observable":28,"../util/isScheduler":170,"./EmptyObservable":88,"./ScalarObservable":94}],86:[function(require,module,exports){
6875 var __extends = (this && this.__extends) || function (d, b) {
6876 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6877 function __() { this.constructor = d; }
6878 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6880 var Subject_1 = require('../Subject');
6881 var Observable_1 = require('../Observable');
6882 var Subscriber_1 = require('../Subscriber');
6883 var Subscription_1 = require('../Subscription');
6885 * @class ConnectableObservable<T>
6887 var ConnectableObservable = (function (_super) {
6888 __extends(ConnectableObservable, _super);
6889 function ConnectableObservable(source, subjectFactory) {
6891 this.source = source;
6892 this.subjectFactory = subjectFactory;
6894 this._isComplete = false;
6896 ConnectableObservable.prototype._subscribe = function (subscriber) {
6897 return this.getSubject().subscribe(subscriber);
6899 ConnectableObservable.prototype.getSubject = function () {
6900 var subject = this._subject;
6901 if (!subject || subject.isStopped) {
6902 this._subject = this.subjectFactory();
6904 return this._subject;
6906 ConnectableObservable.prototype.connect = function () {
6907 var connection = this._connection;
6909 this._isComplete = false;
6910 connection = this._connection = new Subscription_1.Subscription();
6911 connection.add(this.source
6912 .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
6913 if (connection.closed) {
6914 this._connection = null;
6915 connection = Subscription_1.Subscription.EMPTY;
6918 this._connection = connection;
6923 ConnectableObservable.prototype.refCount = function () {
6924 return this.lift(new RefCountOperator(this));
6926 return ConnectableObservable;
6927 }(Observable_1.Observable));
6928 exports.ConnectableObservable = ConnectableObservable;
6929 var connectableProto = ConnectableObservable.prototype;
6930 exports.connectableObservableDescriptor = {
6931 operator: { value: null },
6932 _refCount: { value: 0, writable: true },
6933 _subject: { value: null, writable: true },
6934 _connection: { value: null, writable: true },
6935 _subscribe: { value: connectableProto._subscribe },
6936 _isComplete: { value: connectableProto._isComplete, writable: true },
6937 getSubject: { value: connectableProto.getSubject },
6938 connect: { value: connectableProto.connect },
6939 refCount: { value: connectableProto.refCount }
6941 var ConnectableSubscriber = (function (_super) {
6942 __extends(ConnectableSubscriber, _super);
6943 function ConnectableSubscriber(destination, connectable) {
6944 _super.call(this, destination);
6945 this.connectable = connectable;
6947 ConnectableSubscriber.prototype._error = function (err) {
6948 this._unsubscribe();
6949 _super.prototype._error.call(this, err);
6951 ConnectableSubscriber.prototype._complete = function () {
6952 this.connectable._isComplete = true;
6953 this._unsubscribe();
6954 _super.prototype._complete.call(this);
6956 ConnectableSubscriber.prototype._unsubscribe = function () {
6957 var connectable = this.connectable;
6959 this.connectable = null;
6960 var connection = connectable._connection;
6961 connectable._refCount = 0;
6962 connectable._subject = null;
6963 connectable._connection = null;
6965 connection.unsubscribe();
6969 return ConnectableSubscriber;
6970 }(Subject_1.SubjectSubscriber));
6971 var RefCountOperator = (function () {
6972 function RefCountOperator(connectable) {
6973 this.connectable = connectable;
6975 RefCountOperator.prototype.call = function (subscriber, source) {
6976 var connectable = this.connectable;
6977 connectable._refCount++;
6978 var refCounter = new RefCountSubscriber(subscriber, connectable);
6979 var subscription = source.subscribe(refCounter);
6980 if (!refCounter.closed) {
6981 refCounter.connection = connectable.connect();
6983 return subscription;
6985 return RefCountOperator;
6987 var RefCountSubscriber = (function (_super) {
6988 __extends(RefCountSubscriber, _super);
6989 function RefCountSubscriber(destination, connectable) {
6990 _super.call(this, destination);
6991 this.connectable = connectable;
6993 RefCountSubscriber.prototype._unsubscribe = function () {
6994 var connectable = this.connectable;
6996 this.connection = null;
6999 this.connectable = null;
7000 var refCount = connectable._refCount;
7001 if (refCount <= 0) {
7002 this.connection = null;
7005 connectable._refCount = refCount - 1;
7007 this.connection = null;
7011 // Compare the local RefCountSubscriber's connection Subscription to the
7012 // connection Subscription on the shared ConnectableObservable. In cases
7013 // where the ConnectableObservable source synchronously emits values, and
7014 // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
7015 // execution continues to here before the RefCountOperator has a chance to
7016 // supply the RefCountSubscriber with the shared connection Subscription.
7019 // Observable.range(0, 10)
7025 // In order to account for this case, RefCountSubscriber should only dispose
7026 // the ConnectableObservable's shared connection Subscription if the
7027 // connection Subscription exists, *and* either:
7028 // a. RefCountSubscriber doesn't have a reference to the shared connection
7029 // Subscription yet, or,
7030 // b. RefCountSubscriber's connection Subscription reference is identical
7031 // to the shared connection Subscription
7033 var connection = this.connection;
7034 var sharedConnection = connectable._connection;
7035 this.connection = null;
7036 if (sharedConnection && (!connection || sharedConnection === connection)) {
7037 sharedConnection.unsubscribe();
7040 return RefCountSubscriber;
7041 }(Subscriber_1.Subscriber));
7043 },{"../Observable":28,"../Subject":33,"../Subscriber":35,"../Subscription":36}],87:[function(require,module,exports){
7045 var __extends = (this && this.__extends) || function (d, b) {
7046 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7047 function __() { this.constructor = d; }
7048 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7050 var Observable_1 = require('../Observable');
7051 var subscribeToResult_1 = require('../util/subscribeToResult');
7052 var OuterSubscriber_1 = require('../OuterSubscriber');
7054 * We need this JSDoc comment for affecting ESDoc.
7055 * @extends {Ignored}
7058 var DeferObservable = (function (_super) {
7059 __extends(DeferObservable, _super);
7060 function DeferObservable(observableFactory) {
7062 this.observableFactory = observableFactory;
7065 * Creates an Observable that, on subscribe, calls an Observable factory to
7066 * make an Observable for each new Observer.
7068 * <span class="informal">Creates the Observable lazily, that is, only when it
7072 * <img src="./img/defer.png" width="100%">
7074 * `defer` allows you to create the Observable only when the Observer
7075 * subscribes, and create a fresh Observable for each Observer. It waits until
7076 * an Observer subscribes to it, and then it generates an Observable,
7077 * typically with an Observable factory function. It does this afresh for each
7078 * subscriber, so although each subscriber may think it is subscribing to the
7079 * same Observable, in fact each subscriber gets its own individual
7082 * @example <caption>Subscribe to either an Observable of clicks or an Observable of interval, at random</caption>
7083 * var clicksOrInterval = Rx.Observable.defer(function () {
7084 * if (Math.random() > 0.5) {
7085 * return Rx.Observable.fromEvent(document, 'click');
7087 * return Rx.Observable.interval(1000);
7090 * clicksOrInterval.subscribe(x => console.log(x));
7092 * // Results in the following behavior:
7093 * // If the result of Math.random() is greater than 0.5 it will listen
7094 * // for clicks anywhere on the "document"; when document is clicked it
7095 * // will log a MouseEvent object to the console. If the result is less
7096 * // than 0.5 it will emit ascending numbers, one every second(1000ms).
7098 * @see {@link create}
7100 * @param {function(): SubscribableOrPromise} observableFactory The Observable
7101 * factory function to invoke for each Observer that subscribes to the output
7102 * Observable. May also return a Promise, which will be converted on the fly
7104 * @return {Observable} An Observable whose Observers' subscriptions trigger
7105 * an invocation of the given Observable factory function.
7110 DeferObservable.create = function (observableFactory) {
7111 return new DeferObservable(observableFactory);
7113 DeferObservable.prototype._subscribe = function (subscriber) {
7114 return new DeferSubscriber(subscriber, this.observableFactory);
7116 return DeferObservable;
7117 }(Observable_1.Observable));
7118 exports.DeferObservable = DeferObservable;
7119 var DeferSubscriber = (function (_super) {
7120 __extends(DeferSubscriber, _super);
7121 function DeferSubscriber(destination, factory) {
7122 _super.call(this, destination);
7123 this.factory = factory;
7126 DeferSubscriber.prototype.tryDefer = function () {
7128 this._callFactory();
7134 DeferSubscriber.prototype._callFactory = function () {
7135 var result = this.factory();
7137 this.add(subscribeToResult_1.subscribeToResult(this, result));
7140 return DeferSubscriber;
7141 }(OuterSubscriber_1.OuterSubscriber));
7143 },{"../Observable":28,"../OuterSubscriber":30,"../util/subscribeToResult":172}],88:[function(require,module,exports){
7145 var __extends = (this && this.__extends) || function (d, b) {
7146 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7147 function __() { this.constructor = d; }
7148 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7150 var Observable_1 = require('../Observable');
7152 * We need this JSDoc comment for affecting ESDoc.
7153 * @extends {Ignored}
7156 var EmptyObservable = (function (_super) {
7157 __extends(EmptyObservable, _super);
7158 function EmptyObservable(scheduler) {
7160 this.scheduler = scheduler;
7163 * Creates an Observable that emits no items to the Observer and immediately
7164 * emits a complete notification.
7166 * <span class="informal">Just emits 'complete', and nothing else.
7169 * <img src="./img/empty.png" width="100%">
7171 * This static operator is useful for creating a simple Observable that only
7172 * emits the complete notification. It can be used for composing with other
7173 * Observables, such as in a {@link mergeMap}.
7175 * @example <caption>Emit the number 7, then complete.</caption>
7176 * var result = Rx.Observable.empty().startWith(7);
7177 * result.subscribe(x => console.log(x));
7179 * @example <caption>Map and flatten only odd numbers to the sequence 'a', 'b', 'c'</caption>
7180 * var interval = Rx.Observable.interval(1000);
7181 * var result = interval.mergeMap(x =>
7182 * x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.empty()
7184 * result.subscribe(x => console.log(x));
7186 * // Results in the following to the console:
7187 * // x is equal to the count on the interval eg(0,1,2,3,...)
7188 * // x will occur every 1000ms
7189 * // if x % 2 is equal to 1 print abc
7190 * // if x % 2 is not equal to 1 nothing will be output
7192 * @see {@link create}
7193 * @see {@link never}
7195 * @see {@link throw}
7197 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7198 * the emission of the complete notification.
7199 * @return {Observable} An "empty" Observable: emits only the complete
7205 EmptyObservable.create = function (scheduler) {
7206 return new EmptyObservable(scheduler);
7208 EmptyObservable.dispatch = function (arg) {
7209 var subscriber = arg.subscriber;
7210 subscriber.complete();
7212 EmptyObservable.prototype._subscribe = function (subscriber) {
7213 var scheduler = this.scheduler;
7215 return scheduler.schedule(EmptyObservable.dispatch, 0, { subscriber: subscriber });
7218 subscriber.complete();
7221 return EmptyObservable;
7222 }(Observable_1.Observable));
7223 exports.EmptyObservable = EmptyObservable;
7225 },{"../Observable":28}],89:[function(require,module,exports){
7227 var __extends = (this && this.__extends) || function (d, b) {
7228 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7229 function __() { this.constructor = d; }
7230 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7232 var Observable_1 = require('../Observable');
7234 * We need this JSDoc comment for affecting ESDoc.
7235 * @extends {Ignored}
7238 var ErrorObservable = (function (_super) {
7239 __extends(ErrorObservable, _super);
7240 function ErrorObservable(error, scheduler) {
7243 this.scheduler = scheduler;
7246 * Creates an Observable that emits no items to the Observer and immediately
7247 * emits an error notification.
7249 * <span class="informal">Just emits 'error', and nothing else.
7252 * <img src="./img/throw.png" width="100%">
7254 * This static operator is useful for creating a simple Observable that only
7255 * emits the error notification. It can be used for composing with other
7256 * Observables, such as in a {@link mergeMap}.
7258 * @example <caption>Emit the number 7, then emit an error.</caption>
7259 * var result = Rx.Observable.throw(new Error('oops!')).startWith(7);
7260 * result.subscribe(x => console.log(x), e => console.error(e));
7262 * @example <caption>Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 13</caption>
7263 * var interval = Rx.Observable.interval(1000);
7264 * var result = interval.mergeMap(x =>
7266 * Rx.Observable.throw('Thirteens are bad') :
7267 * Rx.Observable.of('a', 'b', 'c')
7269 * result.subscribe(x => console.log(x), e => console.error(e));
7271 * @see {@link create}
7272 * @see {@link empty}
7273 * @see {@link never}
7276 * @param {any} error The particular Error to pass to the error notification.
7277 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7278 * the emission of the error notification.
7279 * @return {Observable} An error Observable: emits only the error notification
7280 * using the given error argument.
7285 ErrorObservable.create = function (error, scheduler) {
7286 return new ErrorObservable(error, scheduler);
7288 ErrorObservable.dispatch = function (arg) {
7289 var error = arg.error, subscriber = arg.subscriber;
7290 subscriber.error(error);
7292 ErrorObservable.prototype._subscribe = function (subscriber) {
7293 var error = this.error;
7294 var scheduler = this.scheduler;
7296 return scheduler.schedule(ErrorObservable.dispatch, 0, {
7297 error: error, subscriber: subscriber
7301 subscriber.error(error);
7304 return ErrorObservable;
7305 }(Observable_1.Observable));
7306 exports.ErrorObservable = ErrorObservable;
7308 },{"../Observable":28}],90:[function(require,module,exports){
7310 var __extends = (this && this.__extends) || function (d, b) {
7311 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7312 function __() { this.constructor = d; }
7313 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7315 var Observable_1 = require('../Observable');
7316 var tryCatch_1 = require('../util/tryCatch');
7317 var isFunction_1 = require('../util/isFunction');
7318 var errorObject_1 = require('../util/errorObject');
7319 var Subscription_1 = require('../Subscription');
7320 var toString = Object.prototype.toString;
7321 function isNodeStyleEventEmitter(sourceObj) {
7322 return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
7324 function isJQueryStyleEventEmitter(sourceObj) {
7325 return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
7327 function isNodeList(sourceObj) {
7328 return !!sourceObj && toString.call(sourceObj) === '[object NodeList]';
7330 function isHTMLCollection(sourceObj) {
7331 return !!sourceObj && toString.call(sourceObj) === '[object HTMLCollection]';
7333 function isEventTarget(sourceObj) {
7334 return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
7337 * We need this JSDoc comment for affecting ESDoc.
7338 * @extends {Ignored}
7341 var FromEventObservable = (function (_super) {
7342 __extends(FromEventObservable, _super);
7343 function FromEventObservable(sourceObj, eventName, selector, options) {
7345 this.sourceObj = sourceObj;
7346 this.eventName = eventName;
7347 this.selector = selector;
7348 this.options = options;
7350 /* tslint:enable:max-line-length */
7352 * Creates an Observable that emits events of a specific type coming from the
7353 * given event target.
7355 * <span class="informal">Creates an Observable from DOM events, or Node
7356 * EventEmitter events or others.</span>
7358 * <img src="./img/fromEvent.png" width="100%">
7360 * Creates an Observable by attaching an event listener to an "event target",
7361 * which may be an object with `addEventListener` and `removeEventListener`,
7362 * a Node.js EventEmitter, a jQuery style EventEmitter, a NodeList from the
7363 * DOM, or an HTMLCollection from the DOM. The event handler is attached when
7364 * the output Observable is subscribed, and removed when the Subscription is
7367 * @example <caption>Emits clicks happening on the DOM document</caption>
7368 * var clicks = Rx.Observable.fromEvent(document, 'click');
7369 * clicks.subscribe(x => console.log(x));
7372 * // MouseEvent object logged to console everytime a click
7373 * // occurs on the document.
7376 * @see {@link fromEventPattern}
7378 * @param {EventTargetLike} target The DOMElement, event target, Node.js
7379 * EventEmitter, NodeList or HTMLCollection to attach the event handler to.
7380 * @param {string} eventName The event name of interest, being emitted by the
7382 * @param {EventListenerOptions} [options] Options to pass through to addEventListener
7383 * @param {SelectorMethodSignature<T>} [selector] An optional function to
7384 * post-process results. It takes the arguments from the event handler and
7385 * should return a single value.
7386 * @return {Observable<T>}
7391 FromEventObservable.create = function (target, eventName, options, selector) {
7392 if (isFunction_1.isFunction(options)) {
7394 options = undefined;
7396 return new FromEventObservable(target, eventName, selector, options);
7398 FromEventObservable.setupSubscription = function (sourceObj, eventName, handler, subscriber, options) {
7400 if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
7401 for (var i = 0, len = sourceObj.length; i < len; i++) {
7402 FromEventObservable.setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
7405 else if (isEventTarget(sourceObj)) {
7406 var source_1 = sourceObj;
7407 sourceObj.addEventListener(eventName, handler, options);
7408 unsubscribe = function () { return source_1.removeEventListener(eventName, handler); };
7410 else if (isJQueryStyleEventEmitter(sourceObj)) {
7411 var source_2 = sourceObj;
7412 sourceObj.on(eventName, handler);
7413 unsubscribe = function () { return source_2.off(eventName, handler); };
7415 else if (isNodeStyleEventEmitter(sourceObj)) {
7416 var source_3 = sourceObj;
7417 sourceObj.addListener(eventName, handler);
7418 unsubscribe = function () { return source_3.removeListener(eventName, handler); };
7421 throw new TypeError('Invalid event target');
7423 subscriber.add(new Subscription_1.Subscription(unsubscribe));
7425 FromEventObservable.prototype._subscribe = function (subscriber) {
7426 var sourceObj = this.sourceObj;
7427 var eventName = this.eventName;
7428 var options = this.options;
7429 var selector = this.selector;
7430 var handler = selector ? function () {
7432 for (var _i = 0; _i < arguments.length; _i++) {
7433 args[_i - 0] = arguments[_i];
7435 var result = tryCatch_1.tryCatch(selector).apply(void 0, args);
7436 if (result === errorObject_1.errorObject) {
7437 subscriber.error(errorObject_1.errorObject.e);
7440 subscriber.next(result);
7442 } : function (e) { return subscriber.next(e); };
7443 FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber, options);
7445 return FromEventObservable;
7446 }(Observable_1.Observable));
7447 exports.FromEventObservable = FromEventObservable;
7449 },{"../Observable":28,"../Subscription":36,"../util/errorObject":162,"../util/isFunction":166,"../util/tryCatch":174}],91:[function(require,module,exports){
7451 var __extends = (this && this.__extends) || function (d, b) {
7452 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7453 function __() { this.constructor = d; }
7454 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7456 var isArray_1 = require('../util/isArray');
7457 var isArrayLike_1 = require('../util/isArrayLike');
7458 var isPromise_1 = require('../util/isPromise');
7459 var PromiseObservable_1 = require('./PromiseObservable');
7460 var IteratorObservable_1 = require('./IteratorObservable');
7461 var ArrayObservable_1 = require('./ArrayObservable');
7462 var ArrayLikeObservable_1 = require('./ArrayLikeObservable');
7463 var iterator_1 = require('../symbol/iterator');
7464 var Observable_1 = require('../Observable');
7465 var observeOn_1 = require('../operator/observeOn');
7466 var observable_1 = require('../symbol/observable');
7468 * We need this JSDoc comment for affecting ESDoc.
7469 * @extends {Ignored}
7472 var FromObservable = (function (_super) {
7473 __extends(FromObservable, _super);
7474 function FromObservable(ish, scheduler) {
7475 _super.call(this, null);
7477 this.scheduler = scheduler;
7480 * Creates an Observable from an Array, an array-like object, a Promise, an
7481 * iterable object, or an Observable-like object.
7483 * <span class="informal">Converts almost anything to an Observable.</span>
7485 * <img src="./img/from.png" width="100%">
7487 * Convert various other objects and data types into Observables. `from`
7488 * converts a Promise or an array-like or an
7489 * [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)
7490 * object into an Observable that emits the items in that promise or array or
7491 * iterable. A String, in this context, is treated as an array of characters.
7492 * Observable-like objects (contains a function named with the ES2015 Symbol
7493 * for Observable) can also be converted through this operator.
7495 * @example <caption>Converts an array to an Observable</caption>
7496 * var array = [10, 20, 30];
7497 * var result = Rx.Observable.from(array);
7498 * result.subscribe(x => console.log(x));
7500 * // Results in the following:
7503 * @example <caption>Convert an infinite iterable (from a generator) to an Observable</caption>
7504 * function* generateDoubles(seed) {
7508 * i = 2 * i; // double it
7512 * var iterator = generateDoubles(3);
7513 * var result = Rx.Observable.from(iterator).take(10);
7514 * result.subscribe(x => console.log(x));
7516 * // Results in the following:
7517 * // 3 6 12 24 48 96 192 384 768 1536
7519 * @see {@link create}
7520 * @see {@link fromEvent}
7521 * @see {@link fromEventPattern}
7522 * @see {@link fromPromise}
7524 * @param {ObservableInput<T>} ish A subscribable object, a Promise, an
7525 * Observable-like, an Array, an iterable or an array-like object to be
7527 * @param {Scheduler} [scheduler] The scheduler on which to schedule the
7528 * emissions of values.
7529 * @return {Observable<T>} The Observable whose values are originally from the
7530 * input object that was converted.
7535 FromObservable.create = function (ish, scheduler) {
7537 if (typeof ish[observable_1.observable] === 'function') {
7538 if (ish instanceof Observable_1.Observable && !scheduler) {
7541 return new FromObservable(ish, scheduler);
7543 else if (isArray_1.isArray(ish)) {
7544 return new ArrayObservable_1.ArrayObservable(ish, scheduler);
7546 else if (isPromise_1.isPromise(ish)) {
7547 return new PromiseObservable_1.PromiseObservable(ish, scheduler);
7549 else if (typeof ish[iterator_1.iterator] === 'function' || typeof ish === 'string') {
7550 return new IteratorObservable_1.IteratorObservable(ish, scheduler);
7552 else if (isArrayLike_1.isArrayLike(ish)) {
7553 return new ArrayLikeObservable_1.ArrayLikeObservable(ish, scheduler);
7556 throw new TypeError((ish !== null && typeof ish || ish) + ' is not observable');
7558 FromObservable.prototype._subscribe = function (subscriber) {
7560 var scheduler = this.scheduler;
7561 if (scheduler == null) {
7562 return ish[observable_1.observable]().subscribe(subscriber);
7565 return ish[observable_1.observable]().subscribe(new observeOn_1.ObserveOnSubscriber(subscriber, scheduler, 0));
7568 return FromObservable;
7569 }(Observable_1.Observable));
7570 exports.FromObservable = FromObservable;
7572 },{"../Observable":28,"../operator/observeOn":128,"../symbol/iterator":153,"../symbol/observable":154,"../util/isArray":163,"../util/isArrayLike":164,"../util/isPromise":169,"./ArrayLikeObservable":84,"./ArrayObservable":85,"./IteratorObservable":92,"./PromiseObservable":93}],92:[function(require,module,exports){
7574 var __extends = (this && this.__extends) || function (d, b) {
7575 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7576 function __() { this.constructor = d; }
7577 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7579 var root_1 = require('../util/root');
7580 var Observable_1 = require('../Observable');
7581 var iterator_1 = require('../symbol/iterator');
7583 * We need this JSDoc comment for affecting ESDoc.
7584 * @extends {Ignored}
7587 var IteratorObservable = (function (_super) {
7588 __extends(IteratorObservable, _super);
7589 function IteratorObservable(iterator, scheduler) {
7591 this.scheduler = scheduler;
7592 if (iterator == null) {
7593 throw new Error('iterator cannot be null.');
7595 this.iterator = getIterator(iterator);
7597 IteratorObservable.create = function (iterator, scheduler) {
7598 return new IteratorObservable(iterator, scheduler);
7600 IteratorObservable.dispatch = function (state) {
7601 var index = state.index, hasError = state.hasError, iterator = state.iterator, subscriber = state.subscriber;
7603 subscriber.error(state.error);
7606 var result = iterator.next();
7608 subscriber.complete();
7611 subscriber.next(result.value);
7612 state.index = index + 1;
7613 if (subscriber.closed) {
7614 if (typeof iterator.return === 'function') {
7619 this.schedule(state);
7621 IteratorObservable.prototype._subscribe = function (subscriber) {
7623 var _a = this, iterator = _a.iterator, scheduler = _a.scheduler;
7625 return scheduler.schedule(IteratorObservable.dispatch, 0, {
7626 index: index, iterator: iterator, subscriber: subscriber
7631 var result = iterator.next();
7633 subscriber.complete();
7637 subscriber.next(result.value);
7639 if (subscriber.closed) {
7640 if (typeof iterator.return === 'function') {
7648 return IteratorObservable;
7649 }(Observable_1.Observable));
7650 exports.IteratorObservable = IteratorObservable;
7651 var StringIterator = (function () {
7652 function StringIterator(str, idx, len) {
7653 if (idx === void 0) { idx = 0; }
7654 if (len === void 0) { len = str.length; }
7659 StringIterator.prototype[iterator_1.iterator] = function () { return (this); };
7660 StringIterator.prototype.next = function () {
7661 return this.idx < this.len ? {
7663 value: this.str.charAt(this.idx++)
7669 return StringIterator;
7671 var ArrayIterator = (function () {
7672 function ArrayIterator(arr, idx, len) {
7673 if (idx === void 0) { idx = 0; }
7674 if (len === void 0) { len = toLength(arr); }
7679 ArrayIterator.prototype[iterator_1.iterator] = function () { return this; };
7680 ArrayIterator.prototype.next = function () {
7681 return this.idx < this.len ? {
7683 value: this.arr[this.idx++]
7689 return ArrayIterator;
7691 function getIterator(obj) {
7692 var i = obj[iterator_1.iterator];
7693 if (!i && typeof obj === 'string') {
7694 return new StringIterator(obj);
7696 if (!i && obj.length !== undefined) {
7697 return new ArrayIterator(obj);
7700 throw new TypeError('object is not iterable');
7702 return obj[iterator_1.iterator]();
7704 var maxSafeInteger = Math.pow(2, 53) - 1;
7705 function toLength(o) {
7706 var len = +o.length;
7710 if (len === 0 || !numberIsFinite(len)) {
7713 len = sign(len) * Math.floor(Math.abs(len));
7717 if (len > maxSafeInteger) {
7718 return maxSafeInteger;
7722 function numberIsFinite(value) {
7723 return typeof value === 'number' && root_1.root.isFinite(value);
7725 function sign(value) {
7726 var valueAsNumber = +value;
7727 if (valueAsNumber === 0) {
7728 return valueAsNumber;
7730 if (isNaN(valueAsNumber)) {
7731 return valueAsNumber;
7733 return valueAsNumber < 0 ? -1 : 1;
7736 },{"../Observable":28,"../symbol/iterator":153,"../util/root":171}],93:[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 root_1 = require('../util/root');
7744 var Observable_1 = require('../Observable');
7746 * We need this JSDoc comment for affecting ESDoc.
7747 * @extends {Ignored}
7750 var PromiseObservable = (function (_super) {
7751 __extends(PromiseObservable, _super);
7752 function PromiseObservable(promise, scheduler) {
7754 this.promise = promise;
7755 this.scheduler = scheduler;
7758 * Converts a Promise to an Observable.
7760 * <span class="informal">Returns an Observable that just emits the Promise's
7761 * resolved value, then completes.</span>
7763 * Converts an ES2015 Promise or a Promises/A+ spec compliant Promise to an
7764 * Observable. If the Promise resolves with a value, the output Observable
7765 * emits that resolved value as a `next`, and then completes. If the Promise
7766 * is rejected, then the output Observable emits the corresponding Error.
7768 * @example <caption>Convert the Promise returned by Fetch to an Observable</caption>
7769 * var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
7770 * result.subscribe(x => console.log(x), e => console.error(e));
7772 * @see {@link bindCallback}
7775 * @param {PromiseLike<T>} promise The promise to be converted.
7776 * @param {Scheduler} [scheduler] An optional IScheduler to use for scheduling
7777 * the delivery of the resolved value (or the rejection).
7778 * @return {Observable<T>} An Observable which wraps the Promise.
7783 PromiseObservable.create = function (promise, scheduler) {
7784 return new PromiseObservable(promise, scheduler);
7786 PromiseObservable.prototype._subscribe = function (subscriber) {
7788 var promise = this.promise;
7789 var scheduler = this.scheduler;
7790 if (scheduler == null) {
7791 if (this._isScalar) {
7792 if (!subscriber.closed) {
7793 subscriber.next(this.value);
7794 subscriber.complete();
7798 promise.then(function (value) {
7799 _this.value = value;
7800 _this._isScalar = true;
7801 if (!subscriber.closed) {
7802 subscriber.next(value);
7803 subscriber.complete();
7806 if (!subscriber.closed) {
7807 subscriber.error(err);
7810 .then(null, function (err) {
7811 // escape the promise trap, throw unhandled errors
7812 root_1.root.setTimeout(function () { throw err; });
7817 if (this._isScalar) {
7818 if (!subscriber.closed) {
7819 return scheduler.schedule(dispatchNext, 0, { value: this.value, subscriber: subscriber });
7823 promise.then(function (value) {
7824 _this.value = value;
7825 _this._isScalar = true;
7826 if (!subscriber.closed) {
7827 subscriber.add(scheduler.schedule(dispatchNext, 0, { value: value, subscriber: subscriber }));
7830 if (!subscriber.closed) {
7831 subscriber.add(scheduler.schedule(dispatchError, 0, { err: err, subscriber: subscriber }));
7834 .then(null, function (err) {
7835 // escape the promise trap, throw unhandled errors
7836 root_1.root.setTimeout(function () { throw err; });
7841 return PromiseObservable;
7842 }(Observable_1.Observable));
7843 exports.PromiseObservable = PromiseObservable;
7844 function dispatchNext(arg) {
7845 var value = arg.value, subscriber = arg.subscriber;
7846 if (!subscriber.closed) {
7847 subscriber.next(value);
7848 subscriber.complete();
7851 function dispatchError(arg) {
7852 var err = arg.err, subscriber = arg.subscriber;
7853 if (!subscriber.closed) {
7854 subscriber.error(err);
7858 },{"../Observable":28,"../util/root":171}],94:[function(require,module,exports){
7860 var __extends = (this && this.__extends) || function (d, b) {
7861 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7862 function __() { this.constructor = d; }
7863 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7865 var Observable_1 = require('../Observable');
7867 * We need this JSDoc comment for affecting ESDoc.
7868 * @extends {Ignored}
7871 var ScalarObservable = (function (_super) {
7872 __extends(ScalarObservable, _super);
7873 function ScalarObservable(value, scheduler) {
7876 this.scheduler = scheduler;
7877 this._isScalar = true;
7879 this._isScalar = false;
7882 ScalarObservable.create = function (value, scheduler) {
7883 return new ScalarObservable(value, scheduler);
7885 ScalarObservable.dispatch = function (state) {
7886 var done = state.done, value = state.value, subscriber = state.subscriber;
7888 subscriber.complete();
7891 subscriber.next(value);
7892 if (subscriber.closed) {
7896 this.schedule(state);
7898 ScalarObservable.prototype._subscribe = function (subscriber) {
7899 var value = this.value;
7900 var scheduler = this.scheduler;
7902 return scheduler.schedule(ScalarObservable.dispatch, 0, {
7903 done: false, value: value, subscriber: subscriber
7907 subscriber.next(value);
7908 if (!subscriber.closed) {
7909 subscriber.complete();
7913 return ScalarObservable;
7914 }(Observable_1.Observable));
7915 exports.ScalarObservable = ScalarObservable;
7917 },{"../Observable":28}],95:[function(require,module,exports){
7919 var __extends = (this && this.__extends) || function (d, b) {
7920 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7921 function __() { this.constructor = d; }
7922 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7924 var isNumeric_1 = require('../util/isNumeric');
7925 var Observable_1 = require('../Observable');
7926 var async_1 = require('../scheduler/async');
7927 var isScheduler_1 = require('../util/isScheduler');
7928 var isDate_1 = require('../util/isDate');
7930 * We need this JSDoc comment for affecting ESDoc.
7931 * @extends {Ignored}
7934 var TimerObservable = (function (_super) {
7935 __extends(TimerObservable, _super);
7936 function TimerObservable(dueTime, period, scheduler) {
7937 if (dueTime === void 0) { dueTime = 0; }
7941 if (isNumeric_1.isNumeric(period)) {
7942 this.period = Number(period) < 1 && 1 || Number(period);
7944 else if (isScheduler_1.isScheduler(period)) {
7947 if (!isScheduler_1.isScheduler(scheduler)) {
7948 scheduler = async_1.async;
7950 this.scheduler = scheduler;
7951 this.dueTime = isDate_1.isDate(dueTime) ?
7952 (+dueTime - this.scheduler.now()) :
7956 * Creates an Observable that starts emitting after an `initialDelay` and
7957 * emits ever increasing numbers after each `period` of time thereafter.
7959 * <span class="informal">Its like {@link interval}, but you can specify when
7960 * should the emissions start.</span>
7962 * <img src="./img/timer.png" width="100%">
7964 * `timer` returns an Observable that emits an infinite sequence of ascending
7965 * integers, with a constant interval of time, `period` of your choosing
7966 * between those emissions. The first emission happens after the specified
7967 * `initialDelay`. The initial delay may be a {@link Date}. By default, this
7968 * operator uses the `async` IScheduler to provide a notion of time, but you
7969 * may pass any IScheduler to it. If `period` is not specified, the output
7970 * Observable emits only one value, `0`. Otherwise, it emits an infinite
7973 * @example <caption>Emits ascending numbers, one every second (1000ms), starting after 3 seconds</caption>
7974 * var numbers = Rx.Observable.timer(3000, 1000);
7975 * numbers.subscribe(x => console.log(x));
7977 * @example <caption>Emits one number after five seconds</caption>
7978 * var numbers = Rx.Observable.timer(5000);
7979 * numbers.subscribe(x => console.log(x));
7981 * @see {@link interval}
7982 * @see {@link delay}
7984 * @param {number|Date} initialDelay The initial delay time to wait before
7985 * emitting the first value of `0`.
7986 * @param {number} [period] The period of time between emissions of the
7987 * subsequent numbers.
7988 * @param {Scheduler} [scheduler=async] The IScheduler to use for scheduling
7989 * the emission of values, and providing a notion of "time".
7990 * @return {Observable} An Observable that emits a `0` after the
7991 * `initialDelay` and ever increasing numbers after each `period` of time
7997 TimerObservable.create = function (initialDelay, period, scheduler) {
7998 if (initialDelay === void 0) { initialDelay = 0; }
7999 return new TimerObservable(initialDelay, period, scheduler);
8001 TimerObservable.dispatch = function (state) {
8002 var index = state.index, period = state.period, subscriber = state.subscriber;
8004 subscriber.next(index);
8005 if (subscriber.closed) {
8008 else if (period === -1) {
8009 return subscriber.complete();
8011 state.index = index + 1;
8012 action.schedule(state, period);
8014 TimerObservable.prototype._subscribe = function (subscriber) {
8016 var _a = this, period = _a.period, dueTime = _a.dueTime, scheduler = _a.scheduler;
8017 return scheduler.schedule(TimerObservable.dispatch, dueTime, {
8018 index: index, period: period, subscriber: subscriber
8021 return TimerObservable;
8022 }(Observable_1.Observable));
8023 exports.TimerObservable = TimerObservable;
8025 },{"../Observable":28,"../scheduler/async":151,"../util/isDate":165,"../util/isNumeric":167,"../util/isScheduler":170}],96:[function(require,module,exports){
8027 var isScheduler_1 = require('../util/isScheduler');
8028 var isArray_1 = require('../util/isArray');
8029 var ArrayObservable_1 = require('./ArrayObservable');
8030 var combineLatest_1 = require('../operator/combineLatest');
8031 /* tslint:enable:max-line-length */
8033 * Combines multiple Observables to create an Observable whose values are
8034 * calculated from the latest values of each of its input Observables.
8036 * <span class="informal">Whenever any input Observable emits a value, it
8037 * computes a formula using the latest values from all the inputs, then emits
8038 * the output of that formula.</span>
8040 * <img src="./img/combineLatest.png" width="100%">
8042 * `combineLatest` combines the values from all the Observables passed as
8043 * arguments. This is done by subscribing to each Observable in order and,
8044 * whenever any Observable emits, collecting an array of the most recent
8045 * values from each Observable. So if you pass `n` Observables to operator,
8046 * returned Observable will always emit an array of `n` values, in order
8047 * corresponding to order of passed Observables (value from the first Observable
8048 * on the first place and so on).
8050 * Static version of `combineLatest` accepts either an array of Observables
8051 * or each Observable can be put directly as an argument. Note that array of
8052 * Observables is good choice, if you don't know beforehand how many Observables
8053 * you will combine. Passing empty array will result in Observable that
8054 * completes immediately.
8056 * To ensure output array has always the same length, `combineLatest` will
8057 * actually wait for all input Observables to emit at least once,
8058 * before it starts emitting results. This means if some Observable emits
8059 * values before other Observables started emitting, all that values but last
8060 * will be lost. On the other hand, is some Observable does not emit value but
8061 * completes, resulting Observable will complete at the same moment without
8062 * emitting anything, since it will be now impossible to include value from
8063 * completed Observable in resulting array. Also, if some input Observable does
8064 * not emit any value and never completes, `combineLatest` will also never emit
8065 * and never complete, since, again, it will wait for all streams to emit some
8068 * If at least one Observable was passed to `combineLatest` and all passed Observables
8069 * emitted something, resulting Observable will complete when all combined
8070 * streams complete. So even if some Observable completes, result of
8071 * `combineLatest` will still emit values when other Observables do. In case
8072 * of completed Observable, its value from now on will always be the last
8073 * emitted value. On the other hand, if any Observable errors, `combineLatest`
8074 * will error immediately as well, and all other Observables will be unsubscribed.
8076 * `combineLatest` accepts as optional parameter `project` function, which takes
8077 * as arguments all values that would normally be emitted by resulting Observable.
8078 * `project` can return any kind of value, which will be then emitted by Observable
8079 * instead of default array. Note that `project` does not take as argument that array
8080 * of values, but values themselves. That means default `project` can be imagined
8081 * as function that takes all its arguments and puts them into an array.
8084 * @example <caption>Combine two timer Observables</caption>
8085 * const firstTimer = Rx.Observable.timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
8086 * const secondTimer = Rx.Observable.timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now
8087 * const combinedTimers = Rx.Observable.combineLatest(firstTimer, secondTimer);
8088 * combinedTimers.subscribe(value => console.log(value));
8090 * // [0, 0] after 0.5s
8091 * // [1, 0] after 1s
8092 * // [1, 1] after 1.5s
8093 * // [2, 1] after 2s
8096 * @example <caption>Combine an array of Observables</caption>
8097 * const observables = [1, 5, 10].map(
8098 * n => Rx.Observable.of(n).delay(n * 1000).startWith(0) // emit 0 and then emit n after n seconds
8100 * const combined = Rx.Observable.combineLatest(observables);
8101 * combined.subscribe(value => console.log(value));
8103 * // [0, 0, 0] immediately
8104 * // [1, 0, 0] after 1s
8105 * // [1, 5, 0] after 5s
8106 * // [1, 5, 10] after 10s
8109 * @example <caption>Use project function to dynamically calculate the Body-Mass Index</caption>
8110 * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8111 * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8112 * var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => w / (h * h));
8113 * bmi.subscribe(x => console.log('BMI is ' + x));
8115 * // With output to console:
8116 * // BMI is 24.212293388429753
8117 * // BMI is 23.93948099205209
8118 * // BMI is 23.671253629592222
8121 * @see {@link combineAll}
8122 * @see {@link merge}
8123 * @see {@link withLatestFrom}
8125 * @param {ObservableInput} observable1 An input Observable to combine with other Observables.
8126 * @param {ObservableInput} observable2 An input Observable to combine with other Observables.
8127 * More than one input Observables may be given as arguments
8128 * or an array of Observables may be given as the first argument.
8129 * @param {function} [project] An optional function to project the values from
8130 * the combined latest values into a new value on the output Observable.
8131 * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
8132 * each input Observable.
8133 * @return {Observable} An Observable of projected values from the most recent
8134 * values from each input Observable, or an array of the most recent values from
8135 * each input Observable.
8137 * @name combineLatest
8140 function combineLatest() {
8141 var observables = [];
8142 for (var _i = 0; _i < arguments.length; _i++) {
8143 observables[_i - 0] = arguments[_i];
8146 var scheduler = null;
8147 if (isScheduler_1.isScheduler(observables[observables.length - 1])) {
8148 scheduler = observables.pop();
8150 if (typeof observables[observables.length - 1] === 'function') {
8151 project = observables.pop();
8153 // if the first and only other argument besides the resultSelector is an array
8154 // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
8155 if (observables.length === 1 && isArray_1.isArray(observables[0])) {
8156 observables = observables[0];
8158 return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new combineLatest_1.CombineLatestOperator(project));
8160 exports.combineLatest = combineLatest;
8162 },{"../operator/combineLatest":111,"../util/isArray":163,"../util/isScheduler":170,"./ArrayObservable":85}],97:[function(require,module,exports){
8164 var DeferObservable_1 = require('./DeferObservable');
8165 exports.defer = DeferObservable_1.DeferObservable.create;
8167 },{"./DeferObservable":87}],98:[function(require,module,exports){
8169 var EmptyObservable_1 = require('./EmptyObservable');
8170 exports.empty = EmptyObservable_1.EmptyObservable.create;
8172 },{"./EmptyObservable":88}],99:[function(require,module,exports){
8174 var FromObservable_1 = require('./FromObservable');
8175 exports.from = FromObservable_1.FromObservable.create;
8177 },{"./FromObservable":91}],100:[function(require,module,exports){
8179 var FromEventObservable_1 = require('./FromEventObservable');
8180 exports.fromEvent = FromEventObservable_1.FromEventObservable.create;
8182 },{"./FromEventObservable":90}],101:[function(require,module,exports){
8184 var PromiseObservable_1 = require('./PromiseObservable');
8185 exports.fromPromise = PromiseObservable_1.PromiseObservable.create;
8187 },{"./PromiseObservable":93}],102:[function(require,module,exports){
8189 var merge_1 = require('../operator/merge');
8190 exports.merge = merge_1.mergeStatic;
8192 },{"../operator/merge":124}],103:[function(require,module,exports){
8194 var ArrayObservable_1 = require('./ArrayObservable');
8195 exports.of = ArrayObservable_1.ArrayObservable.of;
8197 },{"./ArrayObservable":85}],104:[function(require,module,exports){
8199 var ErrorObservable_1 = require('./ErrorObservable');
8200 exports._throw = ErrorObservable_1.ErrorObservable.create;
8202 },{"./ErrorObservable":89}],105:[function(require,module,exports){
8204 var TimerObservable_1 = require('./TimerObservable');
8205 exports.timer = TimerObservable_1.TimerObservable.create;
8207 },{"./TimerObservable":95}],106:[function(require,module,exports){
8209 var zip_1 = require('../operator/zip');
8210 exports.zip = zip_1.zipStatic;
8212 },{"../operator/zip":145}],107:[function(require,module,exports){
8214 var __extends = (this && this.__extends) || function (d, b) {
8215 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8216 function __() { this.constructor = d; }
8217 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8219 var OuterSubscriber_1 = require('../OuterSubscriber');
8220 var subscribeToResult_1 = require('../util/subscribeToResult');
8222 * Buffers the source Observable values until `closingNotifier` emits.
8224 * <span class="informal">Collects values from the past as an array, and emits
8225 * that array only when another Observable emits.</span>
8227 * <img src="./img/buffer.png" width="100%">
8229 * Buffers the incoming Observable values until the given `closingNotifier`
8230 * Observable emits a value, at which point it emits the buffer on the output
8231 * Observable and starts a new buffer internally, awaiting the next time
8232 * `closingNotifier` emits.
8234 * @example <caption>On every click, emit array of most recent interval events</caption>
8235 * var clicks = Rx.Observable.fromEvent(document, 'click');
8236 * var interval = Rx.Observable.interval(1000);
8237 * var buffered = interval.buffer(clicks);
8238 * buffered.subscribe(x => console.log(x));
8240 * @see {@link bufferCount}
8241 * @see {@link bufferTime}
8242 * @see {@link bufferToggle}
8243 * @see {@link bufferWhen}
8244 * @see {@link window}
8246 * @param {Observable<any>} closingNotifier An Observable that signals the
8247 * buffer to be emitted on the output Observable.
8248 * @return {Observable<T[]>} An Observable of buffers, which are arrays of
8253 function buffer(closingNotifier) {
8254 return this.lift(new BufferOperator(closingNotifier));
8256 exports.buffer = buffer;
8257 var BufferOperator = (function () {
8258 function BufferOperator(closingNotifier) {
8259 this.closingNotifier = closingNotifier;
8261 BufferOperator.prototype.call = function (subscriber, source) {
8262 return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
8264 return BufferOperator;
8267 * We need this JSDoc comment for affecting ESDoc.
8269 * @extends {Ignored}
8271 var BufferSubscriber = (function (_super) {
8272 __extends(BufferSubscriber, _super);
8273 function BufferSubscriber(destination, closingNotifier) {
8274 _super.call(this, destination);
8276 this.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
8278 BufferSubscriber.prototype._next = function (value) {
8279 this.buffer.push(value);
8281 BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8282 var buffer = this.buffer;
8284 this.destination.next(buffer);
8286 return BufferSubscriber;
8287 }(OuterSubscriber_1.OuterSubscriber));
8289 },{"../OuterSubscriber":30,"../util/subscribeToResult":172}],108:[function(require,module,exports){
8291 var __extends = (this && this.__extends) || function (d, b) {
8292 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8293 function __() { this.constructor = d; }
8294 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8296 var Subscriber_1 = require('../Subscriber');
8298 * Buffers the source Observable values until the size hits the maximum
8299 * `bufferSize` given.
8301 * <span class="informal">Collects values from the past as an array, and emits
8302 * that array only when its size reaches `bufferSize`.</span>
8304 * <img src="./img/bufferCount.png" width="100%">
8306 * Buffers a number of values from the source Observable by `bufferSize` then
8307 * emits the buffer and clears it, and starts a new buffer each
8308 * `startBufferEvery` values. If `startBufferEvery` is not provided or is
8309 * `null`, then new buffers are started immediately at the start of the source
8310 * and when each buffer closes and is emitted.
8312 * @example <caption>Emit the last two click events as an array</caption>
8313 * var clicks = Rx.Observable.fromEvent(document, 'click');
8314 * var buffered = clicks.bufferCount(2);
8315 * buffered.subscribe(x => console.log(x));
8317 * @example <caption>On every click, emit the last two click events as an array</caption>
8318 * var clicks = Rx.Observable.fromEvent(document, 'click');
8319 * var buffered = clicks.bufferCount(2, 1);
8320 * buffered.subscribe(x => console.log(x));
8322 * @see {@link buffer}
8323 * @see {@link bufferTime}
8324 * @see {@link bufferToggle}
8325 * @see {@link bufferWhen}
8326 * @see {@link pairwise}
8327 * @see {@link windowCount}
8329 * @param {number} bufferSize The maximum size of the buffer emitted.
8330 * @param {number} [startBufferEvery] Interval at which to start a new buffer.
8331 * For example if `startBufferEvery` is `2`, then a new buffer will be started
8332 * on every other value from the source. A new buffer is started at the
8333 * beginning of the source by default.
8334 * @return {Observable<T[]>} An Observable of arrays of buffered values.
8335 * @method bufferCount
8338 function bufferCount(bufferSize, startBufferEvery) {
8339 if (startBufferEvery === void 0) { startBufferEvery = null; }
8340 return this.lift(new BufferCountOperator(bufferSize, startBufferEvery));
8342 exports.bufferCount = bufferCount;
8343 var BufferCountOperator = (function () {
8344 function BufferCountOperator(bufferSize, startBufferEvery) {
8345 this.bufferSize = bufferSize;
8346 this.startBufferEvery = startBufferEvery;
8347 if (!startBufferEvery || bufferSize === startBufferEvery) {
8348 this.subscriberClass = BufferCountSubscriber;
8351 this.subscriberClass = BufferSkipCountSubscriber;
8354 BufferCountOperator.prototype.call = function (subscriber, source) {
8355 return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
8357 return BufferCountOperator;
8360 * We need this JSDoc comment for affecting ESDoc.
8362 * @extends {Ignored}
8364 var BufferCountSubscriber = (function (_super) {
8365 __extends(BufferCountSubscriber, _super);
8366 function BufferCountSubscriber(destination, bufferSize) {
8367 _super.call(this, destination);
8368 this.bufferSize = bufferSize;
8371 BufferCountSubscriber.prototype._next = function (value) {
8372 var buffer = this.buffer;
8374 if (buffer.length == this.bufferSize) {
8375 this.destination.next(buffer);
8379 BufferCountSubscriber.prototype._complete = function () {
8380 var buffer = this.buffer;
8381 if (buffer.length > 0) {
8382 this.destination.next(buffer);
8384 _super.prototype._complete.call(this);
8386 return BufferCountSubscriber;
8387 }(Subscriber_1.Subscriber));
8389 * We need this JSDoc comment for affecting ESDoc.
8391 * @extends {Ignored}
8393 var BufferSkipCountSubscriber = (function (_super) {
8394 __extends(BufferSkipCountSubscriber, _super);
8395 function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) {
8396 _super.call(this, destination);
8397 this.bufferSize = bufferSize;
8398 this.startBufferEvery = startBufferEvery;
8402 BufferSkipCountSubscriber.prototype._next = function (value) {
8403 var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count;
8405 if (count % startBufferEvery === 0) {
8408 for (var i = buffers.length; i--;) {
8409 var buffer = buffers[i];
8411 if (buffer.length === bufferSize) {
8412 buffers.splice(i, 1);
8413 this.destination.next(buffer);
8417 BufferSkipCountSubscriber.prototype._complete = function () {
8418 var _a = this, buffers = _a.buffers, destination = _a.destination;
8419 while (buffers.length > 0) {
8420 var buffer = buffers.shift();
8421 if (buffer.length > 0) {
8422 destination.next(buffer);
8425 _super.prototype._complete.call(this);
8427 return BufferSkipCountSubscriber;
8428 }(Subscriber_1.Subscriber));
8430 },{"../Subscriber":35}],109:[function(require,module,exports){
8432 var __extends = (this && this.__extends) || function (d, b) {
8433 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8434 function __() { this.constructor = d; }
8435 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8437 var Subscription_1 = require('../Subscription');
8438 var tryCatch_1 = require('../util/tryCatch');
8439 var errorObject_1 = require('../util/errorObject');
8440 var OuterSubscriber_1 = require('../OuterSubscriber');
8441 var subscribeToResult_1 = require('../util/subscribeToResult');
8443 * Buffers the source Observable values, using a factory function of closing
8444 * Observables to determine when to close, emit, and reset the buffer.
8446 * <span class="informal">Collects values from the past as an array. When it
8447 * starts collecting values, it calls a function that returns an Observable that
8448 * tells when to close the buffer and restart collecting.</span>
8450 * <img src="./img/bufferWhen.png" width="100%">
8452 * Opens a buffer immediately, then closes the buffer when the observable
8453 * returned by calling `closingSelector` function emits a value. When it closes
8454 * the buffer, it immediately opens a new buffer and repeats the process.
8456 * @example <caption>Emit an array of the last clicks every [1-5] random seconds</caption>
8457 * var clicks = Rx.Observable.fromEvent(document, 'click');
8458 * var buffered = clicks.bufferWhen(() =>
8459 * Rx.Observable.interval(1000 + Math.random() * 4000)
8461 * buffered.subscribe(x => console.log(x));
8463 * @see {@link buffer}
8464 * @see {@link bufferCount}
8465 * @see {@link bufferTime}
8466 * @see {@link bufferToggle}
8467 * @see {@link windowWhen}
8469 * @param {function(): Observable} closingSelector A function that takes no
8470 * arguments and returns an Observable that signals buffer closure.
8471 * @return {Observable<T[]>} An observable of arrays of buffered values.
8472 * @method bufferWhen
8475 function bufferWhen(closingSelector) {
8476 return this.lift(new BufferWhenOperator(closingSelector));
8478 exports.bufferWhen = bufferWhen;
8479 var BufferWhenOperator = (function () {
8480 function BufferWhenOperator(closingSelector) {
8481 this.closingSelector = closingSelector;
8483 BufferWhenOperator.prototype.call = function (subscriber, source) {
8484 return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
8486 return BufferWhenOperator;
8489 * We need this JSDoc comment for affecting ESDoc.
8491 * @extends {Ignored}
8493 var BufferWhenSubscriber = (function (_super) {
8494 __extends(BufferWhenSubscriber, _super);
8495 function BufferWhenSubscriber(destination, closingSelector) {
8496 _super.call(this, destination);
8497 this.closingSelector = closingSelector;
8498 this.subscribing = false;
8501 BufferWhenSubscriber.prototype._next = function (value) {
8502 this.buffer.push(value);
8504 BufferWhenSubscriber.prototype._complete = function () {
8505 var buffer = this.buffer;
8507 this.destination.next(buffer);
8509 _super.prototype._complete.call(this);
8511 BufferWhenSubscriber.prototype._unsubscribe = function () {
8513 this.subscribing = false;
8515 BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8518 BufferWhenSubscriber.prototype.notifyComplete = function () {
8519 if (this.subscribing) {
8526 BufferWhenSubscriber.prototype.openBuffer = function () {
8527 var closingSubscription = this.closingSubscription;
8528 if (closingSubscription) {
8529 this.remove(closingSubscription);
8530 closingSubscription.unsubscribe();
8532 var buffer = this.buffer;
8534 this.destination.next(buffer);
8537 var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)();
8538 if (closingNotifier === errorObject_1.errorObject) {
8539 this.error(errorObject_1.errorObject.e);
8542 closingSubscription = new Subscription_1.Subscription();
8543 this.closingSubscription = closingSubscription;
8544 this.add(closingSubscription);
8545 this.subscribing = true;
8546 closingSubscription.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
8547 this.subscribing = false;
8550 return BufferWhenSubscriber;
8551 }(OuterSubscriber_1.OuterSubscriber));
8553 },{"../OuterSubscriber":30,"../Subscription":36,"../util/errorObject":162,"../util/subscribeToResult":172,"../util/tryCatch":174}],110:[function(require,module,exports){
8555 var __extends = (this && this.__extends) || function (d, b) {
8556 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8557 function __() { this.constructor = d; }
8558 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8560 var OuterSubscriber_1 = require('../OuterSubscriber');
8561 var subscribeToResult_1 = require('../util/subscribeToResult');
8563 * Catches errors on the observable to be handled by returning a new observable or throwing an error.
8565 * <img src="./img/catch.png" width="100%">
8567 * @example <caption>Continues with a different Observable when there's an error</caption>
8569 * Observable.of(1, 2, 3, 4, 5)
8576 * .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
8577 * .subscribe(x => console.log(x));
8578 * // 1, 2, 3, I, II, III, IV, V
8580 * @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
8582 * Observable.of(1, 2, 3, 4, 5)
8589 * .catch((err, caught) => caught)
8591 * .subscribe(x => console.log(x));
8592 * // 1, 2, 3, 1, 2, 3, ...
8594 * @example <caption>Throws a new error when the source Observable throws an error</caption>
8596 * Observable.of(1, 2, 3, 4, 5)
8604 * throw 'error in source. Details: ' + err;
8607 * x => console.log(x),
8608 * err => console.log(err)
8610 * // 1, 2, 3, error in source. Details: four!
8612 * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
8613 * is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
8614 * is returned by the `selector` will be used to continue the observable chain.
8615 * @return {Observable} An observable that originates from either the source or the observable returned by the
8616 * catch `selector` function.
8621 function _catch(selector) {
8622 var operator = new CatchOperator(selector);
8623 var caught = this.lift(operator);
8624 return (operator.caught = caught);
8626 exports._catch = _catch;
8627 var CatchOperator = (function () {
8628 function CatchOperator(selector) {
8629 this.selector = selector;
8631 CatchOperator.prototype.call = function (subscriber, source) {
8632 return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
8634 return CatchOperator;
8637 * We need this JSDoc comment for affecting ESDoc.
8639 * @extends {Ignored}
8641 var CatchSubscriber = (function (_super) {
8642 __extends(CatchSubscriber, _super);
8643 function CatchSubscriber(destination, selector, caught) {
8644 _super.call(this, destination);
8645 this.selector = selector;
8646 this.caught = caught;
8648 // NOTE: overriding `error` instead of `_error` because we don't want
8649 // to have this flag this subscriber as `isStopped`. We can mimic the
8650 // behavior of the RetrySubscriber (from the `retry` operator), where
8651 // we unsubscribe from our source chain, reset our Subscriber flags,
8652 // then subscribe to the selector result.
8653 CatchSubscriber.prototype.error = function (err) {
8654 if (!this.isStopped) {
8655 var result = void 0;
8657 result = this.selector(err, this.caught);
8660 _super.prototype.error.call(this, err2);
8663 this._unsubscribeAndRecycle();
8664 this.add(subscribeToResult_1.subscribeToResult(this, result));
8667 return CatchSubscriber;
8668 }(OuterSubscriber_1.OuterSubscriber));
8670 },{"../OuterSubscriber":30,"../util/subscribeToResult":172}],111:[function(require,module,exports){
8672 var __extends = (this && this.__extends) || function (d, b) {
8673 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8674 function __() { this.constructor = d; }
8675 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8677 var ArrayObservable_1 = require('../observable/ArrayObservable');
8678 var isArray_1 = require('../util/isArray');
8679 var OuterSubscriber_1 = require('../OuterSubscriber');
8680 var subscribeToResult_1 = require('../util/subscribeToResult');
8682 /* tslint:enable:max-line-length */
8684 * Combines multiple Observables to create an Observable whose values are
8685 * calculated from the latest values of each of its input Observables.
8687 * <span class="informal">Whenever any input Observable emits a value, it
8688 * computes a formula using the latest values from all the inputs, then emits
8689 * the output of that formula.</span>
8691 * <img src="./img/combineLatest.png" width="100%">
8693 * `combineLatest` combines the values from this Observable with values from
8694 * Observables passed as arguments. This is done by subscribing to each
8695 * Observable, in order, and collecting an array of each of the most recent
8696 * values any time any of the input Observables emits, then either taking that
8697 * array and passing it as arguments to an optional `project` function and
8698 * emitting the return value of that, or just emitting the array of recent
8699 * values directly if there is no `project` function.
8701 * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
8702 * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8703 * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8704 * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
8705 * bmi.subscribe(x => console.log('BMI is ' + x));
8707 * // With output to console:
8708 * // BMI is 24.212293388429753
8709 * // BMI is 23.93948099205209
8710 * // BMI is 23.671253629592222
8712 * @see {@link combineAll}
8713 * @see {@link merge}
8714 * @see {@link withLatestFrom}
8716 * @param {ObservableInput} other An input Observable to combine with the source
8717 * Observable. More than one input Observables may be given as argument.
8718 * @param {function} [project] An optional function to project the values from
8719 * the combined latest values into a new value on the output Observable.
8720 * @return {Observable} An Observable of projected values from the most recent
8721 * values from each input Observable, or an array of the most recent values from
8722 * each input Observable.
8723 * @method combineLatest
8726 function combineLatest() {
8727 var observables = [];
8728 for (var _i = 0; _i < arguments.length; _i++) {
8729 observables[_i - 0] = arguments[_i];
8732 if (typeof observables[observables.length - 1] === 'function') {
8733 project = observables.pop();
8735 // if the first and only other argument besides the resultSelector is an array
8736 // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
8737 if (observables.length === 1 && isArray_1.isArray(observables[0])) {
8738 observables = observables[0].slice();
8740 observables.unshift(this);
8741 return this.lift.call(new ArrayObservable_1.ArrayObservable(observables), new CombineLatestOperator(project));
8743 exports.combineLatest = combineLatest;
8744 var CombineLatestOperator = (function () {
8745 function CombineLatestOperator(project) {
8746 this.project = project;
8748 CombineLatestOperator.prototype.call = function (subscriber, source) {
8749 return source.subscribe(new CombineLatestSubscriber(subscriber, this.project));
8751 return CombineLatestOperator;
8753 exports.CombineLatestOperator = CombineLatestOperator;
8755 * We need this JSDoc comment for affecting ESDoc.
8757 * @extends {Ignored}
8759 var CombineLatestSubscriber = (function (_super) {
8760 __extends(CombineLatestSubscriber, _super);
8761 function CombineLatestSubscriber(destination, project) {
8762 _super.call(this, destination);
8763 this.project = project;
8766 this.observables = [];
8768 CombineLatestSubscriber.prototype._next = function (observable) {
8769 this.values.push(none);
8770 this.observables.push(observable);
8772 CombineLatestSubscriber.prototype._complete = function () {
8773 var observables = this.observables;
8774 var len = observables.length;
8776 this.destination.complete();
8780 this.toRespond = len;
8781 for (var i = 0; i < len; i++) {
8782 var observable = observables[i];
8783 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
8787 CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
8788 if ((this.active -= 1) === 0) {
8789 this.destination.complete();
8792 CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8793 var values = this.values;
8794 var oldVal = values[outerIndex];
8795 var toRespond = !this.toRespond
8797 : oldVal === none ? --this.toRespond : this.toRespond;
8798 values[outerIndex] = innerValue;
8799 if (toRespond === 0) {
8801 this._tryProject(values);
8804 this.destination.next(values.slice());
8808 CombineLatestSubscriber.prototype._tryProject = function (values) {
8811 result = this.project.apply(this, values);
8814 this.destination.error(err);
8817 this.destination.next(result);
8819 return CombineLatestSubscriber;
8820 }(OuterSubscriber_1.OuterSubscriber));
8821 exports.CombineLatestSubscriber = CombineLatestSubscriber;
8823 },{"../OuterSubscriber":30,"../observable/ArrayObservable":85,"../util/isArray":163,"../util/subscribeToResult":172}],112:[function(require,module,exports){
8825 var Observable_1 = require('../Observable');
8826 var isScheduler_1 = require('../util/isScheduler');
8827 var ArrayObservable_1 = require('../observable/ArrayObservable');
8828 var mergeAll_1 = require('./mergeAll');
8829 /* tslint:enable:max-line-length */
8831 * Creates an output Observable which sequentially emits all values from every
8832 * given input Observable after the current Observable.
8834 * <span class="informal">Concatenates multiple Observables together by
8835 * sequentially emitting their values, one Observable after the other.</span>
8837 * <img src="./img/concat.png" width="100%">
8839 * Joins this Observable with multiple other Observables by subscribing to them
8840 * one at a time, starting with the source, and merging their results into the
8841 * output Observable. Will wait for each Observable to complete before moving
8844 * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
8845 * var timer = Rx.Observable.interval(1000).take(4);
8846 * var sequence = Rx.Observable.range(1, 10);
8847 * var result = timer.concat(sequence);
8848 * result.subscribe(x => console.log(x));
8851 * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
8853 * @example <caption>Concatenate 3 Observables</caption>
8854 * var timer1 = Rx.Observable.interval(1000).take(10);
8855 * var timer2 = Rx.Observable.interval(2000).take(6);
8856 * var timer3 = Rx.Observable.interval(500).take(10);
8857 * var result = timer1.concat(timer2, timer3);
8858 * result.subscribe(x => console.log(x));
8860 * // results in the following:
8861 * // (Prints to console sequentially)
8862 * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
8863 * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
8864 * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
8866 * @see {@link concatAll}
8867 * @see {@link concatMap}
8868 * @see {@link concatMapTo}
8870 * @param {ObservableInput} other An input Observable to concatenate after the source
8871 * Observable. More than one input Observables may be given as argument.
8872 * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
8873 * Observable subscription on.
8874 * @return {Observable} All values of each passed Observable merged into a
8875 * single Observable, in order, in serial fashion.
8880 var observables = [];
8881 for (var _i = 0; _i < arguments.length; _i++) {
8882 observables[_i - 0] = arguments[_i];
8884 return this.lift.call(concatStatic.apply(void 0, [this].concat(observables)));
8886 exports.concat = concat;
8887 /* tslint:enable:max-line-length */
8889 * Creates an output Observable which sequentially emits all values from given
8890 * Observable and then moves on to the next.
8892 * <span class="informal">Concatenates multiple Observables together by
8893 * sequentially emitting their values, one Observable after the other.</span>
8895 * <img src="./img/concat.png" width="100%">
8897 * `concat` joins multiple Observables together, by subscribing to them one at a time and
8898 * merging their results into the output Observable. You can pass either an array of
8899 * Observables, or put them directly as arguments. Passing an empty array will result
8900 * in Observable that completes immediately.
8902 * `concat` will subscribe to first input Observable and emit all its values, without
8903 * changing or affecting them in any way. When that Observable completes, it will
8904 * subscribe to then next Observable passed and, again, emit its values. This will be
8905 * repeated, until the operator runs out of Observables. When last input Observable completes,
8906 * `concat` will complete as well. At any given moment only one Observable passed to operator
8907 * emits values. If you would like to emit values from passed Observables concurrently, check out
8908 * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,
8909 * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.
8911 * Note that if some input Observable never completes, `concat` will also never complete
8912 * and Observables following the one that did not complete will never be subscribed. On the other
8913 * hand, if some Observable simply completes immediately after it is subscribed, it will be
8914 * invisible for `concat`, which will just move on to the next Observable.
8916 * If any Observable in chain errors, instead of passing control to the next Observable,
8917 * `concat` will error immediately as well. Observables that would be subscribed after
8918 * the one that emitted error, never will.
8920 * If you pass to `concat` the same Observable many times, its stream of values
8921 * will be "replayed" on every subscription, which means you can repeat given Observable
8922 * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,
8923 * you can always use {@link repeat}.
8925 * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
8926 * var timer = Rx.Observable.interval(1000).take(4);
8927 * var sequence = Rx.Observable.range(1, 10);
8928 * var result = Rx.Observable.concat(timer, sequence);
8929 * result.subscribe(x => console.log(x));
8932 * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
8935 * @example <caption>Concatenate an array of 3 Observables</caption>
8936 * var timer1 = Rx.Observable.interval(1000).take(10);
8937 * var timer2 = Rx.Observable.interval(2000).take(6);
8938 * var timer3 = Rx.Observable.interval(500).take(10);
8939 * var result = Rx.Observable.concat([timer1, timer2, timer3]); // note that array is passed
8940 * result.subscribe(x => console.log(x));
8942 * // results in the following:
8943 * // (Prints to console sequentially)
8944 * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
8945 * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
8946 * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
8949 * @example <caption>Concatenate the same Observable to repeat it</caption>
8950 * const timer = Rx.Observable.interval(1000).take(2);
8952 * Rx.Observable.concat(timer, timer) // concating the same Observable!
8954 * value => console.log(value),
8956 * () => console.log('...and it is done!')
8964 * // "...and it is done!" also after 4s
8966 * @see {@link concatAll}
8967 * @see {@link concatMap}
8968 * @see {@link concatMapTo}
8970 * @param {ObservableInput} input1 An input Observable to concatenate with others.
8971 * @param {ObservableInput} input2 An input Observable to concatenate with others.
8972 * More than one input Observables may be given as argument.
8973 * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
8974 * Observable subscription on.
8975 * @return {Observable} All values of each passed Observable merged into a
8976 * single Observable, in order, in serial fashion.
8981 function concatStatic() {
8982 var observables = [];
8983 for (var _i = 0; _i < arguments.length; _i++) {
8984 observables[_i - 0] = arguments[_i];
8986 var scheduler = null;
8987 var args = observables;
8988 if (isScheduler_1.isScheduler(args[observables.length - 1])) {
8989 scheduler = args.pop();
8991 if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
8992 return observables[0];
8994 return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(1));
8996 exports.concatStatic = concatStatic;
8998 },{"../Observable":28,"../observable/ArrayObservable":85,"../util/isScheduler":170,"./mergeAll":125}],113:[function(require,module,exports){
9000 var __extends = (this && this.__extends) || function (d, b) {
9001 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9002 function __() { this.constructor = d; }
9003 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9005 var Subscriber_1 = require('../Subscriber');
9006 var async_1 = require('../scheduler/async');
9008 * Emits a value from the source Observable only after a particular time span
9009 * has passed without another source emission.
9011 * <span class="informal">It's like {@link delay}, but passes only the most
9012 * recent value from each burst of emissions.</span>
9014 * <img src="./img/debounceTime.png" width="100%">
9016 * `debounceTime` delays values emitted by the source Observable, but drops
9017 * previous pending delayed emissions if a new value arrives on the source
9018 * Observable. This operator keeps track of the most recent value from the
9019 * source Observable, and emits that only when `dueTime` enough time has passed
9020 * without any other value appearing on the source Observable. If a new value
9021 * appears before `dueTime` silence occurs, the previous value will be dropped
9022 * and will not be emitted on the output Observable.
9024 * This is a rate-limiting operator, because it is impossible for more than one
9025 * value to be emitted in any time window of duration `dueTime`, but it is also
9026 * a delay-like operator since output emissions do not occur at the same time as
9027 * they did on the source Observable. Optionally takes a {@link IScheduler} for
9030 * @example <caption>Emit the most recent click after a burst of clicks</caption>
9031 * var clicks = Rx.Observable.fromEvent(document, 'click');
9032 * var result = clicks.debounceTime(1000);
9033 * result.subscribe(x => console.log(x));
9035 * @see {@link auditTime}
9036 * @see {@link debounce}
9037 * @see {@link delay}
9038 * @see {@link sampleTime}
9039 * @see {@link throttleTime}
9041 * @param {number} dueTime The timeout duration in milliseconds (or the time
9042 * unit determined internally by the optional `scheduler`) for the window of
9043 * time required to wait for emission silence before emitting the most recent
9045 * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
9046 * managing the timers that handle the timeout for each value.
9047 * @return {Observable} An Observable that delays the emissions of the source
9048 * Observable by the specified `dueTime`, and may drop some values if they occur
9050 * @method debounceTime
9053 function debounceTime(dueTime, scheduler) {
9054 if (scheduler === void 0) { scheduler = async_1.async; }
9055 return this.lift(new DebounceTimeOperator(dueTime, scheduler));
9057 exports.debounceTime = debounceTime;
9058 var DebounceTimeOperator = (function () {
9059 function DebounceTimeOperator(dueTime, scheduler) {
9060 this.dueTime = dueTime;
9061 this.scheduler = scheduler;
9063 DebounceTimeOperator.prototype.call = function (subscriber, source) {
9064 return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
9066 return DebounceTimeOperator;
9069 * We need this JSDoc comment for affecting ESDoc.
9071 * @extends {Ignored}
9073 var DebounceTimeSubscriber = (function (_super) {
9074 __extends(DebounceTimeSubscriber, _super);
9075 function DebounceTimeSubscriber(destination, dueTime, scheduler) {
9076 _super.call(this, destination);
9077 this.dueTime = dueTime;
9078 this.scheduler = scheduler;
9079 this.debouncedSubscription = null;
9080 this.lastValue = null;
9081 this.hasValue = false;
9083 DebounceTimeSubscriber.prototype._next = function (value) {
9084 this.clearDebounce();
9085 this.lastValue = value;
9086 this.hasValue = true;
9087 this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
9089 DebounceTimeSubscriber.prototype._complete = function () {
9090 this.debouncedNext();
9091 this.destination.complete();
9093 DebounceTimeSubscriber.prototype.debouncedNext = function () {
9094 this.clearDebounce();
9095 if (this.hasValue) {
9096 this.destination.next(this.lastValue);
9097 this.lastValue = null;
9098 this.hasValue = false;
9101 DebounceTimeSubscriber.prototype.clearDebounce = function () {
9102 var debouncedSubscription = this.debouncedSubscription;
9103 if (debouncedSubscription !== null) {
9104 this.remove(debouncedSubscription);
9105 debouncedSubscription.unsubscribe();
9106 this.debouncedSubscription = null;
9109 return DebounceTimeSubscriber;
9110 }(Subscriber_1.Subscriber));
9111 function dispatchNext(subscriber) {
9112 subscriber.debouncedNext();
9115 },{"../Subscriber":35,"../scheduler/async":151}],114:[function(require,module,exports){
9117 var __extends = (this && this.__extends) || function (d, b) {
9118 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9119 function __() { this.constructor = d; }
9120 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9122 var async_1 = require('../scheduler/async');
9123 var isDate_1 = require('../util/isDate');
9124 var Subscriber_1 = require('../Subscriber');
9125 var Notification_1 = require('../Notification');
9127 * Delays the emission of items from the source Observable by a given timeout or
9128 * until a given Date.
9130 * <span class="informal">Time shifts each item by some specified amount of
9131 * milliseconds.</span>
9133 * <img src="./img/delay.png" width="100%">
9135 * If the delay argument is a Number, this operator time shifts the source
9136 * Observable by that amount of time expressed in milliseconds. The relative
9137 * time intervals between the values are preserved.
9139 * If the delay argument is a Date, this operator time shifts the start of the
9140 * Observable execution until the given date occurs.
9142 * @example <caption>Delay each click by one second</caption>
9143 * var clicks = Rx.Observable.fromEvent(document, 'click');
9144 * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
9145 * delayedClicks.subscribe(x => console.log(x));
9147 * @example <caption>Delay all clicks until a future date happens</caption>
9148 * var clicks = Rx.Observable.fromEvent(document, 'click');
9149 * var date = new Date('March 15, 2050 12:00:00'); // in the future
9150 * var delayedClicks = clicks.delay(date); // click emitted only after that date
9151 * delayedClicks.subscribe(x => console.log(x));
9153 * @see {@link debounceTime}
9154 * @see {@link delayWhen}
9156 * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
9157 * a `Date` until which the emission of the source items is delayed.
9158 * @param {Scheduler} [scheduler=async] The IScheduler to use for
9159 * managing the timers that handle the time-shift for each item.
9160 * @return {Observable} An Observable that delays the emissions of the source
9161 * Observable by the specified timeout or Date.
9165 function delay(delay, scheduler) {
9166 if (scheduler === void 0) { scheduler = async_1.async; }
9167 var absoluteDelay = isDate_1.isDate(delay);
9168 var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
9169 return this.lift(new DelayOperator(delayFor, scheduler));
9171 exports.delay = delay;
9172 var DelayOperator = (function () {
9173 function DelayOperator(delay, scheduler) {
9175 this.scheduler = scheduler;
9177 DelayOperator.prototype.call = function (subscriber, source) {
9178 return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
9180 return DelayOperator;
9183 * We need this JSDoc comment for affecting ESDoc.
9185 * @extends {Ignored}
9187 var DelaySubscriber = (function (_super) {
9188 __extends(DelaySubscriber, _super);
9189 function DelaySubscriber(destination, delay, scheduler) {
9190 _super.call(this, destination);
9192 this.scheduler = scheduler;
9194 this.active = false;
9195 this.errored = false;
9197 DelaySubscriber.dispatch = function (state) {
9198 var source = state.source;
9199 var queue = source.queue;
9200 var scheduler = state.scheduler;
9201 var destination = state.destination;
9202 while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
9203 queue.shift().notification.observe(destination);
9205 if (queue.length > 0) {
9206 var delay_1 = Math.max(0, queue[0].time - scheduler.now());
9207 this.schedule(state, delay_1);
9210 source.active = false;
9213 DelaySubscriber.prototype._schedule = function (scheduler) {
9215 this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
9216 source: this, destination: this.destination, scheduler: scheduler
9219 DelaySubscriber.prototype.scheduleNotification = function (notification) {
9220 if (this.errored === true) {
9223 var scheduler = this.scheduler;
9224 var message = new DelayMessage(scheduler.now() + this.delay, notification);
9225 this.queue.push(message);
9226 if (this.active === false) {
9227 this._schedule(scheduler);
9230 DelaySubscriber.prototype._next = function (value) {
9231 this.scheduleNotification(Notification_1.Notification.createNext(value));
9233 DelaySubscriber.prototype._error = function (err) {
9234 this.errored = true;
9236 this.destination.error(err);
9238 DelaySubscriber.prototype._complete = function () {
9239 this.scheduleNotification(Notification_1.Notification.createComplete());
9241 return DelaySubscriber;
9242 }(Subscriber_1.Subscriber));
9243 var DelayMessage = (function () {
9244 function DelayMessage(time, notification) {
9246 this.notification = notification;
9248 return DelayMessage;
9251 },{"../Notification":27,"../Subscriber":35,"../scheduler/async":151,"../util/isDate":165}],115:[function(require,module,exports){
9253 var __extends = (this && this.__extends) || function (d, b) {
9254 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9255 function __() { this.constructor = d; }
9256 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9258 var OuterSubscriber_1 = require('../OuterSubscriber');
9259 var subscribeToResult_1 = require('../util/subscribeToResult');
9260 var Set_1 = require('../util/Set');
9262 * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
9264 * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
9265 * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
9266 * source observable directly with an equality check against previous values.
9268 * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
9270 * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
9271 * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
9272 * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
9273 * that the internal `Set` can be "flushed", basically clearing it of values.
9275 * @example <caption>A simple example with numbers</caption>
9276 * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
9278 * .subscribe(x => console.log(x)); // 1, 2, 3, 4
9280 * @example <caption>An example using a keySelector function</caption>
9281 * interface Person {
9286 * Observable.of<Person>(
9287 * { age: 4, name: 'Foo'},
9288 * { age: 7, name: 'Bar'},
9289 * { age: 5, name: 'Foo'})
9290 * .distinct((p: Person) => p.name)
9291 * .subscribe(x => console.log(x));
9294 * // { age: 4, name: 'Foo' }
9295 * // { age: 7, name: 'Bar' }
9297 * @see {@link distinctUntilChanged}
9298 * @see {@link distinctUntilKeyChanged}
9300 * @param {function} [keySelector] Optional function to select which value you want to check as distinct.
9301 * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.
9302 * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9306 function distinct(keySelector, flushes) {
9307 return this.lift(new DistinctOperator(keySelector, flushes));
9309 exports.distinct = distinct;
9310 var DistinctOperator = (function () {
9311 function DistinctOperator(keySelector, flushes) {
9312 this.keySelector = keySelector;
9313 this.flushes = flushes;
9315 DistinctOperator.prototype.call = function (subscriber, source) {
9316 return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
9318 return DistinctOperator;
9321 * We need this JSDoc comment for affecting ESDoc.
9323 * @extends {Ignored}
9325 var DistinctSubscriber = (function (_super) {
9326 __extends(DistinctSubscriber, _super);
9327 function DistinctSubscriber(destination, keySelector, flushes) {
9328 _super.call(this, destination);
9329 this.keySelector = keySelector;
9330 this.values = new Set_1.Set();
9332 this.add(subscribeToResult_1.subscribeToResult(this, flushes));
9335 DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9336 this.values.clear();
9338 DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
9341 DistinctSubscriber.prototype._next = function (value) {
9342 if (this.keySelector) {
9343 this._useKeySelector(value);
9346 this._finalizeNext(value, value);
9349 DistinctSubscriber.prototype._useKeySelector = function (value) {
9351 var destination = this.destination;
9353 key = this.keySelector(value);
9356 destination.error(err);
9359 this._finalizeNext(key, value);
9361 DistinctSubscriber.prototype._finalizeNext = function (key, value) {
9362 var values = this.values;
9363 if (!values.has(key)) {
9365 this.destination.next(value);
9368 return DistinctSubscriber;
9369 }(OuterSubscriber_1.OuterSubscriber));
9370 exports.DistinctSubscriber = DistinctSubscriber;
9372 },{"../OuterSubscriber":30,"../util/Set":160,"../util/subscribeToResult":172}],116:[function(require,module,exports){
9374 var __extends = (this && this.__extends) || function (d, b) {
9375 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9376 function __() { this.constructor = d; }
9377 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9379 var Subscriber_1 = require('../Subscriber');
9380 var tryCatch_1 = require('../util/tryCatch');
9381 var errorObject_1 = require('../util/errorObject');
9382 /* tslint:enable:max-line-length */
9384 * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
9386 * 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.
9388 * If a comparator function is not provided, an equality check is used by default.
9390 * @example <caption>A simple example with numbers</caption>
9391 * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
9392 * .distinctUntilChanged()
9393 * .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
9395 * @example <caption>An example using a compare function</caption>
9396 * interface Person {
9401 * Observable.of<Person>(
9402 * { age: 4, name: 'Foo'},
9403 * { age: 7, name: 'Bar'},
9404 * { age: 5, name: 'Foo'})
9405 * { age: 6, name: 'Foo'})
9406 * .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
9407 * .subscribe(x => console.log(x));
9410 * // { age: 4, name: 'Foo' }
9411 * // { age: 7, name: 'Bar' }
9412 * // { age: 5, name: 'Foo' }
9414 * @see {@link distinct}
9415 * @see {@link distinctUntilKeyChanged}
9417 * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
9418 * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9419 * @method distinctUntilChanged
9422 function distinctUntilChanged(compare, keySelector) {
9423 return this.lift(new DistinctUntilChangedOperator(compare, keySelector));
9425 exports.distinctUntilChanged = distinctUntilChanged;
9426 var DistinctUntilChangedOperator = (function () {
9427 function DistinctUntilChangedOperator(compare, keySelector) {
9428 this.compare = compare;
9429 this.keySelector = keySelector;
9431 DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
9432 return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
9434 return DistinctUntilChangedOperator;
9437 * We need this JSDoc comment for affecting ESDoc.
9439 * @extends {Ignored}
9441 var DistinctUntilChangedSubscriber = (function (_super) {
9442 __extends(DistinctUntilChangedSubscriber, _super);
9443 function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
9444 _super.call(this, destination);
9445 this.keySelector = keySelector;
9446 this.hasKey = false;
9447 if (typeof compare === 'function') {
9448 this.compare = compare;
9451 DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
9454 DistinctUntilChangedSubscriber.prototype._next = function (value) {
9455 var keySelector = this.keySelector;
9458 key = tryCatch_1.tryCatch(this.keySelector)(value);
9459 if (key === errorObject_1.errorObject) {
9460 return this.destination.error(errorObject_1.errorObject.e);
9465 result = tryCatch_1.tryCatch(this.compare)(this.key, key);
9466 if (result === errorObject_1.errorObject) {
9467 return this.destination.error(errorObject_1.errorObject.e);
9473 if (Boolean(result) === false) {
9475 this.destination.next(value);
9478 return DistinctUntilChangedSubscriber;
9479 }(Subscriber_1.Subscriber));
9481 },{"../Subscriber":35,"../util/errorObject":162,"../util/tryCatch":174}],117:[function(require,module,exports){
9483 var __extends = (this && this.__extends) || function (d, b) {
9484 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9485 function __() { this.constructor = d; }
9486 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9488 var Subscriber_1 = require('../Subscriber');
9489 /* tslint:enable:max-line-length */
9491 * Perform a side effect for every emission on the source Observable, but return
9492 * an Observable that is identical to the source.
9494 * <span class="informal">Intercepts each emission on the source and runs a
9495 * function, but returns an output which is identical to the source as long as errors don't occur.</span>
9497 * <img src="./img/do.png" width="100%">
9499 * Returns a mirrored Observable of the source Observable, but modified so that
9500 * the provided Observer is called to perform a side effect for every value,
9501 * error, and completion emitted by the source. Any errors that are thrown in
9502 * the aforementioned Observer or handlers are safely sent down the error path
9503 * of the output Observable.
9505 * This operator is useful for debugging your Observables for the correct values
9506 * or performing other side effects.
9508 * Note: this is different to a `subscribe` on the Observable. If the Observable
9509 * returned by `do` is not subscribed, the side effects specified by the
9510 * Observer will never happen. `do` therefore simply spies on existing
9511 * execution, it does not trigger an execution to happen like `subscribe` does.
9513 * @example <caption>Map every every click to the clientX position of that click, while also logging the click event</caption>
9514 * var clicks = Rx.Observable.fromEvent(document, 'click');
9515 * var positions = clicks
9516 * .do(ev => console.log(ev))
9517 * .map(ev => ev.clientX);
9518 * positions.subscribe(x => console.log(x));
9521 * @see {@link subscribe}
9523 * @param {Observer|function} [nextOrObserver] A normal Observer object or a
9524 * callback for `next`.
9525 * @param {function} [error] Callback for errors in the source.
9526 * @param {function} [complete] Callback for the completion of the source.
9527 * @return {Observable} An Observable identical to the source, but runs the
9528 * specified Observer or callback(s) for each item.
9533 function _do(nextOrObserver, error, complete) {
9534 return this.lift(new DoOperator(nextOrObserver, error, complete));
9537 var DoOperator = (function () {
9538 function DoOperator(nextOrObserver, error, complete) {
9539 this.nextOrObserver = nextOrObserver;
9541 this.complete = complete;
9543 DoOperator.prototype.call = function (subscriber, source) {
9544 return source.subscribe(new DoSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
9549 * We need this JSDoc comment for affecting ESDoc.
9551 * @extends {Ignored}
9553 var DoSubscriber = (function (_super) {
9554 __extends(DoSubscriber, _super);
9555 function DoSubscriber(destination, nextOrObserver, error, complete) {
9556 _super.call(this, destination);
9557 var safeSubscriber = new Subscriber_1.Subscriber(nextOrObserver, error, complete);
9558 safeSubscriber.syncErrorThrowable = true;
9559 this.add(safeSubscriber);
9560 this.safeSubscriber = safeSubscriber;
9562 DoSubscriber.prototype._next = function (value) {
9563 var safeSubscriber = this.safeSubscriber;
9564 safeSubscriber.next(value);
9565 if (safeSubscriber.syncErrorThrown) {
9566 this.destination.error(safeSubscriber.syncErrorValue);
9569 this.destination.next(value);
9572 DoSubscriber.prototype._error = function (err) {
9573 var safeSubscriber = this.safeSubscriber;
9574 safeSubscriber.error(err);
9575 if (safeSubscriber.syncErrorThrown) {
9576 this.destination.error(safeSubscriber.syncErrorValue);
9579 this.destination.error(err);
9582 DoSubscriber.prototype._complete = function () {
9583 var safeSubscriber = this.safeSubscriber;
9584 safeSubscriber.complete();
9585 if (safeSubscriber.syncErrorThrown) {
9586 this.destination.error(safeSubscriber.syncErrorValue);
9589 this.destination.complete();
9592 return DoSubscriber;
9593 }(Subscriber_1.Subscriber));
9595 },{"../Subscriber":35}],118:[function(require,module,exports){
9597 var __extends = (this && this.__extends) || function (d, b) {
9598 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9599 function __() { this.constructor = d; }
9600 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9602 var tryCatch_1 = require('../util/tryCatch');
9603 var errorObject_1 = require('../util/errorObject');
9604 var OuterSubscriber_1 = require('../OuterSubscriber');
9605 var subscribeToResult_1 = require('../util/subscribeToResult');
9606 /* tslint:enable:max-line-length */
9608 * Recursively projects each source value to an Observable which is merged in
9609 * the output Observable.
9611 * <span class="informal">It's similar to {@link mergeMap}, but applies the
9612 * projection function to every source value as well as every output value.
9613 * It's recursive.</span>
9615 * <img src="./img/expand.png" width="100%">
9617 * Returns an Observable that emits items based on applying a function that you
9618 * supply to each item emitted by the source Observable, where that function
9619 * returns an Observable, and then merging those resulting Observables and
9620 * emitting the results of this merger. *Expand* will re-emit on the output
9621 * Observable every source value. Then, each output value is given to the
9622 * `project` function which returns an inner Observable to be merged on the
9623 * output Observable. Those output values resulting from the projection are also
9624 * given to the `project` function to produce new output values. This is how
9625 * *expand* behaves recursively.
9627 * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
9628 * var clicks = Rx.Observable.fromEvent(document, 'click');
9629 * var powersOfTwo = clicks
9631 * .expand(x => Rx.Observable.of(2 * x).delay(1000))
9633 * powersOfTwo.subscribe(x => console.log(x));
9635 * @see {@link mergeMap}
9636 * @see {@link mergeScan}
9638 * @param {function(value: T, index: number) => Observable} project A function
9639 * that, when applied to an item emitted by the source or the output Observable,
9640 * returns an Observable.
9641 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9642 * Observables being subscribed to concurrently.
9643 * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
9644 * each projected inner Observable.
9645 * @return {Observable} An Observable that emits the source values and also
9646 * result of applying the projection function to each value emitted on the
9647 * output Observable and and merging the results of the Observables obtained
9648 * from this transformation.
9652 function expand(project, concurrent, scheduler) {
9653 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9654 if (scheduler === void 0) { scheduler = undefined; }
9655 concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
9656 return this.lift(new ExpandOperator(project, concurrent, scheduler));
9658 exports.expand = expand;
9659 var ExpandOperator = (function () {
9660 function ExpandOperator(project, concurrent, scheduler) {
9661 this.project = project;
9662 this.concurrent = concurrent;
9663 this.scheduler = scheduler;
9665 ExpandOperator.prototype.call = function (subscriber, source) {
9666 return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
9668 return ExpandOperator;
9670 exports.ExpandOperator = ExpandOperator;
9672 * We need this JSDoc comment for affecting ESDoc.
9674 * @extends {Ignored}
9676 var ExpandSubscriber = (function (_super) {
9677 __extends(ExpandSubscriber, _super);
9678 function ExpandSubscriber(destination, project, concurrent, scheduler) {
9679 _super.call(this, destination);
9680 this.project = project;
9681 this.concurrent = concurrent;
9682 this.scheduler = scheduler;
9685 this.hasCompleted = false;
9686 if (concurrent < Number.POSITIVE_INFINITY) {
9690 ExpandSubscriber.dispatch = function (arg) {
9691 var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
9692 subscriber.subscribeToProjection(result, value, index);
9694 ExpandSubscriber.prototype._next = function (value) {
9695 var destination = this.destination;
9696 if (destination.closed) {
9700 var index = this.index++;
9701 if (this.active < this.concurrent) {
9702 destination.next(value);
9703 var result = tryCatch_1.tryCatch(this.project)(value, index);
9704 if (result === errorObject_1.errorObject) {
9705 destination.error(errorObject_1.errorObject.e);
9707 else if (!this.scheduler) {
9708 this.subscribeToProjection(result, value, index);
9711 var state = { subscriber: this, result: result, value: value, index: index };
9712 this.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
9716 this.buffer.push(value);
9719 ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
9721 this.add(subscribeToResult_1.subscribeToResult(this, result, value, index));
9723 ExpandSubscriber.prototype._complete = function () {
9724 this.hasCompleted = true;
9725 if (this.hasCompleted && this.active === 0) {
9726 this.destination.complete();
9729 ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9730 this._next(innerValue);
9732 ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
9733 var buffer = this.buffer;
9734 this.remove(innerSub);
9736 if (buffer && buffer.length > 0) {
9737 this._next(buffer.shift());
9739 if (this.hasCompleted && this.active === 0) {
9740 this.destination.complete();
9743 return ExpandSubscriber;
9744 }(OuterSubscriber_1.OuterSubscriber));
9745 exports.ExpandSubscriber = ExpandSubscriber;
9747 },{"../OuterSubscriber":30,"../util/errorObject":162,"../util/subscribeToResult":172,"../util/tryCatch":174}],119:[function(require,module,exports){
9749 var __extends = (this && this.__extends) || function (d, b) {
9750 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9751 function __() { this.constructor = d; }
9752 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9754 var Subscriber_1 = require('../Subscriber');
9755 /* tslint:enable:max-line-length */
9757 * Filter items emitted by the source Observable by only emitting those that
9758 * satisfy a specified predicate.
9760 * <span class="informal">Like
9761 * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
9762 * it only emits a value from the source if it passes a criterion function.</span>
9764 * <img src="./img/filter.png" width="100%">
9766 * Similar to the well-known `Array.prototype.filter` method, this operator
9767 * takes values from the source Observable, passes them through a `predicate`
9768 * function and only emits those values that yielded `true`.
9770 * @example <caption>Emit only click events whose target was a DIV element</caption>
9771 * var clicks = Rx.Observable.fromEvent(document, 'click');
9772 * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
9773 * clicksOnDivs.subscribe(x => console.log(x));
9775 * @see {@link distinct}
9776 * @see {@link distinctUntilChanged}
9777 * @see {@link distinctUntilKeyChanged}
9778 * @see {@link ignoreElements}
9779 * @see {@link partition}
9782 * @param {function(value: T, index: number): boolean} predicate A function that
9783 * evaluates each value emitted by the source Observable. If it returns `true`,
9784 * the value is emitted, if `false` the value is not passed to the output
9785 * Observable. The `index` parameter is the number `i` for the i-th source
9786 * emission that has happened since the subscription, starting from the number
9788 * @param {any} [thisArg] An optional argument to determine the value of `this`
9789 * in the `predicate` function.
9790 * @return {Observable} An Observable of values from the source that were
9791 * allowed by the `predicate` function.
9795 function filter(predicate, thisArg) {
9796 return this.lift(new FilterOperator(predicate, thisArg));
9798 exports.filter = filter;
9799 var FilterOperator = (function () {
9800 function FilterOperator(predicate, thisArg) {
9801 this.predicate = predicate;
9802 this.thisArg = thisArg;
9804 FilterOperator.prototype.call = function (subscriber, source) {
9805 return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
9807 return FilterOperator;
9810 * We need this JSDoc comment for affecting ESDoc.
9812 * @extends {Ignored}
9814 var FilterSubscriber = (function (_super) {
9815 __extends(FilterSubscriber, _super);
9816 function FilterSubscriber(destination, predicate, thisArg) {
9817 _super.call(this, destination);
9818 this.predicate = predicate;
9819 this.thisArg = thisArg;
9821 this.predicate = predicate;
9823 // the try catch block below is left specifically for
9824 // optimization and perf reasons. a tryCatcher is not necessary here.
9825 FilterSubscriber.prototype._next = function (value) {
9828 result = this.predicate.call(this.thisArg, value, this.count++);
9831 this.destination.error(err);
9835 this.destination.next(value);
9838 return FilterSubscriber;
9839 }(Subscriber_1.Subscriber));
9841 },{"../Subscriber":35}],120:[function(require,module,exports){
9843 var __extends = (this && this.__extends) || function (d, b) {
9844 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9845 function __() { this.constructor = d; }
9846 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9848 var Subscriber_1 = require('../Subscriber');
9849 var Subscription_1 = require('../Subscription');
9851 * Returns an Observable that mirrors the source Observable, but will call a specified function when
9852 * the source terminates on complete or error.
9853 * @param {function} callback Function to be called when source terminates.
9854 * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.
9858 function _finally(callback) {
9859 return this.lift(new FinallyOperator(callback));
9861 exports._finally = _finally;
9862 var FinallyOperator = (function () {
9863 function FinallyOperator(callback) {
9864 this.callback = callback;
9866 FinallyOperator.prototype.call = function (subscriber, source) {
9867 return source.subscribe(new FinallySubscriber(subscriber, this.callback));
9869 return FinallyOperator;
9872 * We need this JSDoc comment for affecting ESDoc.
9874 * @extends {Ignored}
9876 var FinallySubscriber = (function (_super) {
9877 __extends(FinallySubscriber, _super);
9878 function FinallySubscriber(destination, callback) {
9879 _super.call(this, destination);
9880 this.add(new Subscription_1.Subscription(callback));
9882 return FinallySubscriber;
9883 }(Subscriber_1.Subscriber));
9885 },{"../Subscriber":35,"../Subscription":36}],121:[function(require,module,exports){
9887 var __extends = (this && this.__extends) || function (d, b) {
9888 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9889 function __() { this.constructor = d; }
9890 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9892 var Subscriber_1 = require('../Subscriber');
9893 var EmptyError_1 = require('../util/EmptyError');
9895 * Emits only the first value (or the first value that meets some condition)
9896 * emitted by the source Observable.
9898 * <span class="informal">Emits only the first value. Or emits only the first
9899 * value that passes some test.</span>
9901 * <img src="./img/first.png" width="100%">
9903 * If called with no arguments, `first` emits the first value of the source
9904 * Observable, then completes. If called with a `predicate` function, `first`
9905 * emits the first value of the source that matches the specified condition. It
9906 * may also take a `resultSelector` function to produce the output value from
9907 * the input value, and a `defaultValue` to emit in case the source completes
9908 * before it is able to emit a valid value. Throws an error if `defaultValue`
9909 * was not provided and a matching element is not found.
9911 * @example <caption>Emit only the first click that happens on the DOM</caption>
9912 * var clicks = Rx.Observable.fromEvent(document, 'click');
9913 * var result = clicks.first();
9914 * result.subscribe(x => console.log(x));
9916 * @example <caption>Emits the first click that happens on a DIV</caption>
9917 * var clicks = Rx.Observable.fromEvent(document, 'click');
9918 * var result = clicks.first(ev => ev.target.tagName === 'DIV');
9919 * result.subscribe(x => console.log(x));
9921 * @see {@link filter}
9925 * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
9926 * callback if the Observable completes before any `next` notification was sent.
9928 * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
9929 * An optional function called with each item to test for condition matching.
9930 * @param {function(value: T, index: number): R} [resultSelector] A function to
9931 * produce the value on the output Observable based on the values
9932 * and the indices of the source Observable. The arguments passed to this
9934 * - `value`: the value that was emitted on the source.
9935 * - `index`: the "index" of the value from the source.
9936 * @param {R} [defaultValue] The default value emitted in case no valid value
9937 * was found on the source.
9938 * @return {Observable<T|R>} An Observable of the first item that matches the
9943 function first(predicate, resultSelector, defaultValue) {
9944 return this.lift(new FirstOperator(predicate, resultSelector, defaultValue, this));
9946 exports.first = first;
9947 var FirstOperator = (function () {
9948 function FirstOperator(predicate, resultSelector, defaultValue, source) {
9949 this.predicate = predicate;
9950 this.resultSelector = resultSelector;
9951 this.defaultValue = defaultValue;
9952 this.source = source;
9954 FirstOperator.prototype.call = function (observer, source) {
9955 return source.subscribe(new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
9957 return FirstOperator;
9960 * We need this JSDoc comment for affecting ESDoc.
9962 * @extends {Ignored}
9964 var FirstSubscriber = (function (_super) {
9965 __extends(FirstSubscriber, _super);
9966 function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) {
9967 _super.call(this, destination);
9968 this.predicate = predicate;
9969 this.resultSelector = resultSelector;
9970 this.defaultValue = defaultValue;
9971 this.source = source;
9973 this.hasCompleted = false;
9974 this._emitted = false;
9976 FirstSubscriber.prototype._next = function (value) {
9977 var index = this.index++;
9978 if (this.predicate) {
9979 this._tryPredicate(value, index);
9982 this._emit(value, index);
9985 FirstSubscriber.prototype._tryPredicate = function (value, index) {
9988 result = this.predicate(value, index, this.source);
9991 this.destination.error(err);
9995 this._emit(value, index);
9998 FirstSubscriber.prototype._emit = function (value, index) {
9999 if (this.resultSelector) {
10000 this._tryResultSelector(value, index);
10003 this._emitFinal(value);
10005 FirstSubscriber.prototype._tryResultSelector = function (value, index) {
10008 result = this.resultSelector(value, index);
10011 this.destination.error(err);
10014 this._emitFinal(result);
10016 FirstSubscriber.prototype._emitFinal = function (value) {
10017 var destination = this.destination;
10018 if (!this._emitted) {
10019 this._emitted = true;
10020 destination.next(value);
10021 destination.complete();
10022 this.hasCompleted = true;
10025 FirstSubscriber.prototype._complete = function () {
10026 var destination = this.destination;
10027 if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') {
10028 destination.next(this.defaultValue);
10029 destination.complete();
10031 else if (!this.hasCompleted) {
10032 destination.error(new EmptyError_1.EmptyError);
10035 return FirstSubscriber;
10036 }(Subscriber_1.Subscriber));
10038 },{"../Subscriber":35,"../util/EmptyError":158}],122:[function(require,module,exports){
10040 var __extends = (this && this.__extends) || function (d, b) {
10041 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10042 function __() { this.constructor = d; }
10043 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10045 var Subscriber_1 = require('../Subscriber');
10046 var EmptyError_1 = require('../util/EmptyError');
10047 /* tslint:enable:max-line-length */
10049 * Returns an Observable that emits only the last item emitted by the source Observable.
10050 * It optionally takes a predicate function as a parameter, in which case, rather than emitting
10051 * the last item from the source Observable, the resulting Observable will emit the last item
10052 * from the source Observable that satisfies the predicate.
10054 * <img src="./img/last.png" width="100%">
10056 * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
10057 * callback if the Observable completes before any `next` notification was sent.
10058 * @param {function} predicate - The condition any source emitted item has to satisfy.
10059 * @return {Observable} An Observable that emits only the last item satisfying the given condition
10060 * from the source, or an NoSuchElementException if no such items are emitted.
10061 * @throws - Throws if no items that match the predicate are emitted by the source Observable.
10063 * @owner Observable
10065 function last(predicate, resultSelector, defaultValue) {
10066 return this.lift(new LastOperator(predicate, resultSelector, defaultValue, this));
10068 exports.last = last;
10069 var LastOperator = (function () {
10070 function LastOperator(predicate, resultSelector, defaultValue, source) {
10071 this.predicate = predicate;
10072 this.resultSelector = resultSelector;
10073 this.defaultValue = defaultValue;
10074 this.source = source;
10076 LastOperator.prototype.call = function (observer, source) {
10077 return source.subscribe(new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
10079 return LastOperator;
10082 * We need this JSDoc comment for affecting ESDoc.
10084 * @extends {Ignored}
10086 var LastSubscriber = (function (_super) {
10087 __extends(LastSubscriber, _super);
10088 function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) {
10089 _super.call(this, destination);
10090 this.predicate = predicate;
10091 this.resultSelector = resultSelector;
10092 this.defaultValue = defaultValue;
10093 this.source = source;
10094 this.hasValue = false;
10096 if (typeof defaultValue !== 'undefined') {
10097 this.lastValue = defaultValue;
10098 this.hasValue = true;
10101 LastSubscriber.prototype._next = function (value) {
10102 var index = this.index++;
10103 if (this.predicate) {
10104 this._tryPredicate(value, index);
10107 if (this.resultSelector) {
10108 this._tryResultSelector(value, index);
10111 this.lastValue = value;
10112 this.hasValue = true;
10115 LastSubscriber.prototype._tryPredicate = function (value, index) {
10118 result = this.predicate(value, index, this.source);
10121 this.destination.error(err);
10125 if (this.resultSelector) {
10126 this._tryResultSelector(value, index);
10129 this.lastValue = value;
10130 this.hasValue = true;
10133 LastSubscriber.prototype._tryResultSelector = function (value, index) {
10136 result = this.resultSelector(value, index);
10139 this.destination.error(err);
10142 this.lastValue = result;
10143 this.hasValue = true;
10145 LastSubscriber.prototype._complete = function () {
10146 var destination = this.destination;
10147 if (this.hasValue) {
10148 destination.next(this.lastValue);
10149 destination.complete();
10152 destination.error(new EmptyError_1.EmptyError);
10155 return LastSubscriber;
10156 }(Subscriber_1.Subscriber));
10158 },{"../Subscriber":35,"../util/EmptyError":158}],123:[function(require,module,exports){
10160 var __extends = (this && this.__extends) || function (d, b) {
10161 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10162 function __() { this.constructor = d; }
10163 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10165 var Subscriber_1 = require('../Subscriber');
10167 * Applies a given `project` function to each value emitted by the source
10168 * Observable, and emits the resulting values as an Observable.
10170 * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
10171 * it passes each source value through a transformation function to get
10172 * corresponding output values.</span>
10174 * <img src="./img/map.png" width="100%">
10176 * Similar to the well known `Array.prototype.map` function, this operator
10177 * applies a projection to each value and emits that projection in the output
10180 * @example <caption>Map every click to the clientX position of that click</caption>
10181 * var clicks = Rx.Observable.fromEvent(document, 'click');
10182 * var positions = clicks.map(ev => ev.clientX);
10183 * positions.subscribe(x => console.log(x));
10185 * @see {@link mapTo}
10186 * @see {@link pluck}
10188 * @param {function(value: T, index: number): R} project The function to apply
10189 * to each `value` emitted by the source Observable. The `index` parameter is
10190 * the number `i` for the i-th emission that has happened since the
10191 * subscription, starting from the number `0`.
10192 * @param {any} [thisArg] An optional argument to define what `this` is in the
10193 * `project` function.
10194 * @return {Observable<R>} An Observable that emits the values from the source
10195 * Observable transformed by the given `project` function.
10197 * @owner Observable
10199 function map(project, thisArg) {
10200 if (typeof project !== 'function') {
10201 throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
10203 return this.lift(new MapOperator(project, thisArg));
10206 var MapOperator = (function () {
10207 function MapOperator(project, thisArg) {
10208 this.project = project;
10209 this.thisArg = thisArg;
10211 MapOperator.prototype.call = function (subscriber, source) {
10212 return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
10214 return MapOperator;
10216 exports.MapOperator = MapOperator;
10218 * We need this JSDoc comment for affecting ESDoc.
10220 * @extends {Ignored}
10222 var MapSubscriber = (function (_super) {
10223 __extends(MapSubscriber, _super);
10224 function MapSubscriber(destination, project, thisArg) {
10225 _super.call(this, destination);
10226 this.project = project;
10228 this.thisArg = thisArg || this;
10230 // NOTE: This looks unoptimized, but it's actually purposefully NOT
10231 // using try/catch optimizations.
10232 MapSubscriber.prototype._next = function (value) {
10235 result = this.project.call(this.thisArg, value, this.count++);
10238 this.destination.error(err);
10241 this.destination.next(result);
10243 return MapSubscriber;
10244 }(Subscriber_1.Subscriber));
10246 },{"../Subscriber":35}],124:[function(require,module,exports){
10248 var Observable_1 = require('../Observable');
10249 var ArrayObservable_1 = require('../observable/ArrayObservable');
10250 var mergeAll_1 = require('./mergeAll');
10251 var isScheduler_1 = require('../util/isScheduler');
10252 /* tslint:enable:max-line-length */
10254 * Creates an output Observable which concurrently emits all values from every
10255 * given input Observable.
10257 * <span class="informal">Flattens multiple Observables together by blending
10258 * their values into one Observable.</span>
10260 * <img src="./img/merge.png" width="100%">
10262 * `merge` subscribes to each given input Observable (either the source or an
10263 * Observable given as argument), and simply forwards (without doing any
10264 * transformation) all the values from all the input Observables to the output
10265 * Observable. The output Observable only completes once all input Observables
10266 * have completed. Any error delivered by an input Observable will be immediately
10267 * emitted on the output Observable.
10269 * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
10270 * var clicks = Rx.Observable.fromEvent(document, 'click');
10271 * var timer = Rx.Observable.interval(1000);
10272 * var clicksOrTimer = clicks.merge(timer);
10273 * clicksOrTimer.subscribe(x => console.log(x));
10275 * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
10276 * var timer1 = Rx.Observable.interval(1000).take(10);
10277 * var timer2 = Rx.Observable.interval(2000).take(6);
10278 * var timer3 = Rx.Observable.interval(500).take(10);
10279 * var concurrent = 2; // the argument
10280 * var merged = timer1.merge(timer2, timer3, concurrent);
10281 * merged.subscribe(x => console.log(x));
10283 * @see {@link mergeAll}
10284 * @see {@link mergeMap}
10285 * @see {@link mergeMapTo}
10286 * @see {@link mergeScan}
10288 * @param {ObservableInput} other An input Observable to merge with the source
10289 * Observable. More than one input Observables may be given as argument.
10290 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10291 * Observables being subscribed to concurrently.
10292 * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
10293 * concurrency of input Observables.
10294 * @return {Observable} An Observable that emits items that are the result of
10295 * every input Observable.
10297 * @owner Observable
10300 var observables = [];
10301 for (var _i = 0; _i < arguments.length; _i++) {
10302 observables[_i - 0] = arguments[_i];
10304 return this.lift.call(mergeStatic.apply(void 0, [this].concat(observables)));
10306 exports.merge = merge;
10307 /* tslint:enable:max-line-length */
10309 * Creates an output Observable which concurrently emits all values from every
10310 * given input Observable.
10312 * <span class="informal">Flattens multiple Observables together by blending
10313 * their values into one Observable.</span>
10315 * <img src="./img/merge.png" width="100%">
10317 * `merge` subscribes to each given input Observable (as arguments), and simply
10318 * forwards (without doing any transformation) all the values from all the input
10319 * Observables to the output Observable. The output Observable only completes
10320 * once all input Observables have completed. Any error delivered by an input
10321 * Observable will be immediately emitted on the output Observable.
10323 * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
10324 * var clicks = Rx.Observable.fromEvent(document, 'click');
10325 * var timer = Rx.Observable.interval(1000);
10326 * var clicksOrTimer = Rx.Observable.merge(clicks, timer);
10327 * clicksOrTimer.subscribe(x => console.log(x));
10329 * // Results in the following:
10330 * // timer will emit ascending values, one every second(1000ms) to console
10331 * // clicks logs MouseEvents to console everytime the "document" is clicked
10332 * // Since the two streams are merged you see these happening
10333 * // as they occur.
10335 * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
10336 * var timer1 = Rx.Observable.interval(1000).take(10);
10337 * var timer2 = Rx.Observable.interval(2000).take(6);
10338 * var timer3 = Rx.Observable.interval(500).take(10);
10339 * var concurrent = 2; // the argument
10340 * var merged = Rx.Observable.merge(timer1, timer2, timer3, concurrent);
10341 * merged.subscribe(x => console.log(x));
10343 * // Results in the following:
10344 * // - First timer1 and timer2 will run concurrently
10345 * // - timer1 will emit a value every 1000ms for 10 iterations
10346 * // - timer2 will emit a value every 2000ms for 6 iterations
10347 * // - after timer1 hits it's max iteration, timer2 will
10348 * // continue, and timer3 will start to run concurrently with timer2
10349 * // - when timer2 hits it's max iteration it terminates, and
10350 * // timer3 will continue to emit a value every 500ms until it is complete
10352 * @see {@link mergeAll}
10353 * @see {@link mergeMap}
10354 * @see {@link mergeMapTo}
10355 * @see {@link mergeScan}
10357 * @param {...ObservableInput} observables Input Observables to merge together.
10358 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10359 * Observables being subscribed to concurrently.
10360 * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
10361 * concurrency of input Observables.
10362 * @return {Observable} an Observable that emits items that are the result of
10363 * every input Observable.
10366 * @owner Observable
10368 function mergeStatic() {
10369 var observables = [];
10370 for (var _i = 0; _i < arguments.length; _i++) {
10371 observables[_i - 0] = arguments[_i];
10373 var concurrent = Number.POSITIVE_INFINITY;
10374 var scheduler = null;
10375 var last = observables[observables.length - 1];
10376 if (isScheduler_1.isScheduler(last)) {
10377 scheduler = observables.pop();
10378 if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
10379 concurrent = observables.pop();
10382 else if (typeof last === 'number') {
10383 concurrent = observables.pop();
10385 if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
10386 return observables[0];
10388 return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(concurrent));
10390 exports.mergeStatic = mergeStatic;
10392 },{"../Observable":28,"../observable/ArrayObservable":85,"../util/isScheduler":170,"./mergeAll":125}],125:[function(require,module,exports){
10394 var __extends = (this && this.__extends) || function (d, b) {
10395 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10396 function __() { this.constructor = d; }
10397 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10399 var OuterSubscriber_1 = require('../OuterSubscriber');
10400 var subscribeToResult_1 = require('../util/subscribeToResult');
10402 * Converts a higher-order Observable into a first-order Observable which
10403 * concurrently delivers all values that are emitted on the inner Observables.
10405 * <span class="informal">Flattens an Observable-of-Observables.</span>
10407 * <img src="./img/mergeAll.png" width="100%">
10409 * `mergeAll` subscribes to an Observable that emits Observables, also known as
10410 * a higher-order Observable. Each time it observes one of these emitted inner
10411 * Observables, it subscribes to that and delivers all the values from the
10412 * inner Observable on the output Observable. The output Observable only
10413 * completes once all inner Observables have completed. Any error delivered by
10414 * a inner Observable will be immediately emitted on the output Observable.
10416 * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
10417 * var clicks = Rx.Observable.fromEvent(document, 'click');
10418 * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
10419 * var firstOrder = higherOrder.mergeAll();
10420 * firstOrder.subscribe(x => console.log(x));
10422 * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
10423 * var clicks = Rx.Observable.fromEvent(document, 'click');
10424 * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
10425 * var firstOrder = higherOrder.mergeAll(2);
10426 * firstOrder.subscribe(x => console.log(x));
10428 * @see {@link combineAll}
10429 * @see {@link concatAll}
10430 * @see {@link exhaust}
10431 * @see {@link merge}
10432 * @see {@link mergeMap}
10433 * @see {@link mergeMapTo}
10434 * @see {@link mergeScan}
10435 * @see {@link switch}
10436 * @see {@link zipAll}
10438 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
10439 * Observables being subscribed to concurrently.
10440 * @return {Observable} An Observable that emits values coming from all the
10441 * inner Observables emitted by the source Observable.
10443 * @owner Observable
10445 function mergeAll(concurrent) {
10446 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10447 return this.lift(new MergeAllOperator(concurrent));
10449 exports.mergeAll = mergeAll;
10450 var MergeAllOperator = (function () {
10451 function MergeAllOperator(concurrent) {
10452 this.concurrent = concurrent;
10454 MergeAllOperator.prototype.call = function (observer, source) {
10455 return source.subscribe(new MergeAllSubscriber(observer, this.concurrent));
10457 return MergeAllOperator;
10459 exports.MergeAllOperator = MergeAllOperator;
10461 * We need this JSDoc comment for affecting ESDoc.
10463 * @extends {Ignored}
10465 var MergeAllSubscriber = (function (_super) {
10466 __extends(MergeAllSubscriber, _super);
10467 function MergeAllSubscriber(destination, concurrent) {
10468 _super.call(this, destination);
10469 this.concurrent = concurrent;
10470 this.hasCompleted = false;
10474 MergeAllSubscriber.prototype._next = function (observable) {
10475 if (this.active < this.concurrent) {
10477 this.add(subscribeToResult_1.subscribeToResult(this, observable));
10480 this.buffer.push(observable);
10483 MergeAllSubscriber.prototype._complete = function () {
10484 this.hasCompleted = true;
10485 if (this.active === 0 && this.buffer.length === 0) {
10486 this.destination.complete();
10489 MergeAllSubscriber.prototype.notifyComplete = function (innerSub) {
10490 var buffer = this.buffer;
10491 this.remove(innerSub);
10493 if (buffer.length > 0) {
10494 this._next(buffer.shift());
10496 else if (this.active === 0 && this.hasCompleted) {
10497 this.destination.complete();
10500 return MergeAllSubscriber;
10501 }(OuterSubscriber_1.OuterSubscriber));
10502 exports.MergeAllSubscriber = MergeAllSubscriber;
10504 },{"../OuterSubscriber":30,"../util/subscribeToResult":172}],126:[function(require,module,exports){
10506 var __extends = (this && this.__extends) || function (d, b) {
10507 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10508 function __() { this.constructor = d; }
10509 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10511 var subscribeToResult_1 = require('../util/subscribeToResult');
10512 var OuterSubscriber_1 = require('../OuterSubscriber');
10513 /* tslint:enable:max-line-length */
10515 * Projects each source value to an Observable which is merged in the output
10518 * <span class="informal">Maps each value to an Observable, then flattens all of
10519 * these inner Observables using {@link mergeAll}.</span>
10521 * <img src="./img/mergeMap.png" width="100%">
10523 * Returns an Observable that emits items based on applying a function that you
10524 * supply to each item emitted by the source Observable, where that function
10525 * returns an Observable, and then merging those resulting Observables and
10526 * emitting the results of this merger.
10528 * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
10529 * var letters = Rx.Observable.of('a', 'b', 'c');
10530 * var result = letters.mergeMap(x =>
10531 * Rx.Observable.interval(1000).map(i => x+i)
10533 * result.subscribe(x => console.log(x));
10535 * // Results in the following:
10542 * // continues to list a,b,c with respective ascending integers
10544 * @see {@link concatMap}
10545 * @see {@link exhaustMap}
10546 * @see {@link merge}
10547 * @see {@link mergeAll}
10548 * @see {@link mergeMapTo}
10549 * @see {@link mergeScan}
10550 * @see {@link switchMap}
10552 * @param {function(value: T, ?index: number): ObservableInput} project A function
10553 * that, when applied to an item emitted by the source Observable, returns an
10555 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
10556 * A function to produce the value on the output Observable based on the values
10557 * and the indices of the source (outer) emission and the inner Observable
10558 * emission. The arguments passed to this function are:
10559 * - `outerValue`: the value that came from the source
10560 * - `innerValue`: the value that came from the projected Observable
10561 * - `outerIndex`: the "index" of the value that came from the source
10562 * - `innerIndex`: the "index" of the value from the projected Observable
10563 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10564 * Observables being subscribed to concurrently.
10565 * @return {Observable} An Observable that emits the result of applying the
10566 * projection function (and the optional `resultSelector`) to each item emitted
10567 * by the source Observable and merging the results of the Observables obtained
10568 * from this transformation.
10570 * @owner Observable
10572 function mergeMap(project, resultSelector, concurrent) {
10573 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10574 if (typeof resultSelector === 'number') {
10575 concurrent = resultSelector;
10576 resultSelector = null;
10578 return this.lift(new MergeMapOperator(project, resultSelector, concurrent));
10580 exports.mergeMap = mergeMap;
10581 var MergeMapOperator = (function () {
10582 function MergeMapOperator(project, resultSelector, concurrent) {
10583 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10584 this.project = project;
10585 this.resultSelector = resultSelector;
10586 this.concurrent = concurrent;
10588 MergeMapOperator.prototype.call = function (observer, source) {
10589 return source.subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent));
10591 return MergeMapOperator;
10593 exports.MergeMapOperator = MergeMapOperator;
10595 * We need this JSDoc comment for affecting ESDoc.
10597 * @extends {Ignored}
10599 var MergeMapSubscriber = (function (_super) {
10600 __extends(MergeMapSubscriber, _super);
10601 function MergeMapSubscriber(destination, project, resultSelector, concurrent) {
10602 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10603 _super.call(this, destination);
10604 this.project = project;
10605 this.resultSelector = resultSelector;
10606 this.concurrent = concurrent;
10607 this.hasCompleted = false;
10612 MergeMapSubscriber.prototype._next = function (value) {
10613 if (this.active < this.concurrent) {
10614 this._tryNext(value);
10617 this.buffer.push(value);
10620 MergeMapSubscriber.prototype._tryNext = function (value) {
10622 var index = this.index++;
10624 result = this.project(value, index);
10627 this.destination.error(err);
10631 this._innerSub(result, value, index);
10633 MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
10634 this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index));
10636 MergeMapSubscriber.prototype._complete = function () {
10637 this.hasCompleted = true;
10638 if (this.active === 0 && this.buffer.length === 0) {
10639 this.destination.complete();
10642 MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10643 if (this.resultSelector) {
10644 this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex);
10647 this.destination.next(innerValue);
10650 MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
10653 result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
10656 this.destination.error(err);
10659 this.destination.next(result);
10661 MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
10662 var buffer = this.buffer;
10663 this.remove(innerSub);
10665 if (buffer.length > 0) {
10666 this._next(buffer.shift());
10668 else if (this.active === 0 && this.hasCompleted) {
10669 this.destination.complete();
10672 return MergeMapSubscriber;
10673 }(OuterSubscriber_1.OuterSubscriber));
10674 exports.MergeMapSubscriber = MergeMapSubscriber;
10676 },{"../OuterSubscriber":30,"../util/subscribeToResult":172}],127:[function(require,module,exports){
10678 var ConnectableObservable_1 = require('../observable/ConnectableObservable');
10679 /* tslint:enable:max-line-length */
10681 * Returns an Observable that emits the results of invoking a specified selector on items
10682 * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.
10684 * <img src="./img/multicast.png" width="100%">
10686 * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through
10687 * which the source sequence's elements will be multicast to the selector function
10688 * or Subject to push source elements into.
10689 * @param {Function} [selector] - Optional selector function that can use the multicasted source stream
10690 * as many times as needed, without causing multiple subscriptions to the source stream.
10691 * Subscribers to the given source will receive all notifications of the source from the
10692 * time of the subscription forward.
10693 * @return {Observable} An Observable that emits the results of invoking the selector
10694 * on the items emitted by a `ConnectableObservable` that shares a single subscription to
10695 * the underlying stream.
10696 * @method multicast
10697 * @owner Observable
10699 function multicast(subjectOrSubjectFactory, selector) {
10700 var subjectFactory;
10701 if (typeof subjectOrSubjectFactory === 'function') {
10702 subjectFactory = subjectOrSubjectFactory;
10705 subjectFactory = function subjectFactory() {
10706 return subjectOrSubjectFactory;
10709 if (typeof selector === 'function') {
10710 return this.lift(new MulticastOperator(subjectFactory, selector));
10712 var connectable = Object.create(this, ConnectableObservable_1.connectableObservableDescriptor);
10713 connectable.source = this;
10714 connectable.subjectFactory = subjectFactory;
10715 return connectable;
10717 exports.multicast = multicast;
10718 var MulticastOperator = (function () {
10719 function MulticastOperator(subjectFactory, selector) {
10720 this.subjectFactory = subjectFactory;
10721 this.selector = selector;
10723 MulticastOperator.prototype.call = function (subscriber, source) {
10724 var selector = this.selector;
10725 var subject = this.subjectFactory();
10726 var subscription = selector(subject).subscribe(subscriber);
10727 subscription.add(source.subscribe(subject));
10728 return subscription;
10730 return MulticastOperator;
10732 exports.MulticastOperator = MulticastOperator;
10734 },{"../observable/ConnectableObservable":86}],128:[function(require,module,exports){
10736 var __extends = (this && this.__extends) || function (d, b) {
10737 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10738 function __() { this.constructor = d; }
10739 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10741 var Subscriber_1 = require('../Subscriber');
10742 var Notification_1 = require('../Notification');
10745 * Re-emits all notifications from source Observable with specified scheduler.
10747 * <span class="informal">Ensure a specific scheduler is used, from outside of an Observable.</span>
10749 * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule
10750 * notifications emitted by the source Observable. It might be useful, if you do not have control over
10751 * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless.
10753 * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable,
10754 * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal
10755 * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits
10756 * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`.
10757 * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split
10758 * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source
10759 * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a
10760 * little bit more, to ensure that they are emitted at expected moments.
10762 * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications
10763 * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn`
10764 * will delay all notifications - including error notifications - while `delay` will pass through error
10765 * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator
10766 * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used
10767 * for notification emissions in general.
10769 * @example <caption>Ensure values in subscribe are called just before browser repaint.</caption>
10770 * const intervals = Rx.Observable.interval(10); // Intervals are scheduled
10771 * // with async scheduler by default...
10774 * .observeOn(Rx.Scheduler.animationFrame) // ...but we will observe on animationFrame
10775 * .subscribe(val => { // scheduler to ensure smooth animation.
10776 * someDiv.style.height = val + 'px';
10779 * @see {@link delay}
10781 * @param {IScheduler} scheduler Scheduler that will be used to reschedule notifications from source Observable.
10782 * @param {number} [delay] Number of milliseconds that states with what delay every notification should be rescheduled.
10783 * @return {Observable<T>} Observable that emits the same notifications as the source Observable,
10784 * but with provided scheduler.
10786 * @method observeOn
10787 * @owner Observable
10789 function observeOn(scheduler, delay) {
10790 if (delay === void 0) { delay = 0; }
10791 return this.lift(new ObserveOnOperator(scheduler, delay));
10793 exports.observeOn = observeOn;
10794 var ObserveOnOperator = (function () {
10795 function ObserveOnOperator(scheduler, delay) {
10796 if (delay === void 0) { delay = 0; }
10797 this.scheduler = scheduler;
10798 this.delay = delay;
10800 ObserveOnOperator.prototype.call = function (subscriber, source) {
10801 return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
10803 return ObserveOnOperator;
10805 exports.ObserveOnOperator = ObserveOnOperator;
10807 * We need this JSDoc comment for affecting ESDoc.
10809 * @extends {Ignored}
10811 var ObserveOnSubscriber = (function (_super) {
10812 __extends(ObserveOnSubscriber, _super);
10813 function ObserveOnSubscriber(destination, scheduler, delay) {
10814 if (delay === void 0) { delay = 0; }
10815 _super.call(this, destination);
10816 this.scheduler = scheduler;
10817 this.delay = delay;
10819 ObserveOnSubscriber.dispatch = function (arg) {
10820 var notification = arg.notification, destination = arg.destination;
10821 notification.observe(destination);
10822 this.unsubscribe();
10824 ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
10825 this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
10827 ObserveOnSubscriber.prototype._next = function (value) {
10828 this.scheduleMessage(Notification_1.Notification.createNext(value));
10830 ObserveOnSubscriber.prototype._error = function (err) {
10831 this.scheduleMessage(Notification_1.Notification.createError(err));
10833 ObserveOnSubscriber.prototype._complete = function () {
10834 this.scheduleMessage(Notification_1.Notification.createComplete());
10836 return ObserveOnSubscriber;
10837 }(Subscriber_1.Subscriber));
10838 exports.ObserveOnSubscriber = ObserveOnSubscriber;
10839 var ObserveOnMessage = (function () {
10840 function ObserveOnMessage(notification, destination) {
10841 this.notification = notification;
10842 this.destination = destination;
10844 return ObserveOnMessage;
10846 exports.ObserveOnMessage = ObserveOnMessage;
10848 },{"../Notification":27,"../Subscriber":35}],129:[function(require,module,exports){
10850 var __extends = (this && this.__extends) || function (d, b) {
10851 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10852 function __() { this.constructor = d; }
10853 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10855 var Subscriber_1 = require('../Subscriber');
10857 * Groups pairs of consecutive emissions together and emits them as an array of
10860 * <span class="informal">Puts the current value and previous value together as
10861 * an array, and emits that.</span>
10863 * <img src="./img/pairwise.png" width="100%">
10865 * The Nth emission from the source Observable will cause the output Observable
10866 * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
10867 * pair. For this reason, `pairwise` emits on the second and subsequent
10868 * emissions from the source Observable, but not on the first emission, because
10869 * there is no previous value in that case.
10871 * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
10872 * var clicks = Rx.Observable.fromEvent(document, 'click');
10873 * var pairs = clicks.pairwise();
10874 * var distance = pairs.map(pair => {
10875 * var x0 = pair[0].clientX;
10876 * var y0 = pair[0].clientY;
10877 * var x1 = pair[1].clientX;
10878 * var y1 = pair[1].clientY;
10879 * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
10881 * distance.subscribe(x => console.log(x));
10883 * @see {@link buffer}
10884 * @see {@link bufferCount}
10886 * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
10887 * consecutive values from the source Observable.
10889 * @owner Observable
10891 function pairwise() {
10892 return this.lift(new PairwiseOperator());
10894 exports.pairwise = pairwise;
10895 var PairwiseOperator = (function () {
10896 function PairwiseOperator() {
10898 PairwiseOperator.prototype.call = function (subscriber, source) {
10899 return source.subscribe(new PairwiseSubscriber(subscriber));
10901 return PairwiseOperator;
10904 * We need this JSDoc comment for affecting ESDoc.
10906 * @extends {Ignored}
10908 var PairwiseSubscriber = (function (_super) {
10909 __extends(PairwiseSubscriber, _super);
10910 function PairwiseSubscriber(destination) {
10911 _super.call(this, destination);
10912 this.hasPrev = false;
10914 PairwiseSubscriber.prototype._next = function (value) {
10915 if (this.hasPrev) {
10916 this.destination.next([this.prev, value]);
10919 this.hasPrev = true;
10923 return PairwiseSubscriber;
10924 }(Subscriber_1.Subscriber));
10926 },{"../Subscriber":35}],130:[function(require,module,exports){
10928 var map_1 = require('./map');
10930 * Maps each source value (an object) to its specified nested property.
10932 * <span class="informal">Like {@link map}, but meant only for picking one of
10933 * the nested properties of every emitted object.</span>
10935 * <img src="./img/pluck.png" width="100%">
10937 * Given a list of strings describing a path to an object property, retrieves
10938 * the value of a specified nested property from all values in the source
10939 * Observable. If a property can't be resolved, it will return `undefined` for
10942 * @example <caption>Map every every click to the tagName of the clicked target element</caption>
10943 * var clicks = Rx.Observable.fromEvent(document, 'click');
10944 * var tagNames = clicks.pluck('target', 'tagName');
10945 * tagNames.subscribe(x => console.log(x));
10949 * @param {...string} properties The nested properties to pluck from each source
10950 * value (an object).
10951 * @return {Observable} A new Observable of property values from the source values.
10953 * @owner Observable
10956 var properties = [];
10957 for (var _i = 0; _i < arguments.length; _i++) {
10958 properties[_i - 0] = arguments[_i];
10960 var length = properties.length;
10961 if (length === 0) {
10962 throw new Error('list of properties cannot be empty.');
10964 return map_1.map.call(this, plucker(properties, length));
10966 exports.pluck = pluck;
10967 function plucker(props, length) {
10968 var mapper = function (x) {
10969 var currentProp = x;
10970 for (var i = 0; i < length; i++) {
10971 var p = currentProp[props[i]];
10972 if (typeof p !== 'undefined') {
10979 return currentProp;
10984 },{"./map":123}],131:[function(require,module,exports){
10986 var Subject_1 = require('../Subject');
10987 var multicast_1 = require('./multicast');
10988 /* tslint:enable:max-line-length */
10990 * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
10991 * before it begins emitting items to those Observers that have subscribed to it.
10993 * <img src="./img/publish.png" width="100%">
10995 * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
10996 * as needed, without causing multiple subscriptions to the source sequence.
10997 * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
10998 * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
11000 * @owner Observable
11002 function publish(selector) {
11003 return selector ? multicast_1.multicast.call(this, function () { return new Subject_1.Subject(); }, selector) :
11004 multicast_1.multicast.call(this, new Subject_1.Subject());
11006 exports.publish = publish;
11008 },{"../Subject":33,"./multicast":127}],132:[function(require,module,exports){
11010 var ReplaySubject_1 = require('../ReplaySubject');
11011 var multicast_1 = require('./multicast');
11013 * @param bufferSize
11014 * @param windowTime
11016 * @return {ConnectableObservable<T>}
11017 * @method publishReplay
11018 * @owner Observable
11020 function publishReplay(bufferSize, windowTime, scheduler) {
11021 if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
11022 if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
11023 return multicast_1.multicast.call(this, new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler));
11025 exports.publishReplay = publishReplay;
11027 },{"../ReplaySubject":31,"./multicast":127}],133:[function(require,module,exports){
11029 var __extends = (this && this.__extends) || function (d, b) {
11030 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11031 function __() { this.constructor = d; }
11032 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11034 var Subscriber_1 = require('../Subscriber');
11035 /* tslint:enable:max-line-length */
11037 * Applies an accumulator function over the source Observable, and returns each
11038 * intermediate result, with an optional seed value.
11040 * <span class="informal">It's like {@link reduce}, but emits the current
11041 * accumulation whenever the source emits a value.</span>
11043 * <img src="./img/scan.png" width="100%">
11045 * Combines together all values emitted on the source, using an accumulator
11046 * function that knows how to join a new source value into the accumulation from
11047 * the past. Is similar to {@link reduce}, but emits the intermediate
11050 * Returns an Observable that applies a specified `accumulator` function to each
11051 * item emitted by the source Observable. If a `seed` value is specified, then
11052 * that value will be used as the initial value for the accumulator. If no seed
11053 * value is specified, the first item of the source is used as the seed.
11055 * @example <caption>Count the number of click events</caption>
11056 * var clicks = Rx.Observable.fromEvent(document, 'click');
11057 * var ones = clicks.mapTo(1);
11059 * var count = ones.scan((acc, one) => acc + one, seed);
11060 * count.subscribe(x => console.log(x));
11062 * @see {@link expand}
11063 * @see {@link mergeScan}
11064 * @see {@link reduce}
11066 * @param {function(acc: R, value: T, index: number): R} accumulator
11067 * The accumulator function called on each source value.
11068 * @param {T|R} [seed] The initial accumulation value.
11069 * @return {Observable<R>} An observable of the accumulated values.
11071 * @owner Observable
11073 function scan(accumulator, seed) {
11074 var hasSeed = false;
11075 // providing a seed of `undefined` *should* be valid and trigger
11076 // hasSeed! so don't use `seed !== undefined` checks!
11077 // For this reason, we have to check it here at the original call site
11078 // otherwise inside Operator/Subscriber we won't know if `undefined`
11079 // means they didn't provide anything or if they literally provided `undefined`
11080 if (arguments.length >= 2) {
11083 return this.lift(new ScanOperator(accumulator, seed, hasSeed));
11085 exports.scan = scan;
11086 var ScanOperator = (function () {
11087 function ScanOperator(accumulator, seed, hasSeed) {
11088 if (hasSeed === void 0) { hasSeed = false; }
11089 this.accumulator = accumulator;
11091 this.hasSeed = hasSeed;
11093 ScanOperator.prototype.call = function (subscriber, source) {
11094 return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
11096 return ScanOperator;
11099 * We need this JSDoc comment for affecting ESDoc.
11101 * @extends {Ignored}
11103 var ScanSubscriber = (function (_super) {
11104 __extends(ScanSubscriber, _super);
11105 function ScanSubscriber(destination, accumulator, _seed, hasSeed) {
11106 _super.call(this, destination);
11107 this.accumulator = accumulator;
11108 this._seed = _seed;
11109 this.hasSeed = hasSeed;
11112 Object.defineProperty(ScanSubscriber.prototype, "seed", {
11116 set: function (value) {
11117 this.hasSeed = true;
11118 this._seed = value;
11123 ScanSubscriber.prototype._next = function (value) {
11124 if (!this.hasSeed) {
11126 this.destination.next(value);
11129 return this._tryNext(value);
11132 ScanSubscriber.prototype._tryNext = function (value) {
11133 var index = this.index++;
11136 result = this.accumulator(this.seed, value, index);
11139 this.destination.error(err);
11141 this.seed = result;
11142 this.destination.next(result);
11144 return ScanSubscriber;
11145 }(Subscriber_1.Subscriber));
11147 },{"../Subscriber":35}],134:[function(require,module,exports){
11149 var multicast_1 = require('./multicast');
11150 var Subject_1 = require('../Subject');
11151 function shareSubjectFactory() {
11152 return new Subject_1.Subject();
11155 * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
11156 * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
11157 * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
11158 * This is an alias for .publish().refCount().
11160 * <img src="./img/share.png" width="100%">
11162 * @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.
11164 * @owner Observable
11167 return multicast_1.multicast.call(this, shareSubjectFactory).refCount();
11169 exports.share = share;
11172 },{"../Subject":33,"./multicast":127}],135:[function(require,module,exports){
11174 var __extends = (this && this.__extends) || function (d, b) {
11175 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11176 function __() { this.constructor = d; }
11177 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11179 var Subscriber_1 = require('../Subscriber');
11181 * Returns an Observable that skips the first `count` items emitted by the source Observable.
11183 * <img src="./img/skip.png" width="100%">
11185 * @param {Number} count - The number of times, items emitted by source Observable should be skipped.
11186 * @return {Observable} An Observable that skips values emitted by the source Observable.
11189 * @owner Observable
11191 function skip(count) {
11192 return this.lift(new SkipOperator(count));
11194 exports.skip = skip;
11195 var SkipOperator = (function () {
11196 function SkipOperator(total) {
11197 this.total = total;
11199 SkipOperator.prototype.call = function (subscriber, source) {
11200 return source.subscribe(new SkipSubscriber(subscriber, this.total));
11202 return SkipOperator;
11205 * We need this JSDoc comment for affecting ESDoc.
11207 * @extends {Ignored}
11209 var SkipSubscriber = (function (_super) {
11210 __extends(SkipSubscriber, _super);
11211 function SkipSubscriber(destination, total) {
11212 _super.call(this, destination);
11213 this.total = total;
11216 SkipSubscriber.prototype._next = function (x) {
11217 if (++this.count > this.total) {
11218 this.destination.next(x);
11221 return SkipSubscriber;
11222 }(Subscriber_1.Subscriber));
11224 },{"../Subscriber":35}],136:[function(require,module,exports){
11226 var __extends = (this && this.__extends) || function (d, b) {
11227 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11228 function __() { this.constructor = d; }
11229 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11231 var OuterSubscriber_1 = require('../OuterSubscriber');
11232 var subscribeToResult_1 = require('../util/subscribeToResult');
11234 * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
11236 * <img src="./img/skipUntil.png" width="100%">
11238 * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to
11239 * be mirrored by the resulting Observable.
11240 * @return {Observable<T>} An Observable that skips items from the source Observable until the second Observable emits
11241 * an item, then emits the remaining items.
11242 * @method skipUntil
11243 * @owner Observable
11245 function skipUntil(notifier) {
11246 return this.lift(new SkipUntilOperator(notifier));
11248 exports.skipUntil = skipUntil;
11249 var SkipUntilOperator = (function () {
11250 function SkipUntilOperator(notifier) {
11251 this.notifier = notifier;
11253 SkipUntilOperator.prototype.call = function (subscriber, source) {
11254 return source.subscribe(new SkipUntilSubscriber(subscriber, this.notifier));
11256 return SkipUntilOperator;
11259 * We need this JSDoc comment for affecting ESDoc.
11261 * @extends {Ignored}
11263 var SkipUntilSubscriber = (function (_super) {
11264 __extends(SkipUntilSubscriber, _super);
11265 function SkipUntilSubscriber(destination, notifier) {
11266 _super.call(this, destination);
11267 this.hasValue = false;
11268 this.isInnerStopped = false;
11269 this.add(subscribeToResult_1.subscribeToResult(this, notifier));
11271 SkipUntilSubscriber.prototype._next = function (value) {
11272 if (this.hasValue) {
11273 _super.prototype._next.call(this, value);
11276 SkipUntilSubscriber.prototype._complete = function () {
11277 if (this.isInnerStopped) {
11278 _super.prototype._complete.call(this);
11281 this.unsubscribe();
11284 SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11285 this.hasValue = true;
11287 SkipUntilSubscriber.prototype.notifyComplete = function () {
11288 this.isInnerStopped = true;
11289 if (this.isStopped) {
11290 _super.prototype._complete.call(this);
11293 return SkipUntilSubscriber;
11294 }(OuterSubscriber_1.OuterSubscriber));
11296 },{"../OuterSubscriber":30,"../util/subscribeToResult":172}],137:[function(require,module,exports){
11298 var __extends = (this && this.__extends) || function (d, b) {
11299 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11300 function __() { this.constructor = d; }
11301 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11303 var Subscriber_1 = require('../Subscriber');
11305 * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
11306 * true, but emits all further source items as soon as the condition becomes false.
11308 * <img src="./img/skipWhile.png" width="100%">
11310 * @param {Function} predicate - A function to test each item emitted from the source Observable.
11311 * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the
11312 * specified predicate becomes false.
11313 * @method skipWhile
11314 * @owner Observable
11316 function skipWhile(predicate) {
11317 return this.lift(new SkipWhileOperator(predicate));
11319 exports.skipWhile = skipWhile;
11320 var SkipWhileOperator = (function () {
11321 function SkipWhileOperator(predicate) {
11322 this.predicate = predicate;
11324 SkipWhileOperator.prototype.call = function (subscriber, source) {
11325 return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
11327 return SkipWhileOperator;
11330 * We need this JSDoc comment for affecting ESDoc.
11332 * @extends {Ignored}
11334 var SkipWhileSubscriber = (function (_super) {
11335 __extends(SkipWhileSubscriber, _super);
11336 function SkipWhileSubscriber(destination, predicate) {
11337 _super.call(this, destination);
11338 this.predicate = predicate;
11339 this.skipping = true;
11342 SkipWhileSubscriber.prototype._next = function (value) {
11343 var destination = this.destination;
11344 if (this.skipping) {
11345 this.tryCallPredicate(value);
11347 if (!this.skipping) {
11348 destination.next(value);
11351 SkipWhileSubscriber.prototype.tryCallPredicate = function (value) {
11353 var result = this.predicate(value, this.index++);
11354 this.skipping = Boolean(result);
11357 this.destination.error(err);
11360 return SkipWhileSubscriber;
11361 }(Subscriber_1.Subscriber));
11363 },{"../Subscriber":35}],138:[function(require,module,exports){
11365 var ArrayObservable_1 = require('../observable/ArrayObservable');
11366 var ScalarObservable_1 = require('../observable/ScalarObservable');
11367 var EmptyObservable_1 = require('../observable/EmptyObservable');
11368 var concat_1 = require('./concat');
11369 var isScheduler_1 = require('../util/isScheduler');
11370 /* tslint:enable:max-line-length */
11372 * Returns an Observable that emits the items you specify as arguments before it begins to emit
11373 * items emitted by the source Observable.
11375 * <img src="./img/startWith.png" width="100%">
11377 * @param {...T} values - Items you want the modified Observable to emit first.
11378 * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling
11379 * the emissions of the `next` notifications.
11380 * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items
11381 * emitted by the source Observable.
11382 * @method startWith
11383 * @owner Observable
11385 function startWith() {
11387 for (var _i = 0; _i < arguments.length; _i++) {
11388 array[_i - 0] = arguments[_i];
11390 var scheduler = array[array.length - 1];
11391 if (isScheduler_1.isScheduler(scheduler)) {
11397 var len = array.length;
11399 return concat_1.concatStatic(new ScalarObservable_1.ScalarObservable(array[0], scheduler), this);
11401 else if (len > 1) {
11402 return concat_1.concatStatic(new ArrayObservable_1.ArrayObservable(array, scheduler), this);
11405 return concat_1.concatStatic(new EmptyObservable_1.EmptyObservable(scheduler), this);
11408 exports.startWith = startWith;
11410 },{"../observable/ArrayObservable":85,"../observable/EmptyObservable":88,"../observable/ScalarObservable":94,"../util/isScheduler":170,"./concat":112}],139:[function(require,module,exports){
11412 var __extends = (this && this.__extends) || function (d, b) {
11413 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11414 function __() { this.constructor = d; }
11415 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11417 var OuterSubscriber_1 = require('../OuterSubscriber');
11418 var subscribeToResult_1 = require('../util/subscribeToResult');
11419 /* tslint:enable:max-line-length */
11421 * Projects each source value to an Observable which is merged in the output
11422 * Observable, emitting values only from the most recently projected Observable.
11424 * <span class="informal">Maps each value to an Observable, then flattens all of
11425 * these inner Observables using {@link switch}.</span>
11427 * <img src="./img/switchMap.png" width="100%">
11429 * Returns an Observable that emits items based on applying a function that you
11430 * supply to each item emitted by the source Observable, where that function
11431 * returns an (so-called "inner") Observable. Each time it observes one of these
11432 * inner Observables, the output Observable begins emitting the items emitted by
11433 * that inner Observable. When a new inner Observable is emitted, `switchMap`
11434 * stops emitting items from the earlier-emitted inner Observable and begins
11435 * emitting items from the new one. It continues to behave like this for
11436 * subsequent inner Observables.
11438 * @example <caption>Rerun an interval Observable on every click event</caption>
11439 * var clicks = Rx.Observable.fromEvent(document, 'click');
11440 * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
11441 * result.subscribe(x => console.log(x));
11443 * @see {@link concatMap}
11444 * @see {@link exhaustMap}
11445 * @see {@link mergeMap}
11446 * @see {@link switch}
11447 * @see {@link switchMapTo}
11449 * @param {function(value: T, ?index: number): ObservableInput} project A function
11450 * that, when applied to an item emitted by the source Observable, returns an
11452 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
11453 * A function to produce the value on the output Observable based on the values
11454 * and the indices of the source (outer) emission and the inner Observable
11455 * emission. The arguments passed to this function are:
11456 * - `outerValue`: the value that came from the source
11457 * - `innerValue`: the value that came from the projected Observable
11458 * - `outerIndex`: the "index" of the value that came from the source
11459 * - `innerIndex`: the "index" of the value from the projected Observable
11460 * @return {Observable} An Observable that emits the result of applying the
11461 * projection function (and the optional `resultSelector`) to each item emitted
11462 * by the source Observable and taking only the values from the most recently
11463 * projected inner Observable.
11464 * @method switchMap
11465 * @owner Observable
11467 function switchMap(project, resultSelector) {
11468 return this.lift(new SwitchMapOperator(project, resultSelector));
11470 exports.switchMap = switchMap;
11471 var SwitchMapOperator = (function () {
11472 function SwitchMapOperator(project, resultSelector) {
11473 this.project = project;
11474 this.resultSelector = resultSelector;
11476 SwitchMapOperator.prototype.call = function (subscriber, source) {
11477 return source.subscribe(new SwitchMapSubscriber(subscriber, this.project, this.resultSelector));
11479 return SwitchMapOperator;
11482 * We need this JSDoc comment for affecting ESDoc.
11484 * @extends {Ignored}
11486 var SwitchMapSubscriber = (function (_super) {
11487 __extends(SwitchMapSubscriber, _super);
11488 function SwitchMapSubscriber(destination, project, resultSelector) {
11489 _super.call(this, destination);
11490 this.project = project;
11491 this.resultSelector = resultSelector;
11494 SwitchMapSubscriber.prototype._next = function (value) {
11496 var index = this.index++;
11498 result = this.project(value, index);
11501 this.destination.error(error);
11504 this._innerSub(result, value, index);
11506 SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
11507 var innerSubscription = this.innerSubscription;
11508 if (innerSubscription) {
11509 innerSubscription.unsubscribe();
11511 this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index));
11513 SwitchMapSubscriber.prototype._complete = function () {
11514 var innerSubscription = this.innerSubscription;
11515 if (!innerSubscription || innerSubscription.closed) {
11516 _super.prototype._complete.call(this);
11519 SwitchMapSubscriber.prototype._unsubscribe = function () {
11520 this.innerSubscription = null;
11522 SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
11523 this.remove(innerSub);
11524 this.innerSubscription = null;
11525 if (this.isStopped) {
11526 _super.prototype._complete.call(this);
11529 SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11530 if (this.resultSelector) {
11531 this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex);
11534 this.destination.next(innerValue);
11537 SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
11540 result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
11543 this.destination.error(err);
11546 this.destination.next(result);
11548 return SwitchMapSubscriber;
11549 }(OuterSubscriber_1.OuterSubscriber));
11551 },{"../OuterSubscriber":30,"../util/subscribeToResult":172}],140:[function(require,module,exports){
11553 var __extends = (this && this.__extends) || function (d, b) {
11554 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11555 function __() { this.constructor = d; }
11556 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11558 var Subscriber_1 = require('../Subscriber');
11559 var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError');
11560 var EmptyObservable_1 = require('../observable/EmptyObservable');
11562 * Emits only the first `count` values emitted by the source Observable.
11564 * <span class="informal">Takes the first `count` values from the source, then
11565 * completes.</span>
11567 * <img src="./img/take.png" width="100%">
11569 * `take` returns an Observable that emits only the first `count` values emitted
11570 * by the source Observable. If the source emits fewer than `count` values then
11571 * all of its values are emitted. After that, it completes, regardless if the
11572 * source completes.
11574 * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
11575 * var interval = Rx.Observable.interval(1000);
11576 * var five = interval.take(5);
11577 * five.subscribe(x => console.log(x));
11579 * @see {@link takeLast}
11580 * @see {@link takeUntil}
11581 * @see {@link takeWhile}
11582 * @see {@link skip}
11584 * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
11585 * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
11587 * @param {number} count The maximum number of `next` values to emit.
11588 * @return {Observable<T>} An Observable that emits only the first `count`
11589 * values emitted by the source Observable, or all of the values from the source
11590 * if the source emits fewer than `count` values.
11592 * @owner Observable
11594 function take(count) {
11596 return new EmptyObservable_1.EmptyObservable();
11599 return this.lift(new TakeOperator(count));
11602 exports.take = take;
11603 var TakeOperator = (function () {
11604 function TakeOperator(total) {
11605 this.total = total;
11606 if (this.total < 0) {
11607 throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
11610 TakeOperator.prototype.call = function (subscriber, source) {
11611 return source.subscribe(new TakeSubscriber(subscriber, this.total));
11613 return TakeOperator;
11616 * We need this JSDoc comment for affecting ESDoc.
11618 * @extends {Ignored}
11620 var TakeSubscriber = (function (_super) {
11621 __extends(TakeSubscriber, _super);
11622 function TakeSubscriber(destination, total) {
11623 _super.call(this, destination);
11624 this.total = total;
11627 TakeSubscriber.prototype._next = function (value) {
11628 var total = this.total;
11629 var count = ++this.count;
11630 if (count <= total) {
11631 this.destination.next(value);
11632 if (count === total) {
11633 this.destination.complete();
11634 this.unsubscribe();
11638 return TakeSubscriber;
11639 }(Subscriber_1.Subscriber));
11641 },{"../Subscriber":35,"../observable/EmptyObservable":88,"../util/ArgumentOutOfRangeError":157}],141:[function(require,module,exports){
11643 var __extends = (this && this.__extends) || function (d, b) {
11644 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11645 function __() { this.constructor = d; }
11646 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11648 var OuterSubscriber_1 = require('../OuterSubscriber');
11649 var subscribeToResult_1 = require('../util/subscribeToResult');
11651 * Emits the values emitted by the source Observable until a `notifier`
11652 * Observable emits a value.
11654 * <span class="informal">Lets values pass until a second Observable,
11655 * `notifier`, emits something. Then, it completes.</span>
11657 * <img src="./img/takeUntil.png" width="100%">
11659 * `takeUntil` subscribes and begins mirroring the source Observable. It also
11660 * monitors a second Observable, `notifier` that you provide. If the `notifier`
11661 * emits a value or a complete notification, the output Observable stops
11662 * mirroring the source Observable and completes.
11664 * @example <caption>Tick every second until the first click happens</caption>
11665 * var interval = Rx.Observable.interval(1000);
11666 * var clicks = Rx.Observable.fromEvent(document, 'click');
11667 * var result = interval.takeUntil(clicks);
11668 * result.subscribe(x => console.log(x));
11670 * @see {@link take}
11671 * @see {@link takeLast}
11672 * @see {@link takeWhile}
11673 * @see {@link skip}
11675 * @param {Observable} notifier The Observable whose first emitted value will
11676 * cause the output Observable of `takeUntil` to stop emitting values from the
11677 * source Observable.
11678 * @return {Observable<T>} An Observable that emits the values from the source
11679 * Observable until such time as `notifier` emits its first value.
11680 * @method takeUntil
11681 * @owner Observable
11683 function takeUntil(notifier) {
11684 return this.lift(new TakeUntilOperator(notifier));
11686 exports.takeUntil = takeUntil;
11687 var TakeUntilOperator = (function () {
11688 function TakeUntilOperator(notifier) {
11689 this.notifier = notifier;
11691 TakeUntilOperator.prototype.call = function (subscriber, source) {
11692 return source.subscribe(new TakeUntilSubscriber(subscriber, this.notifier));
11694 return TakeUntilOperator;
11697 * We need this JSDoc comment for affecting ESDoc.
11699 * @extends {Ignored}
11701 var TakeUntilSubscriber = (function (_super) {
11702 __extends(TakeUntilSubscriber, _super);
11703 function TakeUntilSubscriber(destination, notifier) {
11704 _super.call(this, destination);
11705 this.notifier = notifier;
11706 this.add(subscribeToResult_1.subscribeToResult(this, notifier));
11708 TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11711 TakeUntilSubscriber.prototype.notifyComplete = function () {
11714 return TakeUntilSubscriber;
11715 }(OuterSubscriber_1.OuterSubscriber));
11717 },{"../OuterSubscriber":30,"../util/subscribeToResult":172}],142:[function(require,module,exports){
11719 var __extends = (this && this.__extends) || function (d, b) {
11720 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11721 function __() { this.constructor = d; }
11722 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11724 var OuterSubscriber_1 = require('../OuterSubscriber');
11725 var subscribeToResult_1 = require('../util/subscribeToResult');
11726 exports.defaultThrottleConfig = {
11731 * Emits a value from the source Observable, then ignores subsequent source
11732 * values for a duration determined by another Observable, then repeats this
11735 * <span class="informal">It's like {@link throttleTime}, but the silencing
11736 * duration is determined by a second Observable.</span>
11738 * <img src="./img/throttle.png" width="100%">
11740 * `throttle` emits the source Observable values on the output Observable
11741 * when its internal timer is disabled, and ignores source values when the timer
11742 * is enabled. Initially, the timer is disabled. As soon as the first source
11743 * value arrives, it is forwarded to the output Observable, and then the timer
11744 * is enabled by calling the `durationSelector` function with the source value,
11745 * which returns the "duration" Observable. When the duration Observable emits a
11746 * value or completes, the timer is disabled, and this process repeats for the
11747 * next source value.
11749 * @example <caption>Emit clicks at a rate of at most one click per second</caption>
11750 * var clicks = Rx.Observable.fromEvent(document, 'click');
11751 * var result = clicks.throttle(ev => Rx.Observable.interval(1000));
11752 * result.subscribe(x => console.log(x));
11754 * @see {@link audit}
11755 * @see {@link debounce}
11756 * @see {@link delayWhen}
11757 * @see {@link sample}
11758 * @see {@link throttleTime}
11760 * @param {function(value: T): SubscribableOrPromise} durationSelector A function
11761 * that receives a value from the source Observable, for computing the silencing
11762 * duration for each source value, returned as an Observable or a Promise.
11763 * @param {Object} config a configuration object to define `leading` and `trailing` behavior. Defaults
11764 * to `{ leading: true, trailing: false }`.
11765 * @return {Observable<T>} An Observable that performs the throttle operation to
11766 * limit the rate of emissions from the source.
11768 * @owner Observable
11770 function throttle(durationSelector, config) {
11771 if (config === void 0) { config = exports.defaultThrottleConfig; }
11772 return this.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing));
11774 exports.throttle = throttle;
11775 var ThrottleOperator = (function () {
11776 function ThrottleOperator(durationSelector, leading, trailing) {
11777 this.durationSelector = durationSelector;
11778 this.leading = leading;
11779 this.trailing = trailing;
11781 ThrottleOperator.prototype.call = function (subscriber, source) {
11782 return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
11784 return ThrottleOperator;
11787 * We need this JSDoc comment for affecting ESDoc
11789 * @extends {Ignored}
11791 var ThrottleSubscriber = (function (_super) {
11792 __extends(ThrottleSubscriber, _super);
11793 function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) {
11794 _super.call(this, destination);
11795 this.destination = destination;
11796 this.durationSelector = durationSelector;
11797 this._leading = _leading;
11798 this._trailing = _trailing;
11799 this._hasTrailingValue = false;
11801 ThrottleSubscriber.prototype._next = function (value) {
11802 if (this.throttled) {
11803 if (this._trailing) {
11804 this._hasTrailingValue = true;
11805 this._trailingValue = value;
11809 var duration = this.tryDurationSelector(value);
11811 this.add(this.throttled = subscribeToResult_1.subscribeToResult(this, duration));
11813 if (this._leading) {
11814 this.destination.next(value);
11815 if (this._trailing) {
11816 this._hasTrailingValue = true;
11817 this._trailingValue = value;
11822 ThrottleSubscriber.prototype.tryDurationSelector = function (value) {
11824 return this.durationSelector(value);
11827 this.destination.error(err);
11831 ThrottleSubscriber.prototype._unsubscribe = function () {
11832 var _a = this, throttled = _a.throttled, _trailingValue = _a._trailingValue, _hasTrailingValue = _a._hasTrailingValue, _trailing = _a._trailing;
11833 this._trailingValue = null;
11834 this._hasTrailingValue = false;
11836 this.remove(throttled);
11837 this.throttled = null;
11838 throttled.unsubscribe();
11841 ThrottleSubscriber.prototype._sendTrailing = function () {
11842 var _a = this, destination = _a.destination, throttled = _a.throttled, _trailing = _a._trailing, _trailingValue = _a._trailingValue, _hasTrailingValue = _a._hasTrailingValue;
11843 if (throttled && _trailing && _hasTrailingValue) {
11844 destination.next(_trailingValue);
11845 this._trailingValue = null;
11846 this._hasTrailingValue = false;
11849 ThrottleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11850 this._sendTrailing();
11851 this._unsubscribe();
11853 ThrottleSubscriber.prototype.notifyComplete = function () {
11854 this._sendTrailing();
11855 this._unsubscribe();
11857 return ThrottleSubscriber;
11858 }(OuterSubscriber_1.OuterSubscriber));
11860 },{"../OuterSubscriber":30,"../util/subscribeToResult":172}],143:[function(require,module,exports){
11862 var __extends = (this && this.__extends) || function (d, b) {
11863 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11864 function __() { this.constructor = d; }
11865 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11867 var Subscriber_1 = require('../Subscriber');
11868 var async_1 = require('../scheduler/async');
11869 var throttle_1 = require('./throttle');
11871 * Emits a value from the source Observable, then ignores subsequent source
11872 * values for `duration` milliseconds, then repeats this process.
11874 * <span class="informal">Lets a value pass, then ignores source values for the
11875 * next `duration` milliseconds.</span>
11877 * <img src="./img/throttleTime.png" width="100%">
11879 * `throttleTime` emits the source Observable values on the output Observable
11880 * when its internal timer is disabled, and ignores source values when the timer
11881 * is enabled. Initially, the timer is disabled. As soon as the first source
11882 * value arrives, it is forwarded to the output Observable, and then the timer
11883 * is enabled. After `duration` milliseconds (or the time unit determined
11884 * internally by the optional `scheduler`) has passed, the timer is disabled,
11885 * and this process repeats for the next source value. Optionally takes a
11886 * {@link IScheduler} for managing timers.
11888 * @example <caption>Emit clicks at a rate of at most one click per second</caption>
11889 * var clicks = Rx.Observable.fromEvent(document, 'click');
11890 * var result = clicks.throttleTime(1000);
11891 * result.subscribe(x => console.log(x));
11893 * @see {@link auditTime}
11894 * @see {@link debounceTime}
11895 * @see {@link delay}
11896 * @see {@link sampleTime}
11897 * @see {@link throttle}
11899 * @param {number} duration Time to wait before emitting another value after
11900 * emitting the last value, measured in milliseconds or the time unit determined
11901 * internally by the optional `scheduler`.
11902 * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
11903 * managing the timers that handle the sampling.
11904 * @return {Observable<T>} An Observable that performs the throttle operation to
11905 * limit the rate of emissions from the source.
11906 * @method throttleTime
11907 * @owner Observable
11909 function throttleTime(duration, scheduler, config) {
11910 if (scheduler === void 0) { scheduler = async_1.async; }
11911 if (config === void 0) { config = throttle_1.defaultThrottleConfig; }
11912 return this.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing));
11914 exports.throttleTime = throttleTime;
11915 var ThrottleTimeOperator = (function () {
11916 function ThrottleTimeOperator(duration, scheduler, leading, trailing) {
11917 this.duration = duration;
11918 this.scheduler = scheduler;
11919 this.leading = leading;
11920 this.trailing = trailing;
11922 ThrottleTimeOperator.prototype.call = function (subscriber, source) {
11923 return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
11925 return ThrottleTimeOperator;
11928 * We need this JSDoc comment for affecting ESDoc.
11930 * @extends {Ignored}
11932 var ThrottleTimeSubscriber = (function (_super) {
11933 __extends(ThrottleTimeSubscriber, _super);
11934 function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) {
11935 _super.call(this, destination);
11936 this.duration = duration;
11937 this.scheduler = scheduler;
11938 this.leading = leading;
11939 this.trailing = trailing;
11940 this._hasTrailingValue = false;
11941 this._trailingValue = null;
11943 ThrottleTimeSubscriber.prototype._next = function (value) {
11944 if (this.throttled) {
11945 if (this.trailing) {
11946 this._trailingValue = value;
11947 this._hasTrailingValue = true;
11951 this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
11952 if (this.leading) {
11953 this.destination.next(value);
11957 ThrottleTimeSubscriber.prototype.clearThrottle = function () {
11958 var throttled = this.throttled;
11960 if (this.trailing && this._hasTrailingValue) {
11961 this.destination.next(this._trailingValue);
11962 this._trailingValue = null;
11963 this._hasTrailingValue = false;
11965 throttled.unsubscribe();
11966 this.remove(throttled);
11967 this.throttled = null;
11970 return ThrottleTimeSubscriber;
11971 }(Subscriber_1.Subscriber));
11972 function dispatchNext(arg) {
11973 var subscriber = arg.subscriber;
11974 subscriber.clearThrottle();
11977 },{"../Subscriber":35,"../scheduler/async":151,"./throttle":142}],144:[function(require,module,exports){
11979 var __extends = (this && this.__extends) || function (d, b) {
11980 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11981 function __() { this.constructor = d; }
11982 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11984 var OuterSubscriber_1 = require('../OuterSubscriber');
11985 var subscribeToResult_1 = require('../util/subscribeToResult');
11986 /* tslint:enable:max-line-length */
11988 * Combines the source Observable with other Observables to create an Observable
11989 * whose values are calculated from the latest values of each, only when the
11992 * <span class="informal">Whenever the source Observable emits a value, it
11993 * computes a formula using that value plus the latest values from other input
11994 * Observables, then emits the output of that formula.</span>
11996 * <img src="./img/withLatestFrom.png" width="100%">
11998 * `withLatestFrom` combines each value from the source Observable (the
11999 * instance) with the latest values from the other input Observables only when
12000 * the source emits a value, optionally using a `project` function to determine
12001 * the value to be emitted on the output Observable. All input Observables must
12002 * emit at least one value before the output Observable will emit a value.
12004 * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
12005 * var clicks = Rx.Observable.fromEvent(document, 'click');
12006 * var timer = Rx.Observable.interval(1000);
12007 * var result = clicks.withLatestFrom(timer);
12008 * result.subscribe(x => console.log(x));
12010 * @see {@link combineLatest}
12012 * @param {ObservableInput} other An input Observable to combine with the source
12013 * Observable. More than one input Observables may be given as argument.
12014 * @param {Function} [project] Projection function for combining values
12015 * together. Receives all values in order of the Observables passed, where the
12016 * first parameter is a value from the source Observable. (e.g.
12017 * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
12018 * passed, arrays will be emitted on the output Observable.
12019 * @return {Observable} An Observable of projected values from the most recent
12020 * values from each input Observable, or an array of the most recent values from
12021 * each input Observable.
12022 * @method withLatestFrom
12023 * @owner Observable
12025 function withLatestFrom() {
12027 for (var _i = 0; _i < arguments.length; _i++) {
12028 args[_i - 0] = arguments[_i];
12031 if (typeof args[args.length - 1] === 'function') {
12032 project = args.pop();
12034 var observables = args;
12035 return this.lift(new WithLatestFromOperator(observables, project));
12037 exports.withLatestFrom = withLatestFrom;
12038 var WithLatestFromOperator = (function () {
12039 function WithLatestFromOperator(observables, project) {
12040 this.observables = observables;
12041 this.project = project;
12043 WithLatestFromOperator.prototype.call = function (subscriber, source) {
12044 return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
12046 return WithLatestFromOperator;
12049 * We need this JSDoc comment for affecting ESDoc.
12051 * @extends {Ignored}
12053 var WithLatestFromSubscriber = (function (_super) {
12054 __extends(WithLatestFromSubscriber, _super);
12055 function WithLatestFromSubscriber(destination, observables, project) {
12056 _super.call(this, destination);
12057 this.observables = observables;
12058 this.project = project;
12059 this.toRespond = [];
12060 var len = observables.length;
12061 this.values = new Array(len);
12062 for (var i = 0; i < len; i++) {
12063 this.toRespond.push(i);
12065 for (var i = 0; i < len; i++) {
12066 var observable = observables[i];
12067 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
12070 WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12071 this.values[outerIndex] = innerValue;
12072 var toRespond = this.toRespond;
12073 if (toRespond.length > 0) {
12074 var found = toRespond.indexOf(outerIndex);
12075 if (found !== -1) {
12076 toRespond.splice(found, 1);
12080 WithLatestFromSubscriber.prototype.notifyComplete = function () {
12083 WithLatestFromSubscriber.prototype._next = function (value) {
12084 if (this.toRespond.length === 0) {
12085 var args = [value].concat(this.values);
12086 if (this.project) {
12087 this._tryProject(args);
12090 this.destination.next(args);
12094 WithLatestFromSubscriber.prototype._tryProject = function (args) {
12097 result = this.project.apply(this, args);
12100 this.destination.error(err);
12103 this.destination.next(result);
12105 return WithLatestFromSubscriber;
12106 }(OuterSubscriber_1.OuterSubscriber));
12108 },{"../OuterSubscriber":30,"../util/subscribeToResult":172}],145:[function(require,module,exports){
12110 var __extends = (this && this.__extends) || function (d, b) {
12111 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12112 function __() { this.constructor = d; }
12113 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12115 var ArrayObservable_1 = require('../observable/ArrayObservable');
12116 var isArray_1 = require('../util/isArray');
12117 var Subscriber_1 = require('../Subscriber');
12118 var OuterSubscriber_1 = require('../OuterSubscriber');
12119 var subscribeToResult_1 = require('../util/subscribeToResult');
12120 var iterator_1 = require('../symbol/iterator');
12121 /* tslint:enable:max-line-length */
12123 * @param observables
12124 * @return {Observable<R>}
12126 * @owner Observable
12128 function zipProto() {
12129 var observables = [];
12130 for (var _i = 0; _i < arguments.length; _i++) {
12131 observables[_i - 0] = arguments[_i];
12133 return this.lift.call(zipStatic.apply(void 0, [this].concat(observables)));
12135 exports.zipProto = zipProto;
12136 /* tslint:enable:max-line-length */
12138 * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each
12139 * of its input Observables.
12141 * If the latest parameter is a function, this function is used to compute the created value from the input values.
12142 * Otherwise, an array of the input values is returned.
12144 * @example <caption>Combine age and name from different sources</caption>
12146 * let age$ = Observable.of<number>(27, 25, 29);
12147 * let name$ = Observable.of<string>('Foo', 'Bar', 'Beer');
12148 * let isDev$ = Observable.of<boolean>(true, true, false);
12154 * (age: number, name: string, isDev: boolean) => ({ age, name, isDev }))
12155 * .subscribe(x => console.log(x));
12158 * // { age: 27, name: 'Foo', isDev: true }
12159 * // { age: 25, name: 'Bar', isDev: true }
12160 * // { age: 29, name: 'Beer', isDev: false }
12162 * @param observables
12163 * @return {Observable<R>}
12166 * @owner Observable
12168 function zipStatic() {
12169 var observables = [];
12170 for (var _i = 0; _i < arguments.length; _i++) {
12171 observables[_i - 0] = arguments[_i];
12173 var project = observables[observables.length - 1];
12174 if (typeof project === 'function') {
12177 return new ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project));
12179 exports.zipStatic = zipStatic;
12180 var ZipOperator = (function () {
12181 function ZipOperator(project) {
12182 this.project = project;
12184 ZipOperator.prototype.call = function (subscriber, source) {
12185 return source.subscribe(new ZipSubscriber(subscriber, this.project));
12187 return ZipOperator;
12189 exports.ZipOperator = ZipOperator;
12191 * We need this JSDoc comment for affecting ESDoc.
12193 * @extends {Ignored}
12195 var ZipSubscriber = (function (_super) {
12196 __extends(ZipSubscriber, _super);
12197 function ZipSubscriber(destination, project, values) {
12198 if (values === void 0) { values = Object.create(null); }
12199 _super.call(this, destination);
12200 this.iterators = [];
12202 this.project = (typeof project === 'function') ? project : null;
12203 this.values = values;
12205 ZipSubscriber.prototype._next = function (value) {
12206 var iterators = this.iterators;
12207 if (isArray_1.isArray(value)) {
12208 iterators.push(new StaticArrayIterator(value));
12210 else if (typeof value[iterator_1.iterator] === 'function') {
12211 iterators.push(new StaticIterator(value[iterator_1.iterator]()));
12214 iterators.push(new ZipBufferIterator(this.destination, this, value));
12217 ZipSubscriber.prototype._complete = function () {
12218 var iterators = this.iterators;
12219 var len = iterators.length;
12221 this.destination.complete();
12225 for (var i = 0; i < len; i++) {
12226 var iterator = iterators[i];
12227 if (iterator.stillUnsubscribed) {
12228 this.add(iterator.subscribe(iterator, i));
12231 this.active--; // not an observable
12235 ZipSubscriber.prototype.notifyInactive = function () {
12237 if (this.active === 0) {
12238 this.destination.complete();
12241 ZipSubscriber.prototype.checkIterators = function () {
12242 var iterators = this.iterators;
12243 var len = iterators.length;
12244 var destination = this.destination;
12245 // abort if not all of them have values
12246 for (var i = 0; i < len; i++) {
12247 var iterator = iterators[i];
12248 if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
12252 var shouldComplete = false;
12254 for (var i = 0; i < len; i++) {
12255 var iterator = iterators[i];
12256 var result = iterator.next();
12257 // check to see if it's completed now that you've gotten
12259 if (iterator.hasCompleted()) {
12260 shouldComplete = true;
12263 destination.complete();
12266 args.push(result.value);
12268 if (this.project) {
12269 this._tryProject(args);
12272 destination.next(args);
12274 if (shouldComplete) {
12275 destination.complete();
12278 ZipSubscriber.prototype._tryProject = function (args) {
12281 result = this.project.apply(this, args);
12284 this.destination.error(err);
12287 this.destination.next(result);
12289 return ZipSubscriber;
12290 }(Subscriber_1.Subscriber));
12291 exports.ZipSubscriber = ZipSubscriber;
12292 var StaticIterator = (function () {
12293 function StaticIterator(iterator) {
12294 this.iterator = iterator;
12295 this.nextResult = iterator.next();
12297 StaticIterator.prototype.hasValue = function () {
12300 StaticIterator.prototype.next = function () {
12301 var result = this.nextResult;
12302 this.nextResult = this.iterator.next();
12305 StaticIterator.prototype.hasCompleted = function () {
12306 var nextResult = this.nextResult;
12307 return nextResult && nextResult.done;
12309 return StaticIterator;
12311 var StaticArrayIterator = (function () {
12312 function StaticArrayIterator(array) {
12313 this.array = array;
12316 this.length = array.length;
12318 StaticArrayIterator.prototype[iterator_1.iterator] = function () {
12321 StaticArrayIterator.prototype.next = function (value) {
12322 var i = this.index++;
12323 var array = this.array;
12324 return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
12326 StaticArrayIterator.prototype.hasValue = function () {
12327 return this.array.length > this.index;
12329 StaticArrayIterator.prototype.hasCompleted = function () {
12330 return this.array.length === this.index;
12332 return StaticArrayIterator;
12335 * We need this JSDoc comment for affecting ESDoc.
12337 * @extends {Ignored}
12339 var ZipBufferIterator = (function (_super) {
12340 __extends(ZipBufferIterator, _super);
12341 function ZipBufferIterator(destination, parent, observable) {
12342 _super.call(this, destination);
12343 this.parent = parent;
12344 this.observable = observable;
12345 this.stillUnsubscribed = true;
12347 this.isComplete = false;
12349 ZipBufferIterator.prototype[iterator_1.iterator] = function () {
12352 // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next
12353 // this is legit because `next()` will never be called by a subscription in this case.
12354 ZipBufferIterator.prototype.next = function () {
12355 var buffer = this.buffer;
12356 if (buffer.length === 0 && this.isComplete) {
12357 return { value: null, done: true };
12360 return { value: buffer.shift(), done: false };
12363 ZipBufferIterator.prototype.hasValue = function () {
12364 return this.buffer.length > 0;
12366 ZipBufferIterator.prototype.hasCompleted = function () {
12367 return this.buffer.length === 0 && this.isComplete;
12369 ZipBufferIterator.prototype.notifyComplete = function () {
12370 if (this.buffer.length > 0) {
12371 this.isComplete = true;
12372 this.parent.notifyInactive();
12375 this.destination.complete();
12378 ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12379 this.buffer.push(innerValue);
12380 this.parent.checkIterators();
12382 ZipBufferIterator.prototype.subscribe = function (value, index) {
12383 return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
12385 return ZipBufferIterator;
12386 }(OuterSubscriber_1.OuterSubscriber));
12388 },{"../OuterSubscriber":30,"../Subscriber":35,"../observable/ArrayObservable":85,"../symbol/iterator":153,"../util/isArray":163,"../util/subscribeToResult":172}],146:[function(require,module,exports){
12390 var __extends = (this && this.__extends) || function (d, b) {
12391 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12392 function __() { this.constructor = d; }
12393 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12395 var Subscription_1 = require('../Subscription');
12397 * A unit of work to be executed in a {@link Scheduler}. An action is typically
12398 * created from within a Scheduler and an RxJS user does not need to concern
12399 * themselves about creating and manipulating an Action.
12402 * class Action<T> extends Subscription {
12403 * new (scheduler: Scheduler, work: (state?: T) => void);
12404 * schedule(state?: T, delay: number = 0): Subscription;
12410 var Action = (function (_super) {
12411 __extends(Action, _super);
12412 function Action(scheduler, work) {
12416 * Schedules this action on its parent Scheduler for execution. May be passed
12417 * some context object, `state`. May happen at some point in the future,
12418 * according to the `delay` parameter, if specified.
12419 * @param {T} [state] Some contextual data that the `work` function uses when
12420 * called by the Scheduler.
12421 * @param {number} [delay] Time to wait before executing the work, where the
12422 * time unit is implicit and defined by the Scheduler.
12425 Action.prototype.schedule = function (state, delay) {
12426 if (delay === void 0) { delay = 0; }
12430 }(Subscription_1.Subscription));
12431 exports.Action = Action;
12433 },{"../Subscription":36}],147:[function(require,module,exports){
12435 var __extends = (this && this.__extends) || function (d, b) {
12436 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12437 function __() { this.constructor = d; }
12438 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12440 var root_1 = require('../util/root');
12441 var Action_1 = require('./Action');
12443 * We need this JSDoc comment for affecting ESDoc.
12445 * @extends {Ignored}
12447 var AsyncAction = (function (_super) {
12448 __extends(AsyncAction, _super);
12449 function AsyncAction(scheduler, work) {
12450 _super.call(this, scheduler, work);
12451 this.scheduler = scheduler;
12453 this.pending = false;
12455 AsyncAction.prototype.schedule = function (state, delay) {
12456 if (delay === void 0) { delay = 0; }
12460 // Always replace the current state with the new state.
12461 this.state = state;
12462 // Set the pending flag indicating that this action has been scheduled, or
12463 // has recursively rescheduled itself.
12464 this.pending = true;
12466 var scheduler = this.scheduler;
12468 // Important implementation note:
12470 // Actions only execute once by default, unless rescheduled from within the
12471 // scheduled callback. This allows us to implement single and repeat
12472 // actions via the same code path, without adding API surface area, as well
12473 // as mimic traditional recursion but across asynchronous boundaries.
12475 // However, JS runtimes and timers distinguish between intervals achieved by
12476 // serial `setTimeout` calls vs. a single `setInterval` call. An interval of
12477 // serial `setTimeout` calls can be individually delayed, which delays
12478 // scheduling the next `setTimeout`, and so on. `setInterval` attempts to
12479 // guarantee the interval callback will be invoked more precisely to the
12480 // interval period, regardless of load.
12482 // Therefore, we use `setInterval` to schedule single and repeat actions.
12483 // If the action reschedules itself with the same delay, the interval is not
12484 // canceled. If the action doesn't reschedule, or reschedules with a
12485 // different delay, the interval will be canceled after scheduled callback
12489 this.id = this.recycleAsyncId(scheduler, id, delay);
12491 this.delay = delay;
12492 // If this action has already an async Id, don't request a new one.
12493 this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
12496 AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
12497 if (delay === void 0) { delay = 0; }
12498 return root_1.root.setInterval(scheduler.flush.bind(scheduler, this), delay);
12500 AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
12501 if (delay === void 0) { delay = 0; }
12502 // If this action is rescheduled with the same delay time, don't clear the interval id.
12503 if (delay !== null && this.delay === delay && this.pending === false) {
12506 // Otherwise, if the action's delay time is different from the current delay,
12507 // or the action has been rescheduled before it's executed, clear the interval id
12508 return root_1.root.clearInterval(id) && undefined || undefined;
12511 * Immediately executes this action and the `work` it contains.
12514 AsyncAction.prototype.execute = function (state, delay) {
12516 return new Error('executing a cancelled action');
12518 this.pending = false;
12519 var error = this._execute(state, delay);
12523 else if (this.pending === false && this.id != null) {
12524 // Dequeue if the action didn't reschedule itself. Don't call
12525 // unsubscribe(), because the action could reschedule later.
12528 // scheduler.schedule(function doWork(counter) {
12529 // /* ... I'm a busy worker bee ... */
12530 // var originalAction = this;
12531 // /* wait 100ms before rescheduling the action */
12532 // setTimeout(function () {
12533 // originalAction.schedule(counter + 1);
12537 this.id = this.recycleAsyncId(this.scheduler, this.id, null);
12540 AsyncAction.prototype._execute = function (state, delay) {
12541 var errored = false;
12542 var errorValue = undefined;
12548 errorValue = !!e && e || new Error(e);
12551 this.unsubscribe();
12555 AsyncAction.prototype._unsubscribe = function () {
12557 var scheduler = this.scheduler;
12558 var actions = scheduler.actions;
12559 var index = actions.indexOf(this);
12563 this.pending = false;
12564 this.scheduler = null;
12565 if (index !== -1) {
12566 actions.splice(index, 1);
12569 this.id = this.recycleAsyncId(scheduler, id, null);
12572 return AsyncAction;
12573 }(Action_1.Action));
12574 exports.AsyncAction = AsyncAction;
12576 },{"../util/root":171,"./Action":146}],148:[function(require,module,exports){
12578 var __extends = (this && this.__extends) || function (d, b) {
12579 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12580 function __() { this.constructor = d; }
12581 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12583 var Scheduler_1 = require('../Scheduler');
12584 var AsyncScheduler = (function (_super) {
12585 __extends(AsyncScheduler, _super);
12586 function AsyncScheduler() {
12587 _super.apply(this, arguments);
12590 * A flag to indicate whether the Scheduler is currently executing a batch of
12594 this.active = false;
12596 * An internal ID used to track the latest asynchronous task such as those
12597 * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
12601 this.scheduled = undefined;
12603 AsyncScheduler.prototype.flush = function (action) {
12604 var actions = this.actions;
12606 actions.push(action);
12610 this.active = true;
12612 if (error = action.execute(action.state, action.delay)) {
12615 } while (action = actions.shift()); // exhaust the scheduler queue
12616 this.active = false;
12618 while (action = actions.shift()) {
12619 action.unsubscribe();
12624 return AsyncScheduler;
12625 }(Scheduler_1.Scheduler));
12626 exports.AsyncScheduler = AsyncScheduler;
12628 },{"../Scheduler":32}],149:[function(require,module,exports){
12630 var __extends = (this && this.__extends) || function (d, b) {
12631 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12632 function __() { this.constructor = d; }
12633 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12635 var AsyncAction_1 = require('./AsyncAction');
12637 * We need this JSDoc comment for affecting ESDoc.
12639 * @extends {Ignored}
12641 var QueueAction = (function (_super) {
12642 __extends(QueueAction, _super);
12643 function QueueAction(scheduler, work) {
12644 _super.call(this, scheduler, work);
12645 this.scheduler = scheduler;
12648 QueueAction.prototype.schedule = function (state, delay) {
12649 if (delay === void 0) { delay = 0; }
12651 return _super.prototype.schedule.call(this, state, delay);
12653 this.delay = delay;
12654 this.state = state;
12655 this.scheduler.flush(this);
12658 QueueAction.prototype.execute = function (state, delay) {
12659 return (delay > 0 || this.closed) ?
12660 _super.prototype.execute.call(this, state, delay) :
12661 this._execute(state, delay);
12663 QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
12664 if (delay === void 0) { delay = 0; }
12665 // If delay exists and is greater than 0, or if the delay is null (the
12666 // action wasn't rescheduled) but was originally scheduled as an async
12667 // action, then recycle as an async action.
12668 if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
12669 return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
12671 // Otherwise flush the scheduler starting with this action.
12672 return scheduler.flush(this);
12674 return QueueAction;
12675 }(AsyncAction_1.AsyncAction));
12676 exports.QueueAction = QueueAction;
12678 },{"./AsyncAction":147}],150:[function(require,module,exports){
12680 var __extends = (this && this.__extends) || function (d, b) {
12681 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12682 function __() { this.constructor = d; }
12683 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12685 var AsyncScheduler_1 = require('./AsyncScheduler');
12686 var QueueScheduler = (function (_super) {
12687 __extends(QueueScheduler, _super);
12688 function QueueScheduler() {
12689 _super.apply(this, arguments);
12691 return QueueScheduler;
12692 }(AsyncScheduler_1.AsyncScheduler));
12693 exports.QueueScheduler = QueueScheduler;
12695 },{"./AsyncScheduler":148}],151:[function(require,module,exports){
12697 var AsyncAction_1 = require('./AsyncAction');
12698 var AsyncScheduler_1 = require('./AsyncScheduler');
12703 * <span class="informal">Schedule task as if you used setTimeout(task, duration)</span>
12705 * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript
12706 * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating
12709 * If you just want to "defer" task, that is to perform it right after currently
12710 * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),
12711 * better choice will be the {@link asap} scheduler.
12713 * @example <caption>Use async scheduler to delay task</caption>
12714 * const task = () => console.log('it works!');
12716 * Rx.Scheduler.async.schedule(task, 2000);
12718 * // After 2 seconds logs:
12722 * @example <caption>Use async scheduler to repeat task in intervals</caption>
12723 * function task(state) {
12724 * console.log(state);
12725 * this.schedule(state + 1, 1000); // `this` references currently executing Action,
12726 * // which we reschedule with new state and delay
12729 * Rx.Scheduler.async.schedule(task, 3000, 0);
12741 exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
12743 },{"./AsyncAction":147,"./AsyncScheduler":148}],152:[function(require,module,exports){
12745 var QueueAction_1 = require('./QueueAction');
12746 var QueueScheduler_1 = require('./QueueScheduler');
12751 * <span class="informal">Put every next task on a queue, instead of executing it immediately</span>
12753 * `queue` scheduler, when used with delay, behaves the same as {@link async} scheduler.
12755 * When used without delay, it schedules given task synchronously - executes it right when
12756 * it is scheduled. However when called recursively, that is when inside the scheduled task,
12757 * another task is scheduled with queue scheduler, instead of executing immediately as well,
12758 * that task will be put on a queue and wait for current one to finish.
12760 * This means that when you execute task with `queue` scheduler, you are sure it will end
12761 * before any other task scheduled with that scheduler will start.
12763 * @examples <caption>Schedule recursively first, then do something</caption>
12765 * Rx.Scheduler.queue.schedule(() => {
12766 * Rx.Scheduler.queue.schedule(() => console.log('second')); // will not happen now, but will be put on a queue
12768 * console.log('first');
12776 * @example <caption>Reschedule itself recursively</caption>
12778 * Rx.Scheduler.queue.schedule(function(state) {
12779 * if (state !== 0) {
12780 * console.log('before', state);
12781 * this.schedule(state - 1); // `this` references currently executing Action,
12782 * // which we reschedule with new state
12783 * console.log('after', state);
12787 * // In scheduler that runs recursively, you would expect:
12795 * // But with queue it logs:
12808 exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
12810 },{"./QueueAction":149,"./QueueScheduler":150}],153:[function(require,module,exports){
12812 var root_1 = require('../util/root');
12813 function symbolIteratorPonyfill(root) {
12814 var Symbol = root.Symbol;
12815 if (typeof Symbol === 'function') {
12816 if (!Symbol.iterator) {
12817 Symbol.iterator = Symbol('iterator polyfill');
12819 return Symbol.iterator;
12822 // [for Mozilla Gecko 27-35:](https://mzl.la/2ewE1zC)
12823 var Set_1 = root.Set;
12824 if (Set_1 && typeof new Set_1()['@@iterator'] === 'function') {
12825 return '@@iterator';
12827 var Map_1 = root.Map;
12828 // required for compatability with es6-shim
12830 var keys = Object.getOwnPropertyNames(Map_1.prototype);
12831 for (var i = 0; i < keys.length; ++i) {
12833 // according to spec, Map.prototype[@@iterator] and Map.orototype.entries must be equal.
12834 if (key !== 'entries' && key !== 'size' && Map_1.prototype[key] === Map_1.prototype['entries']) {
12839 return '@@iterator';
12842 exports.symbolIteratorPonyfill = symbolIteratorPonyfill;
12843 exports.iterator = symbolIteratorPonyfill(root_1.root);
12845 * @deprecated use iterator instead
12847 exports.$$iterator = exports.iterator;
12849 },{"../util/root":171}],154:[function(require,module,exports){
12851 var root_1 = require('../util/root');
12852 function getSymbolObservable(context) {
12854 var Symbol = context.Symbol;
12855 if (typeof Symbol === 'function') {
12856 if (Symbol.observable) {
12857 $$observable = Symbol.observable;
12860 $$observable = Symbol('observable');
12861 Symbol.observable = $$observable;
12865 $$observable = '@@observable';
12867 return $$observable;
12869 exports.getSymbolObservable = getSymbolObservable;
12870 exports.observable = getSymbolObservable(root_1.root);
12872 * @deprecated use observable instead
12874 exports.$$observable = exports.observable;
12876 },{"../util/root":171}],155:[function(require,module,exports){
12878 var root_1 = require('../util/root');
12879 var Symbol = root_1.root.Symbol;
12880 exports.rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ?
12881 Symbol.for('rxSubscriber') : '@@rxSubscriber';
12883 * @deprecated use rxSubscriber instead
12885 exports.$$rxSubscriber = exports.rxSubscriber;
12887 },{"../util/root":171}],156:[function(require,module,exports){
12889 var root_1 = require('./root');
12890 var RequestAnimationFrameDefinition = (function () {
12891 function RequestAnimationFrameDefinition(root) {
12892 if (root.requestAnimationFrame) {
12893 this.cancelAnimationFrame = root.cancelAnimationFrame.bind(root);
12894 this.requestAnimationFrame = root.requestAnimationFrame.bind(root);
12896 else if (root.mozRequestAnimationFrame) {
12897 this.cancelAnimationFrame = root.mozCancelAnimationFrame.bind(root);
12898 this.requestAnimationFrame = root.mozRequestAnimationFrame.bind(root);
12900 else if (root.webkitRequestAnimationFrame) {
12901 this.cancelAnimationFrame = root.webkitCancelAnimationFrame.bind(root);
12902 this.requestAnimationFrame = root.webkitRequestAnimationFrame.bind(root);
12904 else if (root.msRequestAnimationFrame) {
12905 this.cancelAnimationFrame = root.msCancelAnimationFrame.bind(root);
12906 this.requestAnimationFrame = root.msRequestAnimationFrame.bind(root);
12908 else if (root.oRequestAnimationFrame) {
12909 this.cancelAnimationFrame = root.oCancelAnimationFrame.bind(root);
12910 this.requestAnimationFrame = root.oRequestAnimationFrame.bind(root);
12913 this.cancelAnimationFrame = root.clearTimeout.bind(root);
12914 this.requestAnimationFrame = function (cb) { return root.setTimeout(cb, 1000 / 60); };
12917 return RequestAnimationFrameDefinition;
12919 exports.RequestAnimationFrameDefinition = RequestAnimationFrameDefinition;
12920 exports.AnimationFrame = new RequestAnimationFrameDefinition(root_1.root);
12922 },{"./root":171}],157:[function(require,module,exports){
12924 var __extends = (this && this.__extends) || function (d, b) {
12925 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12926 function __() { this.constructor = d; }
12927 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12930 * An error thrown when an element was queried at a certain index of an
12931 * Observable, but no such index or position exists in that sequence.
12933 * @see {@link elementAt}
12934 * @see {@link take}
12935 * @see {@link takeLast}
12937 * @class ArgumentOutOfRangeError
12939 var ArgumentOutOfRangeError = (function (_super) {
12940 __extends(ArgumentOutOfRangeError, _super);
12941 function ArgumentOutOfRangeError() {
12942 var err = _super.call(this, 'argument out of range');
12943 this.name = err.name = 'ArgumentOutOfRangeError';
12944 this.stack = err.stack;
12945 this.message = err.message;
12947 return ArgumentOutOfRangeError;
12949 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError;
12951 },{}],158:[function(require,module,exports){
12953 var __extends = (this && this.__extends) || function (d, b) {
12954 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12955 function __() { this.constructor = d; }
12956 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12959 * An error thrown when an Observable or a sequence was queried but has no
12962 * @see {@link first}
12963 * @see {@link last}
12964 * @see {@link single}
12966 * @class EmptyError
12968 var EmptyError = (function (_super) {
12969 __extends(EmptyError, _super);
12970 function EmptyError() {
12971 var err = _super.call(this, 'no elements in sequence');
12972 this.name = err.name = 'EmptyError';
12973 this.stack = err.stack;
12974 this.message = err.message;
12978 exports.EmptyError = EmptyError;
12980 },{}],159:[function(require,module,exports){
12982 var __extends = (this && this.__extends) || function (d, b) {
12983 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12984 function __() { this.constructor = d; }
12985 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12988 * An error thrown when an action is invalid because the object has been
12991 * @see {@link Subject}
12992 * @see {@link BehaviorSubject}
12994 * @class ObjectUnsubscribedError
12996 var ObjectUnsubscribedError = (function (_super) {
12997 __extends(ObjectUnsubscribedError, _super);
12998 function ObjectUnsubscribedError() {
12999 var err = _super.call(this, 'object unsubscribed');
13000 this.name = err.name = 'ObjectUnsubscribedError';
13001 this.stack = err.stack;
13002 this.message = err.message;
13004 return ObjectUnsubscribedError;
13006 exports.ObjectUnsubscribedError = ObjectUnsubscribedError;
13008 },{}],160:[function(require,module,exports){
13010 var root_1 = require('./root');
13011 function minimalSetImpl() {
13012 // THIS IS NOT a full impl of Set, this is just the minimum
13013 // bits of functionality we need for this library.
13014 return (function () {
13015 function MinimalSet() {
13018 MinimalSet.prototype.add = function (value) {
13019 if (!this.has(value)) {
13020 this._values.push(value);
13023 MinimalSet.prototype.has = function (value) {
13024 return this._values.indexOf(value) !== -1;
13026 Object.defineProperty(MinimalSet.prototype, "size", {
13028 return this._values.length;
13033 MinimalSet.prototype.clear = function () {
13034 this._values.length = 0;
13039 exports.minimalSetImpl = minimalSetImpl;
13040 exports.Set = root_1.root.Set || minimalSetImpl();
13042 },{"./root":171}],161:[function(require,module,exports){
13044 var __extends = (this && this.__extends) || function (d, b) {
13045 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13046 function __() { this.constructor = d; }
13047 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13050 * An error thrown when one or more errors have occurred during the
13051 * `unsubscribe` of a {@link Subscription}.
13053 var UnsubscriptionError = (function (_super) {
13054 __extends(UnsubscriptionError, _super);
13055 function UnsubscriptionError(errors) {
13057 this.errors = errors;
13058 var err = Error.call(this, errors ?
13059 errors.length + " errors occurred during unsubscription:\n " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n ') : '');
13060 this.name = err.name = 'UnsubscriptionError';
13061 this.stack = err.stack;
13062 this.message = err.message;
13064 return UnsubscriptionError;
13066 exports.UnsubscriptionError = UnsubscriptionError;
13068 },{}],162:[function(require,module,exports){
13070 // typeof any so that it we don't have to cast when comparing a result to the error object
13071 exports.errorObject = { e: {} };
13073 },{}],163:[function(require,module,exports){
13075 exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
13077 },{}],164:[function(require,module,exports){
13079 exports.isArrayLike = (function (x) { return x && typeof x.length === 'number'; });
13081 },{}],165:[function(require,module,exports){
13083 function isDate(value) {
13084 return value instanceof Date && !isNaN(+value);
13086 exports.isDate = isDate;
13088 },{}],166:[function(require,module,exports){
13090 function isFunction(x) {
13091 return typeof x === 'function';
13093 exports.isFunction = isFunction;
13095 },{}],167:[function(require,module,exports){
13097 var isArray_1 = require('../util/isArray');
13098 function isNumeric(val) {
13099 // parseFloat NaNs numeric-cast false positives (null|true|false|"")
13100 // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
13101 // subtraction forces infinities to NaN
13102 // adding 1 corrects loss of precision from parseFloat (#15100)
13103 return !isArray_1.isArray(val) && (val - parseFloat(val) + 1) >= 0;
13105 exports.isNumeric = isNumeric;
13108 },{"../util/isArray":163}],168:[function(require,module,exports){
13110 function isObject(x) {
13111 return x != null && typeof x === 'object';
13113 exports.isObject = isObject;
13115 },{}],169:[function(require,module,exports){
13117 function isPromise(value) {
13118 return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
13120 exports.isPromise = isPromise;
13122 },{}],170:[function(require,module,exports){
13124 function isScheduler(value) {
13125 return value && typeof value.schedule === 'function';
13127 exports.isScheduler = isScheduler;
13129 },{}],171:[function(require,module,exports){
13130 (function (global){
13132 // CommonJS / Node have global context exposed as "global" variable.
13133 // We don't want to include the whole node.d.ts this this compilation unit so we'll just fake
13134 // the global "global" var for now.
13135 var __window = typeof window !== 'undefined' && window;
13136 var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
13137 self instanceof WorkerGlobalScope && self;
13138 var __global = typeof global !== 'undefined' && global;
13139 var _root = __window || __global || __self;
13140 exports.root = _root;
13141 // Workaround Closure Compiler restriction: The body of a goog.module cannot use throw.
13142 // This is needed when used with angular/tsickle which inserts a goog.module statement.
13146 throw new Error('RxJS could not find any global context (window, self, global)');
13150 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
13152 },{}],172:[function(require,module,exports){
13154 var root_1 = require('./root');
13155 var isArrayLike_1 = require('./isArrayLike');
13156 var isPromise_1 = require('./isPromise');
13157 var isObject_1 = require('./isObject');
13158 var Observable_1 = require('../Observable');
13159 var iterator_1 = require('../symbol/iterator');
13160 var InnerSubscriber_1 = require('../InnerSubscriber');
13161 var observable_1 = require('../symbol/observable');
13162 function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) {
13163 var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex);
13164 if (destination.closed) {
13167 if (result instanceof Observable_1.Observable) {
13168 if (result._isScalar) {
13169 destination.next(result.value);
13170 destination.complete();
13174 return result.subscribe(destination);
13177 else if (isArrayLike_1.isArrayLike(result)) {
13178 for (var i = 0, len = result.length; i < len && !destination.closed; i++) {
13179 destination.next(result[i]);
13181 if (!destination.closed) {
13182 destination.complete();
13185 else if (isPromise_1.isPromise(result)) {
13186 result.then(function (value) {
13187 if (!destination.closed) {
13188 destination.next(value);
13189 destination.complete();
13191 }, function (err) { return destination.error(err); })
13192 .then(null, function (err) {
13193 // Escaping the Promise trap: globally throw unhandled errors
13194 root_1.root.setTimeout(function () { throw err; });
13196 return destination;
13198 else if (result && typeof result[iterator_1.iterator] === 'function') {
13199 var iterator = result[iterator_1.iterator]();
13201 var item = iterator.next();
13203 destination.complete();
13206 destination.next(item.value);
13207 if (destination.closed) {
13212 else if (result && typeof result[observable_1.observable] === 'function') {
13213 var obs = result[observable_1.observable]();
13214 if (typeof obs.subscribe !== 'function') {
13215 destination.error(new TypeError('Provided object does not correctly implement Symbol.observable'));
13218 return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex));
13222 var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'";
13223 var msg = ("You provided " + value + " where a stream was expected.")
13224 + ' You can provide an Observable, Promise, Array, or Iterable.';
13225 destination.error(new TypeError(msg));
13229 exports.subscribeToResult = subscribeToResult;
13231 },{"../InnerSubscriber":26,"../Observable":28,"../symbol/iterator":153,"../symbol/observable":154,"./isArrayLike":164,"./isObject":168,"./isPromise":169,"./root":171}],173:[function(require,module,exports){
13233 var Subscriber_1 = require('../Subscriber');
13234 var rxSubscriber_1 = require('../symbol/rxSubscriber');
13235 var Observer_1 = require('../Observer');
13236 function toSubscriber(nextOrObserver, error, complete) {
13237 if (nextOrObserver) {
13238 if (nextOrObserver instanceof Subscriber_1.Subscriber) {
13239 return nextOrObserver;
13241 if (nextOrObserver[rxSubscriber_1.rxSubscriber]) {
13242 return nextOrObserver[rxSubscriber_1.rxSubscriber]();
13245 if (!nextOrObserver && !error && !complete) {
13246 return new Subscriber_1.Subscriber(Observer_1.empty);
13248 return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
13250 exports.toSubscriber = toSubscriber;
13252 },{"../Observer":29,"../Subscriber":35,"../symbol/rxSubscriber":155}],174:[function(require,module,exports){
13254 var errorObject_1 = require('./errorObject');
13255 var tryCatchTarget;
13256 function tryCatcher() {
13258 return tryCatchTarget.apply(this, arguments);
13261 errorObject_1.errorObject.e = e;
13262 return errorObject_1.errorObject;
13265 function tryCatch(fn) {
13266 tryCatchTarget = fn;
13269 exports.tryCatch = tryCatch;
13272 },{"./errorObject":162}],175:[function(require,module,exports){
13273 // threejs.org/license
13274 (function(l,oa){"object"===typeof exports&&"undefined"!==typeof module?oa(exports):"function"===typeof define&&define.amd?define(["exports"],oa):oa(l.THREE=l.THREE||{})})(this,function(l){function oa(){}function C(a,b){this.x=a||0;this.y=b||0}function ea(a,b,c,d,e,f,g,h,k,m){Object.defineProperty(this,"id",{value:Oe++});this.uuid=Q.generateUUID();this.name="";this.image=void 0!==a?a:ea.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=void 0!==b?b:ea.DEFAULT_MAPPING;this.wrapS=void 0!==c?c:1001;this.wrapT=
13275 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 C(0,0);this.repeat=new C(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=Q.generateUUID();this.width=
13276 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 ea(void 0,void 0,c.wrapS,c.wrapT,c.magFilter,c.minFilter,c.format,c.type,c.anisotropy,c.encoding);this.depthBuffer=void 0!==c.depthBuffer?c.depthBuffer:!0;this.stencilBuffer=void 0!==c.stencilBuffer?c.stencilBuffer:!0;this.depthTexture=void 0!==c.depthTexture?c.depthTexture:null}function Eb(a,b,c){Db.call(this,a,b,c);this.activeMipMapLevel=
13277 this.activeCubeFace=0}function da(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._w=void 0!==d?d:1}function q(a,b,c){this.x=a||0;this.y=b||0;this.z=c||0}function H(){this.elements=new Float32Array([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 Za(a,b,c,d,e,f,g,h,k,m){a=void 0!==a?a:[];ea.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>=
13278 d||0<d)return a;var e=b*c,f=pe[e];void 0===f&&(f=new Float32Array(e),pe[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 qe(a,b){var c=re[b];void 0===c&&(c=new Int32Array(b),re[b]=c);for(var d=0;d!==b;++d)c[d]=a.allocTextureUnit();return c}function Pe(a,b){a.uniform1f(this.addr,b)}function Qe(a,b){a.uniform1i(this.addr,b)}function Re(a,b){void 0===b.x?a.uniform2fv(this.addr,b):a.uniform2f(this.addr,b.x,b.y)}function Se(a,b){void 0!==b.x?a.uniform3f(this.addr,
13279 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 Te(a,b){void 0===b.x?a.uniform4fv(this.addr,b):a.uniform4f(this.addr,b.x,b.y,b.z,b.w)}function Ue(a,b){a.uniformMatrix2fv(this.addr,!1,b.elements||b)}function Ve(a,b){a.uniformMatrix3fv(this.addr,!1,b.elements||b)}function We(a,b){a.uniformMatrix4fv(this.addr,!1,b.elements||b)}function Xe(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTexture2D(b||se,d)}function Ye(a,b,c){var d=c.allocTextureUnit();
13280 a.uniform1i(this.addr,d);c.setTextureCube(b||te,d)}function ue(a,b){a.uniform2iv(this.addr,b)}function ve(a,b){a.uniform3iv(this.addr,b)}function we(a,b){a.uniform4iv(this.addr,b)}function Ze(a){switch(a){case 5126:return Pe;case 35664:return Re;case 35665:return Se;case 35666:return Te;case 35674:return Ue;case 35675:return Ve;case 35676:return We;case 35678:return Xe;case 35680:return Ye;case 5124:case 35670:return Qe;case 35667:case 35671:return ue;case 35668:case 35672:return ve;case 35669:case 35673:return we}}
13281 function $e(a,b){a.uniform1fv(this.addr,b)}function af(a,b){a.uniform1iv(this.addr,b)}function bf(a,b){a.uniform2fv(this.addr,Fb(b,this.size,2))}function cf(a,b){a.uniform3fv(this.addr,Fb(b,this.size,3))}function df(a,b){a.uniform4fv(this.addr,Fb(b,this.size,4))}function ef(a,b){a.uniformMatrix2fv(this.addr,!1,Fb(b,this.size,4))}function ff(a,b){a.uniformMatrix3fv(this.addr,!1,Fb(b,this.size,9))}function gf(a,b){a.uniformMatrix4fv(this.addr,!1,Fb(b,this.size,16))}function hf(a,b,c){var d=b.length,
13282 e=qe(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTexture2D(b[a]||se,e[a])}function jf(a,b,c){var d=b.length,e=qe(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTextureCube(b[a]||te,e[a])}function kf(a){switch(a){case 5126:return $e;case 35664:return bf;case 35665:return cf;case 35666:return df;case 35674:return ef;case 35675:return ff;case 35676:return gf;case 35678:return hf;case 35680:return jf;case 5124:case 35670:return af;case 35667:case 35671:return ue;case 35668:case 35672:return ve;
13283 case 35669:case 35673:return we}}function lf(a,b,c){this.id=a;this.addr=c;this.setValue=Ze(b.type)}function mf(a,b,c){this.id=a;this.addr=c;this.size=b.size;this.setValue=kf(b.type)}function xe(a){this.id=a;this.seq=[];this.map={}}function $a(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(Id.lastIndex=0;;){var m=Id.exec(h),x=Id.lastIndex,
13284 p=m[1],n=m[3];"]"===m[2]&&(p|=0);if(void 0===n||"["===n&&x+2===k){h=g;e=void 0===n?new lf(p,e,f):new mf(p,e,f);h.seq.push(e);h.map[e.id]=e;break}else n=g.map[p],void 0===n&&(n=new xe(p),p=g,g=n,p.seq.push(g),p.map[g.id]=g),g=n}}}function N(a,b,c){return void 0===b&&void 0===c?this.set(a):this.setRGB(a,b,c)}function db(a,b,c,d,e,f,g,h,k,m,x,p){ea.call(this,null,f,g,h,k,m,d,e,x,p);this.image={data:a,width:b,height:c};this.magFilter=void 0!==k?k:1003;this.minFilter=void 0!==m?m:1003;this.flipY=this.generateMipmaps=
13285 !1;this.unpackAlignment=1}function pc(a,b){this.min=void 0!==a?a:new C(Infinity,Infinity);this.max=void 0!==b?b:new C(-Infinity,-Infinity)}function nf(a,b){var c,d,e,f,g,h,k,m,x,p,n=a.context,r=a.state,w,l,F,t,v,M;this.render=function(z,A,I){if(0!==b.length){z=new q;var E=I.w/I.z,K=.5*I.z,la=.5*I.w,J=16/I.w,ca=new C(J*E,J),Da=new q(1,1,0),eb=new C(1,1),Na=new pc;Na.min.set(I.x,I.y);Na.max.set(I.x+(I.z-16),I.y+(I.w-16));if(void 0===t){var J=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),O=
13286 new Uint16Array([0,1,2,0,2,3]);w=n.createBuffer();l=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,w);n.bufferData(n.ARRAY_BUFFER,J,n.STATIC_DRAW);n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,l);n.bufferData(n.ELEMENT_ARRAY_BUFFER,O,n.STATIC_DRAW);v=n.createTexture();M=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);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);
13287 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,M);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,n.TEXTURE_MAG_FILTER,n.NEAREST);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST);var J=F={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}",
13288 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}"},O=n.createProgram(),P=n.createShader(n.FRAGMENT_SHADER),
13289 R=n.createShader(n.VERTEX_SHADER),T="precision "+a.getPrecision()+" float;\n";n.shaderSource(P,T+J.fragmentShader);n.shaderSource(R,T+J.vertexShader);n.compileShader(P);n.compileShader(R);n.attachShader(O,P);n.attachShader(O,R);n.linkProgram(O);t=O;x=n.getAttribLocation(t,"position");p=n.getAttribLocation(t,"uv");c=n.getUniformLocation(t,"renderType");d=n.getUniformLocation(t,"map");e=n.getUniformLocation(t,"occlusionMap");f=n.getUniformLocation(t,"opacity");g=n.getUniformLocation(t,"color");h=n.getUniformLocation(t,
13290 "scale");k=n.getUniformLocation(t,"rotation");m=n.getUniformLocation(t,"screenPosition")}n.useProgram(t);r.initAttributes();r.enableAttribute(x);r.enableAttribute(p);r.disableUnusedAttributes();n.uniform1i(e,0);n.uniform1i(d,1);n.bindBuffer(n.ARRAY_BUFFER,w);n.vertexAttribPointer(x,2,n.FLOAT,!1,16,0);n.vertexAttribPointer(p,2,n.FLOAT,!1,16,8);n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,l);r.disable(n.CULL_FACE);r.setDepthWrite(!1);O=0;for(P=b.length;O<P;O++)if(J=16/I.w,ca.set(J*E,J),R=b[O],z.set(R.matrixWorld.elements[12],
13291 R.matrixWorld.elements[13],R.matrixWorld.elements[14]),z.applyMatrix4(A.matrixWorldInverse),z.applyProjection(A.projectionMatrix),Da.copy(z),eb.x=I.x+Da.x*K+K-8,eb.y=I.y+Da.y*la+la-8,!0===Na.containsPoint(eb)){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,eb.x,eb.y,16,16,0);n.uniform1i(c,0);n.uniform2f(h,ca.x,ca.y);n.uniform3f(m,Da.x,Da.y,Da.z);r.disable(n.BLEND);r.enable(n.DEPTH_TEST);n.drawElements(n.TRIANGLES,
13292 6,n.UNSIGNED_SHORT,0);r.activeTexture(n.TEXTURE0);r.bindTexture(n.TEXTURE_2D,M);n.copyTexImage2D(n.TEXTURE_2D,0,n.RGBA,eb.x,eb.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);R.positionScreen.copy(Da);R.customUpdateCallback?R.customUpdateCallback(R):R.updateLensFlares();n.uniform1i(c,2);r.enable(n.BLEND);for(var T=0,y=R.lensFlares.length;T<y;T++){var V=R.lensFlares[T];.001<V.opacity&&.001<
13293 V.scale&&(Da.x=V.x,Da.y=V.y,Da.z=V.z,J=V.size*V.scale/I.w,ca.x=J*E,ca.y=J,n.uniform3f(m,Da.x,Da.y,Da.z),n.uniform2f(h,ca.x,ca.y),n.uniform1f(k,V.rotation),n.uniform1f(f,V.opacity),n.uniform3f(g,V.color.r,V.color.g,V.color.b),r.setBlending(V.blending,V.blendEquation,V.blendSrc,V.blendDst),a.setTexture2D(V.texture,1),n.drawElements(n.TRIANGLES,6,n.UNSIGNED_SHORT,0))}}r.enable(n.CULL_FACE);r.enable(n.DEPTH_TEST);r.setDepthWrite(!0);a.resetGLState()}}}function of(a,b){var c,d,e,f,g,h,k,m,x,p,n,r,w,l,
13294 F,t,v;function M(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:b.id-a.id}var z=a.context,A=a.state,I,E,K,la,J=new q,ca=new da,Da=new q;this.render=function(q,Na){if(0!==b.length){if(void 0===K){var O=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]);I=z.createBuffer();E=z.createBuffer();z.bindBuffer(z.ARRAY_BUFFER,I);z.bufferData(z.ARRAY_BUFFER,O,z.STATIC_DRAW);z.bindBuffer(z.ELEMENT_ARRAY_BUFFER,E);z.bufferData(z.ELEMENT_ARRAY_BUFFER,
13295 P,z.STATIC_DRAW);var O=z.createProgram(),P=z.createShader(z.VERTEX_SHADER),R=z.createShader(z.FRAGMENT_SHADER);z.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"));
13296 z.shaderSource(R,["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"));
13297 z.compileShader(P);z.compileShader(R);z.attachShader(O,P);z.attachShader(O,R);z.linkProgram(O);K=O;t=z.getAttribLocation(K,"position");v=z.getAttribLocation(K,"uv");c=z.getUniformLocation(K,"uvOffset");d=z.getUniformLocation(K,"uvScale");e=z.getUniformLocation(K,"rotation");f=z.getUniformLocation(K,"scale");g=z.getUniformLocation(K,"color");h=z.getUniformLocation(K,"map");k=z.getUniformLocation(K,"opacity");m=z.getUniformLocation(K,"modelViewMatrix");x=z.getUniformLocation(K,"projectionMatrix");p=
13298 z.getUniformLocation(K,"fogType");n=z.getUniformLocation(K,"fogDensity");r=z.getUniformLocation(K,"fogNear");w=z.getUniformLocation(K,"fogFar");l=z.getUniformLocation(K,"fogColor");F=z.getUniformLocation(K,"alphaTest");O=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");O.width=8;O.height=8;P=O.getContext("2d");P.fillStyle="white";P.fillRect(0,0,8,8);la=new ea(O);la.needsUpdate=!0}z.useProgram(K);A.initAttributes();A.enableAttribute(t);A.enableAttribute(v);A.disableUnusedAttributes();
13299 A.disable(z.CULL_FACE);A.enable(z.BLEND);z.bindBuffer(z.ARRAY_BUFFER,I);z.vertexAttribPointer(t,2,z.FLOAT,!1,16,0);z.vertexAttribPointer(v,2,z.FLOAT,!1,16,8);z.bindBuffer(z.ELEMENT_ARRAY_BUFFER,E);z.uniformMatrix4fv(x,!1,Na.projectionMatrix.elements);A.activeTexture(z.TEXTURE0);z.uniform1i(h,0);P=O=0;(R=q.fog)?(z.uniform3f(l,R.color.r,R.color.g,R.color.b),R.isFog?(z.uniform1f(r,R.near),z.uniform1f(w,R.far),z.uniform1i(p,1),P=O=1):R.isFogExp2&&(z.uniform1f(n,R.density),z.uniform1i(p,2),P=O=2)):(z.uniform1i(p,
13300 0),P=O=0);for(var R=0,T=b.length;R<T;R++){var y=b[R];y.modelViewMatrix.multiplyMatrices(Na.matrixWorldInverse,y.matrixWorld);y.z=-y.modelViewMatrix.elements[14]}b.sort(M);for(var V=[],R=0,T=b.length;R<T;R++){var y=b[R],ra=y.material;!1!==ra.visible&&(z.uniform1f(F,ra.alphaTest),z.uniformMatrix4fv(m,!1,y.modelViewMatrix.elements),y.matrixWorld.decompose(J,ca,Da),V[0]=Da.x,V[1]=Da.y,y=0,q.fog&&ra.fog&&(y=P),O!==y&&(z.uniform1i(p,y),O=y),null!==ra.map?(z.uniform2f(c,ra.map.offset.x,ra.map.offset.y),
13301 z.uniform2f(d,ra.map.repeat.x,ra.map.repeat.y)):(z.uniform2f(c,0,0),z.uniform2f(d,1,1)),z.uniform1f(k,ra.opacity),z.uniform3f(g,ra.color.r,ra.color.g,ra.color.b),z.uniform1f(e,ra.rotation),z.uniform2fv(f,V),A.setBlending(ra.blending,ra.blendEquation,ra.blendSrc,ra.blendDst),A.setDepthTest(ra.depthTest),A.setDepthWrite(ra.depthWrite),ra.map?a.setTexture2D(ra.map,0):a.setTexture2D(la,0),z.drawElements(z.TRIANGLES,6,z.UNSIGNED_SHORT,0))}A.enable(z.CULL_FACE);a.resetGLState()}}}function W(){Object.defineProperty(this,
13302 "id",{value:pf++});this.uuid=Q.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=
13303 !1;this.alphaTest=this.polygonOffsetUnits=this.polygonOffsetFactor=0;this.premultipliedAlpha=!1;this.overdraw=0;this._needsUpdate=this.visible=!0}function Ia(a){W.call(this);this.type="ShaderMaterial";this.defines={};this.uniforms={};this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";this.linewidth=1;this.wireframe=!1;this.wireframeLinewidth=1;this.morphNormals=
13304 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 ab(a){W.call(this);this.type="MeshDepthMaterial";this.depthPacking=3200;this.morphTargets=
13305 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 ya(a,b){this.min=void 0!==a?a:new q(Infinity,Infinity,Infinity);this.max=void 0!==b?b:new q(-Infinity,-Infinity,-Infinity)}function Fa(a,b){this.center=void 0!==a?a:new q;this.radius=void 0!==b?b:0}function za(){this.elements=new Float32Array([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.")}
13306 function ma(a,b){this.normal=void 0!==a?a:new q(1,0,0);this.constant=void 0!==b?b:0}function qc(a,b,c,d,e,f){this.planes=[void 0!==a?a:new ma,void 0!==b?b:new ma,void 0!==c?c:new ma,void 0!==d?d:new ma,void 0!==e?e:new ma,void 0!==f?f:new ma]}function ye(a,b,c,d){function e(b,c,d,e){var f=b.geometry,g;g=F;var h=b.customDepthMaterial;d&&(g=t,h=b.customDistanceMaterial);h?g=h:(h=!1,c.morphTargets&&(f&&f.isBufferGeometry?h=f.morphAttributes&&f.morphAttributes.position&&0<f.morphAttributes.position.length:
13307 f&&f.isGeometry&&(h=f.morphTargets&&0<f.morphTargets.length)),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=v[f],void 0===b&&(b={},v[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;ca.renderSingleSided&&2==h&&(h=0);ca.renderReverseSided&&(0===h?h=1:1===h&&(h=0));g.side=h;g.clipShadows=c.clipShadows;g.clippingPlanes=c.clippingPlanes;g.wireframeLinewidth=
13308 c.wireframeLinewidth;g.linewidth=c.linewidth;d&&void 0!==g.uniforms.lightPos&&g.uniforms.lightPos.value.copy(e);return g}function f(a,b,c){if(!1!==a.visible){0!==(a.layers.mask&b.layers.mask)&&(a.isMesh||a.isLine||a.isPoints)&&a.castShadow&&(!1===a.frustumCulled||!0===k.intersectsObject(a))&&!0===a.material.visible&&(a.modelViewMatrix.multiplyMatrices(c.matrixWorldInverse,a.matrixWorld),l.push(a));a=a.children;for(var d=0,e=a.length;d<e;d++)f(a[d],b,c)}}var g=a.context,h=a.state,k=new qc,m=new H,
13309 x=b.shadows,p=new C,n=new C(d.maxTextureSize,d.maxTextureSize),r=new q,w=new q,l=[],F=Array(4),t=Array(4),v={},M=[new q(1,0,0),new q(-1,0,0),new q(0,0,1),new q(0,0,-1),new q(0,1,0),new q(0,-1,0)],z=[new q(0,1,0),new q(0,1,0),new q(0,1,0),new q(0,1,0),new q(0,0,1),new q(0,0,-1)],A=[new ga,new ga,new ga,new ga,new ga,new ga];b=new ab;b.depthPacking=3201;b.clipping=!0;d=Gb.distanceRGBA;for(var I=Ja.clone(d.uniforms),E=0;4!==E;++E){var K=0!==(E&1),la=0!==(E&2),J=b.clone();J.morphTargets=K;J.skinning=
13310 la;F[E]=J;K=new Ia({defines:{USE_SHADOWMAP:""},uniforms:I,vertexShader:d.vertexShader,fragmentShader:d.fragmentShader,morphTargets:K,skinning:la,clipping:!0});t[E]=K}var ca=this;this.enabled=!1;this.autoUpdate=!0;this.needsUpdate=!1;this.type=1;this.renderSingleSided=this.renderReverseSided=!0;this.render=function(b,d){if(!1!==ca.enabled&&(!1!==ca.autoUpdate||!1!==ca.needsUpdate)&&0!==x.length){h.buffers.color.setClear(1,1,1,1);h.disable(g.BLEND);h.setDepthTest(!0);h.setScissorTest(!1);for(var v,
13311 q,t=0,F=x.length;t<F;t++){var I=x[t],E=I.shadow;if(void 0===E)console.warn("THREE.WebGLShadowMap:",I,"has no shadow.");else{var K=E.camera;p.copy(E.mapSize);p.min(n);if(I&&I.isPointLight){v=6;q=!0;var J=p.x,la=p.y;A[0].set(2*J,la,J,la);A[1].set(0,la,J,la);A[2].set(3*J,la,J,la);A[3].set(J,la,J,la);A[4].set(3*J,0,J,la);A[5].set(J,0,J,la);p.x*=4;p.y*=2}else v=1,q=!1;null===E.map&&(E.map=new Db(p.x,p.y,{minFilter:1003,magFilter:1003,format:1023}),K.updateProjectionMatrix());E.isSpotLightShadow&&E.update(I);
13312 E&&E.isRectAreaLightShadow&&E.update(I);J=E.map;E=E.matrix;w.setFromMatrixPosition(I.matrixWorld);K.position.copy(w);a.setRenderTarget(J);a.clear();for(J=0;J<v;J++){q?(r.copy(K.position),r.add(M[J]),K.up.copy(z[J]),K.lookAt(r),h.viewport(A[J])):(r.setFromMatrixPosition(I.target.matrixWorld),K.lookAt(r));K.updateMatrixWorld();K.matrixWorldInverse.getInverse(K.matrixWorld);E.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1);E.multiply(K.projectionMatrix);E.multiply(K.matrixWorldInverse);m.multiplyMatrices(K.projectionMatrix,
13313 K.matrixWorldInverse);k.setFromMatrix(m);l.length=0;f(b,d,K);for(var la=0,y=l.length;la<y;la++){var C=l[la],Jd=c.update(C),Ta=C.material;if(Ta&&Ta.isMultiMaterial)for(var G=Jd.groups,Ta=Ta.materials,D=0,Ga=G.length;D<Ga;D++){var N=G[D],H=Ta[N.materialIndex];!0===H.visible&&(H=e(C,H,q,w),a.renderBufferDirect(K,null,Jd,H,C,N))}else H=e(C,Ta,q,w),a.renderBufferDirect(K,null,Jd,H,C,null)}}}}v=a.getClearColor();q=a.getClearAlpha();a.setClearColor(v,q);ca.needsUpdate=!1}}}function bb(a,b){this.origin=void 0!==
13314 a?a:new q;this.direction=void 0!==b?b:new q}function cb(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._order=d||cb.DefaultOrder}function gd(){this.mask=1}function G(){Object.defineProperty(this,"id",{value:qf++});this.uuid=Q.generateUUID();this.name="";this.type="Object3D";this.parent=null;this.children=[];this.up=G.DefaultUp.clone();var a=new q,b=new cb,c=new da,d=new q(1,1,1);b.onChange(function(){c.setFromEuler(b,!1)});c.onChange(function(){b.setFromQuaternion(c,void 0,!1)});Object.defineProperties(this,
13315 {position:{enumerable:!0,value:a},rotation:{enumerable:!0,value:b},quaternion:{enumerable:!0,value:c},scale:{enumerable:!0,value:d},modelViewMatrix:{value:new H},normalMatrix:{value:new za}});this.matrix=new H;this.matrixWorld=new H;this.matrixAutoUpdate=G.DefaultMatrixAutoUpdate;this.matrixWorldNeedsUpdate=!1;this.layers=new gd;this.visible=!0;this.receiveShadow=this.castShadow=!1;this.frustumCulled=!0;this.renderOrder=0;this.userData={};this.onBeforeRender=function(){};this.onAfterRender=function(){}}
13316 function gb(a,b){this.start=void 0!==a?a:new q;this.end=void 0!==b?b:new q}function Aa(a,b,c){this.a=void 0!==a?a:new q;this.b=void 0!==b?b:new q;this.c=void 0!==c?c:new q}function ha(a,b,c,d,e,f){this.a=a;this.b=b;this.c=c;this.normal=d&&d.isVector3?d:new q;this.vertexNormals=Array.isArray(d)?d:[];this.color=e&&e.isColor?e:new N;this.vertexColors=Array.isArray(e)?e:[];this.materialIndex=void 0!==f?f:0}function Ka(a){W.call(this);this.type="MeshBasicMaterial";this.color=new N(16777215);this.lightMap=
13317 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 y(a,b,c){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.uuid=Q.generateUUID();this.array=a;
13318 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){y.call(this,new Int8Array(a),b)}function sc(a,b){y.call(this,new Uint8Array(a),b)}function tc(a,b){y.call(this,new Uint8ClampedArray(a),b)}function uc(a,b){y.call(this,new Int16Array(a),b)}function Ra(a,b){y.call(this,new Uint16Array(a),b)}function vc(a,b){y.call(this,new Int32Array(a),b)}function Ua(a,b){y.call(this,
13319 new Uint32Array(a),b)}function X(a,b){y.call(this,new Float32Array(a),b)}function wc(a,b){y.call(this,new Float64Array(a),b)}function ze(){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=!1}function S(){Object.defineProperty(this,"id",
13320 {value:Kd++});this.uuid=Q.generateUUID();this.name="";this.type="Geometry";this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.lineDistancesNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.uvsNeedUpdate=this.verticesNeedUpdate=this.elementsNeedUpdate=!1}function D(){Object.defineProperty(this,"id",
13321 {value:Kd++});this.uuid=Q.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 Ba(a,b){G.call(this);this.type="Mesh";this.geometry=void 0!==a?a:new D;this.material=void 0!==b?b:new Ka({color:16777215*Math.random()});this.drawMode=0;this.updateMorphTargets()}function hb(a,b,c,d,e,f){function g(a,b,c,d,e,f,g,k,m,y,C){var Na=f/m,O=g/y,
13322 P=f/2,R=g/2,T=k/2;g=m+1;for(var G=y+1,V=f=0,D=new q,L=0;L<G;L++)for(var N=L*O-R,H=0;H<g;H++)D[a]=(H*Na-P)*d,D[b]=N*e,D[c]=T,p[w]=D.x,p[w+1]=D.y,p[w+2]=D.z,D[a]=0,D[b]=0,D[c]=0<k?1:-1,n[w]=D.x,n[w+1]=D.y,n[w+2]=D.z,r[l]=H/m,r[l+1]=1-L/y,w+=3,l+=2,f+=1;for(L=0;L<y;L++)for(H=0;H<m;H++)a=t+H+g*(L+1),b=t+(H+1)+g*(L+1),c=t+(H+1)+g*L,x[F]=t+H+g*L,x[F+1]=a,x[F+2]=c,x[F+3]=a,x[F+4]=b,x[F+5]=c,F+=6,V+=6;h.addGroup(v,V,C);v+=V;t+=f}D.call(this);this.type="BoxBufferGeometry";this.parameters={width:a,height:b,
13323 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=function(a,b,c){return a=0+(a+1)*(b+1)*2+(a+1)*(c+1)*2+(c+1)*(b+1)*2}(d,e,f),m=function(a,b,c){a=0+a*b*2+a*c*2+c*b*2;return 6*a}(d,e,f),x=new (65535<m?Uint32Array:Uint16Array)(m),p=new Float32Array(3*k),n=new Float32Array(3*k),r=new Float32Array(2*k),w=0,l=0,F=0,t=0,v=0;g("z","y","x",-1,-1,c,b,a,f,e,0);g("z","y","x",1,-1,c,b,-a,f,e,1);g("x","z","y",1,1,a,c,b,d,f,2);g("x",
13324 "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(new y(x,1));this.addAttribute("position",new y(p,3));this.addAttribute("normal",new y(n,3));this.addAttribute("uv",new y(r,2))}function ib(a,b,c,d){D.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;b=new Float32Array(g*h*3);a=new Float32Array(g*h*3);
13325 for(var x=new Float32Array(g*h*2),p=0,n=0,r=0;r<h;r++)for(var w=r*m-f,l=0;l<g;l++)b[p]=l*k-e,b[p+1]=-w,a[p+2]=1,x[n]=l/c,x[n+1]=1-r/d,p+=3,n+=2;p=0;e=new (65535<b.length/3?Uint32Array:Uint16Array)(c*d*6);for(r=0;r<d;r++)for(l=0;l<c;l++)f=l+g*(r+1),h=l+1+g*(r+1),k=l+1+g*r,e[p]=l+g*r,e[p+1]=f,e[p+2]=k,e[p+3]=f,e[p+4]=h,e[p+5]=k,p+=6;this.setIndex(new y(e,1));this.addAttribute("position",new y(b,3));this.addAttribute("normal",new y(a,3));this.addAttribute("uv",new y(x,2))}function sa(){G.call(this);
13326 this.type="Camera";this.matrixWorldInverse=new H;this.projectionMatrix=new H}function Ha(a,b,c,d){sa.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 Hb(a,b,c,d,e,f){sa.call(this);this.type="OrthographicCamera";this.zoom=1;this.view=null;this.left=a;this.right=b;this.top=c;this.bottom=d;this.near=
13327 void 0!==e?e:.1;this.far=void 0!==f?f:2E3;this.updateProjectionMatrix()}function rf(a,b,c){var d,e,f;return{setMode:function(a){d=a},setIndex: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)},render:function(b,h){a.drawElements(d,h,e,b*f);c.calls++;c.vertices+=h;d===a.TRIANGLES&&(c.faces+=h/3)},renderInstances:function(g,h,k){var m=b.get("ANGLE_instanced_arrays");null===
13328 m?console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):(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;return{setMode:function(a){d=a},render:function(b,f){a.drawArrays(d,b,f);c.calls++;c.vertices+=f;d===a.TRIANGLES&&(c.faces+=f/3)},renderInstances:function(e){var f=b.get("ANGLE_instanced_arrays");
13329 if(null===f)console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");else{var g=e.attributes.position,g=g.isInterleavedBufferAttribute?g.data.count:g.count;f.drawArraysInstancedANGLE(d,0,g,e.maxInstancedCount);c.calls++;c.vertices+=g*e.maxInstancedCount;d===a.TRIANGLES&&(c.faces+=e.maxInstancedCount*g/3)}}}}function tf(){var a={};return{get:function(b){if(void 0!==a[b.id])return a[b.id];var c;switch(b.type){case "DirectionalLight":c=
13330 {direction:new q,color:new N,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "SpotLight":c={position:new q,direction:new q,color:new N,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "PointLight":c={position:new q,color:new N,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "HemisphereLight":c={direction:new q,skyColor:new N,groundColor:new N};break;case "RectAreaLight":c=
13331 {color:new N,position:new q,halfWidth:new q,halfHeight:new q}}return a[b.id]=c}}}function uf(a){a=a.split("\n");for(var b=0;b<a.length;b++)a[b]=b+1+": "+a[b];return a.join("\n")}function Ae(a,b,c){var d=a.createShader(b);a.shaderSource(d,c);a.compileShader(d);!1===a.getShaderParameter(d,a.COMPILE_STATUS)&&console.error("THREE.WebGLShader: Shader couldn't compile.");""!==a.getShaderInfoLog(d)&&console.warn("THREE.WebGLShader: gl.getShaderInfoLog()",b===a.VERTEX_SHADER?"vertex":"fragment",a.getShaderInfoLog(d),
13332 uf(c));return d}function Be(a){switch(a){case 3E3:return["Linear","( value )"];case 3001:return["sRGB","( value )"];case 3002:return["RGBE","( value )"];case 3004:return["RGBM","( value, 7.0 )"];case 3005:return["RGBM","( value, 16.0 )"];case 3006:return["RGBD","( value, 256.0 )"];case 3007:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw Error("unsupported encoding: "+a);}}function Ld(a,b){var c=Be(b);return"vec4 "+a+"( vec4 value ) { return "+c[0]+"ToLinear"+c[1]+"; }"}function vf(a,
13333 b){var c=Be(b);return"vec4 "+a+"( vec4 value ) { return LinearTo"+c[0]+c[1]+"; }"}function wf(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: "+b);}return"vec3 "+a+"( vec3 color ) { return "+c+"ToneMapping( color ); }"}function xf(a,b,c){a=a||{};return[a.derivatives||b.envMapCubeUV||b.bumpMap||b.normalMap||b.flatShading?"#extension GL_OES_standard_derivatives : enable":
13334 "",(a.fragDepth||b.logarithmicDepthBuffer)&&c.get("EXT_frag_depth")?"#extension GL_EXT_frag_depth : enable":"",a.drawBuffers&&c.get("WEBGL_draw_buffers")?"#extension GL_EXT_draw_buffers : require":"",(a.shaderTextureLOD||b.envMap)&&c.get("EXT_shader_texture_lod")?"#extension GL_EXT_shader_texture_lod : enable":""].filter(xc).join("\n")}function yf(a){var b=[],c;for(c in a){var d=a[c];!1!==d&&b.push("#define "+c+" "+d)}return b.join("\n")}function xc(a){return""!==a}function Ce(a,b){return a.replace(/NUM_DIR_LIGHTS/g,
13335 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 Md(a){return a.replace(/#include +<([\w\d.]+)>/g,function(a,c){var d=Z[c];if(void 0===d)throw Error("Can not resolve #include <"+c+">");return Md(d)})}function De(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<
13336 parseInt(d);c++)a+=e.replace(/\[ i \]/g,"[ "+c+" ]");return a})}function zf(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&&(m="SHADOWMAP_TYPE_PCF_SOFT");var x="ENVMAP_TYPE_CUBE",p="ENVMAP_MODE_REFLECTION",n="ENVMAP_BLENDING_MULTIPLY";if(d.envMap){switch(c.envMap.mapping){case 301:case 302:x="ENVMAP_TYPE_CUBE";break;case 306:case 307:x="ENVMAP_TYPE_CUBE_UV";
13337 break;case 303:case 304:x="ENVMAP_TYPE_EQUIREC";break;case 305:x="ENVMAP_TYPE_SPHERE"}switch(c.envMap.mapping){case 302:case 304:p="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=0<a.gammaFactor?a.gammaFactor:1,f=xf(f,d,a.extensions),l=yf(g),u=e.createProgram();c.isRawShaderMaterial?(g=[l,"\n"].filter(xc).join("\n"),m=[f,l,"\n"].filter(xc).join("\n")):(g=["precision "+d.precision+" float;",
13338 "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.map?"#define USE_MAP":"",d.envMap?"#define USE_ENVMAP":"",d.envMap?"#define "+p:"",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?
13339 "#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?"#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":
13340 "",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":"",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;",
13341 "uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;",
13342 "\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(xc).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":
13343 "",d.map?"#define USE_MAP":"",d.envMap?"#define USE_ENVMAP":"",d.envMap?"#define "+x:"",d.envMap?"#define "+p:"",d.envMap?"#define "+n:"",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.specularMap?"#define USE_SPECULARMAP":"",d.roughnessMap?"#define USE_ROUGHNESSMAP":"",d.metalnessMap?"#define USE_METALNESSMAP":"",d.alphaMap?"#define USE_ALPHAMAP":"",d.vertexColors?
13344 "#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 "+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":
13345 "",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":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",0!==d.toneMapping?"#define TONE_MAPPING":"",0!==d.toneMapping?Z.tonemapping_pars_fragment:"",0!==d.toneMapping?wf("toneMapping",d.toneMapping):"",d.outputEncoding||d.mapEncoding||d.envMapEncoding||d.emissiveMapEncoding?
13346 Z.encodings_pars_fragment:"",d.mapEncoding?Ld("mapTexelToLinear",d.mapEncoding):"",d.envMapEncoding?Ld("envMapTexelToLinear",d.envMapEncoding):"",d.emissiveMapEncoding?Ld("emissiveMapTexelToLinear",d.emissiveMapEncoding):"",d.outputEncoding?vf("linearToOutputTexel",d.outputEncoding):"",d.depthPacking?"#define DEPTH_PACKING "+c.depthPacking:"","\n"].filter(xc).join("\n"));h=Md(h,d);h=Ce(h,d);k=Md(k,d);k=Ce(k,d);c.isShaderMaterial||(h=De(h),k=De(k));k=m+k;h=Ae(e,e.VERTEX_SHADER,g+h);k=Ae(e,e.FRAGMENT_SHADER,
13347 k);e.attachShader(u,h);e.attachShader(u,k);void 0!==c.index0AttributeName?e.bindAttribLocation(u,0,c.index0AttributeName):!0===d.morphTargets&&e.bindAttribLocation(u,0,"position");e.linkProgram(u);d=e.getProgramInfoLog(u);x=e.getShaderInfoLog(h);p=e.getShaderInfoLog(k);r=n=!0;if(!1===e.getProgramParameter(u,e.LINK_STATUS))n=!1,console.error("THREE.WebGLProgram: shader error: ",e.getError(),"gl.VALIDATE_STATUS",e.getProgramParameter(u,e.VALIDATE_STATUS),"gl.getProgramInfoLog",d,x,p);else if(""!==d)console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",
13348 d);else if(""===x||""===p)r=!1;r&&(this.diagnostics={runnable:n,material:c,programLog:d,vertexShader:{log:x,prefix:g},fragmentShader:{log:p,prefix:m}});e.deleteShader(h);e.deleteShader(k);var q;this.getUniforms=function(){void 0===q&&(q=new $a(e,u,a));return q};var t;this.getAttributes=function(){if(void 0===t){for(var a={},b=e.getProgramParameter(u,e.ACTIVE_ATTRIBUTES),c=0;c<b;c++){var d=e.getActiveAttrib(u,c).name;a[d]=e.getAttribLocation(u,d)}t=a}return t};this.destroy=function(){e.deleteProgram(u);
13349 this.program=void 0};Object.defineProperties(this,{uniforms:{get:function(){console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms().");return this.getUniforms()}},attributes:{get:function(){console.warn("THREE.WebGLProgram: .attributes is now .getAttributes().");return this.getAttributes()}}});this.id=Af++;this.code=b;this.usedTimes=1;this.program=u;this.vertexShader=h;this.fragmentShader=k;return this}function Bf(a,b){function c(a,b){var c;a?a.isTexture?c=a.encoding:a.isWebGLRenderTarget&&
13350 (console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead."),c=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"},
13351 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".split(" ");
13352 this.getParameters=function(d,f,k,m,x,p){var n=e[d.type],r;b.floatVertexTextures&&p&&p.skeleton&&p.skeleton.useVertexTexture?r=1024:(r=Math.floor((b.maxVertexUniforms-20)/4),void 0!==p&&p&&p.isSkinnedMesh&&(r=Math.min(p.skeleton.bones.length,r),r<p.skeleton.bones.length&&console.warn("WebGLRenderer: too many bones - "+p.skeleton.bones.length+", this GPU supports just "+r+" (try OpenGL instead of ANGLE)")));var l=a.getPrecision();null!==d.precision&&(l=b.getMaxPrecision(d.precision),l!==d.precision&&
13353 console.warn("THREE.WebGLProgram.getParameters:",d.precision,"not supported, using",l,"instead."));var u=a.getCurrentRenderTarget();return{shaderID:n,precision:l,supportsVertexTextures:b.vertexTextures,outputEncoding:c(u?u.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,
13354 emissiveMap:!!d.emissiveMap,emissiveMapEncoding:c(d.emissiveMap,a.gammaInput),bumpMap:!!d.bumpMap,normalMap:!!d.normalMap,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,
13355 maxBones:r,useVertexTexture:b.floatVertexTextures&&p&&p.skeleton&&p.skeleton.useVertexTexture,morphTargets:d.morphTargets,morphNormals:d.morphNormals,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:x,shadowMapEnabled:a.shadowMap.enabled&&p.receiveShadow&&0<f.shadows.length,shadowMapType:a.shadowMap.type,
13356 toneMapping:a.toneMapping,physicallyCorrectLights:a.physicallyCorrectLights,premultipliedAlpha:d.premultipliedAlpha,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=
13357 function(b,c,e){for(var f,x=0,p=d.length;x<p;x++){var n=d[x];if(n.code===e){f=n;++f.usedTimes;break}}void 0===f&&(f=new zf(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 Cf(a,b,c){function d(a){var h=a.target;a=f[h.id];null!==a.index&&e(a.index);var k=a.attributes,m;for(m in k)e(k[m]);h.removeEventListener("dispose",d);delete f[h.id];m=b.get(h);m.wireframe&&e(m.wireframe);b["delete"](h);
13358 h=b.get(a);h.wireframe&&e(h.wireframe);b["delete"](a);c.memory.geometries--}function e(c){var d;d=c.isInterleavedBufferAttribute?b.get(c.data).__webglBuffer:b.get(c).__webglBuffer;void 0!==d&&(a.deleteBuffer(d),c.isInterleavedBufferAttribute?b["delete"](c.data):b["delete"](c))}var f={};return{get:function(a){var b=a.geometry;if(void 0!==f[b.id])return f[b.id];b.addEventListener("dispose",d);var e;b.isBufferGeometry?e=b:b.isGeometry&&(void 0===b._bufferGeometry&&(b._bufferGeometry=(new D).setFromObject(a)),
13359 e=b._bufferGeometry);f[b.id]=e;c.memory.geometries++;return e}}}function Df(a,b,c){function d(c,d){var e=c.isInterleavedBufferAttribute?c.data:c,k=b.get(e);if(void 0===k.__webglBuffer){k.__webglBuffer=a.createBuffer();a.bindBuffer(d,k.__webglBuffer);a.bufferData(d,e.array,e.dynamic?a.DYNAMIC_DRAW:a.STATIC_DRAW);var m=a.FLOAT,x=e.array;x instanceof Float32Array?m=a.FLOAT:x instanceof Float64Array?console.warn("Unsupported data buffer format: Float64Array"):x instanceof Uint16Array?m=a.UNSIGNED_SHORT:
13360 x instanceof Int16Array?m=a.SHORT:x instanceof Uint32Array?m=a.UNSIGNED_INT:x instanceof Int32Array?m=a.INT:x instanceof Int8Array?m=a.BYTE:x instanceof Uint8Array&&(m=a.UNSIGNED_BYTE);k.bytesPerElement=x.BYTES_PER_ELEMENT;k.type=m;k.version=e.version;e.onUploadCallback()}else k.version!==e.version&&(a.bindBuffer(d,k.__webglBuffer),!1===e.dynamic?a.bufferData(d,e.array,a.STATIC_DRAW):-1===e.updateRange.count?a.bufferSubData(d,0,e.array):0===e.updateRange.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."):
13361 (a.bufferSubData(d,e.updateRange.offset*e.array.BYTES_PER_ELEMENT,e.array.subarray(e.updateRange.offset,e.updateRange.offset+e.updateRange.count)),e.updateRange.count=0),k.version=e.version)}var e=new Cf(a,b,c);return{getAttributeBuffer:function(a){return a.isInterleavedBufferAttribute?b.get(a.data).__webglBuffer:b.get(a).__webglBuffer},getAttributeProperties:function(a){return a.isInterleavedBufferAttribute?b.get(a.data):b.get(a)},getWireframeAttribute:function(c){var e=b.get(c);if(void 0!==e.wireframe)return e.wireframe;
13362 var h=[],k=c.index,m=c.attributes;c=m.position;if(null!==k)for(var k=k.array,m=0,x=k.length;m<x;m+=3){var p=k[m+0],n=k[m+1],r=k[m+2];h.push(p,n,n,r,r,p)}else for(k=m.position.array,m=0,x=k.length/3-1;m<x;m+=3)p=m+0,n=m+1,r=m+2,h.push(p,n,n,r,r,p);h=new y(new (65535<c.count?Uint32Array:Uint16Array)(h),1);d(h,a.ELEMENT_ARRAY_BUFFER);return e.wireframe=h},update:function(b){var c=e.get(b);b.geometry.isGeometry&&c.updateFromObject(b);b=c.index;var h=c.attributes;null!==b&&d(b,a.ELEMENT_ARRAY_BUFFER);
13363 for(var k in h)d(h[k],a.ARRAY_BUFFER);b=c.morphAttributes;for(k in b)for(var h=b[k],m=0,x=h.length;m<x;m++)d(h[m],a.ARRAY_BUFFER);return c}}}function Ef(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 ("+
13364 a.width+"x"+a.height+"). Resized to "+d.width+"x"+d.height,a);return d}return a}function k(a){return Q.isPowerOfTwo(a.width)&&Q.isPowerOfTwo(a.height)}function m(b){return 1003===b||1004===b||1005===b?a.NEAREST:a.LINEAR}function x(b){b=b.target;b.removeEventListener("dispose",x);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["delete"](b)}q.textures--}function p(b){b=b.target;
13365 b.removeEventListener("dispose",p);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["delete"](b.texture);d["delete"](b)}q.textures--}function n(b,
13366 g){var m=d.get(b);if(0<b.version&&m.__version!==b.version){var n=b.image;if(void 0===n)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",b);else if(!1===n.complete)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",b);else{void 0===m.__webglInit&&(m.__webglInit=!0,b.addEventListener("dispose",x),m.__webglTexture=a.createTexture(),q.textures++);c.activeTexture(a.TEXTURE0+g);c.bindTexture(a.TEXTURE_2D,m.__webglTexture);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,
13367 b.flipY);a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha);a.pixelStorei(a.UNPACK_ALIGNMENT,b.unpackAlignment);var p=h(b.image,e.maxTextureSize);if((1001!==b.wrapS||1001!==b.wrapT||1003!==b.minFilter&&1006!==b.minFilter)&&!1===k(p))if(n=p,n instanceof HTMLImageElement||n instanceof HTMLCanvasElement){var l=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");l.width=Q.nearestPowerOfTwo(n.width);l.height=Q.nearestPowerOfTwo(n.height);l.getContext("2d").drawImage(n,0,0,
13368 l.width,l.height);console.warn("THREE.WebGLRenderer: image is not power of two ("+n.width+"x"+n.height+"). Resized to "+l.width+"x"+l.height,n);p=l}else p=n;var n=k(p),l=f(b.format),w=f(b.type);r(a.TEXTURE_2D,b,n);var u=b.mipmaps;if(b.isDepthTexture){u=a.DEPTH_COMPONENT;if(1015===b.type){if(!t)throw Error("Float Depth Texture only supported in WebGL2.0");u=a.DEPTH_COMPONENT32F}else t&&(u=a.DEPTH_COMPONENT16);1026===b.format&&u===a.DEPTH_COMPONENT&&1012!==b.type&&1014!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),
13369 b.type=1012,w=f(b.type));1027===b.format&&(u=a.DEPTH_STENCIL,1020!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),b.type=1020,w=f(b.type)));c.texImage2D(a.TEXTURE_2D,0,u,p.width,p.height,0,l,w,null)}else if(b.isDataTexture)if(0<u.length&&n){for(var J=0,ca=u.length;J<ca;J++)p=u[J],c.texImage2D(a.TEXTURE_2D,J,l,p.width,p.height,0,l,w,p.data);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,l,p.width,p.height,0,l,w,p.data);else if(b.isCompressedTexture)for(J=
13370 0,ca=u.length;J<ca;J++)p=u[J],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(l)?c.compressedTexImage2D(a.TEXTURE_2D,J,l,p.width,p.height,0,p.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):c.texImage2D(a.TEXTURE_2D,J,l,p.width,p.height,0,l,w,p.data);else if(0<u.length&&n){J=0;for(ca=u.length;J<ca;J++)p=u[J],c.texImage2D(a.TEXTURE_2D,J,l,l,w,p);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,l,l,
13371 w,p);b.generateMipmaps&&n&&a.generateMipmap(a.TEXTURE_2D);m.__version=b.version;if(b.onUpdate)b.onUpdate(b);return}}c.activeTexture(a.TEXTURE0+g);c.bindTexture(a.TEXTURE_2D,m.__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,
13372 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"))||
13373 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,
13374 0);a.bindFramebuffer(a.FRAMEBUFFER,null)}function u(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,
13375 a.RGBA4,c.width,c.height);a.bindRenderbuffer(a.RENDERBUFFER,null)}var q=g.memory,t="undefined"!==typeof WebGL2RenderingContext&&a instanceof WebGL2RenderingContext;this.setTexture2D=n;this.setTextureCube=function(b,g){var m=d.get(b);if(6===b.image.length)if(0<b.version&&m.__version!==b.version){m.__image__webglTextureCube||(b.addEventListener("dispose",x),m.__image__webglTextureCube=a.createTexture(),q.textures++);c.activeTexture(a.TEXTURE0+g);c.bindTexture(a.TEXTURE_CUBE_MAP,m.__image__webglTextureCube);
13376 a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);for(var n=b&&b.isCompressedTexture,p=b.image[0]&&b.image[0].isDataTexture,l=[],w=0;6>w;w++)l[w]=n||p?p?b.image[w].image:b.image[w]:h(b.image[w],e.maxCubemapSize);var u=k(l[0]),t=f(b.format),ca=f(b.type);r(a.TEXTURE_CUBE_MAP,b,u);for(w=0;6>w;w++)if(n)for(var y,C=l[w].mipmaps,D=0,O=C.length;D<O;D++)y=C[D],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(t)?c.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+w,D,t,y.width,y.height,
13377 0,y.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+w,D,t,y.width,y.height,0,t,ca,y.data);else p?c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+w,0,t,l[w].width,l[w].height,0,t,ca,l[w].data):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+w,0,t,t,ca,l[w]);b.generateMipmaps&&u&&a.generateMipmap(a.TEXTURE_CUBE_MAP);m.__version=b.version;if(b.onUpdate)b.onUpdate(b)}else c.activeTexture(a.TEXTURE0+
13378 g),c.bindTexture(a.TEXTURE_CUBE_MAP,m.__image__webglTextureCube)};this.setTextureCubeDynamic=function(b,e){c.activeTexture(a.TEXTURE0+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",p);f.__webglTexture=a.createTexture();q.textures++;var g=!0===b.isWebGLRenderTargetCube,h=k(b);if(g){e.__webglFramebuffer=[];for(var m=0;6>m;m++)e.__webglFramebuffer[m]=a.createFramebuffer()}else e.__webglFramebuffer=
13379 a.createFramebuffer();if(g){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);r(a.TEXTURE_CUBE_MAP,b.texture,h);for(m=0;6>m;m++)l(e.__webglFramebuffer[m],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+m);b.texture.generateMipmaps&&h&&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,h),l(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),b.texture.generateMipmaps&&h&&a.generateMipmap(a.TEXTURE_2D),
13380 c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=!0===b.isWebGLRenderTargetCube;if(b.depthTexture){if(f)throw Error("target.depthTexture not supported in Cube render targets");if(b&&b.isWebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported!");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&&
13381 b.depthTexture.image.width===b.width&&b.depthTexture.image.height===b.height||(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0);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");
13382 }else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),u(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),u(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?
13383 a.TEXTURE_CUBE_MAP:a.TEXTURE_2D,e=d.get(e).__webglTexture,c.bindTexture(b,e),a.generateMipmap(b),c.bindTexture(b,null))}}function Ff(){var a={};return{get:function(b){b=b.uuid;var c=a[b];void 0===c&&(c={},a[b]=c);return c},"delete":function(b){delete a[b.uuid]},clear:function(){a={}}}}function Gf(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+
13384 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,g,h,k,m,n,p){0!==b?e(a.BLEND):f(a.BLEND);if(b!==z||p!==ca)2===b?p?(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?p?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.ZERO,a.ONE_MINUS_SRC_COLOR,a.ONE_MINUS_SRC_ALPHA)):
13385 (a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.ONE_MINUS_SRC_COLOR)):4===b?p?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.SRC_COLOR,a.ZERO,a.SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.SRC_COLOR)):p?(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)),
13386 z=b,ca=p;if(5===b){k=k||d;m=m||g;n=n||h;if(d!==A||k!==K)a.blendEquationSeparate(c(d),c(k)),A=d,K=k;if(g!==I||h!==E||m!==y||n!==J)a.blendFuncSeparate(c(g),c(h),c(m),c(n)),I=g,E=h,y=m,J=n}else J=y=K=E=I=A=null}function h(a){n.setFunc(a)}function k(b){C!==b&&(b?a.frontFace(a.CW):a.frontFace(a.CCW),C=b)}function m(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 x(b){void 0===b&&(b=a.TEXTURE0+T-1);V!==b&&(a.activeTexture(b),
13387 V=b)}var p=new function(){var b=!1,c=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!==
13388 b){if(b)switch(b){case 0:a.depthFunc(a.NEVER);break;case 1:a.depthFunc(a.ALWAYS);break;case 2:a.depthFunc(a.LESS);break;case 3:a.depthFunc(a.LEQUAL);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=
13389 null,d=null,g=null,h=null,k=null,m=null,n=null,p=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){p!==b&&(a.clearStencil(b),p=b)},reset:function(){b=!1;p=n=m=k=h=g=d=c=null}}},l=a.getParameter(a.MAX_VERTEX_ATTRIBS),u=new Uint8Array(l),
13390 q=new Uint8Array(l),t=new Uint8Array(l),v={},M=null,z=null,A=null,I=null,E=null,K=null,y=null,J=null,ca=!1,C=null,D=null,G=null,O=null,P=null,R=null,T=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS),l=parseFloat(/^WebGL\ ([0-9])/.exec(a.getParameter(a.VERSION))[1]),H=1<=parseFloat(l),V=null,N={},L=new ga,S=new ga,Q={};Q[a.TEXTURE_2D]=d(a.TEXTURE_2D,a.TEXTURE_2D,1);Q[a.TEXTURE_CUBE_MAP]=d(a.TEXTURE_CUBE_MAP,a.TEXTURE_CUBE_MAP_POSITIVE_X,6);return{buffers:{color:p,depth:n,stencil:r},init:function(){p.setClear(0,
13391 0,0,1);n.setClear(1);r.setClear(0);e(a.DEPTH_TEST);h(3);k(!1);m(1);e(a.CULL_FACE);e(a.BLEND);g(1)},initAttributes:function(){for(var a=0,b=u.length;a<b;a++)u[a]=0},enableAttribute:function(c){u[c]=1;0===q[c]&&(a.enableVertexAttribArray(c),q[c]=1);0!==t[c]&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,0),t[c]=0)},enableAttributeAndDivisor:function(b,c,d){u[b]=1;0===q[b]&&(a.enableVertexAttribArray(b),q[b]=1);t[b]!==c&&(d.vertexAttribDivisorANGLE(b,c),t[b]=c)},disableUnusedAttributes:function(){for(var b=
13392 0,c=q.length;b!==c;++b)q[b]!==u[b]&&(a.disableVertexAttribArray(b),q[b]=0)},enable:e,disable:f,getCompressedTextureFormats:function(){if(null===M&&(M=[],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++)M.push(c[d]);return M},setBlending:g,setColorWrite:function(a){p.setMask(a)},setDepthTest:function(a){n.setTest(a)},setDepthWrite:function(a){n.setMask(a)},
13393 setDepthFunc:h,setStencilTest:function(a){r.setTest(a)},setStencilWrite:function(a){r.setMask(a)},setStencilFunc:function(a,b,c){r.setFunc(a,b,c)},setStencilOp:function(a,b,c){r.setOp(a,b,c)},setFlipSided:k,setCullFace:m,setLineWidth:function(b){b!==G&&(H&&a.lineWidth(b),G=b)},setPolygonOffset:function(b,c,d){if(b){if(e(a.POLYGON_OFFSET_FILL),O!==c||P!==d)a.polygonOffset(c,d),O=c,P=d}else f(a.POLYGON_OFFSET_FILL)},getScissorTest:function(){return R},setScissorTest:function(b){(R=b)?e(a.SCISSOR_TEST):
13394 f(a.SCISSOR_TEST)},activeTexture:x,bindTexture:function(b,c){null===V&&x();var d=N[V];void 0===d&&(d={type:void 0,texture:void 0},N[V]=d);if(d.type!==b||d.texture!==c)a.bindTexture(b,c||Q[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===L.equals(b)&&(a.scissor(b.x,b.y,b.z,b.w),L.copy(b))},viewport:function(b){!1===
13395 S.equals(b)&&(a.viewport(b.x,b.y,b.z,b.w),S.copy(b))},reset:function(){for(var b=0;b<q.length;b++)1===q[b]&&(a.disableVertexAttribArray(b),q[b]=0);v={};V=M=null;N={};D=C=z=null;p.reset();n.reset();r.reset()}}}function Hf(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&&
13396 0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,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),x=a.getParameter(a.MAX_VERTEX_ATTRIBS),
13397 p=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS),n=a.getParameter(a.MAX_VARYING_VECTORS),r=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS),l=0<h,u=!!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:x,maxVertexUniforms:p,
13398 maxVaryings:n,maxFragmentUniforms:r,vertexTextures:l,floatFragmentTextures:u,floatVertexTextures:l&&u}}function If(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")||
13399 a.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case "WEBGL_compressed_texture_s3tc":d=a.getExtension("WEBGL_compressed_texture_s3tc")||a.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case "WEBGL_compressed_texture_pvrtc":d=a.getExtension("WEBGL_compressed_texture_pvrtc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case "WEBGL_compressed_texture_etc1":d=a.getExtension("WEBGL_compressed_texture_etc1");
13400 break;default:d=a.getExtension(c)}null===d&&console.warn("THREE.WebGLRenderer: "+c+" extension not supported.");return b[c]=d}}}function Jf(){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+
13401 3]=h.constant}m.value=g;m.needsUpdate=!0}c.numPlanes=f;return g}var c=this,d=null,e=0,f=!1,g=!1,h=new ma,k=new za,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,u){if(!f||null===c||0===c.length||g&&!k)g?b(null):a();else{k=g?0:e;var q=4*k,t=l.clippingState||null;
13402 m.value=t;t=b(c,r,q,u);for(c=0;c!==q;++c)t[c]=d[c];l.clippingState=t;this.numIntersection=h?this.numPlanes:0;this.numPlanes+=k}}}function Nd(a){function b(){Y.init();Y.scissor(X.copy(fa).multiplyScalar(Sa));Y.viewport(Z.copy(ia).multiplyScalar(Sa));Y.buffers.color.setClear(Ga.r,Ga.g,Ga.b,fb,K)}function c(){W=Q=null;U="";L=-1;Y.reset()}function d(a){a.preventDefault();c();b();ha.clear()}function e(a){a=a.target;a.removeEventListener("dispose",e);f(a);ha["delete"](a)}function f(a){var b=ha.get(a).program;
13403 a.program=void 0;void 0!==b&&za.releaseProgram(b)}function g(a,b){return Math.abs(b[0])-Math.abs(a[0])}function h(a,b){return a.object.renderOrder!==b.object.renderOrder?a.object.renderOrder-b.object.renderOrder:a.material.program&&b.material.program&&a.material.program!==b.material.program?a.material.program.id-b.material.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 k(a,b){return a.object.renderOrder!==b.object.renderOrder?a.object.renderOrder-
13404 b.object.renderOrder:a.z!==b.z?b.z-a.z:a.id-b.id}function m(a,b,c,d,e){var f;c.transparent?(d=G,f=++Na):(d=ca,f=++C);f=d[f];void 0!==f?(f.id=a.id,f.object=a,f.geometry=b,f.material=c,f.z=ba.z,f.group=e):(f={id:a.id,object:a,geometry:b,material:c,z:ba.z,group:e},d.push(f))}function x(a){if(!na.intersectsSphere(a))return!1;var b=da.numPlanes;if(0===b)return!0;var c=T.clippingPlanes,d=a.center;a=-a.radius;var e=0;do if(c[e].distanceToPoint(d)<a)return!1;while(++e!==b);return!0}function p(a,b){if(!1!==
13405 a.visible){if(0!==(a.layers.mask&b.layers.mask))if(a.isLight)J.push(a);else if(a.isSprite){var c;(c=!1===a.frustumCulled)||(oa.center.set(0,0,0),oa.radius=.7071067811865476,oa.applyMatrix4(a.matrixWorld),c=!0===x(oa));c&&P.push(a)}else if(a.isLensFlare)R.push(a);else if(a.isImmediateRenderObject)!0===T.sortObjects&&(ba.setFromMatrixPosition(a.matrixWorld),ba.applyProjection(sa)),m(a,null,a.material,ba.z,null);else if(a.isMesh||a.isLine||a.isPoints)if(a.isSkinnedMesh&&a.skeleton.update(),(c=!1===a.frustumCulled)||
13406 (c=a.geometry,null===c.boundingSphere&&c.computeBoundingSphere(),oa.copy(c.boundingSphere).applyMatrix4(a.matrixWorld),c=!0===x(oa)),c){var d=a.material;if(!0===d.visible)if(!0===T.sortObjects&&(ba.setFromMatrixPosition(a.matrixWorld),ba.applyProjection(sa)),c=ta.update(a),d.isMultiMaterial)for(var e=c.groups,f=d.materials,d=0,g=e.length;d<g;d++){var h=e[d],k=f[h.materialIndex];!0===k.visible&&m(a,c,k,ba.z,h)}else m(a,c,d,ba.z,null)}c=a.children;d=0;for(g=c.length;d<g;d++)p(c[d],b)}}function n(a,
13407 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.modelViewMatrix.multiplyMatrices(c.matrixWorldInverse,h.matrixWorld);h.normalMatrix.getNormalMatrix(h.modelViewMatrix);h.onBeforeRender(T,b,c,k,m,g);if(h.isImmediateRenderObject){r(m);var n=l(c,b.fog,m,h);U="";h.render(function(a){T.renderBufferImmediate(a,n,m)})}else T.renderBufferDirect(c,b.fog,k,m,h,g);h.onAfterRender(T,b,c,k,m,g)}}function r(a){2===a.side?Y.disable(B.CULL_FACE):Y.enable(B.CULL_FACE);
13408 Y.setFlipSided(1===a.side);!0===a.transparent?Y.setBlending(a.blending,a.blendEquation,a.blendSrc,a.blendDst,a.blendEquationAlpha,a.blendSrcAlpha,a.blendDstAlpha,a.premultipliedAlpha):Y.setBlending(0);Y.setDepthFunc(a.depthFunc);Y.setDepthTest(a.depthTest);Y.setDepthWrite(a.depthWrite);Y.setColorWrite(a.colorWrite);Y.setPolygonOffset(a.polygonOffset,a.polygonOffsetFactor,a.polygonOffsetUnits)}function l(a,b,c,d){ea=0;var g=ha.get(c);pa&&(ua||a!==W)&&da.setState(c.clippingPlanes,c.clipIntersection,
13409 c.clipShadows,a,g,a===W&&c.id===L);!1===c.needsUpdate&&(void 0===g.program?c.needsUpdate=!0:c.fog&&g.fog!==b?c.needsUpdate=!0:c.lights&&g.lightsHash!==aa.hash?c.needsUpdate=!0:void 0===g.numClippingPlanes||g.numClippingPlanes===da.numPlanes&&g.numIntersection===da.numIntersection||(c.needsUpdate=!0));if(c.needsUpdate){a:{var h=ha.get(c),k=za.getParameters(c,aa,b,da.numPlanes,da.numIntersection,d),m=za.getProgramCode(c,k),n=h.program,p=!0;if(void 0===n)c.addEventListener("dispose",e);else if(n.code!==
13410 m)f(c);else if(void 0!==k.shaderID)break a;else p=!1;p&&(k.shaderID?(n=Gb[k.shaderID],h.__webglShader={name:c.type,uniforms:Ja.clone(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader}):h.__webglShader={name:c.type,uniforms:c.uniforms,vertexShader:c.vertexShader,fragmentShader:c.fragmentShader},c.__webglShader=h.__webglShader,n=za.acquireProgram(c,k,m),h.program=n,c.program=n);k=n.getAttributes();if(c.morphTargets)for(m=c.numSupportedMorphTargets=0;m<T.maxMorphTargets;m++)0<=
13411 k["morphTarget"+m]&&c.numSupportedMorphTargets++;if(c.morphNormals)for(m=c.numSupportedMorphNormals=0;m<T.maxMorphNormals;m++)0<=k["morphNormal"+m]&&c.numSupportedMorphNormals++;k=h.__webglShader.uniforms;if(!c.isShaderMaterial&&!c.isRawShaderMaterial||!0===c.clipping)h.numClippingPlanes=da.numPlanes,h.numIntersection=da.numIntersection,k.clippingPlanes=da.uniform;h.fog=b;h.lightsHash=aa.hash;c.lights&&(k.ambientLightColor.value=aa.ambient,k.directionalLights.value=aa.directional,k.spotLights.value=
13412 aa.spot,k.rectAreaLights.value=aa.rectArea,k.pointLights.value=aa.point,k.hemisphereLights.value=aa.hemi,k.directionalShadowMap.value=aa.directionalShadowMap,k.directionalShadowMatrix.value=aa.directionalShadowMatrix,k.spotShadowMap.value=aa.spotShadowMap,k.spotShadowMatrix.value=aa.spotShadowMatrix,k.pointShadowMap.value=aa.pointShadowMap,k.pointShadowMatrix.value=aa.pointShadowMatrix);m=h.program.getUniforms();k=$a.seqWithValue(m.seq,k);h.uniformsList=k}c.needsUpdate=!1}var x=!1,p=n=!1,h=g.program,
13413 k=h.getUniforms(),m=g.__webglShader.uniforms;h.id!==Q&&(B.useProgram(h.program),Q=h.id,p=n=x=!0);c.id!==L&&(L=c.id,n=!0);if(x||a!==W){k.set(B,a,"projectionMatrix");ma.logarithmicDepthBuffer&&k.setValue(B,"logDepthBufFC",2/(Math.log(a.far+1)/Math.LN2));a!==W&&(W=a,p=n=!0);if(c.isShaderMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.envMap)x=k.map.cameraPosition,void 0!==x&&x.setValue(B,ba.setFromMatrixPosition(a.matrixWorld));(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial||
13414 c.isMeshStandardMaterial||c.isShaderMaterial||c.skinning)&&k.setValue(B,"viewMatrix",a.matrixWorldInverse);k.set(B,T,"toneMappingExposure");k.set(B,T,"toneMappingWhitePoint")}c.skinning&&(k.setOptional(B,d,"bindMatrix"),k.setOptional(B,d,"bindMatrixInverse"),a=d.skeleton)&&(ma.floatVertexTextures&&a.useVertexTexture?(k.set(B,a,"boneTexture"),k.set(B,a,"boneTextureWidth"),k.set(B,a,"boneTextureHeight")):k.setOptional(B,a,"boneMatrices"));if(n){c.lights&&(a=p,m.ambientLightColor.needsUpdate=a,m.directionalLights.needsUpdate=
13415 a,m.pointLights.needsUpdate=a,m.spotLights.needsUpdate=a,m.rectAreaLights.needsUpdate=a,m.hemisphereLights.needsUpdate=a);b&&c.fog&&(m.fogColor.value=b.color,b.isFog?(m.fogNear.value=b.near,m.fogFar.value=b.far):b.isFogExp2&&(m.fogDensity.value=b.density));if(c.isMeshBasicMaterial||c.isMeshLambertMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.isMeshNormalMaterial||c.isMeshDepthMaterial){m.opacity.value=c.opacity;m.diffuse.value=c.color;c.emissive&&m.emissive.value.copy(c.emissive).multiplyScalar(c.emissiveIntensity);
13416 m.map.value=c.map;m.specularMap.value=c.specularMap;m.alphaMap.value=c.alphaMap;c.lightMap&&(m.lightMap.value=c.lightMap,m.lightMapIntensity.value=c.lightMapIntensity);c.aoMap&&(m.aoMap.value=c.aoMap,m.aoMapIntensity.value=c.aoMapIntensity);var r;c.map?r=c.map:c.specularMap?r=c.specularMap:c.displacementMap?r=c.displacementMap:c.normalMap?r=c.normalMap:c.bumpMap?r=c.bumpMap:c.roughnessMap?r=c.roughnessMap:c.metalnessMap?r=c.metalnessMap:c.alphaMap?r=c.alphaMap:c.emissiveMap&&(r=c.emissiveMap);void 0!==
13417 r&&(r.isWebGLRenderTarget&&(r=r.texture),b=r.offset,r=r.repeat,m.offsetRepeat.value.set(b.x,b.y,r.x,r.y));m.envMap.value=c.envMap;m.flipEnvMap.value=c.envMap&&c.envMap.isCubeTexture?-1:1;m.reflectivity.value=c.reflectivity;m.refractionRatio.value=c.refractionRatio}c.isLineBasicMaterial?(m.diffuse.value=c.color,m.opacity.value=c.opacity):c.isLineDashedMaterial?(m.diffuse.value=c.color,m.opacity.value=c.opacity,m.dashSize.value=c.dashSize,m.totalSize.value=c.dashSize+c.gapSize,m.scale.value=c.scale):
13418 c.isPointsMaterial?(m.diffuse.value=c.color,m.opacity.value=c.opacity,m.size.value=c.size*Sa,m.scale.value=.5*yc,m.map.value=c.map,null!==c.map&&(r=c.map.offset,c=c.map.repeat,m.offsetRepeat.value.set(r.x,r.y,c.x,c.y))):c.isMeshLambertMaterial?c.emissiveMap&&(m.emissiveMap.value=c.emissiveMap):c.isMeshToonMaterial?(u(m,c),c.gradientMap&&(m.gradientMap.value=c.gradientMap)):c.isMeshPhongMaterial?u(m,c):c.isMeshPhysicalMaterial?(m.clearCoat.value=c.clearCoat,m.clearCoatRoughness.value=c.clearCoatRoughness,
13419 F(m,c)):c.isMeshStandardMaterial?F(m,c):c.isMeshDepthMaterial?c.displacementMap&&(m.displacementMap.value=c.displacementMap,m.displacementScale.value=c.displacementScale,m.displacementBias.value=c.displacementBias):c.isMeshNormalMaterial&&(c.bumpMap&&(m.bumpMap.value=c.bumpMap,m.bumpScale.value=c.bumpScale),c.normalMap&&(m.normalMap.value=c.normalMap,m.normalScale.value.copy(c.normalScale)),c.displacementMap&&(m.displacementMap.value=c.displacementMap,m.displacementScale.value=c.displacementScale,
13420 m.displacementBias.value=c.displacementBias));void 0!==m.ltcMat&&(m.ltcMat.value=THREE.UniformsLib.LTC_MAT_TEXTURE);void 0!==m.ltcMag&&(m.ltcMag.value=THREE.UniformsLib.LTC_MAG_TEXTURE);$a.upload(B,g.uniformsList,m,T)}k.set(B,d,"modelViewMatrix");k.set(B,d,"normalMatrix");k.setValue(B,"modelMatrix",d.matrixWorld);return h}function u(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,
13421 a.bumpScale.value=b.bumpScale);b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale));b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias)}function F(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);
13422 b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale);b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale));b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias);b.envMap&&(a.envMapIntensity.value=b.envMapIntensity)}function t(a){var b;if(1E3===a)return B.REPEAT;if(1001===a)return B.CLAMP_TO_EDGE;if(1002===a)return B.MIRRORED_REPEAT;if(1003===a)return B.NEAREST;
13423 if(1004===a)return B.NEAREST_MIPMAP_NEAREST;if(1005===a)return B.NEAREST_MIPMAP_LINEAR;if(1006===a)return B.LINEAR;if(1007===a)return B.LINEAR_MIPMAP_NEAREST;if(1008===a)return B.LINEAR_MIPMAP_LINEAR;if(1009===a)return B.UNSIGNED_BYTE;if(1017===a)return B.UNSIGNED_SHORT_4_4_4_4;if(1018===a)return B.UNSIGNED_SHORT_5_5_5_1;if(1019===a)return B.UNSIGNED_SHORT_5_6_5;if(1010===a)return B.BYTE;if(1011===a)return B.SHORT;if(1012===a)return B.UNSIGNED_SHORT;if(1013===a)return B.INT;if(1014===a)return B.UNSIGNED_INT;
13424 if(1015===a)return B.FLOAT;if(1016===a&&(b=ja.get("OES_texture_half_float"),null!==b))return b.HALF_FLOAT_OES;if(1021===a)return B.ALPHA;if(1022===a)return B.RGB;if(1023===a)return B.RGBA;if(1024===a)return B.LUMINANCE;if(1025===a)return B.LUMINANCE_ALPHA;if(1026===a)return B.DEPTH_COMPONENT;if(1027===a)return B.DEPTH_STENCIL;if(100===a)return B.FUNC_ADD;if(101===a)return B.FUNC_SUBTRACT;if(102===a)return B.FUNC_REVERSE_SUBTRACT;if(200===a)return B.ZERO;if(201===a)return B.ONE;if(202===a)return B.SRC_COLOR;
13425 if(203===a)return B.ONE_MINUS_SRC_COLOR;if(204===a)return B.SRC_ALPHA;if(205===a)return B.ONE_MINUS_SRC_ALPHA;if(206===a)return B.DST_ALPHA;if(207===a)return B.ONE_MINUS_DST_ALPHA;if(208===a)return B.DST_COLOR;if(209===a)return B.ONE_MINUS_DST_COLOR;if(210===a)return B.SRC_ALPHA_SATURATE;if(2001===a||2002===a||2003===a||2004===a)if(b=ja.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;
13426 if(2004===a)return b.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(2100===a||2101===a||2102===a||2103===a)if(b=ja.get("WEBGL_compressed_texture_pvrtc"),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=ja.get("WEBGL_compressed_texture_etc1"),null!==b))return b.COMPRESSED_RGB_ETC1_WEBGL;if(103===a||104===a)if(b=ja.get("EXT_blend_minmax"),
13427 null!==b){if(103===a)return b.MIN_EXT;if(104===a)return b.MAX_EXT}return 1020===a&&(b=ja.get("WEBGL_depth_texture"),null!==b)?b.UNSIGNED_INT_24_8_WEBGL:0}console.log("THREE.WebGLRenderer","83");a=a||{};var v=void 0!==a.canvas?a.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),M=void 0!==a.context?a.context:null,z=void 0!==a.alpha?a.alpha:!1,A=void 0!==a.depth?a.depth:!0,I=void 0!==a.stencil?a.stencil:!0,E=void 0!==a.antialias?a.antialias:!1,K=void 0!==a.premultipliedAlpha?
13428 a.premultipliedAlpha:!0,y=void 0!==a.preserveDrawingBuffer?a.preserveDrawingBuffer:!1,J=[],ca=[],C=-1,G=[],Na=-1,O=new Float32Array(8),P=[],R=[];this.domElement=v;this.context=null;this.sortObjects=this.autoClearStencil=this.autoClearDepth=this.autoClearColor=this.autoClear=!0;this.clippingPlanes=[];this.localClippingEnabled=!1;this.gammaFactor=2;this.physicallyCorrectLights=this.gammaOutput=this.gammaInput=!1;this.toneMappingWhitePoint=this.toneMappingExposure=this.toneMapping=1;this.maxMorphTargets=
13429 8;this.maxMorphNormals=4;var T=this,Q=null,V=null,S=null,L=-1,U="",W=null,X=new ga,Ta=null,Z=new ga,ea=0,Ga=new N(0),fb=0,fd=v.width,yc=v.height,Sa=1,fa=new ga(0,0,fd,yc),ka=!1,ia=new ga(0,0,fd,yc),na=new qc,da=new Jf,pa=!1,ua=!1,oa=new Fa,sa=new H,ba=new q,wa=new H,xa=new H,aa={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],shadows:[]},qa={calls:0,
13430 vertices:0,faces:0,points:0};this.info={render:qa,memory:{geometries:0,textures:0},programs:null};var B;try{z={alpha:z,depth:A,stencil:I,antialias:E,premultipliedAlpha:K,preserveDrawingBuffer:y};B=M||v.getContext("webgl",z)||v.getContext("experimental-webgl",z);if(null===B){if(null!==v.getContext("webgl"))throw"Error creating WebGL context with your selected attributes.";throw"Error creating WebGL context.";}void 0===B.getShaderPrecisionFormat&&(B.getShaderPrecisionFormat=function(){return{rangeMin:1,
13431 rangeMax:1,precision:1}});v.addEventListener("webglcontextlost",d,!1)}catch(Kf){console.error("THREE.WebGLRenderer: "+Kf)}var ja=new If(B);ja.get("WEBGL_depth_texture");ja.get("OES_texture_float");ja.get("OES_texture_float_linear");ja.get("OES_texture_half_float");ja.get("OES_texture_half_float_linear");ja.get("OES_standard_derivatives");ja.get("ANGLE_instanced_arrays");ja.get("OES_element_index_uint")&&(D.MaxIndex=4294967296);var ma=new Hf(B,ja,a),Y=new Gf(B,ja,t),ha=new Ff,va=new Ef(B,ja,Y,ha,ma,
13432 t,this.info),ta=new Df(B,ha,this.info),za=new Bf(this,ma),Aa=new tf;this.info.programs=za.programs;var La=new sf(B,ja,qa),Ma=new rf(B,ja,qa),Oa=new Hb(-1,1,1,-1,0,1),Ca=new Ha,Ea=new Ba(new ib(2,2),new Ka({depthTest:!1,depthWrite:!1,fog:!1}));a=Gb.cube;var ya=new Ba(new hb(5,5,5),new Ia({uniforms:a.uniforms,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1}));b();this.context=B;this.capabilities=ma;this.extensions=ja;this.properties=ha;this.state=
13433 Y;var Pa=new ye(this,aa,ta,ma);this.shadowMap=Pa;var Qa=new of(this,P),Ra=new nf(this,R);this.getContext=function(){return B};this.getContextAttributes=function(){return B.getContextAttributes()};this.forceContextLoss=function(){ja.get("WEBGL_lose_context").loseContext()};this.getMaxAnisotropy=function(){return ma.getMaxAnisotropy()};this.getPrecision=function(){return ma.precision};this.getPixelRatio=function(){return Sa};this.setPixelRatio=function(a){void 0!==a&&(Sa=a,this.setSize(ia.z,ia.w,!1))};
13434 this.getSize=function(){return{width:fd,height:yc}};this.setSize=function(a,b,c){fd=a;yc=b;v.width=a*Sa;v.height=b*Sa;!1!==c&&(v.style.width=a+"px",v.style.height=b+"px");this.setViewport(0,0,a,b)};this.setViewport=function(a,b,c,d){Y.viewport(ia.set(a,b,c,d))};this.setScissor=function(a,b,c,d){Y.scissor(fa.set(a,b,c,d))};this.setScissorTest=function(a){Y.setScissorTest(ka=a)};this.getClearColor=function(){return Ga};this.setClearColor=function(a,b){Ga.set(a);fb=void 0!==b?b:1;Y.buffers.color.setClear(Ga.r,
13435 Ga.g,Ga.b,fb,K)};this.getClearAlpha=function(){return fb};this.setClearAlpha=function(a){fb=a;Y.buffers.color.setClear(Ga.r,Ga.g,Ga.b,fb,K)};this.clear=function(a,b,c){var d=0;if(void 0===a||a)d|=B.COLOR_BUFFER_BIT;if(void 0===b||b)d|=B.DEPTH_BUFFER_BIT;if(void 0===c||c)d|=B.STENCIL_BUFFER_BIT;B.clear(d)};this.clearColor=function(){this.clear(!0,!1,!1)};this.clearDepth=function(){this.clear(!1,!0,!1)};this.clearStencil=function(){this.clear(!1,!1,!0)};this.clearTarget=function(a,b,c,d){this.setRenderTarget(a);
13436 this.clear(b,c,d)};this.resetGLState=c;this.dispose=function(){G=[];Na=-1;ca=[];C=-1;v.removeEventListener("webglcontextlost",d,!1)};this.renderBufferImmediate=function(a,b,c){Y.initAttributes();var d=ha.get(a);a.hasPositions&&!d.position&&(d.position=B.createBuffer());a.hasNormals&&!d.normal&&(d.normal=B.createBuffer());a.hasUvs&&!d.uv&&(d.uv=B.createBuffer());a.hasColors&&!d.color&&(d.color=B.createBuffer());b=b.getAttributes();a.hasPositions&&(B.bindBuffer(B.ARRAY_BUFFER,d.position),B.bufferData(B.ARRAY_BUFFER,
13437 a.positionArray,B.DYNAMIC_DRAW),Y.enableAttribute(b.position),B.vertexAttribPointer(b.position,3,B.FLOAT,!1,0,0));if(a.hasNormals){B.bindBuffer(B.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+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}B.bufferData(B.ARRAY_BUFFER,
13438 a.normalArray,B.DYNAMIC_DRAW);Y.enableAttribute(b.normal);B.vertexAttribPointer(b.normal,3,B.FLOAT,!1,0,0)}a.hasUvs&&c.map&&(B.bindBuffer(B.ARRAY_BUFFER,d.uv),B.bufferData(B.ARRAY_BUFFER,a.uvArray,B.DYNAMIC_DRAW),Y.enableAttribute(b.uv),B.vertexAttribPointer(b.uv,2,B.FLOAT,!1,0,0));a.hasColors&&0!==c.vertexColors&&(B.bindBuffer(B.ARRAY_BUFFER,d.color),B.bufferData(B.ARRAY_BUFFER,a.colorArray,B.DYNAMIC_DRAW),Y.enableAttribute(b.color),B.vertexAttribPointer(b.color,3,B.FLOAT,!1,0,0));Y.disableUnusedAttributes();
13439 B.drawArrays(B.TRIANGLES,0,a.count);a.count=0};this.renderBufferDirect=function(a,b,c,d,e,f){r(d);var h=l(a,b,d,e),k=!1;a=c.id+"_"+h.id+"_"+d.wireframe;a!==U&&(U=a,k=!0);b=e.morphTargetInfluences;if(void 0!==b){var m=[];a=0;for(var n=b.length;a<n;a++)k=b[a],m.push([k,a]);m.sort(g);8<m.length&&(m.length=8);var p=c.morphAttributes;a=0;for(n=m.length;a<n;a++)k=m[a],O[a]=k[0],0!==k[0]?(b=k[1],!0===d.morphTargets&&p.position&&c.addAttribute("morphTarget"+a,p.position[b]),!0===d.morphNormals&&p.normal&&
13440 c.addAttribute("morphNormal"+a,p.normal[b])):(!0===d.morphTargets&&c.removeAttribute("morphTarget"+a),!0===d.morphNormals&&c.removeAttribute("morphNormal"+a));a=m.length;for(b=O.length;a<b;a++)O[a]=0;h.getUniforms().setValue(B,"morphTargetInfluences",O);k=!0}b=c.index;n=c.attributes.position;m=1;!0===d.wireframe&&(b=ta.getWireframeAttribute(c),m=2);null!==b?(a=Ma,a.setIndex(b)):a=La;if(k){a:{var k=void 0,x;if(c&&c.isInstancedBufferGeometry&&(x=ja.get("ANGLE_instanced_arrays"),null===x)){console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");
13441 break a}void 0===k&&(k=0);Y.initAttributes();var p=c.attributes,h=h.getAttributes(),u=d.defaultAttributeValues,q;for(q in h){var v=h[q];if(0<=v){var t=p[q];if(void 0!==t){var z=t.normalized,F=t.itemSize,I=ta.getAttributeProperties(t),E=I.__webglBuffer,M=I.type,I=I.bytesPerElement;if(t.isInterleavedBufferAttribute){var A=t.data,K=A.stride,t=t.offset;A&&A.isInstancedInterleavedBuffer?(Y.enableAttributeAndDivisor(v,A.meshPerAttribute,x),void 0===c.maxInstancedCount&&(c.maxInstancedCount=A.meshPerAttribute*
13442 A.count)):Y.enableAttribute(v);B.bindBuffer(B.ARRAY_BUFFER,E);B.vertexAttribPointer(v,F,M,z,K*I,(k*K+t)*I)}else t.isInstancedBufferAttribute?(Y.enableAttributeAndDivisor(v,t.meshPerAttribute,x),void 0===c.maxInstancedCount&&(c.maxInstancedCount=t.meshPerAttribute*t.count)):Y.enableAttribute(v),B.bindBuffer(B.ARRAY_BUFFER,E),B.vertexAttribPointer(v,F,M,z,0,k*F*I)}else if(void 0!==u&&(z=u[q],void 0!==z))switch(z.length){case 2:B.vertexAttrib2fv(v,z);break;case 3:B.vertexAttrib3fv(v,z);break;case 4:B.vertexAttrib4fv(v,
13443 z);break;default:B.vertexAttrib1fv(v,z)}}}Y.disableUnusedAttributes()}null!==b&&B.bindBuffer(B.ELEMENT_ARRAY_BUFFER,ta.getAttributeBuffer(b))}x=0;null!==b?x=b.count:void 0!==n&&(x=n.count);b=c.drawRange.start*m;n=null!==f?f.start*m:0;q=Math.max(b,n);f=Math.max(0,Math.min(x,b+c.drawRange.count*m,n+(null!==f?f.count*m:Infinity))-1-q+1);if(0!==f){if(e.isMesh)if(!0===d.wireframe)Y.setLineWidth(d.wireframeLinewidth*(null===V?Sa:1)),a.setMode(B.LINES);else switch(e.drawMode){case 0:a.setMode(B.TRIANGLES);
13444 break;case 1:a.setMode(B.TRIANGLE_STRIP);break;case 2:a.setMode(B.TRIANGLE_FAN)}else e.isLine?(d=d.linewidth,void 0===d&&(d=1),Y.setLineWidth(d*(null===V?Sa:1)),e.isLineSegments?a.setMode(B.LINES):a.setMode(B.LINE_STRIP)):e.isPoints&&a.setMode(B.POINTS);c&&c.isInstancedBufferGeometry?0<c.maxInstancedCount&&a.renderInstances(c,q,f):a.render(q,f)}};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.");else{U=
13445 "";L=-1;W=null;!0===a.autoUpdate&&a.updateMatrixWorld();null===b.parent&&b.updateMatrixWorld();b.matrixWorldInverse.getInverse(b.matrixWorld);sa.multiplyMatrices(b.projectionMatrix,b.matrixWorldInverse);na.setFromMatrix(sa);J.length=0;Na=C=-1;P.length=0;R.length=0;ua=this.localClippingEnabled;pa=da.init(this.clippingPlanes,ua,b);p(a,b);ca.length=C+1;G.length=Na+1;!0===T.sortObjects&&(ca.sort(h),G.sort(k));pa&&da.beginShadows();for(var e=J,f=0,g=0,m=e.length;g<m;g++){var x=e[g];x.castShadow&&(aa.shadows[f++]=
13446 x)}aa.shadows.length=f;Pa.render(a,b);for(var e=J,r=x=0,l=0,w,u,v,q,t=b.matrixWorldInverse,z=0,F=0,I=0,E=0,M=0,f=0,g=e.length;f<g;f++)if(m=e[f],w=m.color,u=m.intensity,v=m.distance,q=m.shadow&&m.shadow.map?m.shadow.map.texture:null,m.isAmbientLight)x+=w.r*u,r+=w.g*u,l+=w.b*u;else if(m.isDirectionalLight){var A=Aa.get(m);A.color.copy(m.color).multiplyScalar(m.intensity);A.direction.setFromMatrixPosition(m.matrixWorld);ba.setFromMatrixPosition(m.target.matrixWorld);A.direction.sub(ba);A.direction.transformDirection(t);
13447 if(A.shadow=m.castShadow)A.shadowBias=m.shadow.bias,A.shadowRadius=m.shadow.radius,A.shadowMapSize=m.shadow.mapSize;aa.directionalShadowMap[z]=q;aa.directionalShadowMatrix[z]=m.shadow.matrix;aa.directional[z++]=A}else if(m.isSpotLight){A=Aa.get(m);A.position.setFromMatrixPosition(m.matrixWorld);A.position.applyMatrix4(t);A.color.copy(w).multiplyScalar(u);A.distance=v;A.direction.setFromMatrixPosition(m.matrixWorld);ba.setFromMatrixPosition(m.target.matrixWorld);A.direction.sub(ba);A.direction.transformDirection(t);
13448 A.coneCos=Math.cos(m.angle);A.penumbraCos=Math.cos(m.angle*(1-m.penumbra));A.decay=0===m.distance?0:m.decay;if(A.shadow=m.castShadow)A.shadowBias=m.shadow.bias,A.shadowRadius=m.shadow.radius,A.shadowMapSize=m.shadow.mapSize;aa.spotShadowMap[I]=q;aa.spotShadowMatrix[I]=m.shadow.matrix;aa.spot[I++]=A}else if(m.isRectAreaLight)A=Aa.get(m),A.color.copy(w).multiplyScalar(u/(m.width*m.height)),A.position.setFromMatrixPosition(m.matrixWorld),A.position.applyMatrix4(t),xa.identity(),wa.copy(m.matrixWorld),
13449 wa.premultiply(t),xa.extractRotation(wa),A.halfWidth.set(.5*m.width,0,0),A.halfHeight.set(0,.5*m.height,0),A.halfWidth.applyMatrix4(xa),A.halfHeight.applyMatrix4(xa),aa.rectArea[E++]=A;else if(m.isPointLight){A=Aa.get(m);A.position.setFromMatrixPosition(m.matrixWorld);A.position.applyMatrix4(t);A.color.copy(m.color).multiplyScalar(m.intensity);A.distance=m.distance;A.decay=0===m.distance?0:m.decay;if(A.shadow=m.castShadow)A.shadowBias=m.shadow.bias,A.shadowRadius=m.shadow.radius,A.shadowMapSize=m.shadow.mapSize;
13450 aa.pointShadowMap[F]=q;void 0===aa.pointShadowMatrix[F]&&(aa.pointShadowMatrix[F]=new H);ba.setFromMatrixPosition(m.matrixWorld).negate();aa.pointShadowMatrix[F].identity().setPosition(ba);aa.point[F++]=A}else m.isHemisphereLight&&(A=Aa.get(m),A.direction.setFromMatrixPosition(m.matrixWorld),A.direction.transformDirection(t),A.direction.normalize(),A.skyColor.copy(m.color).multiplyScalar(u),A.groundColor.copy(m.groundColor).multiplyScalar(u),aa.hemi[M++]=A);aa.ambient[0]=x;aa.ambient[1]=r;aa.ambient[2]=
13451 l;aa.directional.length=z;aa.spot.length=I;aa.rectArea.length=E;aa.point.length=F;aa.hemi.length=M;aa.hash=z+","+F+","+I+","+E+","+M+","+aa.shadows.length;pa&&da.endShadows();qa.calls=0;qa.vertices=0;qa.faces=0;qa.points=0;void 0===c&&(c=null);this.setRenderTarget(c);e=a.background;null===e?Y.buffers.color.setClear(Ga.r,Ga.g,Ga.b,fb,K):e&&e.isColor&&(Y.buffers.color.setClear(e.r,e.g,e.b,1,K),d=!0);(this.autoClear||d)&&this.clear(this.autoClearColor,this.autoClearDepth,this.autoClearStencil);e&&e.isCubeTexture?
13452 (Ca.projectionMatrix.copy(b.projectionMatrix),Ca.matrixWorld.extractRotation(b.matrixWorld),Ca.matrixWorldInverse.getInverse(Ca.matrixWorld),ya.material.uniforms.tCube.value=e,ya.modelViewMatrix.multiplyMatrices(Ca.matrixWorldInverse,ya.matrixWorld),ta.update(ya),T.renderBufferDirect(Ca,null,ya.geometry,ya.material,ya,null)):e&&e.isTexture&&(Ea.material.map=e,ta.update(Ea),T.renderBufferDirect(Oa,null,Ea.geometry,Ea.material,Ea,null));a.overrideMaterial?(d=a.overrideMaterial,n(ca,a,b,d),n(G,a,b,d)):
13453 (Y.setBlending(0),n(ca,a,b),n(G,a,b));Qa.render(a,b);Ra.render(a,b,Z);c&&va.updateRenderTargetMipmap(c);Y.setDepthTest(!0);Y.setDepthWrite(!0);Y.setColorWrite(!0)}};this.setFaceCulling=function(a,b){Y.setCullFace(a);Y.setFlipSided(0===b)};this.allocTextureUnit=function(){var a=ea;a>=ma.maxTextures&&console.warn("WebGLRenderer: trying to use "+a+" texture units while this GPU supports only "+ma.maxTextures);ea+=1;return a};this.setTexture2D=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTarget&&
13454 (a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);va.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);va.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."),
13455 a=!0),b=b.texture);b&&b.isCubeTexture||Array.isArray(b.image)&&6===b.image.length?va.setTextureCube(b,c):va.setTextureCubeDynamic(b,c)}}();this.getCurrentRenderTarget=function(){return V};this.setRenderTarget=function(a){(V=a)&&void 0===ha.get(a).__webglFramebuffer&&va.setupRenderTarget(a);var b=a&&a.isWebGLRenderTargetCube,c;a?(c=ha.get(a),c=b?c.__webglFramebuffer[a.activeCubeFace]:c.__webglFramebuffer,X.copy(a.scissor),Ta=a.scissorTest,Z.copy(a.viewport)):(c=null,X.copy(fa).multiplyScalar(Sa),Ta=
13456 ka,Z.copy(ia).multiplyScalar(Sa));S!==c&&(B.bindFramebuffer(B.FRAMEBUFFER,c),S=c);Y.scissor(X);Y.setScissorTest(Ta);Y.viewport(Z);b&&(b=ha.get(a.texture),B.framebufferTexture2D(B.FRAMEBUFFER,B.COLOR_ATTACHMENT0,B.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=ha.get(a).__webglFramebuffer;
13457 if(g){var h=!1;g!==S&&(B.bindFramebuffer(B.FRAMEBUFFER,g),h=!0);try{var k=a.texture,m=k.format,n=k.type;1023!==m&&t(m)!==B.getParameter(B.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===n||t(n)===B.getParameter(B.IMPLEMENTATION_COLOR_READ_TYPE)||1015===n&&(ja.get("OES_texture_float")||ja.get("WEBGL_color_buffer_float"))||1016===n&&ja.get("EXT_color_buffer_half_float")?B.checkFramebufferStatus(B.FRAMEBUFFER)===
13458 B.FRAMEBUFFER_COMPLETE?0<=b&&b<=a.width-d&&0<=c&&c<=a.height-e&&B.readPixels(b,c,d,e,t(m),t(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&&B.bindFramebuffer(B.FRAMEBUFFER,S)}}}}}function Ib(a,b){this.name="";this.color=new N(a);this.density=void 0!==b?b:2.5E-4}function Jb(a,
13459 b,c){this.name="";this.color=new N(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function jb(){G.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function Od(a,b,c,d,e){G.call(this);this.lensFlares=[];this.positionScreen=new q;this.customUpdateCallback=void 0;void 0!==a&&this.add(a,b,c,d,e)}function kb(a){W.call(this);this.type="SpriteMaterial";this.color=new N(16777215);this.map=null;this.rotation=0;this.lights=this.fog=!1;this.setValues(a)}
13460 function zc(a){G.call(this);this.type="Sprite";this.material=void 0!==a?a:new kb}function Ac(){G.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function hd(a,b,c){this.useVertexTexture=void 0!==c?c:!0;this.identityMatrix=new H;a=a||[];this.bones=a.slice(0);this.useVertexTexture?(a=Math.sqrt(4*this.bones.length),a=Q.nextPowerOfTwo(Math.ceil(a)),this.boneTextureHeight=this.boneTextureWidth=a=Math.max(a,4),this.boneMatrices=new Float32Array(this.boneTextureWidth*
13461 this.boneTextureHeight*4),this.boneTexture=new db(this.boneMatrices,this.boneTextureWidth,this.boneTextureHeight,1023,1015)):this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===b)this.calculateInverses();else if(this.bones.length===b.length)this.boneInverses=b.slice(0);else for(console.warn("THREE.Skeleton bonInverses is the wrong length."),this.boneInverses=[],b=0,a=this.bones.length;b<a;b++)this.boneInverses.push(new H)}function id(){G.call(this);this.type="Bone"}function jd(a,
13462 b,c){Ba.call(this,a,b);this.type="SkinnedMesh";this.bindMode="attached";this.bindMatrix=new H;this.bindMatrixInverse=new H;a=[];if(this.geometry&&void 0!==this.geometry.bones){for(var d,e=0,f=this.geometry.bones.length;e<f;++e)d=this.geometry.bones[e],b=new id,a.push(b),b.name=d.name,b.position.fromArray(d.pos),b.quaternion.fromArray(d.rotq),void 0!==d.scl&&b.scale.fromArray(d.scl);e=0;for(f=this.geometry.bones.length;e<f;++e)d=this.geometry.bones[e],-1!==d.parent&&null!==d.parent&&void 0!==a[d.parent]?
13463 a[d.parent].add(a[e]):this.add(a[e])}this.normalizeSkinWeights();this.updateMatrixWorld(!0);this.bind(new hd(a,void 0,c),this.matrixWorld)}function ia(a){W.call(this);this.type="LineBasicMaterial";this.color=new N(16777215);this.linewidth=1;this.linejoin=this.linecap="round";this.lights=!1;this.setValues(a)}function Va(a,b,c){if(1===c)return console.warn("THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead."),new fa(a,b);G.call(this);this.type="Line";this.geometry=
13464 void 0!==a?a:new D;this.material=void 0!==b?b:new ia({color:16777215*Math.random()})}function fa(a,b){Va.call(this,a,b);this.type="LineSegments"}function Oa(a){W.call(this);this.type="PointsMaterial";this.color=new N(16777215);this.map=null;this.size=1;this.sizeAttenuation=!0;this.lights=!1;this.setValues(a)}function Kb(a,b){G.call(this);this.type="Points";this.geometry=void 0!==a?a:new D;this.material=void 0!==b?b:new Oa({color:16777215*Math.random()})}function Bc(){G.call(this);this.type="Group"}
13465 function kd(a,b,c,d,e,f,g,h,k){function m(){requestAnimationFrame(m);a.readyState>=a.HAVE_CURRENT_DATA&&(x.needsUpdate=!0)}ea.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1;var x=this;m()}function Lb(a,b,c,d,e,f,g,h,k,m,x,p){ea.call(this,null,f,g,h,k,m,d,e,x,p);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1}function ld(a,b,c,d,e,f,g,h,k){ea.call(this,a,b,c,d,e,f,g,h,k);this.needsUpdate=!0}function Cc(a,b,c,d,e,f,g,h,k,m){m=void 0!==m?m:1026;if(1026!==m&&1027!==
13466 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);ea.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 Mb(a){function b(a,b){return a-b}D.call(this);var c=[0,0],d={},e=["a","b","c"];if(a&&a.isGeometry){var f=a.vertices,g=a.faces,h=0,k=new Uint32Array(6*g.length);a=0;for(var m=
13467 g.length;a<m;a++)for(var x=g[a],p=0;3>p;p++){c[0]=x[e[p]];c[1]=x[e[(p+1)%3]];c.sort(b);var n=c.toString();void 0===d[n]&&(k[2*h]=c[0],k[2*h+1]=c[1],d[n]=!0,h++)}c=new Float32Array(6*h);a=0;for(m=h;a<m;a++)for(p=0;2>p;p++)d=f[k[2*a+p]],h=6*a+3*p,c[h+0]=d.x,c[h+1]=d.y,c[h+2]=d.z;this.addAttribute("position",new y(c,3))}else if(a&&a.isBufferGeometry){if(null!==a.index){m=a.index.array;f=a.attributes.position;e=a.groups;h=0;0===e.length&&a.addGroup(0,m.length);k=new Uint32Array(2*m.length);g=0;for(x=
13468 e.length;g<x;++g){a=e[g];p=a.start;n=a.count;a=p;for(var r=p+n;a<r;a+=3)for(p=0;3>p;p++)c[0]=m[a+p],c[1]=m[a+(p+1)%3],c.sort(b),n=c.toString(),void 0===d[n]&&(k[2*h]=c[0],k[2*h+1]=c[1],d[n]=!0,h++)}c=new Float32Array(6*h);a=0;for(m=h;a<m;a++)for(p=0;2>p;p++)h=6*a+3*p,d=k[2*a+p],c[h+0]=f.getX(d),c[h+1]=f.getY(d),c[h+2]=f.getZ(d)}else for(f=a.attributes.position.array,h=f.length/3,k=h/3,c=new Float32Array(6*h),a=0,m=k;a<m;a++)for(p=0;3>p;p++)h=18*a+6*p,k=9*a+3*p,c[h+0]=f[k],c[h+1]=f[k+1],c[h+2]=f[k+
13469 2],d=9*a+(p+1)%3*3,c[h+3]=f[d],c[h+4]=f[d+1],c[h+5]=f[d+2];this.addAttribute("position",new y(c,3))}}function Nb(a,b,c){D.call(this);this.type="ParametricBufferGeometry";this.parameters={func:a,slices:b,stacks:c};var d=[],e=[],f,g,h,k,m,x=b+1;for(f=0;f<=c;f++)for(m=f/c,g=0;g<=b;g++)k=g/b,h=a(k,m),d.push(h.x,h.y,h.z),e.push(k,m);a=[];var p;for(f=0;f<c;f++)for(g=0;g<b;g++)h=f*x+g,k=f*x+g+1,m=(f+1)*x+g+1,p=(f+1)*x+g,a.push(h,k,p),a.push(k,m,p);this.setIndex(new (65535<a.length?Ua:Ra)(a,1));this.addAttribute("position",
13470 new X(d,3));this.addAttribute("uv",new X(e,2));this.computeVertexNormals()}function Dc(a,b,c){S.call(this);this.type="ParametricGeometry";this.parameters={func:a,slices:b,stacks:c};this.fromBufferGeometry(new Nb(a,b,c));this.mergeVertices()}function xa(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)}D.call(this);this.type="PolyhedronBufferGeometry";this.parameters=
13471 {vertices:a,indices:b,radius:c,detail:d};c=c||1;var h=[],k=[];(function(a){for(var c=new q,d=new q,g=new q,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,F=g,t=Math.pow(2,a),v=[],M,z;for(M=0;M<=t;M++){v[M]=[];var A=k.clone().lerp(F,M/t),I=l.clone().lerp(F,M/t),E=t-M;for(z=0;z<=E;z++)v[M][z]=0===z&&M===t?A:A.clone().lerp(I,z/E)}for(M=0;M<t;M++)for(z=0;z<2*(t-M)-1;z++)k=Math.floor(z/2),0===z%2?(e(v[M][k+1]),e(v[M+1][k]),e(v[M][k])):(e(v[M][k+1]),e(v[M+1][k+1]),e(v[M+1][k]))}})(d||
13472 0);(function(a){for(var b=new q,c=0;c<h.length;c+=3)b.x=h[c+0],b.y=h[c+1],b.z=h[c+2],b.normalize().multiplyScalar(a),h[c+0]=b.x,h[c+1]=b.y,h[c+2]=b.z})(c);(function(){for(var a=new q,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 q,b=new q,c=new q,d=new q,e=new C,f=new C,l=new C,F=0,t=0;F<h.length;F+=9,t+=6){a.set(h[F+0],h[F+1],h[F+2]);b.set(h[F+3],h[F+4],h[F+5]);c.set(h[F+6],h[F+
13473 7],h[F+8]);e.set(k[t+0],k[t+1]);f.set(k[t+2],k[t+3]);l.set(k[t+4],k[t+5]);d.copy(a).add(b).add(c).divideScalar(3);var v=Math.atan2(d.z,-d.x);g(e,t+0,a,v);g(f,t+2,b,v);g(l,t+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 X(h,3));this.addAttribute("normal",new X(h.slice(),3));this.addAttribute("uv",new X(k,2));this.normalizeNormals();this.boundingSphere=
13474 new Fa(new q,c)}function Ob(a,b){xa.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 Ec(a,b){S.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Ob(a,b));this.mergeVertices()}function lb(a,b){xa.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";
13475 this.parameters={radius:a,detail:b}}function Fc(a,b){S.call(this);this.type="OctahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new lb(a,b));this.mergeVertices()}function Pb(a,b){var c=(1+Math.sqrt(5))/2;xa.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";
13476 this.parameters={radius:a,detail:b}}function Gc(a,b){S.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Pb(a,b));this.mergeVertices()}function Qb(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;xa.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,
13477 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 Hc(a,b){S.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Qb(a,b));this.mergeVertices()}function Ic(a,b,c,d){S.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,
13478 radius:c,detail:d};this.fromBufferGeometry(new xa(a,b,c,d));this.mergeVertices()}function Rb(a,b,c,d,e){function f(e){var f=a.getPointAt(e/b),m=g.normals[e];e=g.binormals[e];for(p=0;p<=d;p++){var x=p/d*Math.PI*2,l=Math.sin(x),x=-Math.cos(x);k.x=x*m.x+l*e.x;k.y=x*m.y+l*e.y;k.z=x*m.z+l*e.z;k.normalize();r.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)}}D.call(this);this.type="TubeBufferGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};
13479 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 q,k=new q,m=new C,x,p,n=[],r=[],l=[],u=[];for(x=0;x<b;x++)f(x);f(!1===e?b:0);for(x=0;x<=b;x++)for(p=0;p<=d;p++)m.x=x/b,m.y=p/d,l.push(m.x,m.y);(function(){for(p=1;p<=b;p++)for(x=1;x<=d;x++){var a=(d+1)*p+(x-1),c=(d+1)*p+x,e=(d+1)*(p-1)+x;u.push((d+1)*(p-1)+(x-1),a,e);u.push(a,c,e)}})();this.setIndex(new (65535<u.length?Ua:Ra)(u,1));this.addAttribute("position",
13480 new X(n,3));this.addAttribute("normal",new X(r,3));this.addAttribute("uv",new X(l,2))}function Jc(a,b,c,d,e,f){S.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 Rb(a,b,c,d,e);this.tangents=a.tangents;this.normals=a.normals;this.binormals=a.binormals;this.fromBufferGeometry(a);this.mergeVertices()}function Sb(a,b,c,d,e,f){function g(a,b,c,d,e){var f=Math.sin(a);
13481 b=c/b*a;c=Math.cos(b);e.x=d*(2+c)*.5*Math.cos(a);e.y=d*(2+c)*f*.5;e.z=d*Math.sin(b)*.5}D.call(this);this.type="TorusKnotBufferGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};a=a||100;b=b||40;c=Math.floor(c)||64;d=Math.floor(d)||8;e=e||2;f=f||3;var h=(d+1)*(c+1),k=d*c*6,k=new y(new (65535<k?Uint32Array:Uint16Array)(k),1),m=new y(new Float32Array(3*h),3),x=new y(new Float32Array(3*h),3),h=new y(new Float32Array(2*h),2),p,n,r=0,l=0,u=new q,F=new q,t=new C,v=new q,
13482 M=new q,z=new q,A=new q,I=new q;for(p=0;p<=c;++p)for(n=p/c*e*Math.PI*2,g(n,e,f,a,v),g(n+.01,e,f,a,M),A.subVectors(M,v),I.addVectors(M,v),z.crossVectors(A,I),I.crossVectors(z,A),z.normalize(),I.normalize(),n=0;n<=d;++n){var E=n/d*Math.PI*2,K=-b*Math.cos(E),E=b*Math.sin(E);u.x=v.x+(K*I.x+E*z.x);u.y=v.y+(K*I.y+E*z.y);u.z=v.z+(K*I.z+E*z.z);m.setXYZ(r,u.x,u.y,u.z);F.subVectors(u,v).normalize();x.setXYZ(r,F.x,F.y,F.z);t.x=p/c;t.y=n/d;h.setXY(r,t.x,t.y);r++}for(n=1;n<=c;n++)for(p=1;p<=d;p++)a=(d+1)*n+(p-
13483 1),b=(d+1)*n+p,e=(d+1)*(n-1)+p,k.setX(l,(d+1)*(n-1)+(p-1)),l++,k.setX(l,a),l++,k.setX(l,e),l++,k.setX(l,a),l++,k.setX(l,b),l++,k.setX(l,e),l++;this.setIndex(k);this.addAttribute("position",m);this.addAttribute("normal",x);this.addAttribute("uv",h)}function Kc(a,b,c,d,e,f,g){S.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.");
13484 this.fromBufferGeometry(new Sb(a,b,c,d,e,f));this.mergeVertices()}function Tb(a,b,c,d,e){D.call(this);this.type="TorusBufferGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};a=a||100;b=b||40;c=Math.floor(c)||8;d=Math.floor(d)||6;e=e||2*Math.PI;var f=(c+1)*(d+1),g=c*d*6,g=new (65535<g?Uint32Array:Uint16Array)(g),h=new Float32Array(3*f),k=new Float32Array(3*f),f=new Float32Array(2*f),m=0,x=0,p=0,n=new q,l=new q,w=new q,u,F;for(u=0;u<=c;u++)for(F=0;F<=d;F++){var t=
13485 F/d*e,v=u/c*Math.PI*2;l.x=(a+b*Math.cos(v))*Math.cos(t);l.y=(a+b*Math.cos(v))*Math.sin(t);l.z=b*Math.sin(v);h[m]=l.x;h[m+1]=l.y;h[m+2]=l.z;n.x=a*Math.cos(t);n.y=a*Math.sin(t);w.subVectors(l,n).normalize();k[m]=w.x;k[m+1]=w.y;k[m+2]=w.z;f[x]=F/d;f[x+1]=u/c;m+=3;x+=2}for(u=1;u<=c;u++)for(F=1;F<=d;F++)a=(d+1)*(u-1)+F-1,b=(d+1)*(u-1)+F,e=(d+1)*u+F,g[p]=(d+1)*u+F-1,g[p+1]=a,g[p+2]=e,g[p+3]=a,g[p+4]=b,g[p+5]=e,p+=6;this.setIndex(new y(g,1));this.addAttribute("position",new y(h,3));this.addAttribute("normal",
13486 new y(k,3));this.addAttribute("uv",new y(f,2))}function Lc(a,b,c,d,e){S.call(this);this.type="TorusGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};this.fromBufferGeometry(new Tb(a,b,c,d,e))}function La(a,b){"undefined"!==typeof a&&(S.call(this),this.type="ExtrudeGeometry",a=Array.isArray(a)?a:[a],this.addShapeList(a,b),this.computeFaceNormals())}function Mc(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."),
13487 new S;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);La.call(this,c,b);this.type="TextGeometry"}function mb(a,b,c,d,e,f,g){D.call(this);this.type="SphereBufferGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};a=a||50;b=Math.max(3,Math.floor(b)||8);c=Math.max(2,Math.floor(c)||
13488 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;for(var h=f+g,k=(b+1)*(c+1),m=new y(new Float32Array(3*k),3),x=new y(new Float32Array(3*k),3),k=new y(new Float32Array(2*k),2),p=0,n=[],l=new q,w=0;w<=c;w++){for(var u=[],F=w/c,t=0;t<=b;t++){var v=t/b,M=-a*Math.cos(d+v*e)*Math.sin(f+F*g),z=a*Math.cos(f+F*g),A=a*Math.sin(d+v*e)*Math.sin(f+F*g);l.set(M,z,A).normalize();m.setXYZ(p,M,z,A);x.setXYZ(p,l.x,l.y,l.z);k.setXY(p,v,1-F);u.push(p);p++}n.push(u)}d=[];for(w=0;w<
13489 c;w++)for(t=0;t<b;t++)e=n[w][t+1],g=n[w][t],p=n[w+1][t],l=n[w+1][t+1],(0!==w||0<f)&&d.push(e,g,l),(w!==c-1||h<Math.PI)&&d.push(g,p,l);this.setIndex(new (65535<m.count?Ua:Ra)(d,1));this.addAttribute("position",m);this.addAttribute("normal",x);this.addAttribute("uv",k);this.boundingSphere=new Fa(new q,a)}function Nc(a,b,c,d,e,f,g){S.call(this);this.type="SphereGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};this.fromBufferGeometry(new mb(a,
13490 b,c,d,e,f,g))}function Ub(a,b,c,d,e,f){D.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=(c+1)*(d+1),h=c*d*6,h=new y(new (65535<h?Uint32Array:Uint16Array)(h),1),k=new y(new Float32Array(3*g),3),m=new y(new Float32Array(3*g),3),g=new y(new Float32Array(2*g),2),x=0,p=0,n,l=a,w=(b-a)/
13491 d,u=new q,F=new C,t;for(a=0;a<=d;a++){for(t=0;t<=c;t++)n=e+t/c*f,u.x=l*Math.cos(n),u.y=l*Math.sin(n),k.setXYZ(x,u.x,u.y,u.z),m.setXYZ(x,0,0,1),F.x=(u.x/b+1)/2,F.y=(u.y/b+1)/2,g.setXY(x,F.x,F.y),x++;l+=w}for(a=0;a<d;a++)for(b=a*(c+1),t=0;t<c;t++)e=n=t+b,f=n+c+1,x=n+c+2,n+=1,h.setX(p,e),p++,h.setX(p,f),p++,h.setX(p,x),p++,h.setX(p,e),p++,h.setX(p,x),p++,h.setX(p,n),p++;this.setIndex(h);this.addAttribute("position",k);this.addAttribute("normal",m);this.addAttribute("uv",g)}function Oc(a,b,c,d,e,f){S.call(this);
13492 this.type="RingGeometry";this.parameters={innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};this.fromBufferGeometry(new Ub(a,b,c,d,e,f))}function Pc(a,b,c,d){S.call(this);this.type="PlaneGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};this.fromBufferGeometry(new ib(a,b,c,d))}function Vb(a,b,c,d){D.call(this);this.type="LatheBufferGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};b=Math.floor(b)||12;c=c||0;d=d||
13493 2*Math.PI;d=Q.clamp(d,0,2*Math.PI);for(var e=(b+1)*a.length,f=b*a.length*6,g=new y(new (65535<f?Uint32Array:Uint16Array)(f),1),h=new y(new Float32Array(3*e),3),k=new y(new Float32Array(2*e),2),m=0,x=0,p=1/b,n=new q,l=new C,e=0;e<=b;e++)for(var f=c+e*p*d,w=Math.sin(f),u=Math.cos(f),f=0;f<=a.length-1;f++)n.x=a[f].x*w,n.y=a[f].y,n.z=a[f].x*u,h.setXYZ(m,n.x,n.y,n.z),l.x=e/b,l.y=f/(a.length-1),k.setXY(m,l.x,l.y),m++;for(e=0;e<b;e++)for(f=0;f<a.length-1;f++)c=f+e*a.length,m=c+a.length,p=c+a.length+1,n=
13494 c+1,g.setX(x,c),x++,g.setX(x,m),x++,g.setX(x,n),x++,g.setX(x,m),x++,g.setX(x,p),x++,g.setX(x,n),x++;this.setIndex(g);this.addAttribute("position",h);this.addAttribute("uv",k);this.computeVertexNormals();if(d===2*Math.PI)for(d=this.attributes.normal.array,g=new q,h=new q,k=new q,c=b*a.length*3,f=e=0;e<a.length;e++,f+=3)g.x=d[f+0],g.y=d[f+1],g.z=d[f+2],h.x=d[c+f+0],h.y=d[c+f+1],h.z=d[c+f+2],k.addVectors(g,h).normalize(),d[f+0]=d[c+f+0]=k.x,d[f+1]=d[c+f+1]=k.y,d[f+2]=d[c+f+2]=k.z}function Qc(a,b,c,d){S.call(this);
13495 this.type="LatheGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};this.fromBufferGeometry(new Vb(a,b,c,d));this.mergeVertices()}function Wb(a,b){function c(a){var c,h,m=d.length/3;a=a.extractPoints(b);var l=a.shape,u=a.holes;if(!1===pa.isClockWise(l))for(l=l.reverse(),a=0,c=u.length;a<c;a++)h=u[a],!0===pa.isClockWise(h)&&(u[a]=h.reverse());var q=pa.triangulateShape(l,u);a=0;for(c=u.length;a<c;a++)h=u[a],l=l.concat(h);a=0;for(c=l.length;a<c;a++)h=l[a],d.push(h.x,h.y,0),e.push(0,
13496 0,1),f.push(h.x,h.y);a=0;for(c=q.length;a<c;a++)l=q[a],g.push(l[0]+m,l[1]+m,l[2]+m),k+=3}D.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(new (65535<g.length?Ua:Ra)(g,1));this.addAttribute("position",new X(d,3));this.addAttribute("normal",new X(e,3));this.addAttribute("uv",new X(f,2))}function Xb(a,b){S.call(this);
13497 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 Wb(a,b));this.mergeVertices()}function Yb(a,b){function c(a,b){return a-b}D.call(this);var d=Math.cos(Q.DEG2RAD*(void 0!==b?b:1)),e=[0,0],f={},g=["a","b","c"],h;a.isBufferGeometry?(h=new S,h.fromBufferGeometry(a)):h=a.clone();h.mergeVertices();h.computeFaceNormals();var k=h.vertices;h=h.faces;
13498 for(var m=0,l=h.length;m<l;m++)for(var p=h[m],n=0;3>n;n++){e[0]=p[g[n]];e[1]=p[g[(n+1)%3]];e.sort(c);var r=e.toString();void 0===f[r]?f[r]={vert1:e[0],vert2:e[1],face1:m,face2:void 0}:f[r].face2=m}e=[];for(r in f)if(g=f[r],void 0===g.face2||h[g.face1].normal.dot(h[g.face2].normal)<=d)m=k[g.vert1],e.push(m.x),e.push(m.y),e.push(m.z),m=k[g.vert2],e.push(m.x),e.push(m.y),e.push(m.z);this.addAttribute("position",new X(e,3))}function Wa(a,b,c,d,e,f,g,h){function k(c){var e,f,k,n=new C,p=new q,l=0,x=!0===
13499 c?a:b,M=!0===c?1:-1;f=t;for(e=1;e<=d;e++)w.setXYZ(t,0,z*M,0),u.setXYZ(t,0,M,0),n.x=.5,n.y=.5,F.setXY(t,n.x,n.y),t++;k=t;for(e=0;e<=d;e++){var y=e/d*h+g,D=Math.cos(y),y=Math.sin(y);p.x=x*y;p.y=z*M;p.z=x*D;w.setXYZ(t,p.x,p.y,p.z);u.setXYZ(t,0,M,0);n.x=.5*D+.5;n.y=.5*y*M+.5;F.setXY(t,n.x,n.y);t++}for(e=0;e<d;e++)n=f+e,p=k+e,!0===c?(r.setX(v,p),v++,r.setX(v,p+1)):(r.setX(v,p+1),v++,r.setX(v,p)),v++,r.setX(v,n),v++,l+=3;m.addGroup(A,l,!0===c?1:2);A+=l}D.call(this);this.type="CylinderBufferGeometry";this.parameters=
13500 {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 l=0;!1===f&&(0<a&&l++,0<b&&l++);var p=function(){var a=(d+1)*(e+1);!1===f&&(a+=(d+1)*l+d*l);return a}(),n=function(){var a=d*e*6;!1===f&&(a+=d*l*3);return a}(),r=new y(new (65535<n?Uint32Array:Uint16Array)(n),1),w=new y(new Float32Array(3*
13501 p),3),u=new y(new Float32Array(3*p),3),F=new y(new Float32Array(2*p),2),t=0,v=0,M=[],z=c/2,A=0;(function(){var f,k,n=new q,p=new q,l=0,x=(b-a)/c;for(k=0;k<=e;k++){var y=[],C=k/e,D=C*(b-a)+a;for(f=0;f<=d;f++){var G=f/d,P=G*h+g,R=Math.sin(P),P=Math.cos(P);p.x=D*R;p.y=-C*c+z;p.z=D*P;w.setXYZ(t,p.x,p.y,p.z);n.set(R,x,P).normalize();u.setXYZ(t,n.x,n.y,n.z);F.setXY(t,G,1-C);y.push(t);t++}M.push(y)}for(f=0;f<d;f++)for(k=0;k<e;k++)n=M[k+1][f],p=M[k+1][f+1],x=M[k][f+1],r.setX(v,M[k][f]),v++,r.setX(v,n),v++,
13502 r.setX(v,x),v++,r.setX(v,n),v++,r.setX(v,p),v++,r.setX(v,x),v++,l+=6;m.addGroup(A,l,0);A+=l})();!1===f&&(0<a&&k(!0),0<b&&k(!1));this.setIndex(r);this.addAttribute("position",w);this.addAttribute("normal",u);this.addAttribute("uv",F)}function nb(a,b,c,d,e,f,g,h){S.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,f,g,h));this.mergeVertices()}
13503 function Rc(a,b,c,d,e,f,g){nb.call(this,0,a,b,c,d,e,f,g);this.type="ConeGeometry";this.parameters={radius:a,height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Sc(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 Zb(a,b,c,d){D.call(this);this.type="CircleBufferGeometry";this.parameters={radius:a,segments:b,thetaStart:c,
13504 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=b+2,f=new Float32Array(3*e),g=new Float32Array(3*e),e=new Float32Array(2*e);g[2]=1;e[0]=.5;e[1]=.5;for(var h=0,k=3,m=2;h<=b;h++,k+=3,m+=2){var l=c+h/b*d;f[k]=a*Math.cos(l);f[k+1]=a*Math.sin(l);g[k+2]=1;e[m]=(f[k]/a+1)/2;e[m+1]=(f[k+1]/a+1)/2}c=[];for(k=1;k<=b;k++)c.push(k,k+1,0);this.setIndex(new y(new Uint16Array(c),1));this.addAttribute("position",new y(f,3));this.addAttribute("normal",new y(g,3));
13505 this.addAttribute("uv",new y(e,2));this.boundingSphere=new Fa(new q,a)}function Tc(a,b,c,d){S.call(this);this.type="CircleGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};this.fromBufferGeometry(new Zb(a,b,c,d))}function $b(a,b,c,d,e,f){S.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};this.fromBufferGeometry(new hb(a,b,c,d,e,f));this.mergeVertices()}function ac(){Ia.call(this,{uniforms:Ja.merge([U.lights,
13506 {opacity:{value:1}}]),vertexShader:Z.shadow_vert,fragmentShader:Z.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}}})}function bc(a){Ia.call(this,a);this.type="RawShaderMaterial"}function Uc(a){this.uuid=Q.generateUUID();this.type="MultiMaterial";this.materials=Array.isArray(a)?a:[];this.visible=!0}function Pa(a){W.call(this);this.defines={STANDARD:""};
13507 this.type="MeshStandardMaterial";this.color=new N(16777215);this.metalness=this.roughness=.5;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new N(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=this.alphaMap=this.metalnessMap=this.roughnessMap=null;this.envMapIntensity=1;this.refractionRatio=
13508 .98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function ob(a){Pa.call(this);this.defines={PHYSICAL:""};this.type="MeshPhysicalMaterial";this.reflectivity=.5;this.clearCoatRoughness=this.clearCoat=0;this.setValues(a)}function Ca(a){W.call(this);this.type="MeshPhongMaterial";this.color=new N(16777215);this.specular=new N(1118481);this.shininess=30;this.lightMap=this.map=null;
13509 this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new N(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=
13510 this.morphTargets=this.skinning=!1;this.setValues(a)}function pb(a){Ca.call(this);this.defines={TOON:""};this.type="MeshToonMaterial";this.gradientMap=null;this.setValues(a)}function qb(a){W.call(this,a);this.type="MeshNormalMaterial";this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.skinning=this.lights=this.fog=
13511 !1;this.setValues(a)}function rb(a){W.call(this);this.type="MeshLambertMaterial";this.color=new N(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new N(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=this.morphTargets=
13512 this.skinning=!1;this.setValues(a)}function sb(a){W.call(this);this.type="LineDashedMaterial";this.color=new N(16777215);this.scale=this.linewidth=1;this.dashSize=3;this.gapSize=1;this.lights=!1;this.setValues(a)}function Pd(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===g&&(e=!1,void 0!==
13513 d.onLoad))d.onLoad()};this.itemError=function(a){if(void 0!==d.onError)d.onError(a)}}function Ma(a){this.manager=void 0!==a?a:va}function Ee(a){this.manager=void 0!==a?a:va;this._parser=null}function Qd(a){this.manager=void 0!==a?a:va;this._parser=null}function Vc(a){this.manager=void 0!==a?a:va}function Rd(a){this.manager=void 0!==a?a:va}function md(a){this.manager=void 0!==a?a:va}function na(a,b){G.call(this);this.type="Light";this.color=new N(a);this.intensity=void 0!==b?b:1;this.receiveShadow=
13514 void 0}function nd(a,b,c){na.call(this,a,c);this.type="HemisphereLight";this.castShadow=void 0;this.position.copy(G.DefaultUp);this.updateMatrix();this.groundColor=new N(b)}function tb(a){this.camera=a;this.bias=0;this.radius=1;this.mapSize=new C(512,512);this.map=null;this.matrix=new H}function od(){tb.call(this,new Ha(50,1,.5,500))}function pd(a,b,c,d,e,f){na.call(this,a,b);this.type="SpotLight";this.position.copy(G.DefaultUp);this.updateMatrix();this.target=new G;Object.defineProperty(this,"power",
13515 {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 od}function qd(a,b,c,d){na.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 tb(new Ha(90,
13516 1,.5,500))}function rd(a){tb.call(this,new Hb(-5,5,5,-5,.5,500))}function sd(a,b){na.call(this,a,b);this.type="DirectionalLight";this.position.copy(G.DefaultUp);this.updateMatrix();this.target=new G;this.shadow=new rd}function td(a,b){na.call(this,a,b);this.type="AmbientLight";this.castShadow=void 0}function qa(a,b,c,d){this.parameterPositions=a;this._cachedIndex=0;this.resultBuffer=void 0!==d?d:new b.constructor(c);this.sampleValues=b;this.valueSize=c}function ud(a,b,c,d){qa.call(this,a,b,c,d);this._offsetNext=
13517 this._weightNext=this._offsetPrev=this._weightPrev=-0}function Wc(a,b,c,d){qa.call(this,a,b,c,d)}function vd(a,b,c,d){qa.call(this,a,b,c,d)}function ub(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=ba.convertArray(b,this.TimeBufferType);this.values=ba.convertArray(c,this.ValueBufferType);this.setInterpolation(d||this.DefaultInterpolation);this.validate();this.optimize()}function cc(a,b,
13518 c,d){ub.call(this,a,b,c,d)}function wd(a,b,c,d){qa.call(this,a,b,c,d)}function Xc(a,b,c,d){ub.call(this,a,b,c,d)}function dc(a,b,c,d){ub.call(this,a,b,c,d)}function xd(a,b,c,d){ub.call(this,a,b,c,d)}function yd(a,b,c){ub.call(this,a,b,c)}function zd(a,b,c,d){ub.call(this,a,b,c,d)}function vb(a,b,c,d){ub.apply(this,arguments)}function ta(a,b,c){this.name=a;this.tracks=c;this.duration=void 0!==b?b:-1;this.uuid=Q.generateUUID();0>this.duration&&this.resetDuration();this.optimize()}function Ad(a){this.manager=
13519 void 0!==a?a:va;this.textures={}}function Sd(a){this.manager=void 0!==a?a:va}function wb(){this.onLoadStart=function(){};this.onLoadProgress=function(){};this.onLoadComplete=function(){}}function Td(a){"boolean"===typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),a=void 0);this.manager=void 0!==a?a:va;this.withCredentials=!1}function Fe(a){this.manager=void 0!==a?a:va;this.texturePath=""}function wa(){}function Qa(a,b){this.v1=a;this.v2=b}function Yc(){this.curves=
13520 [];this.autoClose=!1}function Xa(a,b,c,d,e,f,g,h){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 xb(a){this.points=void 0===a?[]:a}function yb(a,b,c,d){this.v0=a;this.v1=b;this.v2=c;this.v3=d}function zb(a,b,c){this.v0=a;this.v1=b;this.v2=c}function Ab(){Zc.apply(this,arguments);this.holes=[]}function Zc(a){Yc.call(this);this.currentPoint=new C;a&&this.fromPoints(a)}function Ud(){this.subPaths=[];this.currentPath=
13521 null}function Vd(a){this.data=a}function Ge(a){this.manager=void 0!==a?a:va}function Wd(a){this.manager=void 0!==a?a:va}function Xd(a,b,c,d){na.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 He(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new Ha;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new Ha;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=
13522 !1}function Bd(a,b,c){G.call(this);this.type="CubeCamera";var d=new Ha(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new q(1,0,0));this.add(d);var e=new Ha(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new q(-1,0,0));this.add(e);var f=new Ha(90,1,a,b);f.up.set(0,0,1);f.lookAt(new q(0,1,0));this.add(f);var g=new Ha(90,1,a,b);g.up.set(0,0,-1);g.lookAt(new q(0,-1,0));this.add(g);var h=new Ha(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new q(0,0,1));this.add(h);var k=new Ha(90,1,a,b);k.up.set(0,-1,0);k.lookAt(new q(0,0,-1));this.add(k);
13523 this.renderTarget=new Eb(c,c,{format:1022,magFilter:1006,minFilter:1006});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 Yd(){G.call(this);
13524 this.type="AudioListener";this.context=Zd.getContext();this.gain=this.context.createGain();this.gain.connect(this.context.destination);this.filter=null}function ec(a){G.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";this.filters=[]}function $d(a){ec.call(this,a);this.panner=
13525 this.context.createPanner();this.panner.connect(this.gain)}function ae(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 Cd(a,b,c){this.binding=a;this.valueSize=c;a=Float64Array;switch(b){case "quaternion":b=this._slerp;break;case "string":case "bool":a=Array;b=this._select;break;default:b=this._lerp}this.buffer=new a(4*c);this._mixBufferRegion=b;this.referenceCount=
13526 this.useCount=this.cumulativeWeight=0}function ka(a,b,c){this.path=b;this.parsedPath=c||ka.parseTrackName(b);this.node=ka.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function be(a){this.uuid=Q.generateUUID();this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var b={};this._indicesByUUID=b;for(var c=0,d=arguments.length;c!==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},
13527 get inUse(){return this.total-e.nCachedObjects_}},get bindingsPerObject(){return e._bindings.length}}}function ce(a,b,c){this._mixer=a;this._clip=b;this._localRoot=c||null;a=b.tracks;b=a.length;c=Array(b);for(var d={endingStart:2400,endingEnd:2400},e=0;e!==b;++e){var f=a[e].createInterpolant(null);c[e]=f;f.settings=d}this._interpolantSettings=d;this._interpolants=c;this._propertyBindings=Array(b);this._weightInterpolant=this._timeScaleInterpolant=this._byClipCacheIndex=this._cacheIndex=null;this.loop=
13528 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 de(a){this._root=a;this._initMemoryManager();this.time=this._accuIndex=0;this.timeScale=1}function Dd(a,b){"string"===typeof a&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),a=b);this.value=a}function Bb(){D.call(this);
13529 this.type="InstancedBufferGeometry";this.maxInstancedCount=void 0}function ee(a,b,c,d){this.uuid=Q.generateUUID();this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0===d}function fc(a,b){this.uuid=Q.generateUUID();this.array=a;this.stride=b;this.count=void 0!==a?a.length/b:0;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function gc(a,b,c){fc.call(this,a,b);this.meshPerAttribute=c||1}function hc(a,b,c){y.call(this,a,b);this.meshPerAttribute=
13530 c||1}function fe(a,b,c,d){this.ray=new bb(a,b);this.near=c||0;this.far=d||Infinity;this.params={Mesh:{},Line:{},LOD:{},Points:{threshold:1},Sprite:{}};Object.defineProperties(this.params,{PointCloud:{get:function(){console.warn("THREE.Raycaster: params.PointCloud has been renamed to params.Points.");return this.Points}}})}function Ie(a,b){return a.distance-b.distance}function ge(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++)ge(a[d],b,c,!0)}}function he(a){this.autoStart=
13531 void 0!==a?a:!0;this.elapsedTime=this.oldTime=this.startTime=0;this.running=!1}function ie(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 je(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 ua(a,b){Ba.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){G.call(this);
13532 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 D;b=new X(6*b,3);c.addAttribute("position",b);fa.call(this,c,new ia({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function ic(a){G.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=
13533 !1;a=new D;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 X(b,3));b=new ia({fog:!1});this.cone=new fa(a,b);this.add(this.cone);this.update()}function jc(a){this.bones=this.getBoneList(a);for(var b=new D,c=[],d=[],e=new N(0,0,1),f=new N(0,1,0),g=0;g<this.bones.length;g++){var h=this.bones[g];h.parent&&h.parent.isBone&&(c.push(0,
13534 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 X(c,3));b.addAttribute("color",new X(d,3));c=new ia({vertexColors:2,depthTest:!1,depthWrite:!1,transparent:!0});fa.call(this,b,c);this.root=a;this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.update()}function kc(a,b){this.light=a;this.light.updateMatrixWorld();var c=new mb(b,4,2),d=new Ka({wireframe:!0,fog:!1});d.color.copy(this.light.color).multiplyScalar(this.light.intensity);Ba.call(this,c,d);this.matrix=
13535 this.light.matrixWorld;this.matrixAutoUpdate=!1}function lc(a){G.call(this);this.light=a;this.light.updateMatrixWorld();var b=new Ka({color:a.color,fog:!1});a=new Ka({color:a.color,fog:!1,wireframe:!0});var c=new D;c.addAttribute("position",new y(new Float32Array(18),3));this.add(new Ba(c,b));this.add(new Ba(c,a));this.update()}function mc(a,b){G.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;var c=new lb(b);c.rotateY(.5*Math.PI);var d=new Ka({vertexColors:2,
13536 wireframe:!0}),e=c.getAttribute("position"),e=new Float32Array(3*e.count);c.addAttribute("color",new y(e,3));this.add(new Ba(c,d));this.update()}function bd(a,b,c,d){a=a||10;b=b||10;c=new N(void 0!==c?c:4473924);d=new N(void 0!==d?d:8947848);for(var e=b/2,f=2*a/b,g=[],h=[],k=0,m=0,l=-a;k<=b;k++,l+=f){g.push(-a,0,l,a,0,l);g.push(l,0,-a,l,0,a);var p=k===e?c:d;p.toArray(h,m);m+=3;p.toArray(h,m);m+=3;p.toArray(h,m);m+=3;p.toArray(h,m);m+=3}a=new D;a.addAttribute("position",new X(g,3));a.addAttribute("color",
13537 new X(h,3));g=new ia({vertexColors:2});fa.call(this,a,g)}function Ed(a,b,c,d,e,f){a=a||10;b=b||16;c=c||8;d=d||64;e=new N(void 0!==e?e:4473924);f=new N(void 0!==f?f:8947848);var g=[],h=[],k,m,l,p,n;for(l=0;l<=b;l++)m=l/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=l&1?e:f,h.push(n.r,n.g,n.b),h.push(n.r,n.g,n.b);for(l=0;l<=c;l++)for(n=l&1?e:f,p=a-a/c*l,b=0;b<d;b++)m=b/d*2*Math.PI,k=Math.sin(m)*p,m=Math.cos(m)*p,g.push(k,0,m),h.push(n.r,n.g,n.b),m=(b+1)/d*2*Math.PI,k=Math.sin(m)*
13538 p,m=Math.cos(m)*p,g.push(k,0,m),h.push(n.r,n.g,n.b);a=new D;a.addAttribute("position",new X(g,3));a.addAttribute("color",new X(h,3));g=new ia({vertexColors:2});fa.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:console.warn("THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.");c=new D;b=new X(6*b,3);c.addAttribute("position",
13539 b);fa.call(this,c,new ia({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function nc(a,b){G.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;void 0===b&&(b=1);var c=new D;c.addAttribute("position",new X([-b,b,0,b,b,0,b,-b,0,-b,-b,0,-b,b,0],3));var d=new ia({fog:!1});this.add(new Va(c,d));c=new D;c.addAttribute("position",new X([0,0,0,0,0,1],3));this.add(new Va(c,d));this.update()}function dd(a){function b(a,b,d){c(a,d);c(b,d)}
13540 function c(a,b){f.push(0,0,0);g.push(b.r,b.g,b.b);void 0===h[a]&&(h[a]=[]);h[a].push(f.length/3-1)}var d=new D,e=new ia({color:16777215,vertexColors:1}),f=[],g=[],h={},k=new N(16755200),m=new N(16711680),l=new N(43775),p=new N(16777215),n=new N(3355443);b("n1","n2",k);b("n2","n4",k);b("n4","n3",k);b("n3","n1",k);b("f1","f2",k);b("f2","f4",k);b("f4","f3",k);b("f3","f1",k);b("n1","f1",k);b("n2","f2",k);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",
13541 l);b("u2","u3",l);b("u3","u1",l);b("c","t",p);b("p","c",n);b("cn1","cn2",n);b("cn3","cn4",n);b("cf1","cf2",n);b("cf3","cf4",n);d.addAttribute("position",new X(f,3));d.addAttribute("color",new X(g,3));fa.call(this,d,e);this.camera=a;this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.pointMap=h;this.update()}function oc(a,b){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]),
13542 d=new Float32Array(24),e=new D;e.setIndex(new y(c,1));e.addAttribute("position",new y(d,3));fa.call(this,e,new ia({color:b}));void 0!==a&&this.update(a)}function Cb(a,b,c,d,e,f){G.call(this);void 0===d&&(d=16776960);void 0===c&&(c=1);void 0===e&&(e=.2*c);void 0===f&&(f=.2*e);this.position.copy(b);this.line=new Va(Je,new ia({color:d}));this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new Ba(Ke,new Ka({color:d}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);this.setDirection(a);this.setLength(c,
13543 e,f)}function Fd(a){a=a||1;var b=[0,0,0,a,0,0,0,0,0,0,a,0,0,0,0,0,0,a];a=new D;a.addAttribute("position",new X(b,3));a.addAttribute("color",new X([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));b=new ia({vertexColors:2});fa.call(this,a,b)}function Gd(a,b,c,d,e,f){Xa.call(this,a,b,c,c,d,e,f)}function Le(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");ke.call(this,a);this.type="catmullrom";this.closed=!0}void 0===Number.EPSILON&&(Number.EPSILON=Math.pow(2,
13544 -52));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]}});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,
13545 e)&&(b[e]=d[e])}return b}}();Object.assign(oa.prototype,{addEventListener:function(a,b){void 0===this._listeners&&(this._listeners={});var c=this._listeners;void 0===c[a]&&(c[a]=[]);-1===c[a].indexOf(b)&&c[a].push(b)},hasEventListener:function(a,b){if(void 0===this._listeners)return!1;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!==
13546 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 Me={NoBlending:0,NormalBlending:1,AdditiveBlending:2,SubtractiveBlending:3,MultiplyBlending:4,CustomBlending:5},Ne={UVMapping:300,CubeReflectionMapping:301,CubeRefractionMapping:302,EquirectangularReflectionMapping:303,EquirectangularRefractionMapping:304,SphericalReflectionMapping:305,CubeUVReflectionMapping:306,CubeUVRefractionMapping:307},
13547 le={RepeatWrapping:1E3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002},me={NearestFilter:1003,NearestMipMapNearestFilter:1004,NearestMipMapLinearFilter:1005,LinearFilter:1006,LinearMipMapNearestFilter:1007,LinearMipMapLinearFilter:1008},Q={DEG2RAD:Math.PI/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":
13548 (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-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)+
13549 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*Q.DEG2RAD},radToDeg:function(a){return a*Q.RAD2DEG},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}};C.prototype={constructor:C,
13550 isVector2:!0,get width(){return this.x},set width(a){this.x=a},get height(){return this.y},set height(a){this.y=a},set:function(a,b){this.x=a;this.y=b;return this},setScalar:function(a){this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;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;
13551 default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this},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,
13552 b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;return this},subScalar:function(a){this.x-=a;this.y-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this},multiply:function(a){this.x*=a.x;this.y*=a.y;return this},multiplyScalar:function(a){isFinite(a)?(this.x*=a,this.y*=a):this.y=this.x=0;
13553 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=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,b;return function(c,d){void 0===a&&(a=new C,b=new C);a.set(c,
13554 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);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);
13555 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)+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))},
13556 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+=(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+
13557 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},fromAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector2: offset has been removed from .fromAttribute().");this.x=a.getX(b);this.y=a.getY(b);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 Oe=0;ea.DEFAULT_IMAGE=void 0;ea.DEFAULT_MAPPING=300;ea.prototype={constructor:ea,isTexture:!0,
13558 set needsUpdate(a){!0===a&&this.version++},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.image=a.image;this.mipmaps=a.mipmaps.slice(0);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;
13559 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.4,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=
13560 this.image;void 0===c.uuid&&(c.uuid=Q.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","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"})},
13561 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=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(ea.prototype,
13562 oa.prototype);ga.prototype={constructor:ga,isVector4:!0,set:function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.w=d;return this},setScalar:function(a){this.w=this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;case 3:this.w=b;break;default:throw Error("index is out of range: "+
13563 a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z,this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,
13564 b);this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=
13565 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){isFinite(a)?(this.x*=a,this.y*=a,this.z*=a,this.w*=a):this.w=this.z=this.y=this.x=0;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=
13566 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/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>
13567 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):(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)/
13568 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,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));
13569 this.w=Math.max(a.w,Math.min(b.w,this.w));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new ga,b=new ga);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},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);
13570 this.y=Math.round(this.y);this.z=Math.round(this.z);this.w=Math.round(this.w);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);this.w=0>this.w?Math.ceil(this.w):Math.floor(this.w);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this},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*
13571 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())},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,
13572 b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];this.w=a[b+3];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;a[b+3]=this.w;return a},fromAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector4: offset has been removed from .fromAttribute().");this.x=a.getX(b);
13573 this.y=a.getY(b);this.z=a.getZ(b);this.w=a.getW(b);return this}};Object.assign(Db.prototype,oa.prototype,{isWebGLRenderTarget:!0,setSize:function(a,b){if(this.width!==a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0,0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone();this.depthBuffer=a.depthBuffer;this.stencilBuffer=
13574 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;da.prototype={constructor:da,get x(){return this._x},set x(a){this._x=a;this.onChangeCallback()},get y(){return this._y},set y(a){this._y=a;this.onChangeCallback()},get z(){return this._z},set z(a){this._z=a;this.onChangeCallback()},get w(){return this._w},set w(a){this._w=
13575 a;this.onChangeCallback()},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,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=Math.cos(a._x/2),d=Math.cos(a._y/
13576 2),e=Math.cos(a._z/2),f=Math.sin(a._x/2),g=Math.sin(a._y/2),h=Math.sin(a._z/2),k=a.order;"XYZ"===k?(this._x=f*d*e+c*g*h,this._y=c*g*e-f*d*h,this._z=c*d*h+f*g*e,this._w=c*d*e-f*g*h):"YXZ"===k?(this._x=f*d*e+c*g*h,this._y=c*g*e-f*d*h,this._z=c*d*h-f*g*e,this._w=c*d*e+f*g*h):"ZXY"===k?(this._x=f*d*e-c*g*h,this._y=c*g*e+f*d*h,this._z=c*d*h+f*g*e,this._w=c*d*e-f*g*h):"ZYX"===k?(this._x=f*d*e-c*g*h,this._y=c*g*e+f*d*h,this._z=c*d*h-f*g*e,this._w=c*d*e+f*g*h):"YZX"===k?(this._x=f*d*e+c*g*h,this._y=c*g*e+
13577 f*d*h,this._z=c*d*h-f*g*e,this._w=c*d*e-f*g*h):"XZY"===k&&(this._x=f*d*e-c*g*h,this._y=c*g*e-f*d*h,this._z=c*d*h+f*g*e,this._w=c*d*e+f*g*h);if(!1!==b)this.onChangeCallback();return this},setFromAxisAngle:function(a,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=
13578 .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=.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,b;return function(c,d){void 0===a&&(a=new q);b=c.dot(d)+1;1E-6>b?(b=0,Math.abs(c.x)>Math.abs(c.z)?a.set(-c.y,
13579 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*=-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+
13580 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},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,
13581 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();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);
13582 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*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];
13583 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=a;return this},onChangeCallback:function(){}};Object.assign(da,{slerp:function(a,b,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 l=e[f+1],p=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==l||m!==p){f=1-g;var n=h*d+k*l+m*p+c*e,r=0<=
13584 n?1:-1,w=1-n*n;w>Number.EPSILON&&(w=Math.sqrt(w),n=Math.atan2(w,n*r),f=Math.sin(f*n)/w,g=Math.sin(g*n)/w);r*=g;h=h*f+d*r;k=k*f+l*r;m=m*f+p*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}});q.prototype={constructor:q,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=
13585 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;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."),
13586 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},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;
13587 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=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){isFinite(a)?(this.x*=a,this.y*=a,this.z*=a):this.z=this.y=this.x=0;return this},multiplyVectors:function(a,
13588 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;return function(b){!1===(b&&b.isEuler)&&console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");void 0===a&&(a=new da);return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a;return function(b,c){void 0===a&&(a=new da);return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z;
13589 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];return this},applyProjection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;var e=1/(a[3]*b+a[7]*c+a[11]*d+a[15]);this.x=(a[0]*b+a[4]*c+a[8]*d+a[12])*e;this.y=(a[1]*b+a[5]*c+a[9]*d+a[13])*e;this.z=(a[2]*b+a[6]*
13590 c+a[10]*d+a[14])*e;return this},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a=a.w;var h=a*b+f*d-g*c,k=a*c+g*b-e*d,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;return function(b){void 0===a&&(a=new H);a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyProjection(a)}}(),unproject:function(){var a;return function(b){void 0===a&&(a=new H);
13591 a.multiplyMatrices(b.matrixWorld,a.getInverse(b.projectionMatrix));return this.applyProjection(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,
13592 a.z);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);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,b;return function(c,d){void 0===a&&(a=new q,b=new q);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,
13593 Math.min(b,c))/c)},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):
13594 Math.floor(this.z);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},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/
13595 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;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=
13596 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=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;return function(b){void 0===a&&(a=new q);a.copy(this).projectOnVector(b);return this.sub(a)}}(),reflect:function(){var a;return function(b){void 0===a&&(a=new q);return this.sub(a.copy(b).multiplyScalar(2*this.dot(b)))}}(),angleTo:function(a){a=this.dot(a)/Math.sqrt(this.lengthSq()*
13597 a.lengthSq());return Math.acos(Q.clamp(a,-1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},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=
13598 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,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){if("number"===typeof a){console.warn("THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).");var c=
13599 a;a=b;b=c}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]=this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector3: offset has been removed from .fromAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);return this}};
13600 H.prototype={constructor:H,isMatrix4:!0,set:function(a,b,c,d,e,f,g,h,k,m,l,p,n,r,w,u){var q=this.elements;q[0]=a;q[4]=b;q[8]=c;q[12]=d;q[1]=e;q[5]=f;q[9]=g;q[13]=h;q[2]=k;q[6]=m;q[10]=l;q[14]=p;q[3]=n;q[7]=r;q[11]=w;q[15]=u;return this},identity:function(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this},clone:function(){return(new H).fromArray(this.elements)},copy:function(a){this.elements.set(a.elements);return this},copyPosition:function(a){var b=this.elements;a=a.elements;b[12]=a[12];b[13]=
13601 a[13];b[14]=a[14];return this},extractBasis:function(a,b,c){a.setFromMatrixColumn(this,0);b.setFromMatrixColumn(this,1);c.setFromMatrixColumn(this,2);return this},makeBasis:function(a,b,c){this.set(a.x,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;return function(b){void 0===a&&(a=new q);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;
13602 c[1]=d[1]*e;c[2]=d[2]*e;c[4]=d[4]*f;c[5]=d[5]*f;c[6]=d[6]*f;c[8]=d[8]*b;c[9]=d[9]*b;c[10]=d[10]*b;return this}}(),makeRotationFromEuler:function(a){!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,l=c*e;b[0]=g*h;b[4]=-g*e;b[8]=d;b[1]=k+m*d;b[5]=a-
13603 l*d;b[9]=-c*g;b[2]=l-a*d;b[6]=m+k*d;b[10]=f*g}else"YXZ"===a.order?(a=g*h,k=g*e,m=d*h,l=d*e,b[0]=a+l*c,b[4]=m*c-k,b[8]=f*d,b[1]=f*e,b[5]=f*h,b[9]=-c,b[2]=k*c-m,b[6]=l+a*c,b[10]=f*g):"ZXY"===a.order?(a=g*h,k=g*e,m=d*h,l=d*e,b[0]=a-l*c,b[4]=-f*e,b[8]=m+k*c,b[1]=k+m*c,b[5]=f*h,b[9]=l-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,l=c*e,b[0]=g*h,b[4]=m*d-k,b[8]=a*d+l,b[1]=g*e,b[5]=l*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,l=c*d,b[0]=g*h,b[4]=l-
13604 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-l*e):"XZY"===a.order&&(a=f*g,k=f*d,m=c*g,l=c*d,b[0]=g*h,b[4]=-e,b[8]=d*h,b[1]=a*e+l,b[5]=f*h,b[9]=k*e-m,b[2]=m*e-k,b[6]=c*h,b[10]=l*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,l=d*h,d=d*k,e=e*k,g=f*g,h=f*h,f=f*k;b[0]=1-(l+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-
13605 h;b[6]=d+g;b[10]=1-(a+l);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,b,c;return function(d,e,f){void 0===a&&(a=new q,b=new q,c=new q);var g=this.elements;c.subVectors(d,e).normalize();0===c.lengthSq()&&(c.z=1);a.crossVectors(f,c).normalize();0===a.lengthSq()&&(c.z+=1E-4,a.crossVectors(f,c).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!==
13606 b?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(a,b)):this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements,e=this.elements,f=c[0],g=c[4],h=c[8],k=c[12],m=c[1],l=c[5],p=c[9],n=c[13],r=c[2],w=c[6],u=c[10],q=c[14],t=c[3],v=c[7],M=c[11],c=c[15],z=d[0],A=d[4],I=d[8],E=d[12],K=d[1],y=d[5],J=d[9],C=d[13],D=d[2],G=d[6],
13607 H=d[10],O=d[14],P=d[3],R=d[7],T=d[11],d=d[15];e[0]=f*z+g*K+h*D+k*P;e[4]=f*A+g*y+h*G+k*R;e[8]=f*I+g*J+h*H+k*T;e[12]=f*E+g*C+h*O+k*d;e[1]=m*z+l*K+p*D+n*P;e[5]=m*A+l*y+p*G+n*R;e[9]=m*I+l*J+p*H+n*T;e[13]=m*E+l*C+p*O+n*d;e[2]=r*z+w*K+u*D+q*P;e[6]=r*A+w*y+u*G+q*R;e[10]=r*I+w*J+u*H+q*T;e[14]=r*E+w*C+u*O+q*d;e[3]=t*z+v*K+M*D+c*P;e[7]=t*A+v*y+M*G+c*R;e[11]=t*I+v*J+M*H+c*T;e[15]=t*E+v*C+M*O+c*d;return this},multiplyToArray:function(a,b,c){var d=this.elements;this.multiplyMatrices(a,b);c[0]=d[0];c[1]=d[1];c[2]=
13608 d[2];c[3]=d[3];c[4]=d[4];c[5]=d[5];c[6]=d[6];c[7]=d[7];c[8]=d[8];c[9]=d[9];c[10]=d[10];c[11]=d[11];c[12]=d[12];c[13]=d[13];c[14]=d[14];c[15]=d[15];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},applyToVector3Array:function(){var a;return function(b,c,d){void 0===a&&(a=new q);void 0===c&&(c=0);void 0===d&&(d=b.length);for(var e=0;e<d;e+=3,c+=
13609 3)a.fromArray(b,c),a.applyMatrix4(this),a.toArray(b,c);return b}}(),applyToBufferAttribute:function(){var a;return function(b){void 0===a&&(a=new q);for(var c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix4(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),determinant:function(){var a=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],l=a[6],p=a[10],n=a[14];return a[3]*(+e*h*l-d*k*l-e*g*p+c*k*p+d*g*n-c*h*n)+a[7]*(+b*h*n-b*k*p+e*f*p-d*f*n+d*k*m-e*h*
13610 m)+a[11]*(+b*k*l-b*g*n-e*f*l+c*f*n+e*g*m-c*k*m)+a[15]*(-d*g*m-b*h*l+b*g*p+d*f*l-c*f*p+c*h*m)},transpose:function(){var a=this.elements,b;b=a[1];a[1]=a[4];a[4]=b;b=a[2];a[2]=a[8];a[8]=b;b=a[6];a[6]=a[9];a[9]=b;b=a[3];a[3]=a[12];a[12]=b;b=a[7];a[7]=a[13];a[13]=b;b=a[11];a[11]=a[14];a[14]=b;return this},setPosition:function(a){var b=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],p=d[7],
13611 n=d[8],r=d[9],w=d[10],u=d[11],q=d[12],t=d[13],v=d[14],d=d[15],M=r*v*p-t*w*p+t*l*u-m*v*u-r*l*d+m*w*d,z=q*w*p-n*v*p-q*l*u+k*v*u+n*l*d-k*w*d,A=n*t*p-q*r*p+q*m*u-k*t*u-n*m*d+k*r*d,I=q*r*l-n*t*l-q*m*w+k*t*w+n*m*v-k*r*v,E=e*M+f*z+g*A+h*I;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]=M*E;c[1]=(t*w*h-r*v*h-t*g*u+f*v*u+r*g*d-f*w*d)*E;c[2]=
13612 (m*v*h-t*l*h+t*g*p-f*v*p-m*g*d+f*l*d)*E;c[3]=(r*l*h-m*w*h-r*g*p+f*w*p+m*g*u-f*l*u)*E;c[4]=z*E;c[5]=(n*v*h-q*w*h+q*g*u-e*v*u-n*g*d+e*w*d)*E;c[6]=(q*l*h-k*v*h-q*g*p+e*v*p+k*g*d-e*l*d)*E;c[7]=(k*w*h-n*l*h+n*g*p-e*w*p-k*g*u+e*l*u)*E;c[8]=A*E;c[9]=(q*r*h-n*t*h-q*f*u+e*t*u+n*f*d-e*r*d)*E;c[10]=(k*t*h-q*m*h+q*f*p-e*t*p-k*f*d+e*m*d)*E;c[11]=(n*m*h-k*r*h-n*f*p+e*r*p+k*f*u-e*m*u)*E;c[12]=I*E;c[13]=(n*t*g-q*r*g+q*f*w-e*t*w-n*f*v+e*r*v)*E;c[14]=(q*m*g-k*t*g-q*f*l+e*t*l+k*f*v-e*m*v)*E;c[15]=(k*r*g-n*m*g+n*f*l-
13613 e*r*l-k*f*w+e*m*w)*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]*=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);
13614 a=Math.sin(a);this.set(1,0,0,0,0,b,-a,0,0,a,b,0,0,0,0,1);return this},makeRotationY:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,0,a,0,0,1,0,0,-a,0,b,0,0,0,0,1);return this},makeRotationZ:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,-a,0,0,a,b,0,0,0,0,1,0,0,0,0,1);return this},makeRotationAxis:function(a,b){var c=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},
13615 makeScale:function(a,b,c){this.set(a,0,0,0,0,b,0,0,0,0,c,0,0,0,0,1);return this},makeShear:function(a,b,c){this.set(1,b,c,0,a,1,c,0,a,b,1,0,0,0,0,1);return this},compose:function(a,b,c){this.makeRotationFromQuaternion(b);this.scale(c);this.setPosition(a);return this},decompose:function(){var a,b;return function(c,d,e){void 0===a&&(a=new q,b=new H);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=
13616 f[12];c.y=f[13];c.z=f[14];b.elements.set(this.elements);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]*=m;b.elements[9]*=m;b.elements[10]*=m;d.setFromRotationMatrix(b);e.x=g;e.y=h;e.z=k;return this}}(),makeFrustum:function(a,b,c,d,e,f){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/(d-c);g[9]=(d+c)/(d-c);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]=
13617 0;g[11]=-1;g[15]=0;return this},makePerspective:function(a,b,c,d){a=c*Math.tan(Q.DEG2RAD*a*.5);var e=-a;return this.makeFrustum(e*b,a*b,e,a,c,d)},makeOrthographic:function(a,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},
13618 fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;16>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];a[b+9]=c[9];a[b+10]=c[10];a[b+11]=c[11];a[b+12]=c[12];a[b+13]=c[13];a[b+14]=c[14];a[b+15]=c[15];return a}};Za.prototype=Object.create(ea.prototype);Za.prototype.constructor=Za;Za.prototype.isCubeTexture=!0;Object.defineProperty(Za.prototype,
13619 "images",{get:function(){return this.image},set:function(a){this.image=a}});var se=new ea,te=new Za,pe=[],re=[];xe.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 Id=/([\w\d_]+)(\])?(\[|\.)?/g;$a.prototype.setValue=function(a,b,c){b=this.map[b];void 0!==b&&b.setValue(a,c,this.renderer)};$a.prototype.set=function(a,b,c){var d=this.map[c];void 0!==d&&d.setValue(a,b[c],this.renderer)};$a.prototype.setOptional=function(a,b,c){b=b[c];
13620 void 0!==b&&this.setValue(a,c,b)};$a.upload=function(a,b,c,d){for(var e=0,f=b.length;e!==f;++e){var g=b[e],h=c[g.id];!1!==h.needsUpdate&&g.setValue(a,h.value,d)}};$a.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 Ja={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||
13621 e.isVector2||e.isVector3||e.isVector4||e.isTexture)?b[c][d]=e.clone():Array.isArray(e)?b[c][d]=e.slice():b[c][d]=e}}return b}},Z={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",
13622 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\t\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\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 ltcTextureCoords( const in GeometricContext geometry, 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\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\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}\nvoid clipQuadToHorizon( inout vec3 L[5], out int n ) {\n\tint config = 0;\n\tif ( L[0].z > 0.0 ) config += 1;\n\tif ( L[1].z > 0.0 ) config += 2;\n\tif ( L[2].z > 0.0 ) config += 4;\n\tif ( L[3].z > 0.0 ) config += 8;\n\tn = 0;\n\tif ( config == 0 ) {\n\t} else if ( config == 1 ) {\n\t\tn = 3;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 2 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 3 ) {\n\t\tn = 4;\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t\tL[3] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 4 ) {\n\t\tn = 3;\n\t\tL[0] = -L[3].z * L[2] + L[2].z * L[3];\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t} else if ( config == 5 ) {\n\t\tn = 0;\n\t} else if ( config == 6 ) {\n\t\tn = 4;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 7 ) {\n\t\tn = 5;\n\t\tL[4] = -L[3].z * L[0] + L[0].z * L[3];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 8 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[1] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = L[3];\n\t} else if ( config == 9 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[2].z * L[3] + L[3].z * L[2];\n\t} else if ( config == 10 ) {\n\t\tn = 0;\n\t} else if ( config == 11 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 12 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t} else if ( config == 13 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = L[2];\n\t\tL[2] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t} else if ( config == 14 ) {\n\t\tn = 5;\n\t\tL[4] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t} else if ( config == 15 ) {\n\t\tn = 4;\n\t}\n\tif ( n == 3 )\n\t\tL[3] = L[0];\n\tif ( n == 4 )\n\t\tL[4] = L[0];\n}\nfloat integrateLtcBrdfOverRectEdge( vec3 v1, vec3 v2 ) {\n\tfloat cosTheta = dot( v1, v2 );\n\tfloat theta = acos( cosTheta );\n\tfloat res = cross( v1, v2 ).z * ( ( theta > 0.001 ) ? theta / sin( theta ) : 1.0 );\n\treturn res;\n}\nvoid initRectPoints( const in vec3 pos, const in vec3 halfWidth, const in vec3 halfHeight, out vec3 rectPoints[4] ) {\n\trectPoints[0] = pos - halfWidth - halfHeight;\n\trectPoints[1] = pos + halfWidth - halfHeight;\n\trectPoints[2] = pos + halfWidth + halfHeight;\n\trectPoints[3] = pos - halfWidth + halfHeight;\n}\nvec3 integrateLtcBrdfOverRect( const in GeometricContext geometry, const in mat3 brdfMat, const in vec3 rectPoints[4] ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tvec3 T1, T2;\n\tT1 = normalize(V - N * dot( V, N ));\n\tT2 = - cross( N, T1 );\n\tmat3 brdfWrtSurface = brdfMat * transpose( mat3( T1, T2, N ) );\n\tvec3 clippedRect[5];\n\tclippedRect[0] = brdfWrtSurface * ( rectPoints[0] - P );\n\tclippedRect[1] = brdfWrtSurface * ( rectPoints[1] - P );\n\tclippedRect[2] = brdfWrtSurface * ( rectPoints[2] - P );\n\tclippedRect[3] = brdfWrtSurface * ( rectPoints[3] - P );\n\tint n;\n\tclipQuadToHorizon(clippedRect, n);\n\tif ( n == 0 )\n\t\treturn vec3( 0, 0, 0 );\n\tclippedRect[0] = normalize( clippedRect[0] );\n\tclippedRect[1] = normalize( clippedRect[1] );\n\tclippedRect[2] = normalize( clippedRect[2] );\n\tclippedRect[3] = normalize( clippedRect[3] );\n\tclippedRect[4] = normalize( clippedRect[4] );\n\tfloat sum = 0.0;\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[0], clippedRect[1] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[1], clippedRect[2] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[2], clippedRect[3] );\n\tif (n >= 4)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[3], clippedRect[4] );\n\tif (n == 5)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[4], clippedRect[0] );\n\tsum = max( 0.0, sum );\n\tvec3 Lo_i = vec3( sum, sum, sum );\n\treturn Lo_i;\n}\nvec3 Rect_Area_Light_Specular_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight,\n\t\tconst in float roughness,\n\t\tconst in sampler2D ltcMat, const in sampler2D ltcMag ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tvec2 uv = ltcTextureCoords( geometry, roughness );\n\tvec4 brdfLtcApproxParams, t;\n\tbrdfLtcApproxParams = texture2D( ltcMat, uv );\n\tt = texture2D( ltcMat, uv );\n\tfloat brdfLtcScalar = texture2D( ltcMag, uv ).a;\n\tmat3 brdfLtcApproxMat = mat3(\n\t\tvec3( 1, 0, t.y ),\n\t\tvec3( 0, t.z, 0 ),\n\t\tvec3( t.w, 0, t.x )\n\t);\n\tvec3 specularReflectance = integrateLtcBrdfOverRect( geometry, brdfLtcApproxMat, rectPoints );\n\tspecularReflectance *= brdfLtcScalar;\n\treturn specularReflectance;\n}\nvec3 Rect_Area_Light_Diffuse_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tmat3 diffuseBrdfMat = mat3(1);\n\tvec3 diffuseReflectance = integrateLtcBrdfOverRect( geometry, diffuseBrdfMat, rectPoints );\n\treturn diffuseReflectance;\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",
13623 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",
13624 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",
13625 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",
13626 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",
13627 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",
13628 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",
13629 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 return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return 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 return 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 return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return 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 vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return 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 float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n",
13630 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",
13631 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",
13632 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",
13633 fog_fragment:"#ifdef USE_FOG\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\t#else\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\t#endif\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\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\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",
13634 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",
13635 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_RECT_AREA_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\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",
13636 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",
13637 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 void RE_Direct_RectArea_BlinnPhong( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 matDiffColor = material.diffuseColor;\n vec3 matSpecColor = material.specularColor;\n vec3 lightColor = rectAreaLight.color;\n float roughness = BlinnExponentToGGXRoughness( material.specularShininess );\n vec3 spec = Rect_Area_Light_Specular_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n roughness,\n ltcMat, ltcMag );\n vec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n reflectedLight.directSpecular += lightColor * matSpecColor * spec / PI2;\n reflectedLight.directDiffuse += lightColor * matDiffColor * diff / PI2;\n }\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",
13638 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",
13639 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 void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 matDiffColor = material.diffuseColor;\n vec3 matSpecColor = material.specularColor;\n vec3 lightColor = rectAreaLight.color;\n float roughness = material.specularRoughness;\n vec3 spec = Rect_Area_Light_Specular_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n roughness,\n ltcMat, ltcMag );\n vec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n reflectedLight.directSpecular += lightColor * matSpecColor * spec;\n reflectedLight.directDiffuse += lightColor * matDiffColor * diff;\n }\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",
13640 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\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n",
13641 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",
13642 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",
13643 metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\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",
13644 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",
13645 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",
13646 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",
13647 packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 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 return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n",
13648 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",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n",
13649 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 #if NUM_RECT_AREA_LIGHTS > 0\n #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",
13650 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 #if NUM_RECT_AREA_LIGHTS > 0\n #endif\n#endif\n",
13651 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 #if NUM_RECT_AREA_LIGHTS > 0\n #endif\n#endif\n",
13652 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#if NUM_RECT_AREA_LIGHTS > 0\n\t#endif\n\t#endif\n\treturn shadow;\n}\n",
13653 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 boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\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",
13654 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",
13655 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 return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return 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 color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n",
13656 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",
13657 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",
13658 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",
13659 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",
13660 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",
13661 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",
13662 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",
13663 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",
13664 linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_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}\n",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",
13665 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 <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}\n",
13666 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 <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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
13667 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 <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}\n",
13668 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 <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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
13669 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 <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}\n",
13670 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 <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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
13671 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 <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}\n",
13672 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\t#include <premultiplied_alpha_fragment>\n\t#include <encodings_fragment>\n}\n",
13673 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",
13674 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",
13675 points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_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}\n",
13676 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"};N.prototype={constructor:N,
13677 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=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,
13678 c,d){b=Q.euclideanModulo(b,1);c=Q.clamp(c,0,1);d=Q.clamp(d,0,1);0===c?this.r=this.g=this.b=d:(c=.5>=d?d*(1+c):d+c-d*c,d=2*d-c,this.r=a(d,c,b+1/3),this.g=a(d,c,b),this.b=a(d,c,b-1/3));return this}}(),setStyle:function(a){function b(b){void 0!==b&&1>parseFloat(b)&&console.warn("THREE.Color: Alpha component of "+a+" will be ignored.")}var c;if(c=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(a)){var d=c[2];switch(c[1]){case "rgb":case "rgba":if(c=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=
13679 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=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])/
13680 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)+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=Lf[a],void 0!==
13681 c?this.setHex(c):console.warn("THREE.Color: Unknown color "+a));return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(a){this.r=a.r;this.g=a.g;this.b=a.b;return this},copyGammaToLinear:function(a,b){void 0===b&&(b=2);this.r=Math.pow(a.r,b);this.g=Math.pow(a.g,b);this.b=Math.pow(a.b,b);return this},copyLinearToGamma:function(a,b){void 0===b&&(b=2);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=
13682 this.r,b=this.g,c=this.b;this.r=a*a;this.g=b*b;this.b=c*c;return this},convertLinearToGamma:function(){this.r=Math.sqrt(this.r);this.g=Math.sqrt(this.g);this.b=Math.sqrt(this.b);return this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(a){a=a||{h:0,s:0,l:0};var b=this.r,c=this.g,d=this.b,e=Math.max(b,c,d),f=Math.min(b,c,d),g,h=(f+e)/2;if(f===e)f=g=0;else{var k=e-f,f=.5>=h?k/(e+f):
13683 k/(2-e-f);switch(e){case b:g=(c-d)/k+(c<d?6:0);break;case c:g=(d-b)/k+2;break;case d:g=(b-c)/k+4}g/=6}a.h=g;a.s=f;a.l=h;return a},getStyle:function(){return"rgb("+(255*this.r|0)+","+(255*this.g|0)+","+(255*this.b|0)+")"},offsetHSL:function(a,b,c){var d=this.getHSL();d.h+=a;d.s+=b;d.l+=c;this.setHSL(d.h,d.s,d.l);return this},add:function(a){this.r+=a.r;this.g+=a.g;this.b+=a.b;return this},addColors:function(a,b){this.r=a.r+b.r;this.g=a.g+b.g;this.b=a.b+b.b;return this},addScalar:function(a){this.r+=
13684 a;this.g+=a;this.b+=a;return this},sub:function(a){this.r=Math.max(0,this.r-a.r);this.g=Math.max(0,this.g-a.g);this.b=Math.max(0,this.b-a.b);return this},multiply:function(a){this.r*=a.r;this.g*=a.g;this.b*=a.b;return this},multiplyScalar:function(a){this.r*=a;this.g*=a;this.b*=a;return this},lerp:function(a,b){this.r+=(a.r-this.r)*b;this.g+=(a.g-this.g)*b;this.b+=(a.b-this.b)*b;return this},equals:function(a){return a.r===this.r&&a.g===this.g&&a.b===this.b},fromArray:function(a,b){void 0===b&&(b=
13685 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 Lf={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,
13686 cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,
13687 floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,
13688 lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,
13689 moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,
13690 silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};db.prototype=Object.create(ea.prototype);db.prototype.constructor=db;db.prototype.isDataTexture=!0;var U={common:{diffuse:{value:new N(15658734)},opacity:{value:1},map:{value:null},offsetRepeat:{value:new ga(0,
13691 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 C(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},
13692 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 N(16777215)}},lights:{ambientLightColor:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},
13693 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:[],properties:{color:{},position:{},
13694 width:{},height:{}}}},points:{diffuse:{value:new N(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},offsetRepeat:{value:new ga(0,0,1,1)}}},Gb={basic:{uniforms:Ja.merge([U.common,U.aomap,U.lightmap,U.fog]),vertexShader:Z.meshbasic_vert,fragmentShader:Z.meshbasic_frag},lambert:{uniforms:Ja.merge([U.common,U.aomap,U.lightmap,U.emissivemap,U.fog,U.lights,{emissive:{value:new N(0)}}]),vertexShader:Z.meshlambert_vert,fragmentShader:Z.meshlambert_frag},phong:{uniforms:Ja.merge([U.common,
13695 U.aomap,U.lightmap,U.emissivemap,U.bumpmap,U.normalmap,U.displacementmap,U.gradientmap,U.fog,U.lights,{emissive:{value:new N(0)},specular:{value:new N(1118481)},shininess:{value:30}}]),vertexShader:Z.meshphong_vert,fragmentShader:Z.meshphong_frag},standard:{uniforms:Ja.merge([U.common,U.aomap,U.lightmap,U.emissivemap,U.bumpmap,U.normalmap,U.displacementmap,U.roughnessmap,U.metalnessmap,U.fog,U.lights,{emissive:{value:new N(0)},roughness:{value:.5},metalness:{value:0},envMapIntensity:{value:1}}]),
13696 vertexShader:Z.meshphysical_vert,fragmentShader:Z.meshphysical_frag},points:{uniforms:Ja.merge([U.points,U.fog]),vertexShader:Z.points_vert,fragmentShader:Z.points_frag},dashed:{uniforms:Ja.merge([U.common,U.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Z.linedashed_vert,fragmentShader:Z.linedashed_frag},depth:{uniforms:Ja.merge([U.common,U.displacementmap]),vertexShader:Z.depth_vert,fragmentShader:Z.depth_frag},normal:{uniforms:Ja.merge([U.common,U.bumpmap,U.normalmap,
13697 U.displacementmap,{opacity:{value:1}}]),vertexShader:Z.normal_vert,fragmentShader:Z.normal_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Z.cube_vert,fragmentShader:Z.cube_frag},equirect:{uniforms:{tEquirect:{value:null},tFlip:{value:-1}},vertexShader:Z.equirect_vert,fragmentShader:Z.equirect_frag},distanceRGBA:{uniforms:{lightPos:{value:new q}},vertexShader:Z.distanceRGBA_vert,fragmentShader:Z.distanceRGBA_frag}};Gb.physical={uniforms:Ja.merge([Gb.standard.uniforms,
13698 {clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:Z.meshphysical_vert,fragmentShader:Z.meshphysical_frag};pc.prototype={constructor:pc,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new C;return function(b,c){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)},
13699 copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},makeEmpty:function(){this.min.x=this.min.y=Infinity;this.max.x=this.max.y=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y},getCenter:function(a){a=a||new C;return this.isEmpty()?a.set(0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=a||new C;return this.isEmpty()?a.set(0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);
13700 return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y},getParameter:function(a,b){return(b||new C).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-
13701 this.min.y))},intersectsBox:function(a){return a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y?!1:!0},clampPoint:function(a,b){return(b||new C).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new C;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);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);
13702 this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}};var pf=0;W.prototype={constructor:W,isMaterial:!0,get needsUpdate(){return this._needsUpdate},set needsUpdate(a){!0===a&&this.update();this._needsUpdate=a},setValues:function(a){if(void 0!==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."):
13703 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.4,type:"Material",generator:"Material.toJSON"}};d.uuid=this.uuid;d.type=this.type;""!==this.name&&(d.name=this.name);this.color&&this.color.isColor&&(d.color=this.color.getHex());void 0!==this.roughness&&(d.roughness=this.roughness);
13704 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=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=
13705 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,d.normalScale=this.normalScale.toArray());this.displacementMap&&this.displacementMap.isTexture&&(d.displacementMap=this.displacementMap.toJSON(a).uuid,d.displacementScale=this.displacementScale,d.displacementBias=
13706 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);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);
13707 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&&(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;
13708 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);"round"!==this.wireframeLinecap&&(d.wireframeLinecap=this.wireframeLinecap);"round"!==this.wireframeLinejoin&&(d.wireframeLinejoin=this.wireframeLinejoin);d.skinning=this.skinning;d.morphTargets=this.morphTargets;
13709 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;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=
13710 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=a.polygonOffsetFactor;this.polygonOffsetUnits=a.polygonOffsetUnits;this.alphaTest=a.alphaTest;this.premultipliedAlpha=a.premultipliedAlpha;this.overdraw=a.overdraw;this.visible=a.visible;this.clipShadows=a.clipShadows;this.clipIntersection=a.clipIntersection;
13711 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},update:function(){this.dispatchEvent({type:"update"})},dispose:function(){this.dispatchEvent({type:"dispose"})}};Object.assign(W.prototype,oa.prototype);Ia.prototype=Object.create(W.prototype);Ia.prototype.constructor=Ia;Ia.prototype.isShaderMaterial=!0;Ia.prototype.copy=function(a){W.prototype.copy.call(this,a);this.fragmentShader=a.fragmentShader;this.vertexShader=
13712 a.vertexShader;this.uniforms=Ja.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};Ia.prototype.toJSON=function(a){a=W.prototype.toJSON.call(this,a);a.uniforms=this.uniforms;a.vertexShader=this.vertexShader;a.fragmentShader=this.fragmentShader;return a};ab.prototype=
13713 Object.create(W.prototype);ab.prototype.constructor=ab;ab.prototype.isMeshDepthMaterial=!0;ab.prototype.copy=function(a){W.prototype.copy.call(this,a);this.depthPacking=a.depthPacking;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.map=a.map;this.alphaMap=a.alphaMap;this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;return this};ya.prototype=
13714 {constructor:ya,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],p=a[h+2];m<b&&(b=m);l<c&&(c=l);p<d&&(d=p);m>e&&(e=m);l>f&&(f=l);p>g&&(g=p)}this.min.set(b,c,d);this.max.set(e,f,g)},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),
13715 l=a.getY(h),p=a.getZ(h);m<b&&(b=m);l<c&&(c=l);p<d&&(d=p);m>e&&(e=m);l>f&&(f=l);p>g&&(g=p)}this.min.set(b,c,d);this.max.set(e,f,g)},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 q;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}}(),setFromObject:function(){var a=new q;return function(b){var c=this;b.updateMatrixWorld(!0);this.makeEmpty();
13716 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.fromAttribute(g,e).applyMatrix4(b.matrixWorld),c.expandByPoint(a)});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=
13717 this.min.y=this.min.z=Infinity;this.max.x=this.max.y=this.max.z=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z},getCenter:function(a){a=a||new q;return this.isEmpty()?a.set(0,0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=a||new q;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);
13718 this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y||a.z<this.min.z||a.z>this.max.z?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=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 q).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/
13719 (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;return function(b){void 0===a&&(a=new q);this.clampPoint(b.center,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*
13720 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,b){return(b||new q).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new q;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),
13721 getBoundingSphere:function(){var a=new q;return function(b){b=b||new Fa;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=[new q,new q,new q,new q,new q,new q,new q,new q];return function(b){if(this.isEmpty())return this;a[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(b);
13722 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);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);
13723 return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}};Fa.prototype={constructor:Fa,set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a=new ya;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,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);
13724 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)<=b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(this.center.dot(a.normal)-a.constant)<=this.radius},
13725 clampPoint:function(a,b){var c=this.center.distanceToSquared(a),d=b||new q;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 ya;a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a);this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&&
13726 a.radius===this.radius}};za.prototype={constructor:za,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){a=a.elements;this.set(a[0],a[3],a[6],a[1],a[4],a[7],a[2],a[5],a[8]);return this},setFromMatrix4:function(a){a=a.elements;this.set(a[0],a[4],a[8],a[1],a[5],a[9],
13727 a[2],a[6],a[10]);return this},applyToVector3Array:function(){var a;return function(b,c,d){void 0===a&&(a=new q);void 0===c&&(c=0);void 0===d&&(d=b.length);for(var e=0;e<d;e+=3,c+=3)a.fromArray(b,c),a.applyMatrix3(this),a.toArray(b,c);return b}}(),applyToBufferAttribute:function(){var a;return function(b){void 0===a&&(a=new q);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}}(),multiplyScalar:function(a){var b=this.elements;
13728 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},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],p=c[7],c=c[8],n=c*k-m*p,r=m*l-c*h,w=p*h-k*l,q=e*n+f*r+g*w;if(0===
13729 q){if(!0===b)throw Error("THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0");console.warn("THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0");return this.identity()}q=1/q;d[0]=n*q;d[1]=(g*p-c*f)*q;d[2]=(m*f-g*k)*q;d[3]=r*q;d[4]=(c*e-g*l)*q;d[5]=(g*h-m*e)*q;d[6]=w*q;d[7]=(f*l-p*e)*q;d[8]=(k*e-f*h)*q;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()},
13730 transposeIntoArray:function(a){var b=this.elements;a[0]=b[0];a[1]=b[3];a[2]=b[6];a[3]=b[1];a[4]=b[4];a[5]=b[7];a[6]=b[2];a[7]=b[5];a[8]=b[8];return this},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]=c[8];return a}};ma.prototype={constructor:ma,set:function(a,b){this.normal.copy(a);
13731 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 q,b=new q;return function(c,d,e){d=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();this.setFromNormalAndCoplanarPoint(d,c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.normal.copy(a.normal);
13732 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,b){var c=this.distanceToPoint(a);return(b||
13733 new q).copy(this.normal).multiplyScalar(c)},intersectLine:function(){var a=new q;return function(b,c){var d=c||new q,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},intersectsBox:function(a){return a.intersectsPlane(this)},
13734 intersectsSphere:function(a){return a.intersectsPlane(this)},coplanarPoint:function(a){return(a||new q).copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var a=new q,b=new za;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)&&a.constant===
13735 this.constant}};qc.prototype={constructor:qc,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],p=c[9],n=c[10],r=c[11],q=c[12],u=c[13],F=c[14],c=c[15];
13736 b[0].setComponents(f-a,m-g,r-l,c-q).normalize();b[1].setComponents(f+a,m+g,r+l,c+q).normalize();b[2].setComponents(f+d,m+h,r+p,c+u).normalize();b[3].setComponents(f-d,m-h,r-p,c-u).normalize();b[4].setComponents(f-e,m-k,r-n,c-F).normalize();b[5].setComponents(f+e,m+k,r+n,c+F).normalize();return this},intersectsObject:function(){var a=new Fa;return function(b){var c=b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),
13737 intersectsSprite:function(){var a=new Fa;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 q,b=new q;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?
13738 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}};bb.prototype={constructor:bb,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);
13739 this.direction.copy(a.direction);return this},at:function(a,b){return(b||new q).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 q;return function(b){this.origin.copy(this.at(b,a));return this}}(),closestPointToPoint:function(a,b){var c=b||new q;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)},
13740 distanceToPoint:function(a){return Math.sqrt(this.distanceSqToPoint(a))},distanceSqToPoint:function(){var a=new q;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 q,b=new q,c=new q;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);
13741 var h=.5*d.distanceTo(e),k=-this.direction.dot(b),m=c.dot(this.direction),l=-c.dot(b),p=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)+p):(e=h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+p):(e=-h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+p):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)+p):e<=r?(d=0,e=Math.min(Math.max(-h,-l),h),k=e*(e+2*l)+p):(d=Math.max(0,-(k*h+m)),e=0<d?h:Math.min(Math.max(-h,
13742 -l),h),k=-d*d+e*(e+2*l)+p)):(e=0<k?-h:h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+p);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 q;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)<=
13743 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;
13744 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 q;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a=
13745 new q,b=new q,c=new q,d=new q;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);
13746 this.direction.sub(this.origin);this.direction.normalize();return this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}};cb.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" ");cb.DefaultOrder="XYZ";cb.prototype={constructor:cb,isEuler:!0,get x(){return this._x},set x(a){this._x=a;this.onChangeCallback()},get y(){return this._y},set y(a){this._y=a;this.onChangeCallback()},get z(){return this._z},set z(a){this._z=a;this.onChangeCallback()},get order(){return this._order},
13747 set order(a){this._order=a;this.onChangeCallback()},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,b,c){var d=Q.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],p=e[6],e=e[10];b=b||
13748 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(p,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(p,-1,1)),.99999>Math.abs(p)?(this._y=Math.atan2(-l,e),this._z=Math.atan2(-f,k)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(l,-1,1)),.99999>
13749 Math.abs(l)?(this._x=Math.atan2(p,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(p,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-m,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order=b;if(!1!==c)this.onChangeCallback();
13750 return this},setFromQuaternion:function(){var a;return function(b,c,d){void 0===a&&(a=new H);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 da;return function(b){a.setFromEuler(this);return this.setFromQuaternion(a,b)}}(),equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._order===this._order},fromArray:function(a){this._x=a[0];this._y=a[1];
13751 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 q(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}};gd.prototype={constructor:gd,set:function(a){this.mask=1<<a},enable:function(a){this.mask|=1<<a},toggle:function(a){this.mask^=
13752 1<<a},disable:function(a){this.mask&=~(1<<a)},test:function(a){return 0!==(this.mask&a.mask)}};var qf=0;G.DefaultUp=new q(0,1,0);G.DefaultMatrixAutoUpdate=!0;Object.assign(G.prototype,oa.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,!0)},setRotationFromMatrix:function(a){this.quaternion.setFromRotationMatrix(a)},
13753 setRotationFromQuaternion:function(a){this.quaternion.copy(a)},rotateOnAxis:function(){var a=new da;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.multiply(a);return this}}(),rotateX:function(){var a=new q(1,0,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateY:function(){var a=new q(0,1,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateZ:function(){var a=new q(0,0,1);return function(b){return this.rotateOnAxis(a,b)}}(),translateOnAxis:function(){var a=new q;
13754 return function(b,c){a.copy(b).applyQuaternion(this.quaternion);this.position.add(a.multiplyScalar(c));return this}}(),translateX:function(){var a=new q(1,0,0);return function(b){return this.translateOnAxis(a,b)}}(),translateY:function(){var a=new q(0,1,0);return function(b){return this.translateOnAxis(a,b)}}(),translateZ:function(){var a=new q(0,0,1);return function(b){return this.translateOnAxis(a,b)}}(),localToWorld:function(a){return a.applyMatrix4(this.matrixWorld)},worldToLocal:function(){var a=
13755 new H;return function(b){return b.applyMatrix4(a.getInverse(this.matrixWorld))}}(),lookAt:function(){var a=new H;return function(b){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;a&&a.isObject3D?(null!==a.parent&&a.parent.remove(a),a.parent=this,a.dispatchEvent({type:"added"}),
13756 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",a)},getObjectByProperty:function(a,b){if(this[a]===
13757 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 q;this.updateMatrixWorld(!0);return a.setFromMatrixPosition(this.matrixWorld)},getWorldQuaternion:function(){var a=new q,b=new q;return function(c){c=c||new da;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,c,b);return c}}(),getWorldRotation:function(){var a=new da;return function(b){b=b||new cb;this.getWorldQuaternion(a);
13758 return b.setFromQuaternion(a,this.rotation.order,!1)}}(),getWorldScale:function(){var a=new q,b=new da;return function(c){c=c||new q;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,b,c);return c}}(),getWorldDirection:function(){var a=new da;return function(b){b=b||new q;this.getWorldQuaternion(a);return b.set(0,0,1).applyQuaternion(a)}}(),raycast:function(){},traverse:function(a){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverse(a)},traverseVisible:function(a){if(!1!==this.visible){a(this);
13759 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){!0===this.matrixAutoUpdate&&this.updateMatrix();if(!0===this.matrixWorldNeedsUpdate||!0===a)null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,
13760 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(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||""===a,d={};c&&(a={geometries:{},materials:{},textures:{},images:{}},d.metadata={version:4.4,type:"Object",generator:"Object3D.toJSON"});var e={};e.uuid=this.uuid;e.type=this.type;""!==this.name&&(e.name=this.name);"{}"!==JSON.stringify(this.userData)&&(e.userData=
13761 this.userData);!0===this.castShadow&&(e.castShadow=!0);!0===this.receiveShadow&&(e.receiveShadow=!0);!1===this.visible&&(e.visible=!1);e.matrix=this.matrix.toArray();void 0!==this.geometry&&(void 0===a.geometries[this.geometry.uuid]&&(a.geometries[this.geometry.uuid]=this.geometry.toJSON(a)),e.geometry=this.geometry.uuid);void 0!==this.material&&(void 0===a.materials[this.material.uuid]&&(a.materials[this.material.uuid]=this.material.toJSON(a)),e.material=this.material.uuid);if(0<this.children.length){e.children=
13762 [];for(var f=0;f<this.children.length;f++)e.children.push(this.children[f].toJSON(a).object)}if(c){var c=b(a.geometries),f=b(a.materials),g=b(a.textures);a=b(a.images);0<c.length&&(d.geometries=c);0<f.length&&(d.materials=f);0<g.length&&(d.textures=g);0<a.length&&(d.images=a)}d.object=e;return d},clone:function(a){return(new this.constructor).copy(this,a)},copy:function(a,b){void 0===b&&(b=!0);this.name=a.name;this.up.copy(a.up);this.position.copy(a.position);this.quaternion.copy(a.quaternion);this.scale.copy(a.scale);
13763 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());return this}});gb.prototype=
13764 {constructor:gb,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 q).addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){return(a||new q).subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},
13765 at:function(a,b){var c=b||new q;return this.delta(c).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new q,b=new q;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=Q.clamp(e,0,1));return e}}(),closestPointToPoint:function(a,b,c){a=this.closestPointToPointParameter(a,b);c=c||new q;return this.delta(c).multiplyScalar(a).add(this.start)},applyMatrix4:function(a){this.start.applyMatrix4(a);this.end.applyMatrix4(a);
13766 return this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)}};Aa.normal=function(){var a=new q;return function(b,c,d,e){e=e||new q;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)}}();Aa.barycoordFromPoint=function(){var a=new q,b=new q,c=new q;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=d*k-e*e;h=
13767 h||new q;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)}}();Aa.containsPoint=function(){var a=new q;return function(b,c,d,e){b=Aa.barycoordFromPoint(b,c,d,e,a);return 0<=b.x&&0<=b.y&&1>=b.x+b.y}}();Aa.prototype={constructor:Aa,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)},
13768 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 q,b=new q;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 q).addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(a){return Aa.normal(this.a,this.b,this.c,a)},plane:function(a){return(a||new ma).setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return Aa.barycoordFromPoint(a,
13769 this.a,this.b,this.c,b)},containsPoint:function(a){return Aa.containsPoint(a,this.a,this.b,this.c)},closestPointToPoint:function(){var a,b,c,d;return function(e,f){void 0===a&&(a=new ma,b=[new gb,new gb,new gb],c=new q,d=new q);var g=f||new q,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=
13770 c.distanceToSquared(d);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)}};ha.prototype={constructor:ha,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]=
13771 a.vertexColors[b].clone();return this}};Ka.prototype=Object.create(W.prototype);Ka.prototype.constructor=Ka;Ka.prototype.isMeshBasicMaterial=!0;Ka.prototype.copy=function(a){W.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;
13772 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};y.prototype={constructor:y,isBufferAttribute:!0,set needsUpdate(a){!0===a&&this.version++},setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==a?a.length/
13773 this.itemSize:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=new a.array.constructor(a.array);this.itemSize=a.itemSize;this.count=a.count;this.normalized=a.normalized;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.itemSize;c*=b.itemSize;for(var d=0,e=this.itemSize;d<e;d++)this.array[a+d]=b.array[c+d];return this},copyArray:function(a){this.array.set(a);return this},copyColorsArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<
13774 e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",d),f=new N);b[c++]=f.r;b[c++]=f.g;b[c++]=f.b}return this},copyIndicesArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];b[c++]=f.a;b[c++]=f.b;b[c++]=f.c}return this},copyVector2sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector2sArray(): vector is undefined",d),f=new C);b[c++]=f.x;
13775 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 q);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;b[c++]=f.z;b[c++]=f.w}return this},
13776 set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},getX:function(a){return this.array[a*this.itemSize]},setX:function(a,b){this.array[a*this.itemSize]=b;return this},getY:function(a){return this.array[a*this.itemSize+1]},setY:function(a,b){this.array[a*this.itemSize+1]=b;return this},getZ:function(a){return this.array[a*this.itemSize+2]},setZ:function(a,b){this.array[a*this.itemSize+2]=b;return this},getW:function(a){return this.array[a*this.itemSize+3]},setW:function(a,b){this.array[a*
13777 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).copy(this)}};rc.prototype=Object.create(y.prototype);
13778 rc.prototype.constructor=rc;sc.prototype=Object.create(y.prototype);sc.prototype.constructor=sc;tc.prototype=Object.create(y.prototype);tc.prototype.constructor=tc;uc.prototype=Object.create(y.prototype);uc.prototype.constructor=uc;Ra.prototype=Object.create(y.prototype);Ra.prototype.constructor=Ra;vc.prototype=Object.create(y.prototype);vc.prototype.constructor=vc;Ua.prototype=Object.create(y.prototype);Ua.prototype.constructor=Ua;X.prototype=Object.create(y.prototype);X.prototype.constructor=X;
13779 wc.prototype=Object.create(y.prototype);wc.prototype.constructor=wc;Object.assign(ze.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,e=d[0]&&0<d[0].length,f=d[1]&&0<d[1].length,g=a.morphTargets,h=g.length,
13780 k;if(0<h){k=[];for(var m=0;m<h;m++)k[m]=[];this.morphTargets.position=k}var l=a.morphNormals,p=l.length,n;if(0<p){n=[];for(m=0;m<p;m++)n[m]=[];this.morphTargets.normal=n}for(var r=a.skinIndices,q=a.skinWeights,u=r.length===c.length,F=q.length===c.length,m=0;m<b.length;m++){var t=b[m];this.vertices.push(c[t.a],c[t.b],c[t.c]);var v=t.vertexNormals;3===v.length?this.normals.push(v[0],v[1],v[2]):(v=t.normal,this.normals.push(v,v,v));v=t.vertexColors;3===v.length?this.colors.push(v[0],v[1],v[2]):(v=t.color,
13781 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 C,new C,new C)));!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 C,new C,new C)));for(v=0;v<h;v++){var M=g[v].vertices;k[v].push(M[t.a],M[t.b],M[t.c])}for(v=0;v<p;v++)M=l[v].vertexNormals[m],n[v].push(M.a,M.b,M.c);
13782 u&&this.skinIndices.push(r[t.a],r[t.b],r[t.c]);F&&this.skinWeights.push(q[t.a],q[t.b],q[t.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}});Object.assign(S.prototype,oa.prototype,{isGeometry:!0,applyMatrix:function(a){for(var b=(new za).getNormalMatrix(a),c=0,d=this.vertices.length;c<d;c++)this.vertices[c].applyMatrix4(a);
13783 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;return function(b){void 0===a&&(a=new H);a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a;return function(b){void 0===
13784 a&&(a=new H);a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a;return function(b){void 0===a&&(a=new H);a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a;return function(b,c,d){void 0===a&&(a=new H);a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a;return function(b,c,d){void 0===a&&(a=new H);a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a;return function(b){void 0===a&&(a=
13785 new G);a.lookAt(b);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 ha(a,b,d,f,r,e);c.faces.push(e);void 0!==k&&c.faceVertexUvs[0].push([p[a].clone(),p[b].clone(),p[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=
13786 a.attributes,f=e.position.array,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=[],p=[],n=[],r=e=0;e<f.length;e+=3,r+=2)c.vertices.push(new q(f[e],f[e+1],f[e+2])),void 0!==g&&l.push(new q(g[e],g[e+1],g[e+2])),void 0!==h&&c.colors.push(new N(h[e],h[e+1],h[e+2])),void 0!==k&&p.push(new C(k[r],k[r+1])),void 0!==m&&n.push(new C(m[r],m[r+1]));if(void 0!==
13787 d)if(f=a.groups,0<f.length)for(e=0;e<f.length;e++)for(var w=f[e],u=w.start,F=w.count,r=u,u=u+F;r<u;r+=3)b(d[r],d[r+1],d[r+2],w.materialIndex);else 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,
13788 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 H;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 q,b=new q,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===
13789 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 q;if(a){var e,f,g,h=new q,k=new q;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<
13790 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]=
13791 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]=
13792 e.vertexNormals[a].clone();var f=new S;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 q,k={a:new q,b:new q,c:new q},e.push(h),g.push(k)}g=this.morphNormals[a];f.vertices=this.morphTargets[a].vertices;f.computeFaceNormals();f.computeVertexNormals();
13793 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===
13794 this.boundingBox&&(this.boundingBox=new ya);this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new Fa);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],p=this.colors,
13795 n=a.colors;void 0===c&&(c=0);void 0!==b&&(d=(new za).getNormalMatrix(b));a=0;for(var r=g.length;a<r;a++){var q=g[a].clone();void 0!==b&&q.applyMatrix4(b);f.push(q)}a=0;for(r=n.length;a<r;a++)p.push(n[a].clone());a=0;for(r=k.length;a<r;a++){var g=k[a],u=g.vertexNormals,n=g.vertexColors,p=new ha(g.a+e,g.b+e,g.c+e);p.normal.copy(g.normal);void 0!==d&&p.normal.applyMatrix3(d).normalize();b=0;for(f=u.length;b<f;b++)q=u[b].clone(),void 0!==d&&q.applyMatrix3(d).normalize(),p.vertexNormals.push(q);p.color.copy(g.color);
13796 b=0;for(f=n.length;b<f;b++)q=n[b],p.vertexColors.push(q.clone());p.materialIndex=g.materialIndex+c;h.push(p)}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<
13797 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=
13798 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()+
13799 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!==p[b])return p[b];p[b]=l.length;l.push(a.getHex());return p[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.4,type:"Geometry",generator:"Geometry.toJSON"}};e.uuid=this.uuid;e.type=this.type;""!==this.name&&(e.name=this.name);if(void 0!==
13800 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=[],p={},n=[],r={};for(g=0;g<this.faces.length;g++){var q=this.faces[g],u=void 0!==this.faceVertexUvs[0][g],F=0<q.normal.length(),t=0<q.vertexNormals.length,v=1!==q.color.r||1!==q.color.g||1!==q.color.b,M=0<q.vertexColors.length,z=0,z=a(z,0,0),z=a(z,1,!0),z=a(z,2,!1),z=a(z,3,u),z=a(z,4,F),z=a(z,5,t),z=a(z,6,
13801 v),z=a(z,7,M);h.push(z);h.push(q.a,q.b,q.c);h.push(q.materialIndex);u&&(u=this.faceVertexUvs[0][g],h.push(d(u[0]),d(u[1]),d(u[2])));F&&h.push(b(q.normal));t&&(F=q.vertexNormals,h.push(b(F[0]),b(F[1]),b(F[2])));v&&h.push(c(q.color));M&&(q=q.vertexColors,h.push(c(q[0]),c(q[1]),c(q[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 S).copy(this)},copy:function(a){this.vertices=[];this.faces=
13802 [];this.faceVertexUvs=[[]];this.colors=[];for(var b=a.vertices,c=0,d=b.length;c<d;c++)this.vertices.push(b[c].clone());b=a.colors;c=0;for(d=b.length;c<d;c++)this.colors.push(b[c].clone());b=a.faces;c=0;for(d=b.length;c<d;c++)this.faces.push(b[c].clone());c=0;for(d=a.faceVertexUvs.length;c<d;c++){b=a.faceVertexUvs[c];void 0===this.faceVertexUvs[c]&&(this.faceVertexUvs[c]=[]);for(var e=0,f=b.length;e<f;e++){for(var g=b[e],h=[],k=0,m=g.length;k<m;k++)h.push(g[k].clone());this.faceVertexUvs[c].push(h)}}return this},
13803 dispose:function(){this.dispatchEvent({type:"dispose"})}});var Kd=0;Object.assign(D.prototype,oa.prototype,{isBufferGeometry:!0,getIndex:function(){return this.index},setIndex:function(a){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 )."),this.addAttribute(a,new y(b,c));else if("index"===a)console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),
13804 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=b},applyMatrix:function(a){var b=this.attributes.position;void 0!==b&&(a.applyToVector3Array(b.array),b.needsUpdate=!0);b=this.attributes.normal;
13805 void 0!==b&&((new za).getNormalMatrix(a).applyToVector3Array(b.array),b.needsUpdate=!0);null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();return this},rotateX:function(){var a;return function(b){void 0===a&&(a=new H);a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a;return function(b){void 0===a&&(a=new H);a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a;return function(b){void 0===
13806 a&&(a=new H);a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a;return function(b,c,d){void 0===a&&(a=new H);a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a;return function(b,c,d){void 0===a&&(a=new H);a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a;return function(b){void 0===a&&(a=new G);a.lookAt(b);a.updateMatrix();this.applyMatrix(a.matrix)}}(),center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();
13807 this.translate(a.x,a.y,a.z);return a},setFromObject:function(a){var b=a.geometry;if(a.isPoints||a.isLine){a=new X(3*b.vertices.length,3);var c=new X(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 X(b.lineDistances.length,1),this.addAttribute("lineDistance",a.copyArray(b.lineDistances)));null!==b.boundingSphere&&(this.boundingSphere=b.boundingSphere.clone());
13808 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;c.groupsNeedUpdate=b.groupsNeedUpdate;
13809 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),c.needsUpdate=!0),
13810 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 ze).fromGeometry(a);return this.fromDirectGeometry(a.__directGeometry)},
13811 fromDirectGeometry:function(a){var b=new Float32Array(3*a.vertices.length);this.addAttribute("position",(new y(b,3)).copyVector3sArray(a.vertices));0<a.normals.length&&(b=new Float32Array(3*a.normals.length),this.addAttribute("normal",(new y(b,3)).copyVector3sArray(a.normals)));0<a.colors.length&&(b=new Float32Array(3*a.colors.length),this.addAttribute("color",(new y(b,3)).copyColorsArray(a.colors)));0<a.uvs.length&&(b=new Float32Array(2*a.uvs.length),this.addAttribute("uv",(new y(b,2)).copyVector2sArray(a.uvs)));
13812 0<a.uvs2.length&&(b=new Float32Array(2*a.uvs2.length),this.addAttribute("uv2",(new y(b,2)).copyVector2sArray(a.uvs2)));0<a.indices.length&&(b=new (65535<a.vertices.length?Uint32Array:Uint16Array)(3*a.indices.length),this.setIndex((new y(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 X(3*g.length,3);b.push(h.copyVector3sArray(g))}this.morphAttributes[c]=b}0<a.skinIndices.length&&(c=new X(4*
13813 a.skinIndices.length,4),this.addAttribute("skinIndex",c.copyVector4sArray(a.skinIndices)));0<a.skinWeights.length&&(c=new X(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 ya);var a=this.attributes.position;void 0!==a?this.boundingBox.setFromBufferAttribute(a):
13814 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 ya,b=new q;return function(){null===this.boundingSphere&&(this.boundingSphere=new Fa);var c=this.attributes.position;if(c){var d=this.boundingSphere.center;a.setFromBufferAttribute(c);
13815 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;
13816 if(void 0===b.normal)this.addAttribute("normal",new y(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 q,p=new q,n=new q,r=new q,w=new q;if(a){a=a.array;0===c.length&&this.addGroup(0,a.length);for(var u=0,F=c.length;u<F;++u)for(f=c[u],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),p.fromArray(d,k),n.fromArray(d,m),r.subVectors(n,p),w.subVectors(l,p),r.cross(w),e[h]+=r.x,e[h+1]+=r.y,
13817 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),p.fromArray(d,f+3),n.fromArray(d,f+6),r.subVectors(n,p),w.subVectors(l,p),r.cross(w),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.",
13818 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.array,b,c,d,e=0,f=a.length;e<f;e+=3)b=a[e],c=a[e+1],d=a[e+2],b=1/Math.sqrt(b*b+c*c+d*d),a[e]*=b,a[e+1]*=b,a[e+2]*=b},toNonIndexed:function(){if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed."),
13819 this;var a=new D,b=this.index.array,c=this.attributes,d;for(d in c){for(var e=c[d],f=e.array,e=e.itemSize,g=new f.constructor(b.length*e),h,k=0,m=0,l=b.length;m<l;m++){h=b[m]*e;for(var p=0;p<e;p++)g[k++]=f[h++]}a.addAttribute(d,new y(g,e))}return a},toJSON:function(){var a={metadata:{version:4.4,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]&&
13820 (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(),
13821 radius:c.radius});return a},clone:function(){return(new D).copy(this)},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=a.length;c<b;c++){var d=a[c];this.addGroup(d.start,d.count,d.materialIndex)}return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});D.MaxIndex=65535;Ba.prototype=Object.assign(Object.create(G.prototype),{constructor:Ba,isMesh:!0,setDrawMode:function(a){this.drawMode=
13822 a},copy:function(a){G.prototype.copy.call(this,a);this.drawMode=a.drawMode;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){Aa.barycoordFromPoint(a,b,c,d,u);e.multiplyScalar(u.x);f.multiplyScalar(u.y);g.multiplyScalar(u.z);e.add(f).add(g);
13823 return e.clone()}function b(a,b,c,d,e,f,g){var h=a.material;if(null===(1===h.side?c.intersectTriangle(f,e,d,!0,g):c.intersectTriangle(d,e,f,2!==h.side,g)))return null;t.copy(g);t.applyMatrix4(a.matrixWorld);c=b.ray.origin.distanceTo(t);return c<b.near||c>b.far?null:{distance:c,point:t.clone(),object:a}}function c(c,d,e,f,m,l,p,q){g.fromArray(f,3*l);h.fromArray(f,3*p);k.fromArray(f,3*q);if(c=b(c,d,e,g,h,k,F))m&&(n.fromArray(m,2*l),r.fromArray(m,2*p),w.fromArray(m,2*q),c.uv=a(F,g,h,k,n,r,w)),c.face=
13824 new ha(l,p,q,Aa.normal(g,h,k)),c.faceIndex=l;return c}var d=new H,e=new bb,f=new Fa,g=new q,h=new q,k=new q,m=new q,l=new q,p=new q,n=new C,r=new C,w=new C,u=new q,F=new q,t=new q;return function(q,u){var t=this.geometry,A=this.material,I=this.matrixWorld;if(void 0!==A&&(null===t.boundingSphere&&t.computeBoundingSphere(),f.copy(t.boundingSphere),f.applyMatrix4(I),!1!==q.ray.intersectsSphere(f)&&(d.getInverse(I),e.copy(q.ray).applyMatrix4(d),null===t.boundingBox||!1!==e.intersectsBox(t.boundingBox)))){var E,
13825 K;if(t.isBufferGeometry){var y,J,A=t.index,I=t.attributes,t=I.position.array;void 0!==I.uv&&(E=I.uv.array);if(null!==A)for(var I=A.array,C=0,D=I.length;C<D;C+=3){if(A=I[C],y=I[C+1],J=I[C+2],K=c(this,q,e,t,E,A,y,J))K.faceIndex=Math.floor(C/3),u.push(K)}else for(C=0,D=t.length;C<D;C+=9)if(A=C/3,y=A+1,J=A+2,K=c(this,q,e,t,E,A,y,J))K.index=A,u.push(K)}else if(t.isGeometry){var G,H,I=A&&A.isMultiMaterial,C=!0===I?A.materials:null,D=t.vertices;y=t.faces;J=t.faceVertexUvs[0];0<J.length&&(E=J);for(var O=
13826 0,P=y.length;O<P;O++){var R=y[O];K=!0===I?C[R.materialIndex]:A;if(void 0!==K){J=D[R.a];G=D[R.b];H=D[R.c];if(!0===K.morphTargets){K=t.morphTargets;var T=this.morphTargetInfluences;g.set(0,0,0);h.set(0,0,0);k.set(0,0,0);for(var N=0,V=K.length;N<V;N++){var S=T[N];if(0!==S){var L=K[N].vertices;g.addScaledVector(m.subVectors(L[R.a],J),S);h.addScaledVector(l.subVectors(L[R.b],G),S);k.addScaledVector(p.subVectors(L[R.c],H),S)}}g.add(J);h.add(G);k.add(H);J=g;G=h;H=k}if(K=b(this,q,e,J,G,H,F))E&&(T=E[O],n.copy(T[0]),
13827 r.copy(T[1]),w.copy(T[2]),K.uv=a(F,J,G,H,n,r,w)),K.face=R,K.faceIndex=O,u.push(K)}}}}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});hb.prototype=Object.create(D.prototype);hb.prototype.constructor=hb;ib.prototype=Object.create(D.prototype);ib.prototype.constructor=ib;sa.prototype=Object.create(G.prototype);sa.prototype.constructor=sa;sa.prototype.isCamera=!0;sa.prototype.getWorldDirection=function(){var a=new da;return function(b){b=b||new q;this.getWorldQuaternion(a);
13828 return b.set(0,0,-1).applyQuaternion(a)}}();sa.prototype.lookAt=function(){var a=new H;return function(b){a.lookAt(this.position,b,this.up);this.quaternion.setFromRotationMatrix(a)}}();sa.prototype.clone=function(){return(new this.constructor).copy(this)};sa.prototype.copy=function(a){G.prototype.copy.call(this,a);this.matrixWorldInverse.copy(a.matrixWorldInverse);this.projectionMatrix.copy(a.projectionMatrix);return this};Ha.prototype=Object.assign(Object.create(sa.prototype),{constructor:Ha,isPerspectiveCamera:!0,
13829 copy:function(a){sa.prototype.copy.call(this,a);this.fov=a.fov;this.zoom=a.zoom;this.near=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*Q.RAD2DEG*Math.atan(a);this.updateProjectionMatrix()},getFocalLength:function(){var a=Math.tan(.5*Q.DEG2RAD*this.fov);return.5*this.getFilmHeight()/a},getEffectiveFOV:function(){return 2*
13830 Q.RAD2DEG*Math.atan(Math.tan(.5*Q.DEG2RAD*this.fov)/this.zoom)},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*
13831 Q.DEG2RAD*this.fov)/this.zoom,c=2*b,d=this.aspect*c,e=-.5*d,f=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.makeFrustum(e,e+d,b-c,b,a,this.far)},toJSON:function(a){a=G.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!==
13832 this.view&&(a.object.view=Object.assign({},this.view));a.object.filmGauge=this.filmGauge;a.object.filmOffset=this.filmOffset;return a}});Hb.prototype=Object.assign(Object.create(sa.prototype),{constructor:Hb,isOrthographicCamera:!0,copy:function(a){sa.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,
13833 f){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.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),
13834 f=(this.right-this.left)/this.view.width,d=(this.top-this.bottom)/this.view.height,e=e+this.view.offsetX/c*f,c=e+this.view.width/c*f,a=a-this.view.offsetY/b*d,b=a-this.view.height/b*d;this.projectionMatrix.makeOrthographic(e,c,a,b,this.near,this.far)},toJSON:function(a){a=G.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=
13835 Object.assign({},this.view));return a}});var Af=0;Ib.prototype.isFogExp2=!0;Ib.prototype.clone=function(){return new Ib(this.color.getHex(),this.density)};Ib.prototype.toJSON=function(a){return{type:"FogExp2",color:this.color.getHex(),density:this.density}};Jb.prototype.isFog=!0;Jb.prototype.clone=function(){return new Jb(this.color.getHex(),this.near,this.far)};Jb.prototype.toJSON=function(a){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}};jb.prototype=Object.create(G.prototype);
13836 jb.prototype.constructor=jb;jb.prototype.copy=function(a,b){G.prototype.copy.call(this,a,b);null!==a.background&&(this.background=a.background.clone());null!==a.fog&&(this.fog=a.fog.clone());null!==a.overrideMaterial&&(this.overrideMaterial=a.overrideMaterial.clone());this.autoUpdate=a.autoUpdate;this.matrixAutoUpdate=a.matrixAutoUpdate;return this};jb.prototype.toJSON=function(a){var b=G.prototype.toJSON.call(this,a);null!==this.background&&(b.object.background=this.background.toJSON(a));null!==
13837 this.fog&&(b.object.fog=this.fog.toJSON());return b};Od.prototype=Object.assign(Object.create(G.prototype),{constructor:Od,isLensFlare:!0,copy:function(a){G.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 N(16777215));void 0===d&&(d=1);
13838 c=Math.min(c,Math.max(0,c));this.lensFlares.push({texture:a,size:b,distance:c,x:0,y:0,z:0,scale:1,rotation:0,opacity:f,color:e,blending:d})},updateLensFlares:function(){var a,b=this.lensFlares.length,c,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)}});kb.prototype=Object.create(W.prototype);kb.prototype.constructor=
13839 kb;kb.prototype.copy=function(a){W.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.rotation=a.rotation;return this};zc.prototype=Object.assign(Object.create(G.prototype),{constructor:zc,isSprite:!0,raycast:function(){var a=new q;return function(b,c){a.setFromMatrixPosition(this.matrixWorld);var d=b.ray.distanceSqToPoint(a);d>this.scale.x*this.scale.y/4||c.push({distance:Math.sqrt(d),point:this.position,face:null,object:this})}}(),clone:function(){return(new this.constructor(this.material)).copy(this)}});
13840 Ac.prototype=Object.assign(Object.create(G.prototype),{constructor:Ac,copy:function(a){G.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-
13841 1].object},raycast:function(){var a=new q;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 q,b=new q;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;
13842 for(;e<f;e++)d[e].object.visible=!1}}}(),toJSON:function(a){a=G.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(hd.prototype,{calculateInverses:function(){this.boneInverses=[];for(var a=0,b=this.bones.length;a<b;a++){var c=new H;this.bones[a]&&c.getInverse(this.bones[a].matrixWorld);this.boneInverses.push(c)}},pose:function(){for(var a,b=0,c=this.bones.length;b<
13843 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 H;return function(){for(var b=0,c=this.bones.length;b<c;b++)a.multiplyMatrices(this.bones[b]?this.bones[b].matrixWorld:this.identityMatrix,this.boneInverses[b]),
13844 a.toArray(this.boneMatrices,16*b);this.useVertexTexture&&(this.boneTexture.needsUpdate=!0)}}(),clone:function(){return new hd(this.bones,this.boneInverses,this.useVertexTexture)}});id.prototype=Object.assign(Object.create(G.prototype),{constructor:id,isBone:!0});jd.prototype=Object.assign(Object.create(Ba.prototype),{constructor:jd,isSkinnedMesh:!0,bind:function(a,b){this.skeleton=a;void 0===b&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),b=this.matrixWorld);this.bindMatrix.copy(b);
13845 this.bindMatrixInverse.getInverse(b)},pose:function(){this.skeleton.pose()},normalizeSkinWeights:function(){if(this.geometry&&this.geometry.isGeometry)for(var a=0;a<this.geometry.skinWeights.length;a++){var b=this.geometry.skinWeights[a],c=1/b.lengthManhattan();Infinity!==c?b.multiplyScalar(c):b.set(1,0,0,0)}else if(this.geometry&&this.geometry.isBufferGeometry)for(var b=new ga,d=this.geometry.attributes.skinWeight,a=0;a<d.count;a++)b.x=d.getX(a),b.y=d.getY(a),b.z=d.getZ(a),b.w=d.getW(a),c=1/b.lengthManhattan(),
13846 Infinity!==c?b.multiplyScalar(c):b.set(1,0,0,0),d.setXYZW(a,b.x,b.y,b.z,b.w)},updateMatrixWorld:function(a){Ba.prototype.updateMatrixWorld.call(this,!0);"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,this.skeleton.useVertexTexture)).copy(this)}});
13847 ia.prototype=Object.create(W.prototype);ia.prototype.constructor=ia;ia.prototype.isLineBasicMaterial=!0;ia.prototype.copy=function(a){W.prototype.copy.call(this,a);this.color.copy(a.color);this.linewidth=a.linewidth;this.linecap=a.linecap;this.linejoin=a.linejoin;return this};Va.prototype=Object.assign(Object.create(G.prototype),{constructor:Va,isLine:!0,raycast:function(){var a=new H,b=new bb,c=new Fa;return function(d,e){var f=d.linePrecision,f=f*f,g=this.geometry,h=this.matrixWorld;null===g.boundingSphere&&
13848 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 q,m=new q,h=new q,l=new q,p=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,w=n.length-1;g<w;g+=p){var u=n[g+1];k.fromArray(r,3*n[g]);m.fromArray(r,3*u);u=b.distanceSqToSegment(k,m,l,h);u>f||(l.applyMatrix4(this.matrixWorld),u=d.ray.origin.distanceTo(l),u<d.near||
13849 u>d.far||e.push({distance:u,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else for(g=0,w=r.length/3-1;g<w;g+=p)k.fromArray(r,3*g),m.fromArray(r,3*g+3),u=b.distanceSqToSegment(k,m,l,h),u>f||(l.applyMatrix4(this.matrixWorld),u=d.ray.origin.distanceTo(l),u<d.near||u>d.far||e.push({distance:u,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+=p)u=b.distanceSqToSegment(k[g],
13850 k[g+1],l,h),u>f||(l.applyMatrix4(this.matrixWorld),u=d.ray.origin.distanceTo(l),u<d.near||u>d.far||e.push({distance:u,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});fa.prototype=Object.assign(Object.create(Va.prototype),{constructor:fa,isLineSegments:!0});Oa.prototype=Object.create(W.prototype);Oa.prototype.constructor=Oa;Oa.prototype.isPointsMaterial=!0;Oa.prototype.copy=
13851 function(a){W.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.size=a.size;this.sizeAttenuation=a.sizeAttenuation;return this};Kb.prototype=Object.assign(Object.create(G.prototype),{constructor:Kb,isPoints:!0,raycast:function(){var a=new H,b=new bb,c=new Fa;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),
13852 point:h.clone(),index:c,face:null,object:g})}}var g=this,h=this.geometry,k=this.matrixWorld,m=d.params.Points.threshold;null===h.boundingSphere&&h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k);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 q;if(h.isBufferGeometry){var p=h.index,h=h.attributes.position.array;if(null!==p)for(var n=p.array,p=0,r=n.length;p<r;p++){var w=n[p];m.fromArray(h,
13853 3*w);f(m,w)}else for(p=0,n=h.length/3;p<n;p++)m.fromArray(h,3*p),f(m,p)}else for(m=h.vertices,p=0,n=m.length;p<n;p++)f(m[p],p)}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});Bc.prototype=Object.assign(Object.create(G.prototype),{constructor:Bc});kd.prototype=Object.create(ea.prototype);kd.prototype.constructor=kd;Lb.prototype=Object.create(ea.prototype);Lb.prototype.constructor=Lb;Lb.prototype.isCompressedTexture=!0;ld.prototype=Object.create(ea.prototype);
13854 ld.prototype.constructor=ld;Cc.prototype=Object.create(ea.prototype);Cc.prototype.constructor=Cc;Cc.prototype.isDepthTexture=!0;Mb.prototype=Object.create(D.prototype);Mb.prototype.constructor=Mb;Nb.prototype=Object.create(D.prototype);Nb.prototype.constructor=Nb;Dc.prototype=Object.create(S.prototype);Dc.prototype.constructor=Dc;xa.prototype=Object.create(D.prototype);xa.prototype.constructor=xa;Ob.prototype=Object.create(xa.prototype);Ob.prototype.constructor=Ob;Ec.prototype=Object.create(S.prototype);
13855 Ec.prototype.constructor=Ec;lb.prototype=Object.create(xa.prototype);lb.prototype.constructor=lb;Fc.prototype=Object.create(S.prototype);Fc.prototype.constructor=Fc;Pb.prototype=Object.create(xa.prototype);Pb.prototype.constructor=Pb;Gc.prototype=Object.create(S.prototype);Gc.prototype.constructor=Gc;Qb.prototype=Object.create(xa.prototype);Qb.prototype.constructor=Qb;Hc.prototype=Object.create(S.prototype);Hc.prototype.constructor=Hc;Ic.prototype=Object.create(S.prototype);Ic.prototype.constructor=
13856 Ic;Rb.prototype=Object.create(D.prototype);Rb.prototype.constructor=Rb;Jc.prototype=Object.create(S.prototype);Jc.prototype.constructor=Jc;Sb.prototype=Object.create(D.prototype);Sb.prototype.constructor=Sb;Kc.prototype=Object.create(S.prototype);Kc.prototype.constructor=Kc;Tb.prototype=Object.create(D.prototype);Tb.prototype.constructor=Tb;Lc.prototype=Object.create(S.prototype);Lc.prototype.constructor=Lc;var pa={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*
13857 a[d].y;return.5*c},triangulate:function(){return function(a,b){var c=a.length;if(3>c)return null;var d=[],e=[],f=[],g,h,k;if(0<pa.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 p,n,r,q,u,F,t,v;p=a[e[g]].x;n=a[e[g]].y;r=a[e[h]].x;q=a[e[h]].y;u=a[e[k]].x;F=a[e[k]].y;if(0>=(r-p)*(F-n)-(q-n)*(u-p))l=
13858 !1;else{var M,z,A,I,E,K,y,C,D,G;M=u-r;z=F-q;A=p-u;I=n-F;E=r-p;K=q-n;for(l=0;l<c;l++)if(t=a[e[l]].x,v=a[e[l]].y,!(t===p&&v===n||t===r&&v===q||t===u&&v===F)&&(y=t-p,C=v-n,D=t-r,G=v-q,t-=u,v-=F,D=M*G-z*D,y=E*C-K*y,C=A*v-I*t,D>=-Number.EPSILON&&C>=-Number.EPSILON&&y>=-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])&&
13859 a.pop()}function d(a,b,c){return a.x!==b.x?a.x<b.x?a.x<=c.x&&c.x<=b.x:b.x<=c.x&&c.x<=a.x:a.y<b.y?a.y<=c.y&&c.y<=b.y:b.y<=c.y&&c.y<=a.y}function e(a,b,c,e,f){var g=b.x-a.x,h=b.y-a.y,k=e.x-c.x,m=e.y-c.y,l=a.x-c.x,n=a.y-c.y,p=h*k-g*m,q=h*l-g*n;if(Math.abs(p)>Number.EPSILON){if(0<p){if(0>q||q>p)return[];k=m*l-k*n;if(0>k||k>p)return[]}else{if(0<q||q<p)return[];k=m*l-k*n;if(0<k||k<p)return[]}if(0===k)return!f||0!==q&&q!==p?[a]:[];if(k===p)return!f||0!==q&&q!==p?[b]:[];if(0===q)return[c];if(q===p)return[e];
13860 f=k/p;return[{x:a.x+f*g,y:a.y+f*h}]}if(0!==q||m*l!==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,p=c.x,m=e,c=e.x):(b=e,p=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,p=c.y,m=e,c=e.y):(b=e,p=e.y,m=c,c=c.y));return k<=p?a<p?[]:a===p?f?[]:[b]:a<=c?[b,h]:[b,m]:k>c?[]:k===c?f?[]:[g]:a<=c?[g,h]:[g,m]}
13861 function f(a,b,c,d){var e=b.x-a.x,f=b.y-a.y;b=c.x-a.x;c=c.y-a.y;var g=d.x-a.x;d=d.y-a.y;a=e*c-f*b;e=e*d-f*g;return Math.abs(a)>Number.EPSILON?(b=g*c-d*b,0<a?0<=e&&0<=b:0<=e||0<=b):0<e}c(a);b.forEach(c);var g,h,k,m,l,p={};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!==p[l]&&console.warn("THREE.ShapeUtils: Duplicate point",l,g),p[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=
13862 0);d=f(h[a],h[e],h[g],k[b]);if(!d)return!1;d=k.length-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,p,q,x,y=[],C,D,G,H=0;for(l=b.length;H<l;H++)m.push(H);C=0;for(var O=2*
13863 m.length;0<m.length;){O--;if(0>O){console.log("Infinite Loop! Holes left:"+m.length+", Probably Hole outside Shape!");break}for(n=C;n<h.length;n++){p=h[n];l=-1;for(H=0;H<m.length;H++)if(q=m[H],x=p.x+":"+p.y+":"+q,void 0===y[x]){k=b[q];for(D=0;D<k.length;D++)if(q=k[D],c(n,D)&&!d(p,q)&&!g(p,q)){l=D;m.splice(H,1);C=h.slice(0,n+1);q=h.slice(n);D=k.slice(l);G=k.slice(0,l+1);h=C.concat(D).concat(G).concat(q);C=n;break}if(0<=l)break;y[x]=!0}if(0<=l)break}}return h}(a,b);var n=pa.triangulate(g,!1);g=0;for(h=
13864 n.length;g<h;g++)for(m=n[g],k=0;3>k;k++)l=m[k].x+":"+m[k].y,l=p[l],void 0!==l&&(m[k]=l);return n.concat()},isClockWise:function(a){return 0>pa.area(a)},b2:function(){return function(a,b,c,d){var e=1-a;return e*e*b+2*(1-a)*a*c+a*a*d}}(),b3:function(){return function(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}}()};La.prototype=Object.create(S.prototype);La.prototype.constructor=La;La.prototype.addShapeList=function(a,b){for(var c=a.length,d=0;d<c;d++)this.addShape(a[d],
13865 b)};La.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=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 C(d,e);f=Math.sqrt(f/2)}else a=!1,e>Number.EPSILON?d>Number.EPSILON&&
13866 (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 C(d/f,e/f)}function e(a,b){var c,d;for(L=a.length;0<=--L;){c=L;d=L-1;0>d&&(d=a.length-1);var e,f=r+2*l;for(e=0;e<f;e++){var g=U*e,h=U*(e+1),k=b+c+g,g=b+d+g,m=b+d+h,h=b+c+h,k=k+J,g=g+J,m=m+J,h=h+J;G.faces.push(new ha(k,g,h,null,null,1));G.faces.push(new ha(g,m,h,null,null,1));k=t.generateSideWallUV(G,k,g,m,h);G.faceVertexUvs[0].push([k[0],k[1],k[3]]);
13867 G.faceVertexUvs[0].push([k[1],k[2],k[3]])}}}function f(a,b,c){G.vertices.push(new q(a,b,c))}function g(a,b,c){a+=J;b+=J;c+=J;G.faces.push(new ha(a,b,c,null,null,0));a=t.generateTopUV(G,a,b,c);G.faceVertexUvs[0].push(a)}var h=void 0!==b.amount?b.amount:100,k=void 0!==b.bevelThickness?b.bevelThickness:6,m=void 0!==b.bevelSize?b.bevelSize:k-2,l=void 0!==b.bevelSegments?b.bevelSegments:3,p=void 0!==b.bevelEnabled?b.bevelEnabled:!0,n=void 0!==b.curveSegments?b.curveSegments:12,r=void 0!==b.steps?b.steps:
13868 1,w=b.extrudePath,u,F=!1,t=void 0!==b.UVGenerator?b.UVGenerator:La.WorldUVGenerator,v,y,z,A;w&&(u=w.getSpacedPoints(r),F=!0,p=!1,v=void 0!==b.frames?b.frames:w.computeFrenetFrames(r,!1),y=new q,z=new q,A=new q);p||(m=k=l=0);var I,E,D,G=this,J=this.vertices.length,w=a.extractPoints(n),n=w.shape,H=w.holes;if(w=!pa.isClockWise(n)){n=n.reverse();E=0;for(D=H.length;E<D;E++)I=H[E],pa.isClockWise(I)&&(H[E]=I.reverse());w=!1}var N=pa.triangulateShape(n,H),S=n;E=0;for(D=H.length;E<D;E++)I=H[E],n=n.concat(I);
13869 var Q,O,P,R,T,U=n.length,V,W=N.length,w=[],L=0;P=S.length;Q=P-1;for(O=L+1;L<P;L++,Q++,O++)Q===P&&(Q=0),O===P&&(O=0),w[L]=d(S[L],S[Q],S[O]);var X=[],Z,ba=w.concat();E=0;for(D=H.length;E<D;E++){I=H[E];Z=[];L=0;P=I.length;Q=P-1;for(O=L+1;L<P;L++,Q++,O++)Q===P&&(Q=0),O===P&&(O=0),Z[L]=d(I[L],I[Q],I[O]);X.push(Z);ba=ba.concat(Z)}for(Q=0;Q<l;Q++){P=Q/l;R=k*Math.cos(P*Math.PI/2);O=m*Math.sin(P*Math.PI/2);L=0;for(P=S.length;L<P;L++)T=c(S[L],w[L],O),f(T.x,T.y,-R);E=0;for(D=H.length;E<D;E++)for(I=H[E],Z=X[E],
13870 L=0,P=I.length;L<P;L++)T=c(I[L],Z[L],O),f(T.x,T.y,-R)}O=m;for(L=0;L<U;L++)T=p?c(n[L],ba[L],O):n[L],F?(z.copy(v.normals[0]).multiplyScalar(T.x),y.copy(v.binormals[0]).multiplyScalar(T.y),A.copy(u[0]).add(z).add(y),f(A.x,A.y,A.z)):f(T.x,T.y,0);for(P=1;P<=r;P++)for(L=0;L<U;L++)T=p?c(n[L],ba[L],O):n[L],F?(z.copy(v.normals[P]).multiplyScalar(T.x),y.copy(v.binormals[P]).multiplyScalar(T.y),A.copy(u[P]).add(z).add(y),f(A.x,A.y,A.z)):f(T.x,T.y,h/r*P);for(Q=l-1;0<=Q;Q--){P=Q/l;R=k*Math.cos(P*Math.PI/2);O=
13871 m*Math.sin(P*Math.PI/2);L=0;for(P=S.length;L<P;L++)T=c(S[L],w[L],O),f(T.x,T.y,h+R);E=0;for(D=H.length;E<D;E++)for(I=H[E],Z=X[E],L=0,P=I.length;L<P;L++)T=c(I[L],Z[L],O),F?f(T.x,T.y+u[r-1].y,u[r-1].x+R):f(T.x,T.y,h+R)}(function(){if(p){var a=0*U;for(L=0;L<W;L++)V=N[L],g(V[2]+a,V[1]+a,V[0]+a);a=U*(r+2*l);for(L=0;L<W;L++)V=N[L],g(V[0]+a,V[1]+a,V[2]+a)}else{for(L=0;L<W;L++)V=N[L],g(V[2],V[1],V[0]);for(L=0;L<W;L++)V=N[L],g(V[0]+U*r,V[1]+U*r,V[2]+U*r)}})();(function(){var a=0;e(S,a);a+=S.length;E=0;for(D=
13872 H.length;E<D;E++)I=H[E],e(I,a),a+=I.length})()};La.WorldUVGenerator={generateTopUV:function(a,b,c,d){a=a.vertices;b=a[b];c=a[c];d=a[d];return[new C(b.x,b.y),new C(c.x,c.y),new C(d.x,d.y)]},generateSideWallUV:function(a,b,c,d,e){a=a.vertices;b=a[b];c=a[c];d=a[d];e=a[e];return.01>Math.abs(b.y-c.y)?[new C(b.x,1-b.z),new C(c.x,1-c.z),new C(d.x,1-d.z),new C(e.x,1-e.z)]:[new C(b.y,1-b.z),new C(c.y,1-c.z),new C(d.y,1-d.z),new C(e.y,1-e.z)]}};Mc.prototype=Object.create(La.prototype);Mc.prototype.constructor=
13873 Mc;mb.prototype=Object.create(D.prototype);mb.prototype.constructor=mb;Nc.prototype=Object.create(S.prototype);Nc.prototype.constructor=Nc;Ub.prototype=Object.create(D.prototype);Ub.prototype.constructor=Ub;Oc.prototype=Object.create(S.prototype);Oc.prototype.constructor=Oc;Pc.prototype=Object.create(S.prototype);Pc.prototype.constructor=Pc;Vb.prototype=Object.create(D.prototype);Vb.prototype.constructor=Vb;Qc.prototype=Object.create(S.prototype);Qc.prototype.constructor=Qc;Wb.prototype=Object.create(D.prototype);
13874 Wb.prototype.constructor=Wb;Xb.prototype=Object.create(S.prototype);Xb.prototype.constructor=Xb;Yb.prototype=Object.create(D.prototype);Yb.prototype.constructor=Yb;Wa.prototype=Object.create(D.prototype);Wa.prototype.constructor=Wa;nb.prototype=Object.create(S.prototype);nb.prototype.constructor=nb;Rc.prototype=Object.create(nb.prototype);Rc.prototype.constructor=Rc;Sc.prototype=Object.create(Wa.prototype);Sc.prototype.constructor=Sc;Zb.prototype=Object.create(D.prototype);Zb.prototype.constructor=
13875 Zb;Tc.prototype=Object.create(S.prototype);Tc.prototype.constructor=Tc;$b.prototype=Object.create(S.prototype);$b.prototype.constructor=$b;var Ea=Object.freeze({WireframeGeometry:Mb,ParametricGeometry:Dc,ParametricBufferGeometry:Nb,TetrahedronGeometry:Ec,TetrahedronBufferGeometry:Ob,OctahedronGeometry:Fc,OctahedronBufferGeometry:lb,IcosahedronGeometry:Gc,IcosahedronBufferGeometry:Pb,DodecahedronGeometry:Hc,DodecahedronBufferGeometry:Qb,PolyhedronGeometry:Ic,PolyhedronBufferGeometry:xa,TubeGeometry:Jc,
13876 TubeBufferGeometry:Rb,TorusKnotGeometry:Kc,TorusKnotBufferGeometry:Sb,TorusGeometry:Lc,TorusBufferGeometry:Tb,TextGeometry:Mc,SphereBufferGeometry:mb,SphereGeometry:Nc,RingGeometry:Oc,RingBufferGeometry:Ub,PlaneBufferGeometry:ib,PlaneGeometry:Pc,LatheGeometry:Qc,LatheBufferGeometry:Vb,ShapeGeometry:Xb,ShapeBufferGeometry:Wb,ExtrudeGeometry:La,EdgesGeometry:Yb,ConeGeometry:Rc,ConeBufferGeometry:Sc,CylinderGeometry:nb,CylinderBufferGeometry:Wa,CircleBufferGeometry:Zb,CircleGeometry:Tc,BoxBufferGeometry:hb,
13877 BoxGeometry:$b});ac.prototype=Object.create(Ia.prototype);ac.prototype.constructor=ac;ac.prototype.isShadowMaterial=!0;bc.prototype=Object.create(Ia.prototype);bc.prototype.constructor=bc;bc.prototype.isRawShaderMaterial=!0;Uc.prototype={constructor:Uc,isMultiMaterial:!0,toJSON:function(a){for(var b={metadata:{version:4.2,type:"material",generator:"MaterialExporter"},uuid:this.uuid,type:this.type,materials:[]},c=this.materials,d=0,e=c.length;d<e;d++){var f=c[d].toJSON(a);delete f.metadata;b.materials.push(f)}b.visible=
13878 this.visible;return b},clone:function(){for(var a=new this.constructor,b=0;b<this.materials.length;b++)a.materials.push(this.materials[b].clone());a.visible=this.visible;return a}};Pa.prototype=Object.create(W.prototype);Pa.prototype.constructor=Pa;Pa.prototype.isMeshStandardMaterial=!0;Pa.prototype.copy=function(a){W.prototype.copy.call(this,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=
13879 a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.roughnessMap=a.roughnessMap;this.metalnessMap=a.metalnessMap;this.alphaMap=a.alphaMap;
13880 this.envMap=a.envMap;this.envMapIntensity=a.envMapIntensity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};ob.prototype=Object.create(Pa.prototype);ob.prototype.constructor=ob;ob.prototype.isMeshPhysicalMaterial=!0;ob.prototype.copy=function(a){Pa.prototype.copy.call(this,
13881 a);this.defines={PHYSICAL:""};this.reflectivity=a.reflectivity;this.clearCoat=a.clearCoat;this.clearCoatRoughness=a.clearCoatRoughness;return this};Ca.prototype=Object.create(W.prototype);Ca.prototype.constructor=Ca;Ca.prototype.isMeshPhongMaterial=!0;Ca.prototype.copy=function(a){W.prototype.copy.call(this,a);this.color.copy(a.color);this.specular.copy(a.specular);this.shininess=a.shininess;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=
13882 a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=
13883 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};pb.prototype=Object.create(Ca.prototype);pb.prototype.constructor=pb;pb.prototype.isMeshToonMaterial=!0;pb.prototype.copy=function(a){Ca.prototype.copy.call(this,a);this.gradientMap=a.gradientMap;return this};qb.prototype=Object.create(W.prototype);
13884 qb.prototype.constructor=qb;qb.prototype.isMeshNormalMaterial=!0;qb.prototype.copy=function(a){W.prototype.copy.call(this,a);this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=
13885 a.morphNormals;return this};rb.prototype=Object.create(W.prototype);rb.prototype.constructor=rb;rb.prototype.isMeshLambertMaterial=!0;rb.prototype.copy=function(a){W.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.specularMap=a.specularMap;this.alphaMap=
13886 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};sb.prototype=Object.create(W.prototype);sb.prototype.constructor=sb;sb.prototype.isLineDashedMaterial=!0;sb.prototype.copy=
13887 function(a){W.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 Mf=Object.freeze({ShadowMaterial:ac,SpriteMaterial:kb,RawShaderMaterial:bc,ShaderMaterial:Ia,PointsMaterial:Oa,MultiMaterial:Uc,MeshPhysicalMaterial:ob,MeshStandardMaterial:Pa,MeshPhongMaterial:Ca,MeshToonMaterial:pb,MeshNormalMaterial:qb,MeshLambertMaterial:rb,MeshDepthMaterial:ab,MeshBasicMaterial:Ka,LineDashedMaterial:sb,
13888 LineBasicMaterial:ia,Material:W}),ne={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={}}},va=new Pd;Object.assign(Ma.prototype,{load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);var e=this,f=ne.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)?,(.*)$/);
13889 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 p=new Uint8Array(m),k=0;k<g.length;k++)p[k]=g.charCodeAt(k);"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(q){window.setTimeout(function(){d&&
13890 d(q);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;ne.add(a,f);200===this.status?(b&&b(f),e.manager.itemEnd(a)):0===this.status?(console.warn("THREE.FileLoader: HTTP Status 0 received."),b&&b(f),e.manager.itemEnd(a)):(d&&d(c),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.itemError(a)},!1);void 0!==this.responseType&&
13891 (n.responseType=this.responseType);void 0!==this.withCredentials&&(n.withCredentials=this.withCredentials);n.overrideMimeType&&n.overrideMimeType(void 0!==this.mimeType?this.mimeType:"text/plain");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}});Object.assign(Ee.prototype,{load:function(a,
13892 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,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 Lb;h.image=g;var k=new Ma(this.manager);k.setPath(this.path);k.setResponseType("arraybuffer");if(Array.isArray(a))for(var m=0,l=0,p=a.length;l<p;++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,
13893 d=0;d<c;d++){g[d]={mipmaps:[]};for(var e=0;e<a.mipmapCount;e++)g[d].mipmaps.push(a.mipmaps[d*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(Qd.prototype,{load:function(a,b,c,d){var e=this,f=new db,g=new Ma(this.manager);g.setResponseType("arraybuffer");
13894 g.load(a,function(a){if(a=e._parser(a))void 0!==a.image?f.image=a.image:void 0!==a.data&&(f.image.width=a.width,f.image.height=a.height,f.image.data=a.data),f.wrapS=void 0!==a.wrapS?a.wrapS:1001,f.wrapT=void 0!==a.wrapT?a.wrapT:1001,f.magFilter=void 0!==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===
13895 a.mipmapCount&&(f.minFilter=1006),f.needsUpdate=!0,b&&b(f,a)},c,d);return f}});Object.assign(Vc.prototype,{load:function(a,b,c,d){var e=this,f=document.createElementNS("http://www.w3.org/1999/xhtml","img");f.onload=function(){f.onload=null;URL.revokeObjectURL(f.src);b&&b(f);e.manager.itemEnd(a)};f.onerror=d;if(0===a.indexOf("data:"))f.src=a;else if(void 0!==this.crossOrigin)f.crossOrigin=this.crossOrigin,f.src=a;else{var g=new Ma;g.setPath(this.path);g.setResponseType("blob");g.setWithCredentials(this.withCredentials);
13896 g.load(a,function(a){f.src=URL.createObjectURL(a)},c,d)}e.manager.itemStart(a);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setWithCredentials:function(a){this.withCredentials=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(Rd.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);
13897 var h=0;for(c=0;c<a.length;++c)e(c);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(md.prototype,{load:function(a,b,c,d){var e=new ea,f=new Vc(this.manager);f.setCrossOrigin(this.crossOrigin);f.setWithCredentials(this.withCredentials);f.setPath(this.path);f.load(a,function(c){var d=0<a.search(/\.(jpg|jpeg)$/)||0===a.search(/^data\:image\/jpeg/);e.format=d?1022:1023;e.image=c;e.needsUpdate=!0;void 0!==b&&b(e)},c,d);return e},
13898 setCrossOrigin:function(a){this.crossOrigin=a;return this},setWithCredentials:function(a){this.withCredentials=a;return this},setPath:function(a){this.path=a;return this}});na.prototype=Object.assign(Object.create(G.prototype),{constructor:na,isLight:!0,copy:function(a){G.prototype.copy.call(this,a);this.color.copy(a.color);this.intensity=a.intensity;return this},toJSON:function(a){a=G.prototype.toJSON.call(this,a);a.object.color=this.color.getHex();a.object.intensity=this.intensity;void 0!==this.groundColor&&
13899 (a.object.groundColor=this.groundColor.getHex());void 0!==this.distance&&(a.object.distance=this.distance);void 0!==this.angle&&(a.object.angle=this.angle);void 0!==this.decay&&(a.object.decay=this.decay);void 0!==this.penumbra&&(a.object.penumbra=this.penumbra);void 0!==this.shadow&&(a.object.shadow=this.shadow.toJSON());return a}});nd.prototype=Object.assign(Object.create(na.prototype),{constructor:nd,isHemisphereLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.groundColor.copy(a.groundColor);
13900 return this}});Object.assign(tb.prototype,{copy:function(a){this.camera=a.camera.clone();this.bias=a.bias;this.radius=a.radius;this.mapSize.copy(a.mapSize);return this},clone:function(){return(new this.constructor).copy(this)},toJSON:function(){var a={};0!==this.bias&&(a.bias=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}});od.prototype=Object.assign(Object.create(tb.prototype),
13901 {constructor:od,isSpotLightShadow:!0,update:function(a){var b=2*Q.RAD2DEG*a.angle,c=this.mapSize.width/this.mapSize.height;a=a.distance||500;var d=this.camera;if(b!==d.fov||c!==d.aspect||a!==d.far)d.fov=b,d.aspect=c,d.far=a,d.updateProjectionMatrix()}});pd.prototype=Object.assign(Object.create(na.prototype),{constructor:pd,isSpotLight:!0,copy:function(a){na.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();
13902 this.shadow=a.shadow.clone();return this}});qd.prototype=Object.assign(Object.create(na.prototype),{constructor:qd,isPointLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.distance=a.distance;this.decay=a.decay;this.shadow=a.shadow.clone();return this}});rd.prototype=Object.assign(Object.create(tb.prototype),{constructor:rd});sd.prototype=Object.assign(Object.create(na.prototype),{constructor:sd,isDirectionalLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.target=a.target.clone();
13903 this.shadow=a.shadow.clone();return this}});td.prototype=Object.assign(Object.create(na.prototype),{constructor:td,isAmbientLight:!0});var ba={arraySlice:function(a,b,c){return ba.isTypedArray(a)?new a.constructor(a.subarray(b,c)):a.slice(b,c)},convertArray:function(a,b,c){return!a||!c&&a.constructor===b?a:"number"===typeof b.BYTES_PER_ELEMENT?new b(a):Array.prototype.slice.call(a)},isTypedArray:function(a){return ArrayBuffer.isView(a)&&!(a instanceof DataView)},getKeyframeOrder:function(a){for(var b=
13904 a.length,c=Array(b),d=0;d!==b;++d)c[d]=d;c.sort(function(b,c){return a[b]-a[c]});return c},sortedArray:function(a,b,c){for(var d=a.length,e=new a.constructor(d),f=0,g=0;g!==d;++f)for(var h=c[f]*b,k=0;k!==b;++k)e[g++]=a[h+k];return e},flattenJSON:function(a,b,c,d){for(var e=1,f=a[0];void 0!==f&&void 0===f[d];)f=a[e++];if(void 0!==f){var g=f[d];if(void 0!==g)if(Array.isArray(g)){do g=f[d],void 0!==g&&(b.push(f.time),c.push.apply(c,g)),f=a[e++];while(void 0!==f)}else if(void 0!==g.toArray){do g=f[d],
13905 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)}}}};qa.prototype={constructor:qa,evaluate:function(a){var b=this.parameterPositions,c=this._cachedIndex,d=b[c],e=b[c-1];a:{b:{c:{d:if(!(a<d)){for(var f=c+2;;){if(void 0===d){if(a<e)break d;this._cachedIndex=c=b.length;return this.afterEnd_(c-1,a,e)}if(c===f)break;e=d;d=b[++c];if(a<d)break b}d=b.length;break c}if(a>=e)break a;else{f=b[1];a<f&&
13906 (c=2,e=f);for(f=c-2;;){if(void 0===e)return this._cachedIndex=0,this.beforeStart_(0,a,d);if(c===f)break;d=e;e=b[--c-1];if(a>=e)break b}d=c;c=0}}for(;c<d;)e=c+d>>>1,a<b[e]?d=e:c=e+1;d=b[c];e=b[c-1];if(void 0===e)return this._cachedIndex=0,this.beforeStart_(0,a,d);if(void 0===d)return this._cachedIndex=c=b.length,this.afterEnd_(c-1,e,a)}this._cachedIndex=c;this.intervalChanged_(c,e,d)}return this.interpolate_(c,e,a,d)},settings:null,DefaultSettings_:{},getSettings_:function(){return this.settings||
13907 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(qa.prototype,{beforeStart_:qa.prototype.copySampleValue_,afterEnd_:qa.prototype.copySampleValue_});ud.prototype=Object.assign(Object.create(qa.prototype),{constructor:ud,DefaultSettings_:{endingStart:2400,endingEnd:2400},
13908 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=a/(h-c);this._offsetPrev=e*d;this._offsetNext=f*d},interpolate_:function(a,
13909 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,p=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-p)*d+(1.5+p)*c+.5*n;p=p*d-p*c;for(c=0;c!==g;++c)e[c]=b*f[k+c]+l*f[h+c]+n*f[a+c]+p*f[m+c];return e}});Wc.prototype=Object.assign(Object.create(qa.prototype),{constructor:Wc,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;
13910 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}});vd.prototype=Object.assign(Object.create(qa.prototype),{constructor:vd,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 vd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodLinear:function(a){return new Wc(this.times,this.values,
13911 this.getValueSize(),a)},InterpolantFactoryMethodSmooth:function(a){return new ud(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);
13912 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=
13913 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=ba.arraySlice(c,e,f),this.values=ba.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",
13914 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&&ba.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,
13915 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,p=m+c,k=0;k!==c;++k){var n=b[m+k];if(n!==b[l+k]||n!==b[p+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=ba.arraySlice(a,0,e),this.values=ba.arraySlice(b,0,e*c));return this}};cc.prototype=Object.assign(Object.create(Ya),{constructor:cc,ValueTypeName:"vector"});
13916 wd.prototype=Object.assign(Object.create(qa.prototype),{constructor:wd,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)da.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 wd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:void 0});
13917 dc.prototype=Object.assign(Object.create(Ya),{constructor:dc,ValueTypeName:"number"});xd.prototype=Object.assign(Object.create(Ya),{constructor:xd,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});yd.prototype=Object.assign(Object.create(Ya),{constructor:yd,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});
13918 zd.prototype=Object.assign(Object.create(Ya),{constructor:zd,ValueTypeName:"color"});vb.prototype=Ya;Ya.constructor=vb;Object.assign(vb,{parse:function(a){if(void 0===a.type)throw Error("track type undefined, can not parse");var b=vb._getTrackTypeForValueTypeName(a.type);if(void 0===a.times){var c=[],d=[];ba.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=
13919 b.toJSON(a);else{var b={name:a.name,times:ba.convertArray(a.times,Array),values:ba.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 dc;case "vector":case "vector2":case "vector3":case "vector4":return cc;case "color":return zd;case "quaternion":return Xc;case "bool":case "boolean":return yd;
13920 case "string":return xd}throw Error("Unsupported typeName: "+a);}});ta.prototype={constructor:ta,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(ta,{parse:function(a){for(var b=[],c=a.tracks,
13921 d=1/(a.fps||1),e=0,f=c.length;e!==f;++e)b.push(vb.parse(c[e]).scale(d));return new ta(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(vb.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)%e,g,(g+1)%e);k.push(0,1,0);var m=ba.getKeyframeOrder(h),h=ba.sortedArray(h,1,m),k=ba.sortedArray(k,1,m);d||0!==h[0]||(h.push(e),
13922 k.push(k[0]));f.push((new dc(".morphTargetInfluences["+b[g].name+"]",h,k)).scale(1/c))}return new ta(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,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(ta.CreateFromMorphTargetSequence(m,
13923 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=[];ba.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=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 p=0;p<m[l].morphTargets.length;p++)f[m[l].morphTargets[p]]=
13924 -1;for(var n in f){for(var q=[],w=[],p=0;p!==m[l].morphTargets.length;++p){var u=m[l];q.push(u.time);w.push(u.morphTarget===n?1:0)}d.push(new dc(".morphTargetInfluence["+n+"]",q,w))}f=f.length*(g||1)}else l=".bones["+b[k].name+"]",c(cc,l+".position",m,"pos",d),c(Xc,l+".quaternion",m,"rot",d),c(cc,l+".scale",m,"scl",d)}return 0===d.length?null:new ta(e,f,d)}});Object.assign(Ad.prototype,{load:function(a,b,c,d){var e=this;(new Ma(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},setTextures:function(a){this.textures=
13925 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 Mf[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!==a.specular&&d.specular.setHex(a.specular);void 0!==a.shininess&&(d.shininess=a.shininess);
13926 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);void 0!==a.blending&&(d.blending=a.blending);void 0!==a.side&&(d.side=a.side);void 0!==
13927 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!==a.wireframeLinecap&&(d.wireframeLinecap=a.wireframeLinecap);void 0!==a.wireframeLinejoin&&
13928 (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=a.bumpScale);void 0!==a.normalMap&&(d.normalMap=b(a.normalMap));if(void 0!==a.normalScale){var e=
13929 a.normalScale;!1===Array.isArray(e)&&(e=[e,e]);d.normalScale=(new C).fromArray(e)}void 0!==a.displacementMap&&(d.displacementMap=b(a.displacementMap));void 0!==a.displacementScale&&(d.displacementScale=a.displacementScale);void 0!==a.displacementBias&&(d.displacementBias=a.displacementBias);void 0!==a.roughnessMap&&(d.roughnessMap=b(a.roughnessMap));void 0!==a.metalnessMap&&(d.metalnessMap=b(a.metalnessMap));void 0!==a.emissiveMap&&(d.emissiveMap=b(a.emissiveMap));void 0!==a.emissiveIntensity&&(d.emissiveIntensity=
13930 a.emissiveIntensity);void 0!==a.specularMap&&(d.specularMap=b(a.specularMap));void 0!==a.envMap&&(d.envMap=b(a.envMap));void 0!==a.reflectivity&&(d.reflectivity=a.reflectivity);void 0!==a.lightMap&&(d.lightMap=b(a.lightMap));void 0!==a.lightMapIntensity&&(d.lightMapIntensity=a.lightMapIntensity);void 0!==a.aoMap&&(d.aoMap=b(a.aoMap));void 0!==a.aoMapIntensity&&(d.aoMapIntensity=a.aoMapIntensity);void 0!==a.gradientMap&&(d.gradientMap=b(a.gradientMap));if(void 0!==a.materials)for(var e=0,f=a.materials.length;e<
13931 f;e++)d.materials.push(this.parse(a.materials[e]));return d}});Object.assign(Sd.prototype,{load:function(a,b,c,d){var e=this;(new Ma(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},parse:function(a){var b=new D,c=a.data.index,d={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};void 0!==c&&(c=new d[c.type](c.array),
13932 b.setIndex(new y(c,1)));var e=a.data.attributes,f;for(f in e){var g=e[f],c=new d[g.type](g.array);b.addAttribute(f,new y(c,g.itemSize,g.normalized))}d=a.data.groups||a.data.drawcalls||a.data.offsets;if(void 0!==d)for(f=0,c=d.length;f!==c;++f)e=d[f],b.addGroup(e.start,e.count,e.materialIndex);a=a.data.boundingSphere;void 0!==a&&(d=new q,void 0!==a.center&&d.fromArray(a.center),b.boundingSphere=new Fa(d,a.radius));return b}});wb.prototype={constructor:wb,crossOrigin:void 0,extractUrlBase:function(a){a=
13933 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,b,c;return function(d,e,f){function g(a,c,d,g,k){a=e+a;var m=wb.Handlers.get(a);null!==m?a=m.load(a):(b.setCrossOrigin(f),a=b.load(a));void 0!==c&&(a.repeat.fromArray(c),1!==c[0]&&(a.wrapS=1E3),1!==c[1]&&(a.wrapT=1E3));void 0!==d&&a.offset.fromArray(d);void 0!==g&&("repeat"===g[0]&&(a.wrapS=
13934 1E3),"mirror"===g[0]&&(a.wrapS=1002),"repeat"===g[1]&&(a.wrapT=1E3),"mirror"===g[1]&&(a.wrapT=1002));void 0!==k&&(a.anisotropy=k);c=Q.generateUUID();h[c]=a;return c}void 0===a&&(a=new N);void 0===b&&(b=new md);void 0===c&&(c=new Ad);var h={},k={uuid:Q.generateUUID(),type:"MeshLambertMaterial"},m;for(m in d){var l=d[m];switch(m){case "DbgColor":case "DbgIndex":case "opticalDensity":case "illumination":break;case "DbgName":k.name=l;break;case "blending":k.blending=Me[l];break;case "colorAmbient":case "mapAmbient":console.warn("THREE.Loader.createMaterial:",
13935 m,"is no longer supported.");break;case "colorDiffuse":k.color=a.fromArray(l).getHex();break;case "colorSpecular":k.specular=a.fromArray(l).getHex();break;case "colorEmissive":k.emissive=a.fromArray(l).getHex();break;case "specularCoef":k.shininess=l;break;case "shading":"basic"===l.toLowerCase()&&(k.type="MeshBasicMaterial");"phong"===l.toLowerCase()&&(k.type="MeshPhongMaterial");"standard"===l.toLowerCase()&&(k.type="MeshStandardMaterial");break;case "mapDiffuse":k.map=g(l,d.mapDiffuseRepeat,d.mapDiffuseOffset,
13936 d.mapDiffuseWrap,d.mapDiffuseAnisotropy);break;case "mapDiffuseRepeat":case "mapDiffuseOffset":case "mapDiffuseWrap":case "mapDiffuseAnisotropy":break;case "mapEmissive":k.emissiveMap=g(l,d.mapEmissiveRepeat,d.mapEmissiveOffset,d.mapEmissiveWrap,d.mapEmissiveAnisotropy);break;case "mapEmissiveRepeat":case "mapEmissiveOffset":case "mapEmissiveWrap":case "mapEmissiveAnisotropy":break;case "mapLight":k.lightMap=g(l,d.mapLightRepeat,d.mapLightOffset,d.mapLightWrap,d.mapLightAnisotropy);break;case "mapLightRepeat":case "mapLightOffset":case "mapLightWrap":case "mapLightAnisotropy":break;
13937 case "mapAO":k.aoMap=g(l,d.mapAORepeat,d.mapAOOffset,d.mapAOWrap,d.mapAOAnisotropy);break;case "mapAORepeat":case "mapAOOffset":case "mapAOWrap":case "mapAOAnisotropy":break;case "mapBump":k.bumpMap=g(l,d.mapBumpRepeat,d.mapBumpOffset,d.mapBumpWrap,d.mapBumpAnisotropy);break;case "mapBumpScale":k.bumpScale=l;break;case "mapBumpRepeat":case "mapBumpOffset":case "mapBumpWrap":case "mapBumpAnisotropy":break;case "mapNormal":k.normalMap=g(l,d.mapNormalRepeat,d.mapNormalOffset,d.mapNormalWrap,d.mapNormalAnisotropy);
13938 break;case "mapNormalFactor":k.normalScale=[l,l];break;case "mapNormalRepeat":case "mapNormalOffset":case "mapNormalWrap":case "mapNormalAnisotropy":break;case "mapSpecular":k.specularMap=g(l,d.mapSpecularRepeat,d.mapSpecularOffset,d.mapSpecularWrap,d.mapSpecularAnisotropy);break;case "mapSpecularRepeat":case "mapSpecularOffset":case "mapSpecularWrap":case "mapSpecularAnisotropy":break;case "mapMetalness":k.metalnessMap=g(l,d.mapMetalnessRepeat,d.mapMetalnessOffset,d.mapMetalnessWrap,d.mapMetalnessAnisotropy);
13939 break;case "mapMetalnessRepeat":case "mapMetalnessOffset":case "mapMetalnessWrap":case "mapMetalnessAnisotropy":break;case "mapRoughness":k.roughnessMap=g(l,d.mapRoughnessRepeat,d.mapRoughnessOffset,d.mapRoughnessWrap,d.mapRoughnessAnisotropy);break;case "mapRoughnessRepeat":case "mapRoughnessOffset":case "mapRoughnessWrap":case "mapRoughnessAnisotropy":break;case "mapAlpha":k.alphaMap=g(l,d.mapAlphaRepeat,d.mapAlphaOffset,d.mapAlphaWrap,d.mapAlphaAnisotropy);break;case "mapAlphaRepeat":case "mapAlphaOffset":case "mapAlphaWrap":case "mapAlphaAnisotropy":break;
13940 case "flipSided":k.side=1;break;case "doubleSided":k.side=2;break;case "transparency":console.warn("THREE.Loader.createMaterial: transparency has been renamed to opacity");k.opacity=l;break;case "depthTest":case "depthWrite":case "colorWrite":case "opacity":case "reflectivity":case "transparent":case "visible":case "wireframe":k[m]=l;break;case "vertexColors":!0===l&&(k.vertexColors=2);"face"===l&&(k.vertexColors=1);break;default:console.error("THREE.Loader.createMaterial: Unsupported",m,l)}}"MeshBasicMaterial"===
13941 k.type&&delete k.emissive;"MeshPhongMaterial"!==k.type&&delete k.specular;1>k.opacity&&(k.transparent=!0);c.setTextures(h);return c.parse(k)}}()};wb.Handlers={handlers:[],add:function(a,b){this.handlers.push(a,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(Td.prototype,{load:function(a,b,c,d){var e=this,f=this.texturePath&&"string"===typeof this.texturePath?this.texturePath:wb.prototype.extractUrlBase(a),g=new Ma(this.manager);
13942 g.setWithCredentials(this.withCredentials);g.load(a,function(c){c=JSON.parse(c);var d=c.metadata;if(void 0!==d&&(d=d.type,void 0!==d)){if("object"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.ObjectLoader instead.");return}if("scene"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.SceneLoader instead.");return}}c=e.parse(c,f);b(c.geometry,c.materials)},c,d)},setTexturePath:function(a){this.texturePath=a},parse:function(a,
13943 b){var c=new S,d=void 0!==a.scale?1/a.scale:1;(function(b){var d,g,h,k,m,l,p,n,r,w,u,F,t,v=a.faces;l=a.vertices;var y=a.normals,z=a.colors,A=0;if(void 0!==a.uvs){for(d=0;d<a.uvs.length;d++)a.uvs[d].length&&A++;for(d=0;d<A;d++)c.faceVertexUvs[d]=[]}k=0;for(m=l.length;k<m;)d=new q,d.x=l[k++]*b,d.y=l[k++]*b,d.z=l[k++]*b,c.vertices.push(d);k=0;for(m=v.length;k<m;)if(b=v[k++],r=b&1,h=b&2,d=b&8,p=b&16,w=b&32,l=b&64,b&=128,r){r=new ha;r.a=v[k];r.b=v[k+1];r.c=v[k+3];u=new ha;u.a=v[k+1];u.b=v[k+2];u.c=v[k+
13944 3];k+=4;h&&(h=v[k++],r.materialIndex=h,u.materialIndex=h);h=c.faces.length;if(d)for(d=0;d<A;d++)for(F=a.uvs[d],c.faceVertexUvs[d][h]=[],c.faceVertexUvs[d][h+1]=[],g=0;4>g;g++)n=v[k++],t=F[2*n],n=F[2*n+1],t=new C(t,n),2!==g&&c.faceVertexUvs[d][h].push(t),0!==g&&c.faceVertexUvs[d][h+1].push(t);p&&(p=3*v[k++],r.normal.set(y[p++],y[p++],y[p]),u.normal.copy(r.normal));if(w)for(d=0;4>d;d++)p=3*v[k++],w=new q(y[p++],y[p++],y[p]),2!==d&&r.vertexNormals.push(w),0!==d&&u.vertexNormals.push(w);l&&(l=v[k++],
13945 l=z[l],r.color.setHex(l),u.color.setHex(l));if(b)for(d=0;4>d;d++)l=v[k++],l=z[l],2!==d&&r.vertexColors.push(new N(l)),0!==d&&u.vertexColors.push(new N(l));c.faces.push(r);c.faces.push(u)}else{r=new ha;r.a=v[k++];r.b=v[k++];r.c=v[k++];h&&(h=v[k++],r.materialIndex=h);h=c.faces.length;if(d)for(d=0;d<A;d++)for(F=a.uvs[d],c.faceVertexUvs[d][h]=[],g=0;3>g;g++)n=v[k++],t=F[2*n],n=F[2*n+1],t=new C(t,n),c.faceVertexUvs[d][h].push(t);p&&(p=3*v[k++],r.normal.set(y[p++],y[p++],y[p]));if(w)for(d=0;3>d;d++)p=3*
13946 v[k++],w=new q(y[p++],y[p++],y[p]),r.vertexNormals.push(w);l&&(l=v[k++],r.color.setHex(z[l]));if(b)for(d=0;3>d;d++)l=v[k++],r.vertexColors.push(new N(z[l]));c.faces.push(r)}})(d);(function(){var b=void 0!==a.influencesPerVertex?a.influencesPerVertex:2;if(a.skinWeights)for(var d=0,g=a.skinWeights.length;d<g;d+=b)c.skinWeights.push(new ga(a.skinWeights[d],1<b?a.skinWeights[d+1]:0,2<b?a.skinWeights[d+2]:0,3<b?a.skinWeights[d+3]:0));if(a.skinIndices)for(d=0,g=a.skinIndices.length;d<g;d+=b)c.skinIndices.push(new ga(a.skinIndices[d],
13947 1<b?a.skinIndices[d+1]:0,2<b?a.skinIndices[d+2]:0,3<b?a.skinIndices[d+3]:0));c.bones=a.bones;c.bones&&0<c.bones.length&&(c.skinWeights.length!==c.skinIndices.length||c.skinIndices.length!==c.vertices.length)&&console.warn("When skinning, number of vertices ("+c.vertices.length+"), skinIndices ("+c.skinIndices.length+"), and skinWeights ("+c.skinWeights.length+") should match.")})();(function(b){if(void 0!==a.morphTargets)for(var d=0,g=a.morphTargets.length;d<g;d++){c.morphTargets[d]={};c.morphTargets[d].name=
13948 a.morphTargets[d].name;c.morphTargets[d].vertices=[];for(var h=c.morphTargets[d].vertices,k=a.morphTargets[d].vertices,m=0,l=k.length;m<l;m+=3){var p=new q;p.x=k[m]*b;p.y=k[m+1]*b;p.z=k[m+2]*b;h.push(p)}}if(void 0!==a.morphColors&&0<a.morphColors.length)for(console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.'),b=c.faces,h=a.morphColors[0].colors,d=0,g=b.length;d<g;d++)b[d].color.fromArray(h,3*d)})(d);(function(){var b=[],d=[];void 0!==a.animation&&d.push(a.animation);
13949 void 0!==a.animations&&(a.animations.length?d=d.concat(a.animations):d.push(a.animations));for(var g=0;g<d.length;g++){var h=ta.parseAnimation(d[g],c.bones);h&&b.push(h)}c.morphTargets&&(d=ta.CreateClipsFromMorphTargetSequences(c.morphTargets,10),b=b.concat(d));0<b.length&&(c.animations=b)})();c.computeFaceNormals();c.computeBoundingSphere();if(void 0===a.materials||0===a.materials.length)return{geometry:c};d=wb.prototype.initMaterials(a.materials,b,this.crossOrigin);return{geometry:c,materials:d}}});
13950 Object.assign(Fe.prototype,{load:function(a,b,c,d){""===this.texturePath&&(this.texturePath=a.substring(0,a.lastIndexOf("/")+1));var e=this;(new Ma(e.manager)).load(a,function(c){var d=null;try{d=JSON.parse(c)}catch(h){console.error("THREE:ObjectLoader: Can't parse "+a+".",h.message);return}c=d.metadata;void 0===c||void 0===c.type||"geometry"===c.type.toLowerCase()?console.error("THREE.ObjectLoader: Can't load "+a+". Use THREE.JSONLoader instead."):e.parse(d,b)},c,d)},setTexturePath:function(a){this.texturePath=
13951 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&&0!==a.images.length||void 0===b||b(e);return e},parseGeometries:function(a){var b={};if(void 0!==a)for(var c=new Td,d=new Sd,e=0,f=a.length;e<f;e++){var g,
13952 h=a[e];switch(h.type){case "PlaneGeometry":case "PlaneBufferGeometry":g=new Ea[h.type](h.width,h.height,h.widthSegments,h.heightSegments);break;case "BoxGeometry":case "BoxBufferGeometry":case "CubeGeometry":g=new Ea[h.type](h.width,h.height,h.depth,h.widthSegments,h.heightSegments,h.depthSegments);break;case "CircleGeometry":case "CircleBufferGeometry":g=new Ea[h.type](h.radius,h.segments,h.thetaStart,h.thetaLength);break;case "CylinderGeometry":case "CylinderBufferGeometry":g=new Ea[h.type](h.radiusTop,
13953 h.radiusBottom,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "ConeGeometry":case "ConeBufferGeometry":g=new Ea[h.type](h.radius,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "SphereGeometry":case "SphereBufferGeometry":g=new Ea[h.type](h.radius,h.widthSegments,h.heightSegments,h.phiStart,h.phiLength,h.thetaStart,h.thetaLength);break;case "DodecahedronGeometry":case "IcosahedronGeometry":case "OctahedronGeometry":case "TetrahedronGeometry":g=
13954 new Ea[h.type](h.radius,h.detail);break;case "RingGeometry":case "RingBufferGeometry":g=new Ea[h.type](h.innerRadius,h.outerRadius,h.thetaSegments,h.phiSegments,h.thetaStart,h.thetaLength);break;case "TorusGeometry":case "TorusBufferGeometry":g=new Ea[h.type](h.radius,h.tube,h.radialSegments,h.tubularSegments,h.arc);break;case "TorusKnotGeometry":case "TorusKnotBufferGeometry":g=new Ea[h.type](h.radius,h.tube,h.tubularSegments,h.radialSegments,h.p,h.q);break;case "LatheGeometry":case "LatheBufferGeometry":g=
13955 new Ea[h.type](h.points,h.segments,h.phiStart,h.phiLength);break;case "BufferGeometry":g=d.parse(h);break;case "Geometry":g=c.parse(h.data,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);b[h.uuid]=g}return b},parseMaterials:function(a,b){var c={};if(void 0!==a){var d=new Ad;d.setTextures(b);for(var e=0,f=a.length;e<f;e++){var g=d.parse(a[e]);c[g.uuid]=g}}return c},parseAnimations:function(a){for(var b=
13956 [],c=0;c<a.length;c++){var d=ta.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)},void 0,function(){d.manager.itemError(a)})}var d=this,e={};if(void 0!==a&&0<a.length){var f=new Pd(b),g=new Vc(f);g.setCrossOrigin(this.crossOrigin);for(var f=0,h=a.length;f<h;f++){var k=a[f],m=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(k.url)?k.url:d.texturePath+k.url;e[k.uuid]=c(m)}}return e},parseTextures:function(a,b){function c(a,
13957 b){if("number"===typeof a)return a;console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",a);return b[a]}var d={};if(void 0!==a)for(var e=0,f=a.length;e<f;e++){var g=a[e];void 0===g.image&&console.warn('THREE.ObjectLoader: No "image" specified for',g.uuid);void 0===b[g.image]&&console.warn("THREE.ObjectLoader: Undefined image",g.image);var h=new ea(b[g.image]);h.needsUpdate=!0;h.uuid=g.uuid;void 0!==g.name&&(h.name=g.name);void 0!==g.mapping&&(h.mapping=c(g.mapping,Ne));
13958 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],le),h.wrapT=c(g.wrap[1],le));void 0!==g.minFilter&&(h.minFilter=c(g.minFilter,me));void 0!==g.magFilter&&(h.magFilter=c(g.magFilter,me));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 H;return function(b,c,d){function e(a){void 0===c[a]&&console.warn("THREE.ObjectLoader: Undefined geometry",
13959 a);return c[a]}function f(a){if(void 0!==a)return void 0===d[a]&&console.warn("THREE.ObjectLoader: Undefined material",a),d[a]}var g;switch(b.type){case "Scene":g=new jb;void 0!==b.background&&Number.isInteger(b.background)&&(g.background=new N(b.background));void 0!==b.fog&&("Fog"===b.fog.type?g.fog=new Jb(b.fog.color,b.fog.near,b.fog.far):"FogExp2"===b.fog.type&&(g.fog=new Ib(b.fog.color,b.fog.density)));break;case "PerspectiveCamera":g=new Ha(b.fov,b.aspect,b.near,b.far);void 0!==b.focus&&(g.focus=
13960 b.focus);void 0!==b.zoom&&(g.zoom=b.zoom);void 0!==b.filmGauge&&(g.filmGauge=b.filmGauge);void 0!==b.filmOffset&&(g.filmOffset=b.filmOffset);void 0!==b.view&&(g.view=Object.assign({},b.view));break;case "OrthographicCamera":g=new Hb(b.left,b.right,b.top,b.bottom,b.near,b.far);break;case "AmbientLight":g=new td(b.color,b.intensity);break;case "DirectionalLight":g=new sd(b.color,b.intensity);break;case "PointLight":g=new qd(b.color,b.intensity,b.distance,b.decay);break;case "SpotLight":g=new pd(b.color,
13961 b.intensity,b.distance,b.angle,b.penumbra,b.decay);break;case "HemisphereLight":g=new nd(b.color,b.groundColor,b.intensity);break;case "Mesh":g=e(b.geometry);var h=f(b.material);g=g.bones&&0<g.bones.length?new jd(g,h):new Ba(g,h);break;case "LOD":g=new Ac;break;case "Line":g=new Va(e(b.geometry),f(b.material),b.mode);break;case "LineSegments":g=new fa(e(b.geometry),f(b.material));break;case "PointCloud":case "Points":g=new Kb(e(b.geometry),f(b.material));break;case "Sprite":g=new zc(f(b.material));
13962 break;case "Group":g=new Bc;break;case "SkinnedMesh":console.warn("THREE.ObjectLoader.parseObject() does not support SkinnedMesh type. Instantiates Object3D instead.");default:g=new G}g.uuid=b.uuid;void 0!==b.name&&(g.name=b.name);void 0!==b.matrix?(a.fromArray(b.matrix),a.decompose(g.position,g.quaternion,g.scale)):(void 0!==b.position&&g.position.fromArray(b.position),void 0!==b.rotation&&g.rotation.fromArray(b.rotation),void 0!==b.quaternion&&g.quaternion.fromArray(b.quaternion),void 0!==b.scale&&
13963 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!==b.visible&&(g.visible=b.visible);void 0!==b.userData&&(g.userData=b.userData);
13964 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 m=b[h];k=g.getObjectByProperty("uuid",m.object);void 0!==k&&g.addLevel(k,m.distance)}return g}}()});wa.prototype={constructor:wa,getPoint:function(a){console.warn("THREE.Curve: Warning, getPoint() not implemented!");return null},getPointAt:function(a){a=this.getUtoTmapping(a);return this.getPoint(a)},getPoints:function(a){a||(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/
13965 a));return b},getSpacedPoints:function(a){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){a||(a=this.__arcLengthDivisions?this.__arcLengthDivisions:200);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=this.getPoint(e/a),f+=c.distanceTo(d),b.push(f),
13966 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()},getTangentAt:function(a){a=
13967 this.getUtoTmapping(a);return this.getTangent(a)},computeFrenetFrames:function(a,b){var c=new q,d=[],e=[],f=[],g=new q,h=new H,k,m;for(k=0;k<=a;k++)m=k/a,d[k]=this.getTangentAt(m),d[k].normalize();e[0]=new q;f[0]=new q;k=Number.MAX_VALUE;m=Math.abs(d[0].x);var l=Math.abs(d[0].y),p=Math.abs(d[0].z);m<=k&&(k=m,c.set(1,0,0));l<=k&&(k=l,c.set(0,1,0));p<=k&&c.set(0,0,1);g.crossVectors(d[0],c).normalize();e[0].crossVectors(d[0],g);f[0].crossVectors(d[0],e[0]);for(k=1;k<=a;k++)e[k]=e[k-1].clone(),f[k]=f[k-
13968 1].clone(),g.crossVectors(d[k-1],d[k]),g.length()>Number.EPSILON&&(g.normalize(),c=Math.acos(Q.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(Q.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}}};wa.create=function(a,b){a.prototype=Object.create(wa.prototype);
13969 a.prototype.constructor=a;a.prototype.getPoint=b;return a};Qa.prototype=Object.create(wa.prototype);Qa.prototype.constructor=Qa;Qa.prototype.isLineCurve=!0;Qa.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};Qa.prototype.getPointAt=function(a){return this.getPoint(a)};Qa.prototype.getTangent=function(a){return this.v2.clone().sub(this.v1).normalize()};Yc.prototype=Object.assign(Object.create(wa.prototype),
13970 {constructor:Yc,add:function(a){this.curves.push(a)},closePath:function(){var a=this.curves[0].getPoint(0),b=this.curves[this.curves.length-1].getPoint(1);a.equals(b)||this.curves.push(new Qa(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=
13971 !0;this.cacheLengths=null;this.getLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var a=[],b=0,c=0,d=this.curves.length;c<d;c++)b+=this.curves[c].getLength(),a.push(b);return this.cacheLengths=a},getSpacedPoints:function(a){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=
13972 e[d],f=f.getPoints(f&&f.isEllipseCurve?2*a:f&&f.isLineCurve?1:f&&f.isSplineCurve?a*f.points.length:a),g=0;g<f.length;g++){var h=f[g];c&&c.equals(h)||(b.push(h),c=h)}this.autoClose&&1<b.length&&!b[b.length-1].equals(b[0])&&b.push(b[0]);return b},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 S,c=0,d=a.length;c<d;c++){var e=a[c];
13973 b.vertices.push(new q(e.x,e.y,e.z||0))}return b}});Xa.prototype=Object.create(wa.prototype);Xa.prototype.constructor=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),
13974 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 C(a,e)};var ed={tangentQuadraticBezier:function(a,b,c,d){return 2*(1-a)*(c-b)+2*a*(d-c)},tangentCubicBezier:function(a,b,c,d,e){return-3*b*(1-a)*(1-a)+3*c*(1-a)*(1-a)-6*a*c*(1-a)+6*a*d*(1-a)-3*a*a*d+3*a*a*e},tangentSpline:function(a,b,c,d,e){return 6*a*a-6*a+(3*a*a-4*a+1)+(-6*a*a+6*a)+(3*a*a-2*a)},interpolate:function(a,b,c,d,e){a=.5*(c-a);d=.5*(d-b);var f=e*e;return(2*b-2*c+a+d)*e*f+(-3*b+3*c-2*a-d)*
13975 f+a*e+b}};xb.prototype=Object.create(wa.prototype);xb.prototype.constructor=xb;xb.prototype.isSplineCurve=!0;xb.prototype.getPoint=function(a){var b=this.points;a*=b.length-1;var c=Math.floor(a);a-=c;var d=b[0===c?c:c-1],e=b[c],f=b[c>b.length-2?b.length-1:c+1],b=b[c>b.length-3?b.length-1:c+2],c=ed.interpolate;return new C(c(d.x,e.x,f.x,b.x,a),c(d.y,e.y,f.y,b.y,a))};yb.prototype=Object.create(wa.prototype);yb.prototype.constructor=yb;yb.prototype.getPoint=function(a){var b=pa.b3;return new C(b(a,this.v0.x,
13976 this.v1.x,this.v2.x,this.v3.x),b(a,this.v0.y,this.v1.y,this.v2.y,this.v3.y))};yb.prototype.getTangent=function(a){var b=ed.tangentCubicBezier;return(new C(b(a,this.v0.x,this.v1.x,this.v2.x,this.v3.x),b(a,this.v0.y,this.v1.y,this.v2.y,this.v3.y))).normalize()};zb.prototype=Object.create(wa.prototype);zb.prototype.constructor=zb;zb.prototype.getPoint=function(a){var b=pa.b2;return new C(b(a,this.v0.x,this.v1.x,this.v2.x),b(a,this.v0.y,this.v1.y,this.v2.y))};zb.prototype.getTangent=function(a){var b=
13977 ed.tangentQuadraticBezier;return(new C(b(a,this.v0.x,this.v1.x,this.v2.x),b(a,this.v0.y,this.v1.y,this.v2.y))).normalize()};var oe=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 Qa(this.currentPoint.clone(),new C(a,b));this.curves.push(c);this.currentPoint.set(a,b)},quadraticCurveTo:function(a,b,c,d){a=new zb(this.currentPoint.clone(),
13978 new C(a,b),new C(c,d));this.curves.push(a);this.currentPoint.set(c,d)},bezierCurveTo:function(a,b,c,d,e,f){a=new yb(this.currentPoint.clone(),new C(a,b),new C(c,d),new C(e,f));this.curves.push(a);this.currentPoint.set(e,f)},splineThru:function(a){var b=[this.currentPoint.clone()].concat(a),b=new xb(b);this.curves.push(b);this.currentPoint.copy(a[a.length-1])},arc:function(a,b,c,d,e,f){this.absarc(a+this.currentPoint.x,b+this.currentPoint.y,c,d,e,f)},absarc:function(a,b,c,d,e,f){this.absellipse(a,
13979 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)}});Ab.prototype=Object.assign(Object.create(oe),{constructor:Ab,getPointsHoles:function(a){for(var b=[],c=0,d=this.holes.length;c<d;c++)b[c]=this.holes[c].getPoints(a);
13980 return b},extractAllPoints:function(a){return{shape:this.getPoints(a),holes:this.getPointsHoles(a)}},extractPoints:function(a){return this.extractAllPoints(a)}});Zc.prototype=oe;oe.constructor=Zc;Ud.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,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,
13981 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,m=h.y-g.y;if(Math.abs(m)>Number.EPSILON){if(0>m&&(g=b[f],k=-k,h=b[e],m=-m),!(a.y<g.y||a.y>h.y))if(a.y===g.y){if(a.x===g.x)return!0}else{e=m*(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<=
13982 a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=pa.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);var g,h,k,m=[];if(1===f.length)return h=f[0],k=new Ab,k.curves=h.curves,m.push(k),m;var l=!e(f[0].getPoints()),l=a?!l:l;k=[];var p=[],n=[],q=0,w;p[q]=void 0;n[q]=[];for(var u=0,y=f.length;u<y;u++)h=f[u],w=h.getPoints(),g=e(w),(g=a?!g:g)?(!l&&p[q]&&q++,p[q]={s:new Ab,p:w},p[q].s.curves=h.curves,l&&q++,n[q]=[]):n[q].push({h:h,p:w[0]});if(!p[0])return c(f);if(1<p.length){u=
13983 !1;h=[];e=0;for(f=p.length;e<f;e++)k[e]=[];e=0;for(f=p.length;e<f;e++)for(g=n[e],l=0;l<g.length;l++){q=g[l];w=!0;for(y=0;y<p.length;y++)d(q.p,p[y].p)&&(e!==y&&h.push({froms:e,tos:y,hole:l}),w?(w=!1,k[y].push(q)):u=!0);w&&k[e].push(q)}0<h.length&&(u||(n=k))}u=0;for(e=p.length;u<e;u++)for(k=p[u].s,m.push(k),h=n[u],f=0,g=h.length;f<g;f++)k.holes.push(h[f].h);return m}};Object.assign(Vd.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("");
13984 var e=b/d.resolution,f=0;b=[];for(var g=0;g<a.length;g++){var h;h=e;var k=f,m=d.glyphs[a[g]]||d.glyphs["?"];if(m){var l=new Ud,p=[],n=pa.b2,q=pa.b3,w,u,y,t,v,D,z,A;if(m.o)for(var C=m._cachedOutline||(m._cachedOutline=m.o.split(" ")),E=0,G=C.length;E<G;)switch(C[E++]){case "m":w=C[E++]*h+k;u=C[E++]*h;l.moveTo(w,u);break;case "l":w=C[E++]*h+k;u=C[E++]*h;l.lineTo(w,u);break;case "q":w=C[E++]*h+k;u=C[E++]*h;v=C[E++]*h+k;D=C[E++]*h;l.quadraticCurveTo(v,D,w,u);if(t=p[p.length-1]){y=t.x;t=t.y;for(var H=
13985 1;H<=c;H++){var J=H/c;n(J,y,v,w);n(J,t,D,u)}}break;case "b":if(w=C[E++]*h+k,u=C[E++]*h,v=C[E++]*h+k,D=C[E++]*h,z=C[E++]*h+k,A=C[E++]*h,l.bezierCurveTo(v,D,z,A,w,u),t=p[p.length-1])for(y=t.x,t=t.y,H=1;H<=c;H++)J=H/c,q(J,y,v,z,w),q(J,t,D,A,u)}h={offset:m.ha*h,path:l}}else h=void 0;f+=h.offset;b.push(h.path)}c=[];d=0;for(a=b.length;d<a;d++)Array.prototype.push.apply(c,b[d].toShapes());return c}});Object.assign(Ge.prototype,{load:function(a,b,c,d){var e=this;(new Ma(this.manager)).load(a,function(a){var c;
13986 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 Vd(a)}});var Hd,Zd={getContext:function(){void 0===Hd&&(Hd=new (window.AudioContext||window.webkitAudioContext));return Hd},setContext:function(a){Hd=a}};Object.assign(Wd.prototype,{load:function(a,b,c,d){var e=new Ma(this.manager);e.setResponseType("arraybuffer");e.load(a,
13987 function(a){Zd.getContext().decodeAudioData(a,function(a){b(a)})},c,d)}});Xd.prototype=Object.assign(Object.create(na.prototype),{constructor:Xd,isRectAreaLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.width=a.width;this.height=a.height;return this}});Object.assign(He.prototype,{update:function(){var a,b,c,d,e,f,g,h=new H,k=new H;return function(m){if(a!==this||b!==m.focus||c!==m.fov||d!==m.aspect*this.aspect||e!==m.near||f!==m.far||g!==m.zoom){a=this;b=m.focus;c=m.fov;d=m.aspect*this.aspect;
13988 e=m.near;f=m.far;g=m.zoom;var l=m.projectionMatrix.clone(),p=this.eyeSep/2,n=p*e/b,q=e*Math.tan(Q.DEG2RAD*c*.5)/g,w;k.elements[12]=-p;h.elements[12]=p;p=-q*d+n;w=q*d+n;l.elements[0]=2*e/(w-p);l.elements[8]=(w+p)/(w-p);this.cameraL.projectionMatrix.copy(l);p=-q*d-n;w=q*d-n;l.elements[0]=2*e/(w-p);l.elements[8]=(w+p)/(w-p);this.cameraR.projectionMatrix.copy(l)}this.cameraL.matrixWorld.copy(m.matrixWorld).multiply(k);this.cameraR.matrixWorld.copy(m.matrixWorld).multiply(h)}}()});Bd.prototype=Object.create(G.prototype);
13989 Bd.prototype.constructor=Bd;Yd.prototype=Object.assign(Object.create(G.prototype),{constructor:Yd,getInput:function(){return this.gain},removeFilter:function(){null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null)},getFilter:function(){return this.filter},setFilter:function(a){null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination);
13990 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 q,b=new da,c=new q,d=new q;return function(e){G.prototype.updateMatrixWorld.call(this,e);e=this.context.listener;var f=this.up;this.matrixWorld.decompose(a,b,c);d.set(0,0,-1).applyQuaternion(b);e.positionX?(e.positionX.setValueAtTime(a.x,this.context.currentTime),
13991 e.positionY.setValueAtTime(a.y,this.context.currentTime),e.positionZ.setValueAtTime(a.z,this.context.currentTime),e.forwardX.setValueAtTime(d.x,this.context.currentTime),e.forwardY.setValueAtTime(d.y,this.context.currentTime),e.forwardZ.setValueAtTime(d.z,this.context.currentTime),e.upX.setValueAtTime(f.x,this.context.currentTime),e.upY.setValueAtTime(f.y,this.context.currentTime),e.upZ.setValueAtTime(f.z,this.context.currentTime)):(e.setPosition(a.x,a.y,a.z),e.setOrientation(d.x,d.y,d.z,f.x,f.y,
13992 f.z))}}()});ec.prototype=Object.assign(Object.create(G.prototype),{constructor:ec,getOutput:function(){return this.gain},setNodeSource:function(a){this.hasPlaybackControl=!1;this.sourceType="audioNode";this.source=a;this.connect();return this},setBuffer:function(a){this.buffer=a;this.sourceType="buffer";this.autoplay&&this.play();return this},play:function(){if(!0===this.isPlaying)console.warn("THREE.Audio: Audio is already playing.");else if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");
13993 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.");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.");
13994 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());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-
13995 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]},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.");
13996 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."),!1):this.loop},setLoop:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.loop=
13997 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}});$d.prototype=Object.assign(Object.create(ec.prototype),{constructor:$d,getOutput:function(){return this.panner},getRefDistance:function(){return this.panner.refDistance},setRefDistance:function(a){this.panner.refDistance=a},getRolloffFactor:function(){return this.panner.rolloffFactor},setRolloffFactor:function(a){this.panner.rolloffFactor=
13998 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 q;return function(b){G.prototype.updateMatrixWorld.call(this,b);a.setFromMatrixPosition(this.matrixWorld);this.panner.setPosition(a.x,a.y,a.z)}}()});Object.assign(ae.prototype,{getFrequencyData:function(){this.analyser.getByteFrequencyData(this.data);
13999 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}});Cd.prototype={constructor:Cd,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=this.valueSize,c=this.buffer;a=a*b+b;var d=this.cumulativeWeight,e=this.binding;this.cumulativeWeight=0;1>d&&
14000 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=0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d,e){da.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f=
14001 1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}};ka.prototype={constructor:ka,getValue:function(a,b){this.bind();this.getValue(a,b)},setValue:function(a,b){this.bind();this.setValue(a,b)},bind:function(){var a=this.node,b=this.parsedPath,c=b.objectName,d=b.propertyName,e=b.propertyIndex;a||(this.node=a=ka.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",
14002 this);return}if(!a.material.materials){console.error(" can not bind to material.materials as node.material does not have a materials array",this);return}a=a.material.materials;break;case "bones":if(!a.skeleton){console.error(" 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===
14003 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: "+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"===
14004 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",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?
14005 (c=this.BindingType.HasFromToArray,this.resolvedProperty=f):void 0!==f.length?(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: "+this.path+" but it wasn't found.")},unbind:function(){this.node=null;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}};Object.assign(ka.prototype,{_getValue_unavailable:function(){},
14006 _setValue_unavailable:function(){},_getValue_unbound:ka.prototype.getValue,_setValue_unbound:ka.prototype.setValue,BindingType:{Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Versioning:{None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},GetterByBindingType:[function(a,b){a[b]=this.node[this.propertyName]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)a[b++]=c[d]},function(a,b){a[b]=this.resolvedProperty[this.propertyIndex]},function(a,b){this.resolvedProperty.toArray(a,
14007 b)}],SetterByBindingTypeAndVersioning:[[function(a,b){this.node[this.propertyName]=a[b]},function(a,b){this.node[this.propertyName]=a[b];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,
14008 d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty[this.propertyIndex]=a[b]},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty.fromArray(a,b)},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty.fromArray(a,
14009 b);this.targetObject.matrixWorldNeedsUpdate=!0}]]});ka.Composite=function(a,b,c){c=c||ka.parseTrackName(b);this._targetGroup=a;this._bindings=a.subscribe_(b,c)};ka.Composite.prototype={constructor:ka.Composite,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_,
14010 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()}};ka.create=function(a,b,c){return a&&a.isAnimationObjectGroup?new ka.Composite(a,b,c):new ka(a,b,c)};ka.parseTrackName=function(a){var b=/^((?:[\w-]+[\/:])*)([\w-]+)?(?:\.([\w-]+)(?:\[(.+)\])?)?\.([\w-]+)(?:\[(.+)\])?$/.exec(a);if(!b)throw Error("cannot parse trackName at all: "+a);b={nodeName:b[2],objectName:b[3],objectIndex:b[4],propertyName:b[5],propertyIndex:b[6]};
14011 if(null===b.propertyName||0===b.propertyName.length)throw Error("can not parse propertyName from trackName: "+a);return b};ka.findNode=function(a,b){if(!b||""===b||"root"===b||"."===b||-1===b||b===a.name||b===a.uuid)return a;if(a.skeleton){var c=function(a){for(var c=0;c<a.bones.length;c++){var d=a.bones[c];if(d.name===b)return d}return null}(a.skeleton);if(c)return c}if(a.children){var d=function(a){for(var c=0;c<a.length;c++){var g=a[c];if(g.name===b||g.uuid===b||(g=d(g.children)))return g}return null};
14012 if(c=d(a.children))return c}return null};be.prototype={constructor:be,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,q=arguments.length;l!==q;++l){var p=arguments[l],n=p.uuid,r=e[n];if(void 0===r){r=c++;e[n]=r;b.push(p);for(var n=0,w=k;n!==w;++n)h[n].push(new ka(p,f[n],g[n]))}else if(r<d){var u=--d,w=b[u];e[w.uuid]=r;b[r]=w;e[n]=u;b[u]=p;n=0;for(w=k;n!==w;++n){var y=
14013 h[n],t=y[r];y[r]=y[u];void 0===t&&(t=new ka(p,f[n],g[n]));y[u]=t}}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,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,q=d[l];if(void 0!==q&&q>=c){var p=c++,n=b[p];d[n.uuid]=q;b[q]=n;d[l]=p;b[p]=
14014 k;k=0;for(l=f;k!==l;++k){var n=e[k],r=n[q];n[q]=n[p];n[p]=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,q=e[l];if(void 0!==q)if(delete e[l],q<d){var l=--d,p=b[l],n=--c,r=b[n];e[p.uuid]=q;b[q]=p;e[r.uuid]=l;b[l]=r;b.pop();p=0;for(r=g;p!==r;++p){var w=f[p],u=w[n];w[q]=w[l];w[l]=u;w.pop()}}else for(n=--c,r=b[n],e[r.uuid]=q,b[q]=r,b.pop(),
14015 p=0,r=g;p!==r;++p)w=f[p],w[q]=w[n],w.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]=d;f.push(a);g.push(b);e.push(l);c=k;for(d=h.length;c!==d;++c)l[c]=new ka(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=
14016 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()}}};ce.prototype={constructor:ce,play:function(){this._mixer._activateAction(this);return this},stop:function(){this._mixer._deactivateAction(this);return this.reset()},reset:function(){this.paused=!1;this.enabled=!0;this.time=0;this._loopCount=-1;this._startTime=null;return this.stopFading().stopWarping()},isRunning:function(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&
14017 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?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,
14018 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=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},
14019 setDuration:function(a){this.timeScale=this._clip.duration/a;return this.stopWarping()},syncWith:function(a){this.time=a.time;this.timeScale=a.timeScale;return this.stopWarping()},halt:function(a){return this.warp(this._effectiveTimeScale,0,a)},warp:function(a,b,c){var d=this._mixer,e=d.time,f=this._timeScaleInterpolant,g=this.timeScale;null===f&&(this._timeScaleInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;d[1]=e+c;f[0]=a/g;f[1]=b/g;return this},stopWarping:function(){var a=
14020 this._timeScaleInterpolant;null!==a&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(a));return this},getMixer:function(){return this._mixer},getClip:function(){return this._clip},getRoot:function(){return this._localRoot||this._mixer._root},_update:function(a,b,c,d){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,
14021 f=0,g=b.length;f!==g;++f)b[f].evaluate(c),e[f].accumulate(d,a)}},_updateWeight:function(a){var b=0;if(this.enabled){var b=this.weight,c=this._weightInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.parameterPositions[1]&&(this.stopFading(),0===d&&(this.enabled=!1))}}return this._effectiveWeight=b},_updateTimeScale:function(a){var b=0;if(!this.paused){var b=this.timeScale,c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.parameterPositions[1]&&(this.stopWarping(),0===
14022 b?this.paused=!0:this.timeScale=b)}}return this._effectiveTimeScale=b},_updateTime:function(a){var b=this.time+a;if(0===a)return b;var c=this._clip.duration,d=this.loop,e=this._loopCount;if(2200===d)a:{if(-1===e&&(this._loopCount=0,this._setEndings(!0,!0,!1)),b>=c)b=c;else if(0>b)b=0;else break a;this.clampWhenFinished?this.paused=!0:this.enabled=!1;this._mixer.dispatchEvent({type:"finished",action:this,direction:0>a?-1:1})}else{d=2202===d;-1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions,
14023 d)):this._setEndings(0===this.repetitions,!0,d));if(b>=c||0>b){var f=Math.floor(b/c),b=b-c*f,e=e+Math.abs(f),g=this.repetitions-e;0>g?(this.clampWhenFinished?this.paused=!0:this.enabled=!1,b=0<a?c:0,this._mixer.dispatchEvent({type:"finished",action:this,direction:0<a?1:-1})):(0===g?(a=0>a,this._setEndings(a,!a,d)):this._setEndings(!1,!1,d),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:f}))}if(d&&1===(e&1))return this.time=b,c-b}return this.time=b},_setEndings:function(a,
14024 b,c){var d=this._interpolantSettings;c?(d.endingStart=2401,d.endingEnd=2401):(d.endingStart=a?this.zeroSlopeAtStart?2401:2400:2402,d.endingEnd=b?this.zeroSlopeAtEnd?2401:2400:2402)},_scheduleFading:function(a,b,c){var d=this._mixer,e=d.time,f=this._weightInterpolant;null===f&&(this._weightInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;f[0]=b;d[1]=e+a;f[1]=c;return this}};Object.assign(de.prototype,oa.prototype,{clipAction:function(a,b){var c=b||this._root,
14025 d=c.uuid,e="string"===typeof a?ta.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===e&&(e=g._clip)}if(null===e)return null;e=new ce(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?ta.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=
14026 this._actions,b=this._nActiveActions,c=this._bindings,d=this._nActiveBindings,e=this._nActiveBindings=this._nActiveActions=0;e!==b;++e)a[e].reset();for(e=0;e!==d;++e)c[e].useCount=0;return this},update:function(a){a*=this.timeScale;for(var b=this._actions,c=this._nActiveActions,d=this.time+=a,e=Math.sign(a),f=this._accuIndex^=1,g=0;g!==c;++g){var h=b[g];h.enabled&&h._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},
14027 uncacheClip:function(a){var b=this._actions;a=a.uuid;var c=this._actionsByClip,d=c[a];if(void 0!==d){for(var d=d.knownActions,e=0,f=d.length;e!==f;++e){var g=d[e];this._deactivateAction(g);var h=g._cacheIndex,k=b[b.length-1];g._cacheIndex=null;g._byClipCacheIndex=null;k._cacheIndex=h;b[h]=k;b.pop();this._removeInactiveBindingsForAction(g)}delete c[a]}},uncacheRoot:function(a){a=a.uuid;var b=this._actionsByClip,c;for(c in b){var d=b[c].actionByRoot[a];void 0!==d&&(this._deactivateAction(d),this._removeInactiveAction(d))}c=
14028 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,b);null!==c&&(this._deactivateAction(c),this._removeInactiveAction(c))}});Object.assign(de.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 q=
14029 d[k],p=q.name,n=l[p];if(void 0===n){n=f[k];if(void 0!==n){null===n._cacheIndex&&(++n.referenceCount,this._addInactiveBinding(n,h,p));continue}n=new Cd(ka.create(c,p,b&&b._propertyBindings[k].binding.parsedPath),q.ValueTypeName,q.getValueSize());++n.referenceCount;this._addInactiveBinding(n,h,p)}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,
14030 d&&d.knownActions[0]);this._addInactiveAction(a,c,b)}b=a._propertyBindings;c=0;for(d=b.length;c!==d;++c){var e=b[c];0===e.useCount++&&(this._lendBinding(e),e.saveOriginalState())}this._lendAction(a)}},_deactivateAction:function(a){if(this._isActiveAction(a)){for(var b=a._propertyBindings,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=
14031 {};this._bindings=[];this._nActiveBindings=0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var a=this;this.stats={actions:{get total(){return a._actions.length},get inUse(){return a._nActiveActions}},bindings:{get total(){return a._bindings.length},get inUse(){return a._nActiveBindings}},controlInterpolants:{get total(){return a._controlInterpolants.length},get inUse(){return a._nActiveControlInterpolants}}}},_isActiveAction:function(a){a=a._cacheIndex;
14032 return null!==a&&a<this._nActiveActions},_addInactiveAction:function(a,b,c){var d=this._actions,e=this._actionsByClip,f=e[b];void 0===f?(f={knownActions:[a],actionByRoot:{}},a._byClipCacheIndex=0,e[b]=f):(b=f.knownActions,a._byClipCacheIndex=b.length,b.push(a));a._cacheIndex=d.length;d.push(a);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 c=a._clip.uuid,d=this._actionsByClip,e=d[c],f=
14033 e.knownActions,g=f[f.length-1],h=a._byClipCacheIndex;g._byClipCacheIndex=h;f[h]=g;f.pop();a._byClipCacheIndex=null;delete e.actionByRoot[(b._localRoot||this._root).uuid];0===f.length&&delete d[c];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=
14034 d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackAction:function(a){var b=this._actions,c=a._cacheIndex,d=--this._nActiveActions,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_addInactiveBinding:function(a,b,c){var d=this._bindingsByRootAndName,e=d[b],f=this._bindings;void 0===e&&(e={},d[b]=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;
14035 g._cacheIndex=a;b[a]=g;b.pop();delete f[c];a:{for(var h in f)break a;delete e[d]}},_lendBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=this._nActiveBindings++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=--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),
14036 new Float32Array(2),1,this._controlInterpolantsResultBuffer),c.__cacheIndex=b,a[b]=c);return c},_takeBackControlInterpolant:function(a){var b=this._controlInterpolants,c=a.__cacheIndex,d=--this._nActiveControlInterpolants,e=b[d];a.__cacheIndex=d;b[d]=a;e.__cacheIndex=c;b[c]=e},_controlInterpolantsResultBuffer:new Float32Array(1)});Dd.prototype.clone=function(){return new Dd(void 0===this.value.clone?this.value:this.value.clone())};Bb.prototype=Object.create(D.prototype);Bb.prototype.constructor=Bb;
14037 Bb.prototype.isInstancedBufferGeometry=!0;Bb.prototype.addGroup=function(a,b,c){this.groups.push({start:a,count:b,materialIndex:c})};Bb.prototype.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=a.length;c<b;c++){var d=a[c];this.addGroup(d.start,d.count,d.materialIndex)}return this};ee.prototype={constructor:ee,isInterleavedBufferAttribute:!0,get count(){return this.data.count},get array(){return this.data.array},
14038 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+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*
14039 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+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+
14040 3]=e;return this}};fc.prototype={constructor:fc,isInterleavedBuffer:!0,set needsUpdate(a){!0===a&&this.version++},setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==a?a.length/this.stride:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=new a.array.constructor(a.array);this.count=a.count;this.stride=a.stride;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=
14041 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=a;return this}};gc.prototype=Object.create(fc.prototype);gc.prototype.constructor=gc;gc.prototype.isInstancedInterleavedBuffer=!0;gc.prototype.copy=function(a){fc.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;
14042 return this};hc.prototype=Object.create(y.prototype);hc.prototype.constructor=hc;hc.prototype.isInstancedBufferAttribute=!0;hc.prototype.copy=function(a){y.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this};fe.prototype={constructor:fe,linePrecision:1,set:function(a,b){this.ray.set(a,b)},setFromCamera:function(a,b){b&&b.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(b.matrixWorld),this.ray.direction.set(a.x,a.y,.5).unproject(b).sub(this.ray.origin).normalize()):
14043 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=[];ge(a,this,c,b);c.sort(Ie);return c},intersectObjects:function(a,b){var c=[];if(!1===Array.isArray(a))return console.warn("THREE.Raycaster.intersectObjects: objects is not an Array."),c;for(var d=0,e=a.length;d<e;d++)ge(a[d],this,c,b);c.sort(Ie);
14044 return c}};he.prototype={constructor:he,start:function(){this.oldTime=this.startTime=(performance||Date).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=0;this.autoStart&&!this.running&&this.start();if(this.running){var b=(performance||Date).now(),a=(b-this.oldTime)/1E3;this.oldTime=b;this.elapsedTime+=a}return a}};ie.prototype={constructor:ie,set:function(a,
14045 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-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(Q.clamp(a.y/this.radius,-1,1)));return this}};je.prototype={constructor:je,
14046 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*a.x+a.z*a.z);this.theta=Math.atan2(a.x,a.z);this.y=a.y;return this}};ua.prototype=Object.create(Ba.prototype);ua.prototype.constructor=ua;ua.prototype.createAnimation=function(a,b,c,d){b={start:b,end:c,length:c-b+1,fps:d,duration:(c-b)/d,lastFrame:0,
14047 currentFrame:0,active:!1,time:0,direction:1,weight:1,directionBackwards:!1,mirroredLoop:!1};this.animationsMap[a]=b;this.animationsList.push(b)};ua.prototype.autoCreateAnimations=function(a){for(var b=/([a-z]+)_?(\d+)/i,c,d={},e=this.geometry,f=0,g=e.morphTargets.length;f<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,
14048 a);this.firstAnimation=c};ua.prototype.setAnimationDirectionForward=function(a){if(a=this.animationsMap[a])a.direction=1,a.directionBackwards=!1};ua.prototype.setAnimationDirectionBackward=function(a){if(a=this.animationsMap[a])a.direction=-1,a.directionBackwards=!0};ua.prototype.setAnimationFPS=function(a,b){var c=this.animationsMap[a];c&&(c.fps=b,c.duration=(c.end-c.start)/c.fps)};ua.prototype.setAnimationDuration=function(a,b){var c=this.animationsMap[a];c&&(c.duration=b,c.fps=(c.end-c.start)/
14049 c.duration)};ua.prototype.setAnimationWeight=function(a,b){var c=this.animationsMap[a];c&&(c.weight=b)};ua.prototype.setAnimationTime=function(a,b){var c=this.animationsMap[a];c&&(c.time=b)};ua.prototype.getAnimationTime=function(a){var b=0;if(a=this.animationsMap[a])b=a.time;return b};ua.prototype.getAnimationDuration=function(a){var b=-1;if(a=this.animationsMap[a])b=a.duration;return b};ua.prototype.playAnimation=function(a){var b=this.animationsMap[a];b?(b.time=0,b.active=!0):console.warn("THREE.MorphBlendMesh: animation["+
14050 a+"] undefined in .playAnimation()")};ua.prototype.stopAnimation=function(a){if(a=this.animationsMap[a])a.active=!1};ua.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>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+=
14051 d.duration);var f=d.start+Q.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!==d.lastFrame?(this.morphTargetInfluences[d.currentFrame]=e*g,this.morphTargetInfluences[d.lastFrame]=(1-e)*g):this.morphTargetInfluences[d.currentFrame]=g}}};$c.prototype=Object.create(G.prototype);
14052 $c.prototype.constructor=$c;$c.prototype.isImmediateRenderObject=!0;ad.prototype=Object.create(fa.prototype);ad.prototype.constructor=ad;ad.prototype.update=function(){var a=new q,b=new q,c=new za;return function(){var d=["a","b","c"];this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);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,q=k.length;l<q;l++)for(var p=k[l],n=0,r=p.vertexNormals.length;n<
14053 r;n++){var w=p.vertexNormals[n];a.copy(h[p[d[n]]]).applyMatrix4(e);b.copy(w).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<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,
14054 b.z),g+=1;f.needsUpdate=!0;return this}}();ic.prototype=Object.create(G.prototype);ic.prototype.constructor=ic;ic.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()};ic.prototype.update=function(){var a=new q,b=new q;return function(){var c=this.light.distance?this.light.distance:1E3,d=c*Math.tan(this.light.angle);this.cone.scale.set(d,d,c);a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);this.cone.lookAt(b.sub(a));
14055 this.cone.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)}}();jc.prototype=Object.create(fa.prototype);jc.prototype.constructor=jc;jc.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};jc.prototype.update=function(){var a=new q,b=new H,c=new H;return function(){var d=this.geometry,e=d.getAttribute("position");c.getInverse(this.root.matrixWorld);for(var f=0,g=0;f<
14056 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}}();kc.prototype=Object.create(Ba.prototype);kc.prototype.constructor=kc;kc.prototype.dispose=function(){this.geometry.dispose();this.material.dispose()};kc.prototype.update=function(){this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)};
14057 lc.prototype=Object.create(G.prototype);lc.prototype.constructor=lc;lc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose();this.children[1].geometry.dispose();this.children[1].material.dispose()};lc.prototype.update=function(){var a=new q,b=new q;return function(){var c=this.children[0],d=this.children[1];if(this.light.target){a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);var e=b.clone().sub(a);
14058 c.lookAt(e);d.lookAt(e)}c.material.color.copy(this.light.color).multiplyScalar(this.light.intensity);d.material.color.copy(this.light.color).multiplyScalar(this.light.intensity);var d=.5*this.light.width,e=.5*this.light.height,c=c.geometry.getAttribute("position"),f=c.array;f[0]=d;f[1]=-e;f[2]=0;f[3]=d;f[4]=e;f[5]=0;f[6]=-d;f[7]=e;f[8]=0;f[9]=-d;f[10]=e;f[11]=0;f[12]=-d;f[13]=-e;f[14]=0;f[15]=d;f[16]=-e;f[17]=0;c.needsUpdate=!0}}();mc.prototype=Object.create(G.prototype);mc.prototype.constructor=
14059 mc;mc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};mc.prototype.update=function(){var a=new q,b=new N,c=new N;return function(){var d=this.children[0],e=d.geometry.getAttribute("color");b.copy(this.light.color).multiplyScalar(this.light.intensity);c.copy(this.light.groundColor).multiplyScalar(this.light.intensity);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());
14060 e.needsUpdate=!0}}();bd.prototype=Object.create(fa.prototype);bd.prototype.constructor=bd;Ed.prototype=Object.create(fa.prototype);Ed.prototype.constructor=Ed;cd.prototype=Object.create(fa.prototype);cd.prototype.constructor=cd;cd.prototype.update=function(){var a=new q,b=new q,c=new za;return function(){this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);for(var d=this.object.matrixWorld,e=this.geometry.attributes.position,f=this.object.geometry,g=f.vertices,f=f.faces,h=
14061 0,k=0,l=f.length;k<l;k++){var q=f[k],p=q.normal;a.copy(g[q.a]).add(g[q.b]).add(g[q.c]).divideScalar(3).applyMatrix4(d);b.copy(p).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;return this}}();nc.prototype=Object.create(G.prototype);nc.prototype.constructor=nc;nc.prototype.dispose=function(){var a=this.children[0],b=this.children[1];a.geometry.dispose();a.material.dispose();b.geometry.dispose();b.material.dispose()};
14062 nc.prototype.update=function(){var a=new q,b=new q,c=new q;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).multiplyScalar(this.light.intensity);e.lookAt(c);e.scale.z=c.length()}}();dd.prototype=Object.create(fa.prototype);dd.prototype.constructor=dd;dd.prototype.update=function(){function a(a,g,h,k){d.set(g,h,k).unproject(e);
14063 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 q,e=new sa;return function(){b=this.geometry;c=this.pointMap;e.projectionMatrix.copy(this.camera.projectionMatrix);a("c",0,0,-1);a("t",0,0,1);a("n1",-1,-1,-1);a("n2",1,-1,-1);a("n3",-1,1,-1);a("n4",1,1,-1);a("f1",-1,-1,1);a("f2",1,-1,1);a("f3",-1,1,1);a("f4",1,1,1);a("u1",.7,1.1,-1);a("u2",-.7,1.1,-1);a("u3",0,2,-1);a("cf1",-1,0,1);a("cf2",1,0,1);a("cf3",0,-1,1);a("cf4",0,1,1);a("cn1",
14064 -1,0,-1);a("cn2",1,0,-1);a("cn3",0,-1,-1);a("cn4",0,1,-1);b.getAttribute("position").needsUpdate=!0}}();oc.prototype=Object.create(fa.prototype);oc.prototype.constructor=oc;oc.prototype.update=function(){var a=new ya;return function(b){b&&b.isBox3?a.copy(b):a.setFromObject(b);if(!a.isEmpty()){b=a.min;var c=a.max,d=this.geometry.attributes.position,e=d.array;e[0]=c.x;e[1]=c.y;e[2]=c.z;e[3]=b.x;e[4]=c.y;e[5]=c.z;e[6]=b.x;e[7]=b.y;e[8]=c.z;e[9]=c.x;e[10]=b.y;e[11]=c.z;e[12]=c.x;e[13]=c.y;e[14]=b.z;e[15]=
14065 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()}}}();var Je=new D;Je.addAttribute("position",new X([0,0,0,0,1,0],3));var Ke=new Wa(0,.5,1,5,1);Ke.translate(0,-.5,0);Cb.prototype=Object.create(G.prototype);Cb.prototype.constructor=Cb;Cb.prototype.setDirection=function(){var a=new q,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(),
14066 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)};Fd.prototype=Object.create(fa.prototype);Fd.prototype.constructor=Fd;var ke=function(){function a(){}var b=new q,c=new a,
14067 d=new a,e=new a;a.prototype.init=function(a,b,c,d){this.c0=a;this.c1=c;this.c2=-3*a+3*b-2*c-d;this.c3=2*a-2*b+c+d};a.prototype.initNonuniformCatmullRom=function(a,b,c,d,e,l,p){this.init(b,c,((b-a)/e-(c-a)/(e+l)+(c-b)/l)*l,((c-b)/l-(d-b)/(l+p)+(d-c)/p)*l)};a.prototype.initCatmullRom=function(a,b,c,d,e){this.init(b,c,e*(c-a),e*(d-b))};a.prototype.calc=function(a){var b=a*a;return this.c0+this.c1*a+this.c2*b+this.c3*b*a};return wa.create(function(a){this.points=a||[];this.closed=!1},function(a){var g=
14068 this.points,h,k;k=g.length;2>k&&console.log("duh, you need at least 2 points");a*=k-(this.closed?0:1);h=Math.floor(a);a-=h;this.closed?h+=0<h?0:(Math.floor(Math.abs(h)/g.length)+1)*g.length:0===a&&h===k-1&&(h=k-2,a=1);var l,x,p;this.closed||0<h?l=g[(h-1)%k]:(b.subVectors(g[0],g[1]).add(g[0]),l=b);x=g[h%k];p=g[(h+1)%k];this.closed||h+2<k?g=g[(h+2)%k]:(b.subVectors(g[k-1],g[k-2]).add(g[k-1]),g=b);if(void 0===this.type||"centripetal"===this.type||"chordal"===this.type){var n="chordal"===this.type?.5:
14069 .25;k=Math.pow(l.distanceToSquared(x),n);h=Math.pow(x.distanceToSquared(p),n);n=Math.pow(p.distanceToSquared(g),n);1E-4>h&&(h=1);1E-4>k&&(k=h);1E-4>n&&(n=h);c.initNonuniformCatmullRom(l.x,x.x,p.x,g.x,k,h,n);d.initNonuniformCatmullRom(l.y,x.y,p.y,g.y,k,h,n);e.initNonuniformCatmullRom(l.z,x.z,p.z,g.z,k,h,n)}else"catmullrom"===this.type&&(k=void 0!==this.tension?this.tension:.5,c.initCatmullRom(l.x,x.x,p.x,g.x,k),d.initCatmullRom(l.y,x.y,p.y,g.y,k),e.initCatmullRom(l.z,x.z,p.z,g.z,k));return new q(c.calc(a),
14070 d.calc(a),e.calc(a))})}(),Nf=wa.create(function(a){console.warn("THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3");this.points=void 0===a?[]:a},function(a){var b=this.points;a*=b.length-1;var c=Math.floor(a);a-=c;var d=b[0==c?c:c-1],e=b[c],f=b[c>b.length-2?b.length-1:c+1],b=b[c>b.length-3?b.length-1:c+2],c=ed.interpolate;return new q(c(d.x,e.x,f.x,b.x,a),c(d.y,e.y,f.y,b.y,a),c(d.z,e.z,f.z,b.z,a))}),Of=wa.create(function(a,b,c,d){this.v0=a;this.v1=b;this.v2=c;this.v3=d},function(a){var b=
14071 pa.b3;return new q(b(a,this.v0.x,this.v1.x,this.v2.x,this.v3.x),b(a,this.v0.y,this.v1.y,this.v2.y,this.v3.y),b(a,this.v0.z,this.v1.z,this.v2.z,this.v3.z))}),Pf=wa.create(function(a,b,c){this.v0=a;this.v1=b;this.v2=c},function(a){var b=pa.b2;return new q(b(a,this.v0.x,this.v1.x,this.v2.x),b(a,this.v0.y,this.v1.y,this.v2.y),b(a,this.v0.z,this.v1.z,this.v2.z))}),Qf=wa.create(function(a,b){this.v1=a;this.v2=b},function(a){if(1===a)return this.v2.clone();var b=new q;b.subVectors(this.v2,this.v1);b.multiplyScalar(a);
14072 b.add(this.v1);return b});Gd.prototype=Object.create(Xa.prototype);Gd.prototype.constructor=Gd;Le.prototype=Object.create(ke.prototype);bd.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")};Object.assign(pc.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().");
14073 return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},size:function(a){console.warn("THREE.Box2: .size() has been renamed to .getSize().");return this.getSize(a)}});Object.assign(ya.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().");
14074 return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionSphere:function(a){console.warn("THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)},size:function(a){console.warn("THREE.Box3: .size() has been renamed to .getSize().");return this.getSize(a)}});gb.prototype.center=function(a){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");
14075 return this.getCenter(a)};Q.random16=function(){console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead.");return Math.random()};Object.assign(za.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)},
14076 multiplyVector3Array:function(a){console.warn("THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.");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)}});Object.assign(H.prototype,{extractPosition:function(a){console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().");
14077 return this.copyPosition(a)},flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},getPosition:function(){var a;return function(){void 0===a&&(a=new q);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().");
14078 return this.makeRotationFromQuaternion(a)},multiplyVector3:function(a){console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.");return a.applyProjection(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.");
14079 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.")},
14080 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)}});ma.prototype.isIntersectionLine=function(a){console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().");
14081 return this.intersectsLine(a)};da.prototype.multiplyVector3=function(a){console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.");return a.applyQuaternion(this)};Object.assign(bb.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().");
14082 return this.intersectsPlane(a)},isIntersectionSphere:function(a){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)}});Object.assign(Ab.prototype,{extrude:function(a){console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.");return new La(this,a)},makeGeometry:function(a){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");return new Xb(this,a)}});Object.assign(q.prototype,
14083 {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().");
14084 return this.setFromMatrixScale(a)},getColumnFromMatrix:function(a,b){console.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().");return this.setFromMatrixColumn(b,a)}});S.prototype.computeTangents=function(){console.warn("THREE.Geometry: .computeTangents() has been removed.")};Object.assign(G.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.")},
14085 translate:function(a,b){console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.");return this.translateOnAxis(b,a)}});Object.defineProperties(G.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.")},
14086 set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}});Object.defineProperties(Ac.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Ha.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)};Object.defineProperties(na.prototype,
14087 {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.");this.shadow.camera.right=a}},shadowCameraTop:{set:function(a){console.warn("THREE.Light: .shadowCameraTop is now .shadow.camera.top.");
14088 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.");this.shadow.camera.far=a}},shadowCameraVisible:{set:function(){console.warn("THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.")}},
14089 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.");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(y.prototype,
14090 {length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead.");return this.array.length}}});Object.assign(D.prototype,{addIndex:function(a){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().");this.setIndex(a)},addDrawCall:function(a,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,
14091 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.")}});Object.defineProperties(D.prototype,{drawcalls:{get:function(){console.error("THREE.BufferGeometry: .drawcalls has been renamed to .groups.");return this.groups}},offsets:{get:function(){console.warn("THREE.BufferGeometry: .offsets has been renamed to .groups.");
14092 return this.groups}}});Object.defineProperties(Dd.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.");return this}}});Object.defineProperties(W.prototype,{wrapAround:{get:function(){console.warn("THREE."+this.type+": .wrapAround has been removed.")},set:function(){console.warn("THREE."+this.type+
14093 ": .wrapAround has been removed.")}},wrapRGB:{get:function(){console.warn("THREE."+this.type+": .wrapRGB has been removed.");return new N}}});Object.defineProperties(Ca.prototype,{metal:{get:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.");return!1},set:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead")}}});Object.defineProperties(Ia.prototype,{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");
14094 return this.extensions.derivatives},set:function(a){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=a}}});oa.prototype=Object.assign(Object.create({constructor:oa,apply:function(a){console.warn("THREE.EventDispatcher: .apply is deprecated, just inherit or Object.assign the prototype to mix-in.");Object.assign(a,this)}}),oa.prototype);Object.assign(Nd.prototype,{supportsFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' ).");
14095 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' ).");return this.extensions.get("OES_standard_derivatives")},supportsCompressedTextureS3TC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( 'WEBGL_compressed_texture_s3tc' ).");
14096 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")},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.");
14097 return this.capabilities.vertexTextures},supportsInstancedArrays:function(){console.warn("THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( 'ANGLE_instanced_arrays' ).");return this.extensions.get("ANGLE_instanced_arrays")},enableScissorTest:function(a){console.warn("THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().");this.setScissorTest(a)},initMaterial:function(){console.warn("THREE.WebGLRenderer: .initMaterial() has been removed.")},addPrePlugin:function(){console.warn("THREE.WebGLRenderer: .addPrePlugin() has been removed.")},
14098 addPostPlugin:function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},updateShadowMap:function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")}});Object.defineProperties(Nd.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.");
14099 this.shadowMap.type=a}},shadowMapCullFace:{get:function(){return this.shadowMap.cullFace},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.");this.shadowMap.cullFace=a}}});Object.defineProperties(ye.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,
14100 {wrapS:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");return this.texture.wrapS},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");this.texture.wrapS=a}},wrapT:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");return this.texture.wrapT},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");this.texture.wrapT=a}},magFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");
14101 return this.texture.magFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");this.texture.magFilter=a}},minFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");return this.texture.minFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");this.texture.minFilter=a}},anisotropy:{get:function(){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");
14102 return this.texture.anisotropy},set:function(a){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");this.texture.anisotropy=a}},offset:{get:function(){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");return this.texture.offset},set:function(a){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");this.texture.offset=a}},repeat:{get:function(){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");return this.texture.repeat},
14103 set:function(a){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");this.texture.repeat=a}},format:{get:function(){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");return this.texture.format},set:function(a){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");this.texture.format=a}},type:{get:function(){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");return this.texture.type},set:function(a){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");
14104 this.texture.type=a}},generateMipmaps:{get:function(){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");return this.texture.generateMipmaps},set:function(a){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");this.texture.generateMipmaps=a}}});ec.prototype.load=function(a){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");var b=this;(new Wd).load(a,function(a){b.setBuffer(a)});return this};
14105 ae.prototype.getData=function(){console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData().");return this.getFrequencyData()};l.WebGLRenderTargetCube=Eb;l.WebGLRenderTarget=Db;l.WebGLRenderer=Nd;l.ShaderLib=Gb;l.UniformsLib=U;l.UniformsUtils=Ja;l.ShaderChunk=Z;l.FogExp2=Ib;l.Fog=Jb;l.Scene=jb;l.LensFlare=Od;l.Sprite=zc;l.LOD=Ac;l.SkinnedMesh=jd;l.Skeleton=hd;l.Bone=id;l.Mesh=Ba;l.LineSegments=fa;l.Line=Va;l.Points=Kb;l.Group=Bc;l.VideoTexture=kd;l.DataTexture=db;l.CompressedTexture=
14106 Lb;l.CubeTexture=Za;l.CanvasTexture=ld;l.DepthTexture=Cc;l.Texture=ea;l.CompressedTextureLoader=Ee;l.BinaryTextureLoader=Qd;l.DataTextureLoader=Qd;l.CubeTextureLoader=Rd;l.TextureLoader=md;l.ObjectLoader=Fe;l.MaterialLoader=Ad;l.BufferGeometryLoader=Sd;l.DefaultLoadingManager=va;l.LoadingManager=Pd;l.JSONLoader=Td;l.ImageLoader=Vc;l.FontLoader=Ge;l.FileLoader=Ma;l.Loader=wb;l.Cache=ne;l.AudioLoader=Wd;l.SpotLightShadow=od;l.SpotLight=pd;l.PointLight=qd;l.RectAreaLight=Xd;l.HemisphereLight=nd;l.DirectionalLightShadow=
14107 rd;l.DirectionalLight=sd;l.AmbientLight=td;l.LightShadow=tb;l.Light=na;l.StereoCamera=He;l.PerspectiveCamera=Ha;l.OrthographicCamera=Hb;l.CubeCamera=Bd;l.Camera=sa;l.AudioListener=Yd;l.PositionalAudio=$d;l.AudioContext=Zd;l.AudioAnalyser=ae;l.Audio=ec;l.VectorKeyframeTrack=cc;l.StringKeyframeTrack=xd;l.QuaternionKeyframeTrack=Xc;l.NumberKeyframeTrack=dc;l.ColorKeyframeTrack=zd;l.BooleanKeyframeTrack=yd;l.PropertyMixer=Cd;l.PropertyBinding=ka;l.KeyframeTrack=vb;l.AnimationUtils=ba;l.AnimationObjectGroup=
14108 be;l.AnimationMixer=de;l.AnimationClip=ta;l.Uniform=Dd;l.InstancedBufferGeometry=Bb;l.BufferGeometry=D;l.GeometryIdCount=function(){return Kd++};l.Geometry=S;l.InterleavedBufferAttribute=ee;l.InstancedInterleavedBuffer=gc;l.InterleavedBuffer=fc;l.InstancedBufferAttribute=hc;l.Face3=ha;l.Object3D=G;l.Raycaster=fe;l.Layers=gd;l.EventDispatcher=oa;l.Clock=he;l.QuaternionLinearInterpolant=wd;l.LinearInterpolant=Wc;l.DiscreteInterpolant=vd;l.CubicInterpolant=ud;l.Interpolant=qa;l.Triangle=Aa;l.Spline=
14109 function(a){function b(a,b,c,d,e,f,g){a=.5*(c-a);d=.5*(d-b);return(2*(b-c)+a+d)*g+(-3*(b-c)-2*a-d)*f+a*e+b}this.points=a;var c=[],d={x:0,y:0,z:0},e,f,g,h,k,l,x,p,n;this.initFromArray=function(a){this.points=[];for(var b=0;b<a.length;b++)this.points[b]={x:a[b][0],y:a[b][1],z:a[b][2]}};this.getPoint=function(a){e=(this.points.length-1)*a;f=Math.floor(e);g=e-f;c[0]=0===f?f:f-1;c[1]=f;c[2]=f>this.points.length-2?this.points.length-1:f+1;c[3]=f>this.points.length-3?this.points.length-1:f+2;l=this.points[c[0]];
14110 x=this.points[c[1]];p=this.points[c[2]];n=this.points[c[3]];h=g*g;k=g*h;d.x=b(l.x,x.x,p.x,n.x,g,h,k);d.y=b(l.y,x.y,p.y,n.y,g,h,k);d.z=b(l.z,x.z,p.z,n.z,g,h,k);return d};this.getControlPointsArray=function(){var a,b,c=this.points.length,d=[];for(a=0;a<c;a++)b=this.points[a],d[a]=[b.x,b.y,b.z];return d};this.getLength=function(a){var b,c,d,e=0,f=new q,g=new q,h=[],k=0;h[0]=0;a||(a=100);c=this.points.length*a;f.copy(this.points[0]);for(a=1;a<c;a++)b=a/c,d=this.getPoint(b),g.copy(d),k+=g.distanceTo(f),
14111 f.copy(d),b*=this.points.length-1,b=Math.floor(b),b!==e&&(h[b]=k,e=b);h[h.length]=k;return{chunks:h,total:k}};this.reparametrizeByArcLength=function(a){var b,c,d,e,f,g,h=[],k=new q,l=this.getLength();h.push(k.copy(this.points[0]).clone());for(b=1;b<this.points.length;b++){c=l.chunks[b]-l.chunks[b-1];g=Math.ceil(a*c/l.total);e=(b-1)/(this.points.length-1);f=b/(this.points.length-1);for(c=1;c<g-1;c++)d=e+1/g*c*(f-e),d=this.getPoint(d),h.push(k.copy(d).clone());h.push(k.copy(this.points[b]).clone())}this.points=
14112 h}};l.Math=Q;l.Spherical=ie;l.Cylindrical=je;l.Plane=ma;l.Frustum=qc;l.Sphere=Fa;l.Ray=bb;l.Matrix4=H;l.Matrix3=za;l.Box3=ya;l.Box2=pc;l.Line3=gb;l.Euler=cb;l.Vector4=ga;l.Vector3=q;l.Vector2=C;l.Quaternion=da;l.Color=N;l.MorphBlendMesh=ua;l.ImmediateRenderObject=$c;l.VertexNormalsHelper=ad;l.SpotLightHelper=ic;l.SkeletonHelper=jc;l.PointLightHelper=kc;l.RectAreaLightHelper=lc;l.HemisphereLightHelper=mc;l.GridHelper=bd;l.PolarGridHelper=Ed;l.FaceNormalsHelper=cd;l.DirectionalLightHelper=nc;l.CameraHelper=
14113 dd;l.BoxHelper=oc;l.ArrowHelper=Cb;l.AxisHelper=Fd;l.CatmullRomCurve3=ke;l.SplineCurve3=Nf;l.CubicBezierCurve3=Of;l.QuadraticBezierCurve3=Pf;l.LineCurve3=Qf;l.ArcCurve=Gd;l.EllipseCurve=Xa;l.SplineCurve=xb;l.CubicBezierCurve=yb;l.QuadraticBezierCurve=zb;l.LineCurve=Qa;l.Shape=Ab;l.ShapePath=Ud;l.Path=Zc;l.Font=Vd;l.CurvePath=Yc;l.Curve=wa;l.ShapeUtils=pa;l.SceneUtils={createMultiMaterialObject:function(a,b){for(var c=new Bc,d=0,e=b.length;d<e;d++)c.add(new Ba(a,b[d]));return c},detach:function(a,
14114 b,c){a.applyMatrix(b.matrixWorld);b.remove(a);c.add(a)},attach:function(a,b,c){var d=new H;d.getInverse(c.matrixWorld);a.applyMatrix(d);b.remove(a);c.add(a)}};l.CurveUtils=ed;l.WireframeGeometry=Mb;l.ParametricGeometry=Dc;l.ParametricBufferGeometry=Nb;l.TetrahedronGeometry=Ec;l.TetrahedronBufferGeometry=Ob;l.OctahedronGeometry=Fc;l.OctahedronBufferGeometry=lb;l.IcosahedronGeometry=Gc;l.IcosahedronBufferGeometry=Pb;l.DodecahedronGeometry=Hc;l.DodecahedronBufferGeometry=Qb;l.PolyhedronGeometry=Ic;l.PolyhedronBufferGeometry=
14115 xa;l.TubeGeometry=Jc;l.TubeBufferGeometry=Rb;l.TorusKnotGeometry=Kc;l.TorusKnotBufferGeometry=Sb;l.TorusGeometry=Lc;l.TorusBufferGeometry=Tb;l.TextGeometry=Mc;l.SphereBufferGeometry=mb;l.SphereGeometry=Nc;l.RingGeometry=Oc;l.RingBufferGeometry=Ub;l.PlaneBufferGeometry=ib;l.PlaneGeometry=Pc;l.LatheGeometry=Qc;l.LatheBufferGeometry=Vb;l.ShapeGeometry=Xb;l.ShapeBufferGeometry=Wb;l.ExtrudeGeometry=La;l.EdgesGeometry=Yb;l.ConeGeometry=Rc;l.ConeBufferGeometry=Sc;l.CylinderGeometry=nb;l.CylinderBufferGeometry=
14116 Wa;l.CircleBufferGeometry=Zb;l.CircleGeometry=Tc;l.BoxBufferGeometry=hb;l.BoxGeometry=$b;l.ShadowMaterial=ac;l.SpriteMaterial=kb;l.RawShaderMaterial=bc;l.ShaderMaterial=Ia;l.PointsMaterial=Oa;l.MultiMaterial=Uc;l.MeshPhysicalMaterial=ob;l.MeshStandardMaterial=Pa;l.MeshPhongMaterial=Ca;l.MeshToonMaterial=pb;l.MeshNormalMaterial=qb;l.MeshLambertMaterial=rb;l.MeshDepthMaterial=ab;l.MeshBasicMaterial=Ka;l.LineDashedMaterial=sb;l.LineBasicMaterial=ia;l.Material=W;l.Float64BufferAttribute=wc;l.Float32BufferAttribute=
14117 X;l.Uint32BufferAttribute=Ua;l.Int32BufferAttribute=vc;l.Uint16BufferAttribute=Ra;l.Int16BufferAttribute=uc;l.Uint8ClampedBufferAttribute=tc;l.Uint8BufferAttribute=sc;l.Int8BufferAttribute=rc;l.BufferAttribute=y;l.REVISION="83";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;
14118 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.BlendingMode=Me;l.AddEquation=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=
14119 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=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=
14120 304;l.SphericalReflectionMapping=305;l.CubeUVReflectionMapping=306;l.CubeUVRefractionMapping=307;l.TextureMapping=Ne;l.RepeatWrapping=1E3;l.ClampToEdgeWrapping=1001;l.MirroredRepeatWrapping=1002;l.TextureWrapping=le;l.NearestFilter=1003;l.NearestMipMapNearestFilter=1004;l.NearestMipMapLinearFilter=1005;l.LinearFilter=1006;l.LinearMipMapNearestFilter=1007;l.LinearMipMapLinearFilter=1008;l.TextureFilter=me;l.UnsignedByteType=1009;l.ByteType=1010;l.ShortType=1011;l.UnsignedShortType=1012;l.IntType=1013;
14121 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=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=
14122 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=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=
14123 3005;l.RGBDEncoding=3006;l.BasicDepthPacking=3200;l.RGBADepthPacking=3201;l.CubeGeometry=$b;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 ha(a,b,c,e,f,g)};l.LineStrip=0;l.LinePieces=1;l.MeshFaceMaterial=function(a){console.warn("THREE.MeshFaceMaterial has been renamed to THREE.MultiMaterial.");return new Uc(a)};l.PointCloud=function(a,b){console.warn("THREE.PointCloud has been renamed to THREE.Points.");return new Kb(a,
14124 b)};l.Particle=function(a){console.warn("THREE.Particle has been renamed to THREE.Sprite.");return new zc(a)};l.ParticleSystem=function(a,b){console.warn("THREE.ParticleSystem has been renamed to THREE.Points.");return new Kb(a,b)};l.PointCloudMaterial=function(a){console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.");return new Oa(a)};l.ParticleBasicMaterial=function(a){console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.");return new Oa(a)};
14125 l.ParticleSystemMaterial=function(a){console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.");return new Oa(a)};l.Vertex=function(a,b,c){console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead.");return new q(a,b,c)};l.DynamicBufferAttribute=function(a,b){console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.");return(new y(a,b)).setDynamic(!0)};l.Int8Attribute=function(a,b){console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.");
14126 return new rc(a,b)};l.Uint8Attribute=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=
14127 function(a,b){console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.");return new Ra(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 Ua(a,b)};l.Float32Attribute=function(a,b){console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.");
14128 return new X(a,b)};l.Float64Attribute=function(a,b){console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.");return new wc(a,b)};l.ClosedSplineCurve3=Le;l.BoundingBoxHelper=function(a,b){console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.");return new oc(a,b)};l.EdgesHelper=function(a,b){console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.");return new fa(new Yb(a.geometry),new ia({color:void 0!==
14129 b?b:16777215}))};l.WireframeHelper=function(a,b){console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.");return new fa(new Mb(a.geometry),new ia({color:void 0!==b?b:16777215}))};l.XHRLoader=function(a){console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader.");return new Ma(a)};l.GeometryUtils={merge:function(a,b,c){console.warn("THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.");
14130 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.");var e=new md;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a},
14131 loadTextureCube:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");var e=new Rd;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.")}};
14132 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");
14133 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})});
14135 },{}],176:[function(require,module,exports){
14136 // Underscore.js 1.8.3
14137 // http://underscorejs.org
14138 // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
14139 // Underscore may be freely distributed under the MIT license.
14146 // Establish the root object, `window` in the browser, or `exports` on the server.
14149 // Save the previous value of the `_` variable.
14150 var previousUnderscore = root._;
14152 // Save bytes in the minified (but not gzipped) version:
14153 var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
14155 // Create quick reference variables for speed access to core prototypes.
14157 push = ArrayProto.push,
14158 slice = ArrayProto.slice,
14159 toString = ObjProto.toString,
14160 hasOwnProperty = ObjProto.hasOwnProperty;
14162 // All **ECMAScript 5** native function implementations that we hope to use
14163 // are declared here.
14165 nativeIsArray = Array.isArray,
14166 nativeKeys = Object.keys,
14167 nativeBind = FuncProto.bind,
14168 nativeCreate = Object.create;
14170 // Naked function reference for surrogate-prototype-swapping.
14171 var Ctor = function(){};
14173 // Create a safe reference to the Underscore object for use below.
14174 var _ = function(obj) {
14175 if (obj instanceof _) return obj;
14176 if (!(this instanceof _)) return new _(obj);
14177 this._wrapped = obj;
14180 // Export the Underscore object for **Node.js**, with
14181 // backwards-compatibility for the old `require()` API. If we're in
14182 // the browser, add `_` as a global object.
14183 if (typeof exports !== 'undefined') {
14184 if (typeof module !== 'undefined' && module.exports) {
14185 exports = module.exports = _;
14192 // Current version.
14193 _.VERSION = '1.8.3';
14195 // Internal function that returns an efficient (for current engines) version
14196 // of the passed-in callback, to be repeatedly applied in other Underscore
14198 var optimizeCb = function(func, context, argCount) {
14199 if (context === void 0) return func;
14200 switch (argCount == null ? 3 : argCount) {
14201 case 1: return function(value) {
14202 return func.call(context, value);
14204 case 2: return function(value, other) {
14205 return func.call(context, value, other);
14207 case 3: return function(value, index, collection) {
14208 return func.call(context, value, index, collection);
14210 case 4: return function(accumulator, value, index, collection) {
14211 return func.call(context, accumulator, value, index, collection);
14214 return function() {
14215 return func.apply(context, arguments);
14219 // A mostly-internal function to generate callbacks that can be applied
14220 // to each element in a collection, returning the desired result — either
14221 // identity, an arbitrary callback, a property matcher, or a property accessor.
14222 var cb = function(value, context, argCount) {
14223 if (value == null) return _.identity;
14224 if (_.isFunction(value)) return optimizeCb(value, context, argCount);
14225 if (_.isObject(value)) return _.matcher(value);
14226 return _.property(value);
14228 _.iteratee = function(value, context) {
14229 return cb(value, context, Infinity);
14232 // An internal function for creating assigner functions.
14233 var createAssigner = function(keysFunc, undefinedOnly) {
14234 return function(obj) {
14235 var length = arguments.length;
14236 if (length < 2 || obj == null) return obj;
14237 for (var index = 1; index < length; index++) {
14238 var source = arguments[index],
14239 keys = keysFunc(source),
14241 for (var i = 0; i < l; i++) {
14243 if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
14250 // An internal function for creating a new object that inherits from another.
14251 var baseCreate = function(prototype) {
14252 if (!_.isObject(prototype)) return {};
14253 if (nativeCreate) return nativeCreate(prototype);
14254 Ctor.prototype = prototype;
14255 var result = new Ctor;
14256 Ctor.prototype = null;
14260 var property = function(key) {
14261 return function(obj) {
14262 return obj == null ? void 0 : obj[key];
14266 // Helper for collection methods to determine whether a collection
14267 // should be iterated as an array or as an object
14268 // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
14269 // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
14270 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
14271 var getLength = property('length');
14272 var isArrayLike = function(collection) {
14273 var length = getLength(collection);
14274 return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
14277 // Collection Functions
14278 // --------------------
14280 // The cornerstone, an `each` implementation, aka `forEach`.
14281 // Handles raw objects in addition to array-likes. Treats all
14282 // sparse array-likes as if they were dense.
14283 _.each = _.forEach = function(obj, iteratee, context) {
14284 iteratee = optimizeCb(iteratee, context);
14286 if (isArrayLike(obj)) {
14287 for (i = 0, length = obj.length; i < length; i++) {
14288 iteratee(obj[i], i, obj);
14291 var keys = _.keys(obj);
14292 for (i = 0, length = keys.length; i < length; i++) {
14293 iteratee(obj[keys[i]], keys[i], obj);
14299 // Return the results of applying the iteratee to each element.
14300 _.map = _.collect = function(obj, iteratee, context) {
14301 iteratee = cb(iteratee, context);
14302 var keys = !isArrayLike(obj) && _.keys(obj),
14303 length = (keys || obj).length,
14304 results = Array(length);
14305 for (var index = 0; index < length; index++) {
14306 var currentKey = keys ? keys[index] : index;
14307 results[index] = iteratee(obj[currentKey], currentKey, obj);
14312 // Create a reducing function iterating left or right.
14313 function createReduce(dir) {
14314 // Optimized iterator function as using arguments.length
14315 // in the main function will deoptimize the, see #1991.
14316 function iterator(obj, iteratee, memo, keys, index, length) {
14317 for (; index >= 0 && index < length; index += dir) {
14318 var currentKey = keys ? keys[index] : index;
14319 memo = iteratee(memo, obj[currentKey], currentKey, obj);
14324 return function(obj, iteratee, memo, context) {
14325 iteratee = optimizeCb(iteratee, context, 4);
14326 var keys = !isArrayLike(obj) && _.keys(obj),
14327 length = (keys || obj).length,
14328 index = dir > 0 ? 0 : length - 1;
14329 // Determine the initial value if none is provided.
14330 if (arguments.length < 3) {
14331 memo = obj[keys ? keys[index] : index];
14334 return iterator(obj, iteratee, memo, keys, index, length);
14338 // **Reduce** builds up a single result from a list of values, aka `inject`,
14340 _.reduce = _.foldl = _.inject = createReduce(1);
14342 // The right-associative version of reduce, also known as `foldr`.
14343 _.reduceRight = _.foldr = createReduce(-1);
14345 // Return the first value which passes a truth test. Aliased as `detect`.
14346 _.find = _.detect = function(obj, predicate, context) {
14348 if (isArrayLike(obj)) {
14349 key = _.findIndex(obj, predicate, context);
14351 key = _.findKey(obj, predicate, context);
14353 if (key !== void 0 && key !== -1) return obj[key];
14356 // Return all the elements that pass a truth test.
14357 // Aliased as `select`.
14358 _.filter = _.select = function(obj, predicate, context) {
14360 predicate = cb(predicate, context);
14361 _.each(obj, function(value, index, list) {
14362 if (predicate(value, index, list)) results.push(value);
14367 // Return all the elements for which a truth test fails.
14368 _.reject = function(obj, predicate, context) {
14369 return _.filter(obj, _.negate(cb(predicate)), context);
14372 // Determine whether all of the elements match a truth test.
14373 // Aliased as `all`.
14374 _.every = _.all = function(obj, predicate, context) {
14375 predicate = cb(predicate, context);
14376 var keys = !isArrayLike(obj) && _.keys(obj),
14377 length = (keys || obj).length;
14378 for (var index = 0; index < length; index++) {
14379 var currentKey = keys ? keys[index] : index;
14380 if (!predicate(obj[currentKey], currentKey, obj)) return false;
14385 // Determine if at least one element in the object matches a truth test.
14386 // Aliased as `any`.
14387 _.some = _.any = function(obj, predicate, context) {
14388 predicate = cb(predicate, context);
14389 var keys = !isArrayLike(obj) && _.keys(obj),
14390 length = (keys || obj).length;
14391 for (var index = 0; index < length; index++) {
14392 var currentKey = keys ? keys[index] : index;
14393 if (predicate(obj[currentKey], currentKey, obj)) return true;
14398 // Determine if the array or object contains a given item (using `===`).
14399 // Aliased as `includes` and `include`.
14400 _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
14401 if (!isArrayLike(obj)) obj = _.values(obj);
14402 if (typeof fromIndex != 'number' || guard) fromIndex = 0;
14403 return _.indexOf(obj, item, fromIndex) >= 0;
14406 // Invoke a method (with arguments) on every item in a collection.
14407 _.invoke = function(obj, method) {
14408 var args = slice.call(arguments, 2);
14409 var isFunc = _.isFunction(method);
14410 return _.map(obj, function(value) {
14411 var func = isFunc ? method : value[method];
14412 return func == null ? func : func.apply(value, args);
14416 // Convenience version of a common use case of `map`: fetching a property.
14417 _.pluck = function(obj, key) {
14418 return _.map(obj, _.property(key));
14421 // Convenience version of a common use case of `filter`: selecting only objects
14422 // containing specific `key:value` pairs.
14423 _.where = function(obj, attrs) {
14424 return _.filter(obj, _.matcher(attrs));
14427 // Convenience version of a common use case of `find`: getting the first object
14428 // containing specific `key:value` pairs.
14429 _.findWhere = function(obj, attrs) {
14430 return _.find(obj, _.matcher(attrs));
14433 // Return the maximum element (or element-based computation).
14434 _.max = function(obj, iteratee, context) {
14435 var result = -Infinity, lastComputed = -Infinity,
14437 if (iteratee == null && obj != null) {
14438 obj = isArrayLike(obj) ? obj : _.values(obj);
14439 for (var i = 0, length = obj.length; i < length; i++) {
14441 if (value > result) {
14446 iteratee = cb(iteratee, context);
14447 _.each(obj, function(value, index, list) {
14448 computed = iteratee(value, index, list);
14449 if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
14451 lastComputed = computed;
14458 // Return the minimum element (or element-based computation).
14459 _.min = function(obj, iteratee, context) {
14460 var result = Infinity, lastComputed = Infinity,
14462 if (iteratee == null && obj != null) {
14463 obj = isArrayLike(obj) ? obj : _.values(obj);
14464 for (var i = 0, length = obj.length; i < length; i++) {
14466 if (value < result) {
14471 iteratee = cb(iteratee, context);
14472 _.each(obj, function(value, index, list) {
14473 computed = iteratee(value, index, list);
14474 if (computed < lastComputed || computed === Infinity && result === Infinity) {
14476 lastComputed = computed;
14483 // Shuffle a collection, using the modern version of the
14484 // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
14485 _.shuffle = function(obj) {
14486 var set = isArrayLike(obj) ? obj : _.values(obj);
14487 var length = set.length;
14488 var shuffled = Array(length);
14489 for (var index = 0, rand; index < length; index++) {
14490 rand = _.random(0, index);
14491 if (rand !== index) shuffled[index] = shuffled[rand];
14492 shuffled[rand] = set[index];
14497 // Sample **n** random values from a collection.
14498 // If **n** is not specified, returns a single random element.
14499 // The internal `guard` argument allows it to work with `map`.
14500 _.sample = function(obj, n, guard) {
14501 if (n == null || guard) {
14502 if (!isArrayLike(obj)) obj = _.values(obj);
14503 return obj[_.random(obj.length - 1)];
14505 return _.shuffle(obj).slice(0, Math.max(0, n));
14508 // Sort the object's values by a criterion produced by an iteratee.
14509 _.sortBy = function(obj, iteratee, context) {
14510 iteratee = cb(iteratee, context);
14511 return _.pluck(_.map(obj, function(value, index, list) {
14515 criteria: iteratee(value, index, list)
14517 }).sort(function(left, right) {
14518 var a = left.criteria;
14519 var b = right.criteria;
14521 if (a > b || a === void 0) return 1;
14522 if (a < b || b === void 0) return -1;
14524 return left.index - right.index;
14528 // An internal function used for aggregate "group by" operations.
14529 var group = function(behavior) {
14530 return function(obj, iteratee, context) {
14532 iteratee = cb(iteratee, context);
14533 _.each(obj, function(value, index) {
14534 var key = iteratee(value, index, obj);
14535 behavior(result, value, key);
14541 // Groups the object's values by a criterion. Pass either a string attribute
14542 // to group by, or a function that returns the criterion.
14543 _.groupBy = group(function(result, value, key) {
14544 if (_.has(result, key)) result[key].push(value); else result[key] = [value];
14547 // Indexes the object's values by a criterion, similar to `groupBy`, but for
14548 // when you know that your index values will be unique.
14549 _.indexBy = group(function(result, value, key) {
14550 result[key] = value;
14553 // Counts instances of an object that group by a certain criterion. Pass
14554 // either a string attribute to count by, or a function that returns the
14556 _.countBy = group(function(result, value, key) {
14557 if (_.has(result, key)) result[key]++; else result[key] = 1;
14560 // Safely create a real, live array from anything iterable.
14561 _.toArray = function(obj) {
14562 if (!obj) return [];
14563 if (_.isArray(obj)) return slice.call(obj);
14564 if (isArrayLike(obj)) return _.map(obj, _.identity);
14565 return _.values(obj);
14568 // Return the number of elements in an object.
14569 _.size = function(obj) {
14570 if (obj == null) return 0;
14571 return isArrayLike(obj) ? obj.length : _.keys(obj).length;
14574 // Split a collection into two arrays: one whose elements all satisfy the given
14575 // predicate, and one whose elements all do not satisfy the predicate.
14576 _.partition = function(obj, predicate, context) {
14577 predicate = cb(predicate, context);
14578 var pass = [], fail = [];
14579 _.each(obj, function(value, key, obj) {
14580 (predicate(value, key, obj) ? pass : fail).push(value);
14582 return [pass, fail];
14588 // Get the first element of an array. Passing **n** will return the first N
14589 // values in the array. Aliased as `head` and `take`. The **guard** check
14590 // allows it to work with `_.map`.
14591 _.first = _.head = _.take = function(array, n, guard) {
14592 if (array == null) return void 0;
14593 if (n == null || guard) return array[0];
14594 return _.initial(array, array.length - n);
14597 // Returns everything but the last entry of the array. Especially useful on
14598 // the arguments object. Passing **n** will return all the values in
14599 // the array, excluding the last N.
14600 _.initial = function(array, n, guard) {
14601 return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
14604 // Get the last element of an array. Passing **n** will return the last N
14605 // values in the array.
14606 _.last = function(array, n, guard) {
14607 if (array == null) return void 0;
14608 if (n == null || guard) return array[array.length - 1];
14609 return _.rest(array, Math.max(0, array.length - n));
14612 // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
14613 // Especially useful on the arguments object. Passing an **n** will return
14614 // the rest N values in the array.
14615 _.rest = _.tail = _.drop = function(array, n, guard) {
14616 return slice.call(array, n == null || guard ? 1 : n);
14619 // Trim out all falsy values from an array.
14620 _.compact = function(array) {
14621 return _.filter(array, _.identity);
14624 // Internal implementation of a recursive `flatten` function.
14625 var flatten = function(input, shallow, strict, startIndex) {
14626 var output = [], idx = 0;
14627 for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
14628 var value = input[i];
14629 if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
14630 //flatten current level of array or arguments object
14631 if (!shallow) value = flatten(value, shallow, strict);
14632 var j = 0, len = value.length;
14633 output.length += len;
14635 output[idx++] = value[j++];
14637 } else if (!strict) {
14638 output[idx++] = value;
14644 // Flatten out an array, either recursively (by default), or just one level.
14645 _.flatten = function(array, shallow) {
14646 return flatten(array, shallow, false);
14649 // Return a version of the array that does not contain the specified value(s).
14650 _.without = function(array) {
14651 return _.difference(array, slice.call(arguments, 1));
14654 // Produce a duplicate-free version of the array. If the array has already
14655 // been sorted, you have the option of using a faster algorithm.
14656 // Aliased as `unique`.
14657 _.uniq = _.unique = function(array, isSorted, iteratee, context) {
14658 if (!_.isBoolean(isSorted)) {
14659 context = iteratee;
14660 iteratee = isSorted;
14663 if (iteratee != null) iteratee = cb(iteratee, context);
14666 for (var i = 0, length = getLength(array); i < length; i++) {
14667 var value = array[i],
14668 computed = iteratee ? iteratee(value, i, array) : value;
14670 if (!i || seen !== computed) result.push(value);
14672 } else if (iteratee) {
14673 if (!_.contains(seen, computed)) {
14674 seen.push(computed);
14675 result.push(value);
14677 } else if (!_.contains(result, value)) {
14678 result.push(value);
14684 // Produce an array that contains the union: each distinct element from all of
14685 // the passed-in arrays.
14686 _.union = function() {
14687 return _.uniq(flatten(arguments, true, true));
14690 // Produce an array that contains every item shared between all the
14691 // passed-in arrays.
14692 _.intersection = function(array) {
14694 var argsLength = arguments.length;
14695 for (var i = 0, length = getLength(array); i < length; i++) {
14696 var item = array[i];
14697 if (_.contains(result, item)) continue;
14698 for (var j = 1; j < argsLength; j++) {
14699 if (!_.contains(arguments[j], item)) break;
14701 if (j === argsLength) result.push(item);
14706 // Take the difference between one array and a number of other arrays.
14707 // Only the elements present in just the first array will remain.
14708 _.difference = function(array) {
14709 var rest = flatten(arguments, true, true, 1);
14710 return _.filter(array, function(value){
14711 return !_.contains(rest, value);
14715 // Zip together multiple lists into a single array -- elements that share
14716 // an index go together.
14717 _.zip = function() {
14718 return _.unzip(arguments);
14721 // Complement of _.zip. Unzip accepts an array of arrays and groups
14722 // each array's elements on shared indices
14723 _.unzip = function(array) {
14724 var length = array && _.max(array, getLength).length || 0;
14725 var result = Array(length);
14727 for (var index = 0; index < length; index++) {
14728 result[index] = _.pluck(array, index);
14733 // Converts lists into objects. Pass either a single array of `[key, value]`
14734 // pairs, or two parallel arrays of the same length -- one of keys, and one of
14735 // the corresponding values.
14736 _.object = function(list, values) {
14738 for (var i = 0, length = getLength(list); i < length; i++) {
14740 result[list[i]] = values[i];
14742 result[list[i][0]] = list[i][1];
14748 // Generator function to create the findIndex and findLastIndex functions
14749 function createPredicateIndexFinder(dir) {
14750 return function(array, predicate, context) {
14751 predicate = cb(predicate, context);
14752 var length = getLength(array);
14753 var index = dir > 0 ? 0 : length - 1;
14754 for (; index >= 0 && index < length; index += dir) {
14755 if (predicate(array[index], index, array)) return index;
14761 // Returns the first index on an array-like that passes a predicate test
14762 _.findIndex = createPredicateIndexFinder(1);
14763 _.findLastIndex = createPredicateIndexFinder(-1);
14765 // Use a comparator function to figure out the smallest index at which
14766 // an object should be inserted so as to maintain order. Uses binary search.
14767 _.sortedIndex = function(array, obj, iteratee, context) {
14768 iteratee = cb(iteratee, context, 1);
14769 var value = iteratee(obj);
14770 var low = 0, high = getLength(array);
14771 while (low < high) {
14772 var mid = Math.floor((low + high) / 2);
14773 if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
14778 // Generator function to create the indexOf and lastIndexOf functions
14779 function createIndexFinder(dir, predicateFind, sortedIndex) {
14780 return function(array, item, idx) {
14781 var i = 0, length = getLength(array);
14782 if (typeof idx == 'number') {
14784 i = idx >= 0 ? idx : Math.max(idx + length, i);
14786 length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
14788 } else if (sortedIndex && idx && length) {
14789 idx = sortedIndex(array, item);
14790 return array[idx] === item ? idx : -1;
14792 if (item !== item) {
14793 idx = predicateFind(slice.call(array, i, length), _.isNaN);
14794 return idx >= 0 ? idx + i : -1;
14796 for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
14797 if (array[idx] === item) return idx;
14803 // Return the position of the first occurrence of an item in an array,
14804 // or -1 if the item is not included in the array.
14805 // If the array is large and already in sort order, pass `true`
14806 // for **isSorted** to use binary search.
14807 _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
14808 _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
14810 // Generate an integer Array containing an arithmetic progression. A port of
14811 // the native Python `range()` function. See
14812 // [the Python documentation](http://docs.python.org/library/functions.html#range).
14813 _.range = function(start, stop, step) {
14814 if (stop == null) {
14820 var length = Math.max(Math.ceil((stop - start) / step), 0);
14821 var range = Array(length);
14823 for (var idx = 0; idx < length; idx++, start += step) {
14824 range[idx] = start;
14830 // Function (ahem) Functions
14831 // ------------------
14833 // Determines whether to execute a function as a constructor
14834 // or a normal function with the provided arguments
14835 var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
14836 if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
14837 var self = baseCreate(sourceFunc.prototype);
14838 var result = sourceFunc.apply(self, args);
14839 if (_.isObject(result)) return result;
14843 // Create a function bound to a given object (assigning `this`, and arguments,
14844 // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
14846 _.bind = function(func, context) {
14847 if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
14848 if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
14849 var args = slice.call(arguments, 2);
14850 var bound = function() {
14851 return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
14856 // Partially apply a function by creating a version that has had some of its
14857 // arguments pre-filled, without changing its dynamic `this` context. _ acts
14858 // as a placeholder, allowing any combination of arguments to be pre-filled.
14859 _.partial = function(func) {
14860 var boundArgs = slice.call(arguments, 1);
14861 var bound = function() {
14862 var position = 0, length = boundArgs.length;
14863 var args = Array(length);
14864 for (var i = 0; i < length; i++) {
14865 args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
14867 while (position < arguments.length) args.push(arguments[position++]);
14868 return executeBound(func, bound, this, this, args);
14873 // Bind a number of an object's methods to that object. Remaining arguments
14874 // are the method names to be bound. Useful for ensuring that all callbacks
14875 // defined on an object belong to it.
14876 _.bindAll = function(obj) {
14877 var i, length = arguments.length, key;
14878 if (length <= 1) throw new Error('bindAll must be passed function names');
14879 for (i = 1; i < length; i++) {
14880 key = arguments[i];
14881 obj[key] = _.bind(obj[key], obj);
14886 // Memoize an expensive function by storing its results.
14887 _.memoize = function(func, hasher) {
14888 var memoize = function(key) {
14889 var cache = memoize.cache;
14890 var address = '' + (hasher ? hasher.apply(this, arguments) : key);
14891 if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
14892 return cache[address];
14894 memoize.cache = {};
14898 // Delays a function for the given number of milliseconds, and then calls
14899 // it with the arguments supplied.
14900 _.delay = function(func, wait) {
14901 var args = slice.call(arguments, 2);
14902 return setTimeout(function(){
14903 return func.apply(null, args);
14907 // Defers a function, scheduling it to run after the current call stack has
14909 _.defer = _.partial(_.delay, _, 1);
14911 // Returns a function, that, when invoked, will only be triggered at most once
14912 // during a given window of time. Normally, the throttled function will run
14913 // as much as it can, without ever going more than once per `wait` duration;
14914 // but if you'd like to disable the execution on the leading edge, pass
14915 // `{leading: false}`. To disable execution on the trailing edge, ditto.
14916 _.throttle = function(func, wait, options) {
14917 var context, args, result;
14918 var timeout = null;
14920 if (!options) options = {};
14921 var later = function() {
14922 previous = options.leading === false ? 0 : _.now();
14924 result = func.apply(context, args);
14925 if (!timeout) context = args = null;
14927 return function() {
14929 if (!previous && options.leading === false) previous = now;
14930 var remaining = wait - (now - previous);
14933 if (remaining <= 0 || remaining > wait) {
14935 clearTimeout(timeout);
14939 result = func.apply(context, args);
14940 if (!timeout) context = args = null;
14941 } else if (!timeout && options.trailing !== false) {
14942 timeout = setTimeout(later, remaining);
14948 // Returns a function, that, as long as it continues to be invoked, will not
14949 // be triggered. The function will be called after it stops being called for
14950 // N milliseconds. If `immediate` is passed, trigger the function on the
14951 // leading edge, instead of the trailing.
14952 _.debounce = function(func, wait, immediate) {
14953 var timeout, args, context, timestamp, result;
14955 var later = function() {
14956 var last = _.now() - timestamp;
14958 if (last < wait && last >= 0) {
14959 timeout = setTimeout(later, wait - last);
14963 result = func.apply(context, args);
14964 if (!timeout) context = args = null;
14969 return function() {
14972 timestamp = _.now();
14973 var callNow = immediate && !timeout;
14974 if (!timeout) timeout = setTimeout(later, wait);
14976 result = func.apply(context, args);
14977 context = args = null;
14984 // Returns the first function passed as an argument to the second,
14985 // allowing you to adjust arguments, run code before and after, and
14986 // conditionally execute the original function.
14987 _.wrap = function(func, wrapper) {
14988 return _.partial(wrapper, func);
14991 // Returns a negated version of the passed-in predicate.
14992 _.negate = function(predicate) {
14993 return function() {
14994 return !predicate.apply(this, arguments);
14998 // Returns a function that is the composition of a list of functions, each
14999 // consuming the return value of the function that follows.
15000 _.compose = function() {
15001 var args = arguments;
15002 var start = args.length - 1;
15003 return function() {
15005 var result = args[start].apply(this, arguments);
15006 while (i--) result = args[i].call(this, result);
15011 // Returns a function that will only be executed on and after the Nth call.
15012 _.after = function(times, func) {
15013 return function() {
15015 return func.apply(this, arguments);
15020 // Returns a function that will only be executed up to (but not including) the Nth call.
15021 _.before = function(times, func) {
15023 return function() {
15025 memo = func.apply(this, arguments);
15027 if (times <= 1) func = null;
15032 // Returns a function that will be executed at most one time, no matter how
15033 // often you call it. Useful for lazy initialization.
15034 _.once = _.partial(_.before, 2);
15036 // Object Functions
15037 // ----------------
15039 // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
15040 var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
15041 var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
15042 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
15044 function collectNonEnumProps(obj, keys) {
15045 var nonEnumIdx = nonEnumerableProps.length;
15046 var constructor = obj.constructor;
15047 var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
15049 // Constructor is a special case.
15050 var prop = 'constructor';
15051 if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
15053 while (nonEnumIdx--) {
15054 prop = nonEnumerableProps[nonEnumIdx];
15055 if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
15061 // Retrieve the names of an object's own properties.
15062 // Delegates to **ECMAScript 5**'s native `Object.keys`
15063 _.keys = function(obj) {
15064 if (!_.isObject(obj)) return [];
15065 if (nativeKeys) return nativeKeys(obj);
15067 for (var key in obj) if (_.has(obj, key)) keys.push(key);
15069 if (hasEnumBug) collectNonEnumProps(obj, keys);
15073 // Retrieve all the property names of an object.
15074 _.allKeys = function(obj) {
15075 if (!_.isObject(obj)) return [];
15077 for (var key in obj) keys.push(key);
15079 if (hasEnumBug) collectNonEnumProps(obj, keys);
15083 // Retrieve the values of an object's properties.
15084 _.values = function(obj) {
15085 var keys = _.keys(obj);
15086 var length = keys.length;
15087 var values = Array(length);
15088 for (var i = 0; i < length; i++) {
15089 values[i] = obj[keys[i]];
15094 // Returns the results of applying the iteratee to each element of the object
15095 // In contrast to _.map it returns an object
15096 _.mapObject = function(obj, iteratee, context) {
15097 iteratee = cb(iteratee, context);
15098 var keys = _.keys(obj),
15099 length = keys.length,
15102 for (var index = 0; index < length; index++) {
15103 currentKey = keys[index];
15104 results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
15109 // Convert an object into a list of `[key, value]` pairs.
15110 _.pairs = function(obj) {
15111 var keys = _.keys(obj);
15112 var length = keys.length;
15113 var pairs = Array(length);
15114 for (var i = 0; i < length; i++) {
15115 pairs[i] = [keys[i], obj[keys[i]]];
15120 // Invert the keys and values of an object. The values must be serializable.
15121 _.invert = function(obj) {
15123 var keys = _.keys(obj);
15124 for (var i = 0, length = keys.length; i < length; i++) {
15125 result[obj[keys[i]]] = keys[i];
15130 // Return a sorted list of the function names available on the object.
15131 // Aliased as `methods`
15132 _.functions = _.methods = function(obj) {
15134 for (var key in obj) {
15135 if (_.isFunction(obj[key])) names.push(key);
15137 return names.sort();
15140 // Extend a given object with all the properties in passed-in object(s).
15141 _.extend = createAssigner(_.allKeys);
15143 // Assigns a given object with all the own properties in the passed-in object(s)
15144 // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
15145 _.extendOwn = _.assign = createAssigner(_.keys);
15147 // Returns the first key on an object that passes a predicate test
15148 _.findKey = function(obj, predicate, context) {
15149 predicate = cb(predicate, context);
15150 var keys = _.keys(obj), key;
15151 for (var i = 0, length = keys.length; i < length; i++) {
15153 if (predicate(obj[key], key, obj)) return key;
15157 // Return a copy of the object only containing the whitelisted properties.
15158 _.pick = function(object, oiteratee, context) {
15159 var result = {}, obj = object, iteratee, keys;
15160 if (obj == null) return result;
15161 if (_.isFunction(oiteratee)) {
15162 keys = _.allKeys(obj);
15163 iteratee = optimizeCb(oiteratee, context);
15165 keys = flatten(arguments, false, false, 1);
15166 iteratee = function(value, key, obj) { return key in obj; };
15169 for (var i = 0, length = keys.length; i < length; i++) {
15171 var value = obj[key];
15172 if (iteratee(value, key, obj)) result[key] = value;
15177 // Return a copy of the object without the blacklisted properties.
15178 _.omit = function(obj, iteratee, context) {
15179 if (_.isFunction(iteratee)) {
15180 iteratee = _.negate(iteratee);
15182 var keys = _.map(flatten(arguments, false, false, 1), String);
15183 iteratee = function(value, key) {
15184 return !_.contains(keys, key);
15187 return _.pick(obj, iteratee, context);
15190 // Fill in a given object with default properties.
15191 _.defaults = createAssigner(_.allKeys, true);
15193 // Creates an object that inherits from the given prototype object.
15194 // If additional properties are provided then they will be added to the
15196 _.create = function(prototype, props) {
15197 var result = baseCreate(prototype);
15198 if (props) _.extendOwn(result, props);
15202 // Create a (shallow-cloned) duplicate of an object.
15203 _.clone = function(obj) {
15204 if (!_.isObject(obj)) return obj;
15205 return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
15208 // Invokes interceptor with the obj, and then returns obj.
15209 // The primary purpose of this method is to "tap into" a method chain, in
15210 // order to perform operations on intermediate results within the chain.
15211 _.tap = function(obj, interceptor) {
15216 // Returns whether an object has a given set of `key:value` pairs.
15217 _.isMatch = function(object, attrs) {
15218 var keys = _.keys(attrs), length = keys.length;
15219 if (object == null) return !length;
15220 var obj = Object(object);
15221 for (var i = 0; i < length; i++) {
15223 if (attrs[key] !== obj[key] || !(key in obj)) return false;
15229 // Internal recursive comparison function for `isEqual`.
15230 var eq = function(a, b, aStack, bStack) {
15231 // Identical objects are equal. `0 === -0`, but they aren't identical.
15232 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
15233 if (a === b) return a !== 0 || 1 / a === 1 / b;
15234 // A strict comparison is necessary because `null == undefined`.
15235 if (a == null || b == null) return a === b;
15236 // Unwrap any wrapped objects.
15237 if (a instanceof _) a = a._wrapped;
15238 if (b instanceof _) b = b._wrapped;
15239 // Compare `[[Class]]` names.
15240 var className = toString.call(a);
15241 if (className !== toString.call(b)) return false;
15242 switch (className) {
15243 // Strings, numbers, regular expressions, dates, and booleans are compared by value.
15244 case '[object RegExp]':
15245 // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
15246 case '[object String]':
15247 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
15248 // equivalent to `new String("5")`.
15249 return '' + a === '' + b;
15250 case '[object Number]':
15251 // `NaN`s are equivalent, but non-reflexive.
15252 // Object(NaN) is equivalent to NaN
15253 if (+a !== +a) return +b !== +b;
15254 // An `egal` comparison is performed for other numeric values.
15255 return +a === 0 ? 1 / +a === 1 / b : +a === +b;
15256 case '[object Date]':
15257 case '[object Boolean]':
15258 // Coerce dates and booleans to numeric primitive values. Dates are compared by their
15259 // millisecond representations. Note that invalid dates with millisecond representations
15260 // of `NaN` are not equivalent.
15264 var areArrays = className === '[object Array]';
15266 if (typeof a != 'object' || typeof b != 'object') return false;
15268 // Objects with different constructors are not equivalent, but `Object`s or `Array`s
15269 // from different frames are.
15270 var aCtor = a.constructor, bCtor = b.constructor;
15271 if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
15272 _.isFunction(bCtor) && bCtor instanceof bCtor)
15273 && ('constructor' in a && 'constructor' in b)) {
15277 // Assume equality for cyclic structures. The algorithm for detecting cyclic
15278 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
15280 // Initializing stack of traversed objects.
15281 // It's done here since we only need them for objects and arrays comparison.
15282 aStack = aStack || [];
15283 bStack = bStack || [];
15284 var length = aStack.length;
15286 // Linear search. Performance is inversely proportional to the number of
15287 // unique nested structures.
15288 if (aStack[length] === a) return bStack[length] === b;
15291 // Add the first object to the stack of traversed objects.
15295 // Recursively compare objects and arrays.
15297 // Compare array lengths to determine if a deep comparison is necessary.
15299 if (length !== b.length) return false;
15300 // Deep compare the contents, ignoring non-numeric properties.
15302 if (!eq(a[length], b[length], aStack, bStack)) return false;
15305 // Deep compare objects.
15306 var keys = _.keys(a), key;
15307 length = keys.length;
15308 // Ensure that both objects contain the same number of properties before comparing deep equality.
15309 if (_.keys(b).length !== length) return false;
15311 // Deep compare each member
15312 key = keys[length];
15313 if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
15316 // Remove the first object from the stack of traversed objects.
15322 // Perform a deep comparison to check if two objects are equal.
15323 _.isEqual = function(a, b) {
15327 // Is a given array, string, or object empty?
15328 // An "empty" object has no enumerable own-properties.
15329 _.isEmpty = function(obj) {
15330 if (obj == null) return true;
15331 if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
15332 return _.keys(obj).length === 0;
15335 // Is a given value a DOM element?
15336 _.isElement = function(obj) {
15337 return !!(obj && obj.nodeType === 1);
15340 // Is a given value an array?
15341 // Delegates to ECMA5's native Array.isArray
15342 _.isArray = nativeIsArray || function(obj) {
15343 return toString.call(obj) === '[object Array]';
15346 // Is a given variable an object?
15347 _.isObject = function(obj) {
15348 var type = typeof obj;
15349 return type === 'function' || type === 'object' && !!obj;
15352 // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
15353 _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
15354 _['is' + name] = function(obj) {
15355 return toString.call(obj) === '[object ' + name + ']';
15359 // Define a fallback version of the method in browsers (ahem, IE < 9), where
15360 // there isn't any inspectable "Arguments" type.
15361 if (!_.isArguments(arguments)) {
15362 _.isArguments = function(obj) {
15363 return _.has(obj, 'callee');
15367 // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
15368 // IE 11 (#1621), and in Safari 8 (#1929).
15369 if (typeof /./ != 'function' && typeof Int8Array != 'object') {
15370 _.isFunction = function(obj) {
15371 return typeof obj == 'function' || false;
15375 // Is a given object a finite number?
15376 _.isFinite = function(obj) {
15377 return isFinite(obj) && !isNaN(parseFloat(obj));
15380 // Is the given value `NaN`? (NaN is the only number which does not equal itself).
15381 _.isNaN = function(obj) {
15382 return _.isNumber(obj) && obj !== +obj;
15385 // Is a given value a boolean?
15386 _.isBoolean = function(obj) {
15387 return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
15390 // Is a given value equal to null?
15391 _.isNull = function(obj) {
15392 return obj === null;
15395 // Is a given variable undefined?
15396 _.isUndefined = function(obj) {
15397 return obj === void 0;
15400 // Shortcut function for checking if an object has a given property directly
15401 // on itself (in other words, not on a prototype).
15402 _.has = function(obj, key) {
15403 return obj != null && hasOwnProperty.call(obj, key);
15406 // Utility Functions
15407 // -----------------
15409 // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
15410 // previous owner. Returns a reference to the Underscore object.
15411 _.noConflict = function() {
15412 root._ = previousUnderscore;
15416 // Keep the identity function around for default iteratees.
15417 _.identity = function(value) {
15421 // Predicate-generating functions. Often useful outside of Underscore.
15422 _.constant = function(value) {
15423 return function() {
15428 _.noop = function(){};
15430 _.property = property;
15432 // Generates a function for a given object that returns a given property.
15433 _.propertyOf = function(obj) {
15434 return obj == null ? function(){} : function(key) {
15439 // Returns a predicate for checking whether an object has a given set of
15440 // `key:value` pairs.
15441 _.matcher = _.matches = function(attrs) {
15442 attrs = _.extendOwn({}, attrs);
15443 return function(obj) {
15444 return _.isMatch(obj, attrs);
15448 // Run a function **n** times.
15449 _.times = function(n, iteratee, context) {
15450 var accum = Array(Math.max(0, n));
15451 iteratee = optimizeCb(iteratee, context, 1);
15452 for (var i = 0; i < n; i++) accum[i] = iteratee(i);
15456 // Return a random integer between min and max (inclusive).
15457 _.random = function(min, max) {
15462 return min + Math.floor(Math.random() * (max - min + 1));
15465 // A (possibly faster) way to get the current timestamp as an integer.
15466 _.now = Date.now || function() {
15467 return new Date().getTime();
15470 // List of HTML entities for escaping.
15479 var unescapeMap = _.invert(escapeMap);
15481 // Functions for escaping and unescaping strings to/from HTML interpolation.
15482 var createEscaper = function(map) {
15483 var escaper = function(match) {
15486 // Regexes for identifying a key that needs to be escaped
15487 var source = '(?:' + _.keys(map).join('|') + ')';
15488 var testRegexp = RegExp(source);
15489 var replaceRegexp = RegExp(source, 'g');
15490 return function(string) {
15491 string = string == null ? '' : '' + string;
15492 return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
15495 _.escape = createEscaper(escapeMap);
15496 _.unescape = createEscaper(unescapeMap);
15498 // If the value of the named `property` is a function then invoke it with the
15499 // `object` as context; otherwise, return it.
15500 _.result = function(object, property, fallback) {
15501 var value = object == null ? void 0 : object[property];
15502 if (value === void 0) {
15505 return _.isFunction(value) ? value.call(object) : value;
15508 // Generate a unique integer id (unique within the entire client session).
15509 // Useful for temporary DOM ids.
15511 _.uniqueId = function(prefix) {
15512 var id = ++idCounter + '';
15513 return prefix ? prefix + id : id;
15516 // By default, Underscore uses ERB-style template delimiters, change the
15517 // following template settings to use alternative delimiters.
15518 _.templateSettings = {
15519 evaluate : /<%([\s\S]+?)%>/g,
15520 interpolate : /<%=([\s\S]+?)%>/g,
15521 escape : /<%-([\s\S]+?)%>/g
15524 // When customizing `templateSettings`, if you don't want to define an
15525 // interpolation, evaluation or escaping regex, we need one that is
15526 // guaranteed not to match.
15527 var noMatch = /(.)^/;
15529 // Certain characters need to be escaped so that they can be put into a
15540 var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
15542 var escapeChar = function(match) {
15543 return '\\' + escapes[match];
15546 // JavaScript micro-templating, similar to John Resig's implementation.
15547 // Underscore templating handles arbitrary delimiters, preserves whitespace,
15548 // and correctly escapes quotes within interpolated code.
15549 // NB: `oldSettings` only exists for backwards compatibility.
15550 _.template = function(text, settings, oldSettings) {
15551 if (!settings && oldSettings) settings = oldSettings;
15552 settings = _.defaults({}, settings, _.templateSettings);
15554 // Combine delimiters into one regular expression via alternation.
15555 var matcher = RegExp([
15556 (settings.escape || noMatch).source,
15557 (settings.interpolate || noMatch).source,
15558 (settings.evaluate || noMatch).source
15559 ].join('|') + '|$', 'g');
15561 // Compile the template source, escaping string literals appropriately.
15563 var source = "__p+='";
15564 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
15565 source += text.slice(index, offset).replace(escaper, escapeChar);
15566 index = offset + match.length;
15569 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
15570 } else if (interpolate) {
15571 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
15572 } else if (evaluate) {
15573 source += "';\n" + evaluate + "\n__p+='";
15576 // Adobe VMs need the match returned to produce the correct offest.
15581 // If a variable is not specified, place data values in local scope.
15582 if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
15584 source = "var __t,__p='',__j=Array.prototype.join," +
15585 "print=function(){__p+=__j.call(arguments,'');};\n" +
15586 source + 'return __p;\n';
15589 var render = new Function(settings.variable || 'obj', '_', source);
15595 var template = function(data) {
15596 return render.call(this, data, _);
15599 // Provide the compiled source as a convenience for precompilation.
15600 var argument = settings.variable || 'obj';
15601 template.source = 'function(' + argument + '){\n' + source + '}';
15606 // Add a "chain" function. Start chaining a wrapped Underscore object.
15607 _.chain = function(obj) {
15608 var instance = _(obj);
15609 instance._chain = true;
15615 // If Underscore is called as a function, it returns a wrapped object that
15616 // can be used OO-style. This wrapper holds altered versions of all the
15617 // underscore functions. Wrapped objects may be chained.
15619 // Helper function to continue chaining intermediate results.
15620 var result = function(instance, obj) {
15621 return instance._chain ? _(obj).chain() : obj;
15624 // Add your own custom functions to the Underscore object.
15625 _.mixin = function(obj) {
15626 _.each(_.functions(obj), function(name) {
15627 var func = _[name] = obj[name];
15628 _.prototype[name] = function() {
15629 var args = [this._wrapped];
15630 push.apply(args, arguments);
15631 return result(this, func.apply(_, args));
15636 // Add all of the Underscore functions to the wrapper object.
15639 // Add all mutator Array functions to the wrapper.
15640 _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
15641 var method = ArrayProto[name];
15642 _.prototype[name] = function() {
15643 var obj = this._wrapped;
15644 method.apply(obj, arguments);
15645 if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
15646 return result(this, obj);
15650 // Add all accessor Array functions to the wrapper.
15651 _.each(['concat', 'join', 'slice'], function(name) {
15652 var method = ArrayProto[name];
15653 _.prototype[name] = function() {
15654 return result(this, method.apply(this._wrapped, arguments));
15658 // Extracts the result from a wrapped and chained object.
15659 _.prototype.value = function() {
15660 return this._wrapped;
15663 // Provide unwrapping proxy for some methods used in engine operations
15664 // such as arithmetic and JSON stringification.
15665 _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
15667 _.prototype.toString = function() {
15668 return '' + this._wrapped;
15671 // AMD registration happens at the end for compatibility with AMD loaders
15672 // that may not enforce next-turn semantics on modules. Even though general
15673 // practice for AMD registration is to be anonymous, underscore registers
15674 // as a named module because, like jQuery, it is a base library that is
15675 // popular enough to be bundled in a third party lib, but not be part of
15676 // an AMD load request. Those cases could generate an error when an
15677 // anonymous define() is called outside of a loader request.
15678 if (typeof define === 'function' && define.amd) {
15679 define('underscore', [], function() {
15685 },{}],177:[function(require,module,exports){
15687 * Copyright (C) 2008 Apple Inc. All Rights Reserved.
15689 * Redistribution and use in source and binary forms, with or without
15690 * modification, are permitted provided that the following conditions
15692 * 1. Redistributions of source code must retain the above copyright
15693 * notice, this list of conditions and the following disclaimer.
15694 * 2. Redistributions in binary form must reproduce the above copyright
15695 * notice, this list of conditions and the following disclaimer in the
15696 * documentation and/or other materials provided with the distribution.
15698 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
15699 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15700 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
15701 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
15702 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
15703 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
15704 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
15705 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
15706 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
15707 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15708 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15710 * Ported from Webkit
15711 * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h
15714 module.exports = UnitBezier;
15716 function UnitBezier(p1x, p1y, p2x, p2y) {
15717 // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
15718 this.cx = 3.0 * p1x;
15719 this.bx = 3.0 * (p2x - p1x) - this.cx;
15720 this.ax = 1.0 - this.cx - this.bx;
15722 this.cy = 3.0 * p1y;
15723 this.by = 3.0 * (p2y - p1y) - this.cy;
15724 this.ay = 1.0 - this.cy - this.by;
15732 UnitBezier.prototype.sampleCurveX = function(t) {
15733 // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
15734 return ((this.ax * t + this.bx) * t + this.cx) * t;
15737 UnitBezier.prototype.sampleCurveY = function(t) {
15738 return ((this.ay * t + this.by) * t + this.cy) * t;
15741 UnitBezier.prototype.sampleCurveDerivativeX = function(t) {
15742 return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
15745 UnitBezier.prototype.solveCurveX = function(x, epsilon) {
15746 if (typeof epsilon === 'undefined') epsilon = 1e-6;
15748 var t0, t1, t2, x2, i;
15750 // First try a few iterations of Newton's method -- normally very fast.
15751 for (t2 = x, i = 0; i < 8; i++) {
15753 x2 = this.sampleCurveX(t2) - x;
15754 if (Math.abs(x2) < epsilon) return t2;
15756 var d2 = this.sampleCurveDerivativeX(t2);
15757 if (Math.abs(d2) < 1e-6) break;
15762 // Fall back to the bisection method for reliability.
15767 if (t2 < t0) return t0;
15768 if (t2 > t1) return t1;
15772 x2 = this.sampleCurveX(t2);
15773 if (Math.abs(x2 - x) < epsilon) return t2;
15781 t2 = (t1 - t0) * 0.5 + t0;
15788 UnitBezier.prototype.solve = function(x, epsilon) {
15789 return this.sampleCurveY(this.solveCurveX(x, epsilon));
15792 },{}],178:[function(require,module,exports){
15793 var createElement = require("./vdom/create-element.js")
15795 module.exports = createElement
15797 },{"./vdom/create-element.js":184}],179:[function(require,module,exports){
15798 var diff = require("./vtree/diff.js")
15800 module.exports = diff
15802 },{"./vtree/diff.js":204}],180:[function(require,module,exports){
15803 var h = require("./virtual-hyperscript/index.js")
15807 },{"./virtual-hyperscript/index.js":191}],181:[function(require,module,exports){
15808 var diff = require("./diff.js")
15809 var patch = require("./patch.js")
15810 var h = require("./h.js")
15811 var create = require("./create-element.js")
15812 var VNode = require('./vnode/vnode.js')
15813 var VText = require('./vnode/vtext.js')
15824 },{"./create-element.js":178,"./diff.js":179,"./h.js":180,"./patch.js":182,"./vnode/vnode.js":200,"./vnode/vtext.js":202}],182:[function(require,module,exports){
15825 var patch = require("./vdom/patch.js")
15827 module.exports = patch
15829 },{"./vdom/patch.js":187}],183:[function(require,module,exports){
15830 var isObject = require("is-object")
15831 var isHook = require("../vnode/is-vhook.js")
15833 module.exports = applyProperties
15835 function applyProperties(node, props, previous) {
15836 for (var propName in props) {
15837 var propValue = props[propName]
15839 if (propValue === undefined) {
15840 removeProperty(node, propName, propValue, previous);
15841 } else if (isHook(propValue)) {
15842 removeProperty(node, propName, propValue, previous)
15843 if (propValue.hook) {
15844 propValue.hook(node,
15846 previous ? previous[propName] : undefined)
15849 if (isObject(propValue)) {
15850 patchObject(node, props, previous, propName, propValue);
15852 node[propName] = propValue
15858 function removeProperty(node, propName, propValue, previous) {
15860 var previousValue = previous[propName]
15862 if (!isHook(previousValue)) {
15863 if (propName === "attributes") {
15864 for (var attrName in previousValue) {
15865 node.removeAttribute(attrName)
15867 } else if (propName === "style") {
15868 for (var i in previousValue) {
15871 } else if (typeof previousValue === "string") {
15872 node[propName] = ""
15874 node[propName] = null
15876 } else if (previousValue.unhook) {
15877 previousValue.unhook(node, propName, propValue)
15882 function patchObject(node, props, previous, propName, propValue) {
15883 var previousValue = previous ? previous[propName] : undefined
15886 if (propName === "attributes") {
15887 for (var attrName in propValue) {
15888 var attrValue = propValue[attrName]
15890 if (attrValue === undefined) {
15891 node.removeAttribute(attrName)
15893 node.setAttribute(attrName, attrValue)
15900 if(previousValue && isObject(previousValue) &&
15901 getPrototype(previousValue) !== getPrototype(propValue)) {
15902 node[propName] = propValue
15906 if (!isObject(node[propName])) {
15907 node[propName] = {}
15910 var replacer = propName === "style" ? "" : undefined
15912 for (var k in propValue) {
15913 var value = propValue[k]
15914 node[propName][k] = (value === undefined) ? replacer : value
15918 function getPrototype(value) {
15919 if (Object.getPrototypeOf) {
15920 return Object.getPrototypeOf(value)
15921 } else if (value.__proto__) {
15922 return value.__proto__
15923 } else if (value.constructor) {
15924 return value.constructor.prototype
15928 },{"../vnode/is-vhook.js":195,"is-object":18}],184:[function(require,module,exports){
15929 var document = require("global/document")
15931 var applyProperties = require("./apply-properties")
15933 var isVNode = require("../vnode/is-vnode.js")
15934 var isVText = require("../vnode/is-vtext.js")
15935 var isWidget = require("../vnode/is-widget.js")
15936 var handleThunk = require("../vnode/handle-thunk.js")
15938 module.exports = createElement
15940 function createElement(vnode, opts) {
15941 var doc = opts ? opts.document || document : document
15942 var warn = opts ? opts.warn : null
15944 vnode = handleThunk(vnode).a
15946 if (isWidget(vnode)) {
15947 return vnode.init()
15948 } else if (isVText(vnode)) {
15949 return doc.createTextNode(vnode.text)
15950 } else if (!isVNode(vnode)) {
15952 warn("Item is not a valid virtual dom node", vnode)
15957 var node = (vnode.namespace === null) ?
15958 doc.createElement(vnode.tagName) :
15959 doc.createElementNS(vnode.namespace, vnode.tagName)
15961 var props = vnode.properties
15962 applyProperties(node, props)
15964 var children = vnode.children
15966 for (var i = 0; i < children.length; i++) {
15967 var childNode = createElement(children[i], opts)
15969 node.appendChild(childNode)
15976 },{"../vnode/handle-thunk.js":193,"../vnode/is-vnode.js":196,"../vnode/is-vtext.js":197,"../vnode/is-widget.js":198,"./apply-properties":183,"global/document":14}],185:[function(require,module,exports){
15977 // Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
15978 // We don't want to read all of the DOM nodes in the tree so we use
15979 // the in-order tree indexing to eliminate recursion down certain branches.
15980 // We only recurse into a DOM node if we know that it contains a child of
15985 module.exports = domIndex
15987 function domIndex(rootNode, tree, indices, nodes) {
15988 if (!indices || indices.length === 0) {
15991 indices.sort(ascending)
15992 return recurse(rootNode, tree, indices, nodes, 0)
15996 function recurse(rootNode, tree, indices, nodes, rootIndex) {
15997 nodes = nodes || {}
16001 if (indexInRange(indices, rootIndex, rootIndex)) {
16002 nodes[rootIndex] = rootNode
16005 var vChildren = tree.children
16009 var childNodes = rootNode.childNodes
16011 for (var i = 0; i < tree.children.length; i++) {
16014 var vChild = vChildren[i] || noChild
16015 var nextIndex = rootIndex + (vChild.count || 0)
16017 // skip recursion down the tree if there are no nodes down here
16018 if (indexInRange(indices, rootIndex, nextIndex)) {
16019 recurse(childNodes[i], vChild, indices, nodes, rootIndex)
16022 rootIndex = nextIndex
16030 // Binary search for an index in the interval [left, right]
16031 function indexInRange(indices, left, right) {
16032 if (indices.length === 0) {
16037 var maxIndex = indices.length - 1
16041 while (minIndex <= maxIndex) {
16042 currentIndex = ((maxIndex + minIndex) / 2) >> 0
16043 currentItem = indices[currentIndex]
16045 if (minIndex === maxIndex) {
16046 return currentItem >= left && currentItem <= right
16047 } else if (currentItem < left) {
16048 minIndex = currentIndex + 1
16049 } else if (currentItem > right) {
16050 maxIndex = currentIndex - 1
16059 function ascending(a, b) {
16060 return a > b ? 1 : -1
16063 },{}],186:[function(require,module,exports){
16064 var applyProperties = require("./apply-properties")
16066 var isWidget = require("../vnode/is-widget.js")
16067 var VPatch = require("../vnode/vpatch.js")
16069 var updateWidget = require("./update-widget")
16071 module.exports = applyPatch
16073 function applyPatch(vpatch, domNode, renderOptions) {
16074 var type = vpatch.type
16075 var vNode = vpatch.vNode
16076 var patch = vpatch.patch
16079 case VPatch.REMOVE:
16080 return removeNode(domNode, vNode)
16081 case VPatch.INSERT:
16082 return insertNode(domNode, patch, renderOptions)
16084 return stringPatch(domNode, vNode, patch, renderOptions)
16085 case VPatch.WIDGET:
16086 return widgetPatch(domNode, vNode, patch, renderOptions)
16088 return vNodePatch(domNode, vNode, patch, renderOptions)
16090 reorderChildren(domNode, patch)
16093 applyProperties(domNode, patch, vNode.properties)
16096 return replaceRoot(domNode,
16097 renderOptions.patch(domNode, patch, renderOptions))
16103 function removeNode(domNode, vNode) {
16104 var parentNode = domNode.parentNode
16107 parentNode.removeChild(domNode)
16110 destroyWidget(domNode, vNode);
16115 function insertNode(parentNode, vNode, renderOptions) {
16116 var newNode = renderOptions.render(vNode, renderOptions)
16119 parentNode.appendChild(newNode)
16125 function stringPatch(domNode, leftVNode, vText, renderOptions) {
16128 if (domNode.nodeType === 3) {
16129 domNode.replaceData(0, domNode.length, vText.text)
16132 var parentNode = domNode.parentNode
16133 newNode = renderOptions.render(vText, renderOptions)
16135 if (parentNode && newNode !== domNode) {
16136 parentNode.replaceChild(newNode, domNode)
16143 function widgetPatch(domNode, leftVNode, widget, renderOptions) {
16144 var updating = updateWidget(leftVNode, widget)
16148 newNode = widget.update(leftVNode, domNode) || domNode
16150 newNode = renderOptions.render(widget, renderOptions)
16153 var parentNode = domNode.parentNode
16155 if (parentNode && newNode !== domNode) {
16156 parentNode.replaceChild(newNode, domNode)
16160 destroyWidget(domNode, leftVNode)
16166 function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
16167 var parentNode = domNode.parentNode
16168 var newNode = renderOptions.render(vNode, renderOptions)
16170 if (parentNode && newNode !== domNode) {
16171 parentNode.replaceChild(newNode, domNode)
16177 function destroyWidget(domNode, w) {
16178 if (typeof w.destroy === "function" && isWidget(w)) {
16183 function reorderChildren(domNode, moves) {
16184 var childNodes = domNode.childNodes
16190 for (var i = 0; i < moves.removes.length; i++) {
16191 remove = moves.removes[i]
16192 node = childNodes[remove.from]
16194 keyMap[remove.key] = node
16196 domNode.removeChild(node)
16199 var length = childNodes.length
16200 for (var j = 0; j < moves.inserts.length; j++) {
16201 insert = moves.inserts[j]
16202 node = keyMap[insert.key]
16203 // this is the weirdest bug i've ever seen in webkit
16204 domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to])
16208 function replaceRoot(oldRoot, newRoot) {
16209 if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
16210 oldRoot.parentNode.replaceChild(newRoot, oldRoot)
16216 },{"../vnode/is-widget.js":198,"../vnode/vpatch.js":201,"./apply-properties":183,"./update-widget":188}],187:[function(require,module,exports){
16217 var document = require("global/document")
16218 var isArray = require("x-is-array")
16220 var render = require("./create-element")
16221 var domIndex = require("./dom-index")
16222 var patchOp = require("./patch-op")
16223 module.exports = patch
16225 function patch(rootNode, patches, renderOptions) {
16226 renderOptions = renderOptions || {}
16227 renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch
16228 ? renderOptions.patch
16230 renderOptions.render = renderOptions.render || render
16232 return renderOptions.patch(rootNode, patches, renderOptions)
16235 function patchRecursive(rootNode, patches, renderOptions) {
16236 var indices = patchIndices(patches)
16238 if (indices.length === 0) {
16242 var index = domIndex(rootNode, patches.a, indices)
16243 var ownerDocument = rootNode.ownerDocument
16245 if (!renderOptions.document && ownerDocument !== document) {
16246 renderOptions.document = ownerDocument
16249 for (var i = 0; i < indices.length; i++) {
16250 var nodeIndex = indices[i]
16251 rootNode = applyPatch(rootNode,
16253 patches[nodeIndex],
16260 function applyPatch(rootNode, domNode, patchList, renderOptions) {
16267 if (isArray(patchList)) {
16268 for (var i = 0; i < patchList.length; i++) {
16269 newNode = patchOp(patchList[i], domNode, renderOptions)
16271 if (domNode === rootNode) {
16276 newNode = patchOp(patchList, domNode, renderOptions)
16278 if (domNode === rootNode) {
16286 function patchIndices(patches) {
16289 for (var key in patches) {
16291 indices.push(Number(key))
16298 },{"./create-element":184,"./dom-index":185,"./patch-op":186,"global/document":14,"x-is-array":223}],188:[function(require,module,exports){
16299 var isWidget = require("../vnode/is-widget.js")
16301 module.exports = updateWidget
16303 function updateWidget(a, b) {
16304 if (isWidget(a) && isWidget(b)) {
16305 if ("name" in a && "name" in b) {
16306 return a.id === b.id
16308 return a.init === b.init
16315 },{"../vnode/is-widget.js":198}],189:[function(require,module,exports){
16318 var EvStore = require('ev-store');
16320 module.exports = EvHook;
16322 function EvHook(value) {
16323 if (!(this instanceof EvHook)) {
16324 return new EvHook(value);
16327 this.value = value;
16330 EvHook.prototype.hook = function (node, propertyName) {
16331 var es = EvStore(node);
16332 var propName = propertyName.substr(3);
16334 es[propName] = this.value;
16337 EvHook.prototype.unhook = function(node, propertyName) {
16338 var es = EvStore(node);
16339 var propName = propertyName.substr(3);
16341 es[propName] = undefined;
16344 },{"ev-store":7}],190:[function(require,module,exports){
16347 module.exports = SoftSetHook;
16349 function SoftSetHook(value) {
16350 if (!(this instanceof SoftSetHook)) {
16351 return new SoftSetHook(value);
16354 this.value = value;
16357 SoftSetHook.prototype.hook = function (node, propertyName) {
16358 if (node[propertyName] !== this.value) {
16359 node[propertyName] = this.value;
16363 },{}],191:[function(require,module,exports){
16366 var isArray = require('x-is-array');
16368 var VNode = require('../vnode/vnode.js');
16369 var VText = require('../vnode/vtext.js');
16370 var isVNode = require('../vnode/is-vnode');
16371 var isVText = require('../vnode/is-vtext');
16372 var isWidget = require('../vnode/is-widget');
16373 var isHook = require('../vnode/is-vhook');
16374 var isVThunk = require('../vnode/is-thunk');
16376 var parseTag = require('./parse-tag.js');
16377 var softSetHook = require('./hooks/soft-set-hook.js');
16378 var evHook = require('./hooks/ev-hook.js');
16380 module.exports = h;
16382 function h(tagName, properties, children) {
16383 var childNodes = [];
16384 var tag, props, key, namespace;
16386 if (!children && isChildren(properties)) {
16387 children = properties;
16391 props = props || properties || {};
16392 tag = parseTag(tagName, props);
16395 if (props.hasOwnProperty('key')) {
16397 props.key = undefined;
16400 // support namespace
16401 if (props.hasOwnProperty('namespace')) {
16402 namespace = props.namespace;
16403 props.namespace = undefined;
16407 if (tag === 'INPUT' &&
16409 props.hasOwnProperty('value') &&
16410 props.value !== undefined &&
16411 !isHook(props.value)
16413 props.value = softSetHook(props.value);
16416 transformProperties(props);
16418 if (children !== undefined && children !== null) {
16419 addChild(children, childNodes, tag, props);
16423 return new VNode(tag, props, childNodes, key, namespace);
16426 function addChild(c, childNodes, tag, props) {
16427 if (typeof c === 'string') {
16428 childNodes.push(new VText(c));
16429 } else if (typeof c === 'number') {
16430 childNodes.push(new VText(String(c)));
16431 } else if (isChild(c)) {
16432 childNodes.push(c);
16433 } else if (isArray(c)) {
16434 for (var i = 0; i < c.length; i++) {
16435 addChild(c[i], childNodes, tag, props);
16437 } else if (c === null || c === undefined) {
16440 throw UnexpectedVirtualElement({
16450 function transformProperties(props) {
16451 for (var propName in props) {
16452 if (props.hasOwnProperty(propName)) {
16453 var value = props[propName];
16455 if (isHook(value)) {
16459 if (propName.substr(0, 3) === 'ev-') {
16460 // add ev-foo support
16461 props[propName] = evHook(value);
16467 function isChild(x) {
16468 return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x);
16471 function isChildren(x) {
16472 return typeof x === 'string' || isArray(x) || isChild(x);
16475 function UnexpectedVirtualElement(data) {
16476 var err = new Error();
16478 err.type = 'virtual-hyperscript.unexpected.virtual-element';
16479 err.message = 'Unexpected virtual child passed to h().\n' +
16480 'Expected a VNode / Vthunk / VWidget / string but:\n' +
16482 errorString(data.foreignObject) +
16484 'The parent vnode is:\n' +
16485 errorString(data.parentVnode)
16487 'Suggested fix: change your `h(..., [ ... ])` callsite.';
16488 err.foreignObject = data.foreignObject;
16489 err.parentVnode = data.parentVnode;
16494 function errorString(obj) {
16496 return JSON.stringify(obj, null, ' ');
16498 return String(obj);
16502 },{"../vnode/is-thunk":194,"../vnode/is-vhook":195,"../vnode/is-vnode":196,"../vnode/is-vtext":197,"../vnode/is-widget":198,"../vnode/vnode.js":200,"../vnode/vtext.js":202,"./hooks/ev-hook.js":189,"./hooks/soft-set-hook.js":190,"./parse-tag.js":192,"x-is-array":223}],192:[function(require,module,exports){
16505 var split = require('browser-split');
16507 var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
16508 var notClassId = /^\.|#/;
16510 module.exports = parseTag;
16512 function parseTag(tag, props) {
16517 var noId = !(props.hasOwnProperty('id'));
16519 var tagParts = split(tag, classIdSplit);
16520 var tagName = null;
16522 if (notClassId.test(tagParts[1])) {
16526 var classes, part, type, i;
16528 for (i = 0; i < tagParts.length; i++) {
16529 part = tagParts[i];
16535 type = part.charAt(0);
16539 } else if (type === '.') {
16540 classes = classes || [];
16541 classes.push(part.substring(1, part.length));
16542 } else if (type === '#' && noId) {
16543 props.id = part.substring(1, part.length);
16548 if (props.className) {
16549 classes.push(props.className);
16552 props.className = classes.join(' ');
16555 return props.namespace ? tagName : tagName.toUpperCase();
16558 },{"browser-split":3}],193:[function(require,module,exports){
16559 var isVNode = require("./is-vnode")
16560 var isVText = require("./is-vtext")
16561 var isWidget = require("./is-widget")
16562 var isThunk = require("./is-thunk")
16564 module.exports = handleThunk
16566 function handleThunk(a, b) {
16571 renderedB = renderThunk(b, a)
16575 renderedA = renderThunk(a, null)
16584 function renderThunk(thunk, previous) {
16585 var renderedThunk = thunk.vnode
16587 if (!renderedThunk) {
16588 renderedThunk = thunk.vnode = thunk.render(previous)
16591 if (!(isVNode(renderedThunk) ||
16592 isVText(renderedThunk) ||
16593 isWidget(renderedThunk))) {
16594 throw new Error("thunk did not return a valid node");
16597 return renderedThunk
16600 },{"./is-thunk":194,"./is-vnode":196,"./is-vtext":197,"./is-widget":198}],194:[function(require,module,exports){
16601 module.exports = isThunk
16603 function isThunk(t) {
16604 return t && t.type === "Thunk"
16607 },{}],195:[function(require,module,exports){
16608 module.exports = isHook
16610 function isHook(hook) {
16612 (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") ||
16613 typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook"))
16616 },{}],196:[function(require,module,exports){
16617 var version = require("./version")
16619 module.exports = isVirtualNode
16621 function isVirtualNode(x) {
16622 return x && x.type === "VirtualNode" && x.version === version
16625 },{"./version":199}],197:[function(require,module,exports){
16626 var version = require("./version")
16628 module.exports = isVirtualText
16630 function isVirtualText(x) {
16631 return x && x.type === "VirtualText" && x.version === version
16634 },{"./version":199}],198:[function(require,module,exports){
16635 module.exports = isWidget
16637 function isWidget(w) {
16638 return w && w.type === "Widget"
16641 },{}],199:[function(require,module,exports){
16642 module.exports = "2"
16644 },{}],200:[function(require,module,exports){
16645 var version = require("./version")
16646 var isVNode = require("./is-vnode")
16647 var isWidget = require("./is-widget")
16648 var isThunk = require("./is-thunk")
16649 var isVHook = require("./is-vhook")
16651 module.exports = VirtualNode
16653 var noProperties = {}
16654 var noChildren = []
16656 function VirtualNode(tagName, properties, children, key, namespace) {
16657 this.tagName = tagName
16658 this.properties = properties || noProperties
16659 this.children = children || noChildren
16660 this.key = key != null ? String(key) : undefined
16661 this.namespace = (typeof namespace === "string") ? namespace : null
16663 var count = (children && children.length) || 0
16664 var descendants = 0
16665 var hasWidgets = false
16666 var hasThunks = false
16667 var descendantHooks = false
16670 for (var propName in properties) {
16671 if (properties.hasOwnProperty(propName)) {
16672 var property = properties[propName]
16673 if (isVHook(property) && property.unhook) {
16678 hooks[propName] = property
16683 for (var i = 0; i < count; i++) {
16684 var child = children[i]
16685 if (isVNode(child)) {
16686 descendants += child.count || 0
16688 if (!hasWidgets && child.hasWidgets) {
16692 if (!hasThunks && child.hasThunks) {
16696 if (!descendantHooks && (child.hooks || child.descendantHooks)) {
16697 descendantHooks = true
16699 } else if (!hasWidgets && isWidget(child)) {
16700 if (typeof child.destroy === "function") {
16703 } else if (!hasThunks && isThunk(child)) {
16708 this.count = count + descendants
16709 this.hasWidgets = hasWidgets
16710 this.hasThunks = hasThunks
16712 this.descendantHooks = descendantHooks
16715 VirtualNode.prototype.version = version
16716 VirtualNode.prototype.type = "VirtualNode"
16718 },{"./is-thunk":194,"./is-vhook":195,"./is-vnode":196,"./is-widget":198,"./version":199}],201:[function(require,module,exports){
16719 var version = require("./version")
16721 VirtualPatch.NONE = 0
16722 VirtualPatch.VTEXT = 1
16723 VirtualPatch.VNODE = 2
16724 VirtualPatch.WIDGET = 3
16725 VirtualPatch.PROPS = 4
16726 VirtualPatch.ORDER = 5
16727 VirtualPatch.INSERT = 6
16728 VirtualPatch.REMOVE = 7
16729 VirtualPatch.THUNK = 8
16731 module.exports = VirtualPatch
16733 function VirtualPatch(type, vNode, patch) {
16734 this.type = Number(type)
16739 VirtualPatch.prototype.version = version
16740 VirtualPatch.prototype.type = "VirtualPatch"
16742 },{"./version":199}],202:[function(require,module,exports){
16743 var version = require("./version")
16745 module.exports = VirtualText
16747 function VirtualText(text) {
16748 this.text = String(text)
16751 VirtualText.prototype.version = version
16752 VirtualText.prototype.type = "VirtualText"
16754 },{"./version":199}],203:[function(require,module,exports){
16755 var isObject = require("is-object")
16756 var isHook = require("../vnode/is-vhook")
16758 module.exports = diffProps
16760 function diffProps(a, b) {
16763 for (var aKey in a) {
16764 if (!(aKey in b)) {
16766 diff[aKey] = undefined
16769 var aValue = a[aKey]
16770 var bValue = b[aKey]
16772 if (aValue === bValue) {
16774 } else if (isObject(aValue) && isObject(bValue)) {
16775 if (getPrototype(bValue) !== getPrototype(aValue)) {
16777 diff[aKey] = bValue
16778 } else if (isHook(bValue)) {
16780 diff[aKey] = bValue
16782 var objectDiff = diffProps(aValue, bValue)
16785 diff[aKey] = objectDiff
16790 diff[aKey] = bValue
16794 for (var bKey in b) {
16795 if (!(bKey in a)) {
16797 diff[bKey] = b[bKey]
16804 function getPrototype(value) {
16805 if (Object.getPrototypeOf) {
16806 return Object.getPrototypeOf(value)
16807 } else if (value.__proto__) {
16808 return value.__proto__
16809 } else if (value.constructor) {
16810 return value.constructor.prototype
16814 },{"../vnode/is-vhook":195,"is-object":18}],204:[function(require,module,exports){
16815 var isArray = require("x-is-array")
16817 var VPatch = require("../vnode/vpatch")
16818 var isVNode = require("../vnode/is-vnode")
16819 var isVText = require("../vnode/is-vtext")
16820 var isWidget = require("../vnode/is-widget")
16821 var isThunk = require("../vnode/is-thunk")
16822 var handleThunk = require("../vnode/handle-thunk")
16824 var diffProps = require("./diff-props")
16826 module.exports = diff
16828 function diff(a, b) {
16829 var patch = { a: a }
16830 walk(a, b, patch, 0)
16834 function walk(a, b, patch, index) {
16839 var apply = patch[index]
16840 var applyClear = false
16842 if (isThunk(a) || isThunk(b)) {
16843 thunks(a, b, patch, index)
16844 } else if (b == null) {
16846 // If a is a widget we will add a remove patch for it
16847 // Otherwise any child widgets/hooks must be destroyed.
16848 // This prevents adding two remove patches for a widget.
16849 if (!isWidget(a)) {
16850 clearState(a, patch, index)
16851 apply = patch[index]
16854 apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
16855 } else if (isVNode(b)) {
16857 if (a.tagName === b.tagName &&
16858 a.namespace === b.namespace &&
16860 var propsPatch = diffProps(a.properties, b.properties)
16862 apply = appendPatch(apply,
16863 new VPatch(VPatch.PROPS, a, propsPatch))
16865 apply = diffChildren(a, b, patch, apply, index)
16867 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
16871 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
16874 } else if (isVText(b)) {
16876 apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
16878 } else if (a.text !== b.text) {
16879 apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
16881 } else if (isWidget(b)) {
16882 if (!isWidget(a)) {
16886 apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
16890 patch[index] = apply
16894 clearState(a, patch, index)
16898 function diffChildren(a, b, patch, apply, index) {
16899 var aChildren = a.children
16900 var orderedSet = reorder(aChildren, b.children)
16901 var bChildren = orderedSet.children
16903 var aLen = aChildren.length
16904 var bLen = bChildren.length
16905 var len = aLen > bLen ? aLen : bLen
16907 for (var i = 0; i < len; i++) {
16908 var leftNode = aChildren[i]
16909 var rightNode = bChildren[i]
16914 // Excess nodes in b need to be added
16915 apply = appendPatch(apply,
16916 new VPatch(VPatch.INSERT, null, rightNode))
16919 walk(leftNode, rightNode, patch, index)
16922 if (isVNode(leftNode) && leftNode.count) {
16923 index += leftNode.count
16927 if (orderedSet.moves) {
16928 // Reorder nodes last
16929 apply = appendPatch(apply, new VPatch(
16939 function clearState(vNode, patch, index) {
16940 // TODO: Make this a single walk, not two
16941 unhook(vNode, patch, index)
16942 destroyWidgets(vNode, patch, index)
16945 // Patch records for all destroyed widgets must be added because we need
16946 // a DOM node reference for the destroy function
16947 function destroyWidgets(vNode, patch, index) {
16948 if (isWidget(vNode)) {
16949 if (typeof vNode.destroy === "function") {
16950 patch[index] = appendPatch(
16952 new VPatch(VPatch.REMOVE, vNode, null)
16955 } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
16956 var children = vNode.children
16957 var len = children.length
16958 for (var i = 0; i < len; i++) {
16959 var child = children[i]
16962 destroyWidgets(child, patch, index)
16964 if (isVNode(child) && child.count) {
16965 index += child.count
16968 } else if (isThunk(vNode)) {
16969 thunks(vNode, null, patch, index)
16973 // Create a sub-patch for thunks
16974 function thunks(a, b, patch, index) {
16975 var nodes = handleThunk(a, b)
16976 var thunkPatch = diff(nodes.a, nodes.b)
16977 if (hasPatches(thunkPatch)) {
16978 patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
16982 function hasPatches(patch) {
16983 for (var index in patch) {
16984 if (index !== "a") {
16992 // Execute hooks when two nodes are identical
16993 function unhook(vNode, patch, index) {
16994 if (isVNode(vNode)) {
16996 patch[index] = appendPatch(
17001 undefinedKeys(vNode.hooks)
17006 if (vNode.descendantHooks || vNode.hasThunks) {
17007 var children = vNode.children
17008 var len = children.length
17009 for (var i = 0; i < len; i++) {
17010 var child = children[i]
17013 unhook(child, patch, index)
17015 if (isVNode(child) && child.count) {
17016 index += child.count
17020 } else if (isThunk(vNode)) {
17021 thunks(vNode, null, patch, index)
17025 function undefinedKeys(obj) {
17028 for (var key in obj) {
17029 result[key] = undefined
17035 // List diff, naive left to right reordering
17036 function reorder(aChildren, bChildren) {
17037 // O(M) time, O(M) memory
17038 var bChildIndex = keyIndex(bChildren)
17039 var bKeys = bChildIndex.keys
17040 var bFree = bChildIndex.free
17042 if (bFree.length === bChildren.length) {
17044 children: bChildren,
17049 // O(N) time, O(N) memory
17050 var aChildIndex = keyIndex(aChildren)
17051 var aKeys = aChildIndex.keys
17052 var aFree = aChildIndex.free
17054 if (aFree.length === aChildren.length) {
17056 children: bChildren,
17061 // O(MAX(N, M)) memory
17062 var newChildren = []
17065 var freeCount = bFree.length
17066 var deletedItems = 0
17068 // Iterate through a and match a node in b
17070 for (var i = 0 ; i < aChildren.length; i++) {
17071 var aItem = aChildren[i]
17075 if (bKeys.hasOwnProperty(aItem.key)) {
17076 // Match up the old keys
17077 itemIndex = bKeys[aItem.key]
17078 newChildren.push(bChildren[itemIndex])
17081 // Remove old keyed items
17082 itemIndex = i - deletedItems++
17083 newChildren.push(null)
17086 // Match the item in a with the next free item in b
17087 if (freeIndex < freeCount) {
17088 itemIndex = bFree[freeIndex++]
17089 newChildren.push(bChildren[itemIndex])
17091 // There are no free items in b to match with
17092 // the free items in a, so the extra free nodes
17094 itemIndex = i - deletedItems++
17095 newChildren.push(null)
17100 var lastFreeIndex = freeIndex >= bFree.length ?
17104 // Iterate through b and append any new keys
17106 for (var j = 0; j < bChildren.length; j++) {
17107 var newItem = bChildren[j]
17110 if (!aKeys.hasOwnProperty(newItem.key)) {
17111 // Add any new keyed items
17112 // We are adding new items to the end and then sorting them
17113 // in place. In future we should insert new items in place.
17114 newChildren.push(newItem)
17116 } else if (j >= lastFreeIndex) {
17117 // Add any leftover non-keyed items
17118 newChildren.push(newItem)
17122 var simulate = newChildren.slice()
17123 var simulateIndex = 0
17128 for (var k = 0; k < bChildren.length;) {
17129 var wantedItem = bChildren[k]
17130 simulateItem = simulate[simulateIndex]
17133 while (simulateItem === null && simulate.length) {
17134 removes.push(remove(simulate, simulateIndex, null))
17135 simulateItem = simulate[simulateIndex]
17138 if (!simulateItem || simulateItem.key !== wantedItem.key) {
17139 // if we need a key in this position...
17140 if (wantedItem.key) {
17141 if (simulateItem && simulateItem.key) {
17142 // if an insert doesn't put this key in place, it needs to move
17143 if (bKeys[simulateItem.key] !== k + 1) {
17144 removes.push(remove(simulate, simulateIndex, simulateItem.key))
17145 simulateItem = simulate[simulateIndex]
17146 // if the remove didn't put the wanted item in place, we need to insert it
17147 if (!simulateItem || simulateItem.key !== wantedItem.key) {
17148 inserts.push({key: wantedItem.key, to: k})
17150 // items are matching, so skip ahead
17156 inserts.push({key: wantedItem.key, to: k})
17160 inserts.push({key: wantedItem.key, to: k})
17164 // a key in simulate has no matching wanted key, remove it
17165 else if (simulateItem && simulateItem.key) {
17166 removes.push(remove(simulate, simulateIndex, simulateItem.key))
17175 // remove all the remaining nodes from simulate
17176 while(simulateIndex < simulate.length) {
17177 simulateItem = simulate[simulateIndex]
17178 removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key))
17181 // If the only moves we have are deletes then we can just
17182 // let the delete patch remove these items.
17183 if (removes.length === deletedItems && !inserts.length) {
17185 children: newChildren,
17191 children: newChildren,
17199 function remove(arr, index, key) {
17200 arr.splice(index, 1)
17208 function keyIndex(children) {
17211 var length = children.length
17213 for (var i = 0; i < length; i++) {
17214 var child = children[i]
17217 keys[child.key] = i
17224 keys: keys, // A hash of key name to index
17225 free: free // An array of unkeyed item indices
17229 function appendPatch(apply, patch) {
17231 if (isArray(apply)) {
17234 apply = [apply, patch]
17243 },{"../vnode/handle-thunk":193,"../vnode/is-thunk":194,"../vnode/is-vnode":196,"../vnode/is-vtext":197,"../vnode/is-widget":198,"../vnode/vpatch":201,"./diff-props":203,"x-is-array":223}],205:[function(require,module,exports){
17244 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17245 /** @author Brian Cavalier */
17246 /** @author John Hann */
17248 (function(define) { 'use strict';
17249 define(function (require) {
17251 var makePromise = require('./makePromise');
17252 var Scheduler = require('./Scheduler');
17253 var async = require('./env').asap;
17255 return makePromise({
17256 scheduler: new Scheduler(async)
17260 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
17262 },{"./Scheduler":206,"./env":218,"./makePromise":220}],206:[function(require,module,exports){
17263 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17264 /** @author Brian Cavalier */
17265 /** @author John Hann */
17267 (function(define) { 'use strict';
17268 define(function() {
17270 // Credit to Twisol (https://github.com/Twisol) for suggesting
17271 // this type of extensible queue + trampoline approach for next-tick conflation.
17274 * Async task scheduler
17275 * @param {function} async function to schedule a single async function
17278 function Scheduler(async) {
17279 this._async = async;
17280 this._running = false;
17282 this._queue = this;
17283 this._queueLen = 0;
17284 this._afterQueue = {};
17285 this._afterQueueLen = 0;
17288 this.drain = function() {
17295 * @param {{ run:function }} task
17297 Scheduler.prototype.enqueue = function(task) {
17298 this._queue[this._queueLen++] = task;
17303 * Enqueue a task to run after the main task queue
17304 * @param {{ run:function }} task
17306 Scheduler.prototype.afterQueue = function(task) {
17307 this._afterQueue[this._afterQueueLen++] = task;
17311 Scheduler.prototype.run = function() {
17312 if (!this._running) {
17313 this._running = true;
17314 this._async(this.drain);
17319 * Drain the handler queue entirely, and then the after queue
17321 Scheduler.prototype._drain = function() {
17323 for (; i < this._queueLen; ++i) {
17324 this._queue[i].run();
17325 this._queue[i] = void 0;
17328 this._queueLen = 0;
17329 this._running = false;
17331 for (i = 0; i < this._afterQueueLen; ++i) {
17332 this._afterQueue[i].run();
17333 this._afterQueue[i] = void 0;
17336 this._afterQueueLen = 0;
17342 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17344 },{}],207:[function(require,module,exports){
17345 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17346 /** @author Brian Cavalier */
17347 /** @author John Hann */
17349 (function(define) { 'use strict';
17350 define(function() {
17353 * Custom error type for promises rejected by promise.timeout
17354 * @param {string} message
17357 function TimeoutError (message) {
17359 this.message = message;
17360 this.name = TimeoutError.name;
17361 if (typeof Error.captureStackTrace === 'function') {
17362 Error.captureStackTrace(this, TimeoutError);
17366 TimeoutError.prototype = Object.create(Error.prototype);
17367 TimeoutError.prototype.constructor = TimeoutError;
17369 return TimeoutError;
17371 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17372 },{}],208:[function(require,module,exports){
17373 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17374 /** @author Brian Cavalier */
17375 /** @author John Hann */
17377 (function(define) { 'use strict';
17378 define(function() {
17380 makeApply.tryCatchResolve = tryCatchResolve;
17384 function makeApply(Promise, call) {
17385 if(arguments.length < 2) {
17386 call = tryCatchResolve;
17391 function apply(f, thisArg, args) {
17392 var p = Promise._defer();
17393 var l = args.length;
17394 var params = new Array(l);
17395 callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
17400 function callAndResolve(c, h) {
17402 return call(c.f, c.thisArg, c.params, h);
17405 var handler = Promise._handler(c.args[c.i]);
17406 handler.fold(callAndResolveNext, c, void 0, h);
17409 function callAndResolveNext(c, x, h) {
17412 callAndResolve(c, h);
17416 function tryCatchResolve(f, thisArg, args, resolver) {
17418 resolver.resolve(f.apply(thisArg, args));
17420 resolver.reject(e);
17425 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17429 },{}],209:[function(require,module,exports){
17430 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17431 /** @author Brian Cavalier */
17432 /** @author John Hann */
17434 (function(define) { 'use strict';
17435 define(function(require) {
17437 var state = require('../state');
17438 var applier = require('../apply');
17440 return function array(Promise) {
17442 var applyFold = applier(Promise);
17443 var toPromise = Promise.resolve;
17444 var all = Promise.all;
17446 var ar = Array.prototype.reduce;
17447 var arr = Array.prototype.reduceRight;
17448 var slice = Array.prototype.slice;
17450 // Additional array combinators
17453 Promise.some = some;
17454 Promise.settle = settle;
17457 Promise.filter = filter;
17458 Promise.reduce = reduce;
17459 Promise.reduceRight = reduceRight;
17462 * When this promise fulfills with an array, do
17463 * onFulfilled.apply(void 0, array)
17464 * @param {function} onFulfilled function to apply
17465 * @returns {Promise} promise for the result of applying onFulfilled
17467 Promise.prototype.spread = function(onFulfilled) {
17468 return this.then(all).then(function(array) {
17469 return onFulfilled.apply(this, array);
17476 * One-winner competitive race.
17477 * Return a promise that will fulfill when one of the promises
17478 * in the input array fulfills, or will reject when all promises
17480 * @param {array} promises
17481 * @returns {Promise} promise for the first fulfilled value
17483 function any(promises) {
17484 var p = Promise._defer();
17485 var resolver = p._handler;
17486 var l = promises.length>>>0;
17491 for (var h, x, i = 0; i < l; ++i) {
17493 if(x === void 0 && !(i in promises)) {
17498 h = Promise._handler(x);
17499 if(h.state() > 0) {
17500 resolver.become(h);
17501 Promise._visitRemaining(promises, i, h);
17504 h.visit(resolver, handleFulfill, handleReject);
17508 if(pending === 0) {
17509 resolver.reject(new RangeError('any(): array must not be empty'));
17514 function handleFulfill(x) {
17515 /*jshint validthis:true*/
17517 this.resolve(x); // this === resolver
17520 function handleReject(e) {
17521 /*jshint validthis:true*/
17522 if(this.resolved) { // this === resolver
17527 if(--pending === 0) {
17528 this.reject(errors);
17534 * N-winner competitive race
17535 * Return a promise that will fulfill when n input promises have
17536 * fulfilled, or will reject when it becomes impossible for n
17537 * input promises to fulfill (ie when promises.length - n + 1
17539 * @param {array} promises
17540 * @param {number} n
17541 * @returns {Promise} promise for the earliest n fulfillment values
17545 function some(promises, n) {
17546 /*jshint maxcomplexity:7*/
17547 var p = Promise._defer();
17548 var resolver = p._handler;
17553 var l = promises.length>>>0;
17556 var x, i; // reused in both for() loops
17558 // First pass: count actual array items
17559 for(i=0; i<l; ++i) {
17561 if(x === void 0 && !(i in promises)) {
17567 // Compute actual goals
17568 n = Math.max(n, 0);
17569 nReject = (nFulfill - n + 1);
17570 nFulfill = Math.min(n, nFulfill);
17573 resolver.reject(new RangeError('some(): array must contain at least '
17574 + n + ' item(s), but had ' + nFulfill));
17575 } else if(nFulfill === 0) {
17576 resolver.resolve(results);
17579 // Second pass: observe each array item, make progress toward goals
17580 for(i=0; i<l; ++i) {
17582 if(x === void 0 && !(i in promises)) {
17586 Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
17591 function fulfill(x) {
17592 /*jshint validthis:true*/
17593 if(this.resolved) { // this === resolver
17598 if(--nFulfill === 0) {
17600 this.resolve(results);
17604 function reject(e) {
17605 /*jshint validthis:true*/
17606 if(this.resolved) { // this === resolver
17611 if(--nReject === 0) {
17613 this.reject(errors);
17619 * Apply f to the value of each promise in a list of promises
17620 * and return a new list containing the results.
17621 * @param {array} promises
17622 * @param {function(x:*, index:Number):*} f mapping function
17623 * @returns {Promise}
17625 function map(promises, f) {
17626 return Promise._traverse(f, promises);
17630 * Filter the provided array of promises using the provided predicate. Input may
17631 * contain promises and values
17632 * @param {Array} promises array of promises and values
17633 * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
17634 * Must return truthy (or promise for truthy) for items to retain.
17635 * @returns {Promise} promise that will fulfill with an array containing all items
17636 * for which predicate returned truthy.
17638 function filter(promises, predicate) {
17639 var a = slice.call(promises);
17640 return Promise._traverse(predicate, a).then(function(keep) {
17641 return filterSync(a, keep);
17645 function filterSync(promises, keep) {
17646 // Safe because we know all promises have fulfilled if we've made it this far
17647 var l = keep.length;
17648 var filtered = new Array(l);
17649 for(var i=0, j=0; i<l; ++i) {
17651 filtered[j++] = Promise._handler(promises[i]).value;
17654 filtered.length = j;
17660 * Return a promise that will always fulfill with an array containing
17661 * the outcome states of all input promises. The returned promise
17662 * will never reject.
17663 * @param {Array} promises
17664 * @returns {Promise} promise for array of settled state descriptors
17666 function settle(promises) {
17667 return all(promises.map(settleOne));
17670 function settleOne(p) {
17671 // Optimize the case where we get an already-resolved when.js promise
17672 // by extracting its state:
17674 if (p instanceof Promise) {
17675 // This is our own Promise type and we can reach its handler internals:
17676 handler = p._handler.join();
17678 if((handler && handler.state() === 0) || !handler) {
17679 // Either still pending, or not a Promise at all:
17680 return toPromise(p).then(state.fulfilled, state.rejected);
17683 // The promise is our own, but it is already resolved. Take a shortcut.
17684 // Since we're not actually handling the resolution, we need to disable
17685 // rejection reporting.
17686 handler._unreport();
17687 return state.inspect(handler);
17691 * Traditional reduce function, similar to `Array.prototype.reduce()`, but
17692 * input may contain promises and/or values, and reduceFunc
17693 * may return either a value or a promise, *and* initialValue may
17694 * be a promise for the starting value.
17695 * @param {Array|Promise} promises array or promise for an array of anything,
17696 * may contain a mix of promises and values.
17697 * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
17698 * @returns {Promise} that will resolve to the final reduced value
17700 function reduce(promises, f /*, initialValue */) {
17701 return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
17702 : ar.call(promises, liftCombine(f));
17706 * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
17707 * input may contain promises and/or values, and reduceFunc
17708 * may return either a value or a promise, *and* initialValue may
17709 * be a promise for the starting value.
17710 * @param {Array|Promise} promises array or promise for an array of anything,
17711 * may contain a mix of promises and values.
17712 * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
17713 * @returns {Promise} that will resolve to the final reduced value
17715 function reduceRight(promises, f /*, initialValue */) {
17716 return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
17717 : arr.call(promises, liftCombine(f));
17720 function liftCombine(f) {
17721 return function(z, x, i) {
17722 return applyFold(f, void 0, [z,x,i]);
17728 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
17730 },{"../apply":208,"../state":221}],210:[function(require,module,exports){
17731 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17732 /** @author Brian Cavalier */
17733 /** @author John Hann */
17735 (function(define) { 'use strict';
17736 define(function() {
17738 return function flow(Promise) {
17740 var resolve = Promise.resolve;
17741 var reject = Promise.reject;
17742 var origCatch = Promise.prototype['catch'];
17745 * Handle the ultimate fulfillment value or rejection reason, and assume
17746 * responsibility for all errors. If an error propagates out of result
17747 * or handleFatalError, it will be rethrown to the host, resulting in a
17748 * loud stack track on most platforms and a crash on some.
17749 * @param {function?} onResult
17750 * @param {function?} onError
17751 * @returns {undefined}
17753 Promise.prototype.done = function(onResult, onError) {
17754 this._handler.visit(this._handler.receiver, onResult, onError);
17758 * Add Error-type and predicate matching to catch. Examples:
17759 * promise.catch(TypeError, handleTypeError)
17760 * .catch(predicate, handleMatchedErrors)
17761 * .catch(handleRemainingErrors)
17762 * @param onRejected
17765 Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
17766 if (arguments.length < 2) {
17767 return origCatch.call(this, onRejected);
17770 if(typeof onRejected !== 'function') {
17771 return this.ensure(rejectInvalidPredicate);
17774 return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
17778 * Wraps the provided catch handler, so that it will only be called
17779 * if the predicate evaluates truthy
17780 * @param {?function} handler
17781 * @param {function} predicate
17782 * @returns {function} conditional catch handler
17784 function createCatchFilter(handler, predicate) {
17785 return function(e) {
17786 return evaluatePredicate(e, predicate)
17787 ? handler.call(this, e)
17793 * Ensures that onFulfilledOrRejected will be called regardless of whether
17794 * this promise is fulfilled or rejected. onFulfilledOrRejected WILL NOT
17795 * receive the promises' value or reason. Any returned value will be disregarded.
17796 * onFulfilledOrRejected may throw or return a rejected promise to signal
17797 * an additional error.
17798 * @param {function} handler handler to be called regardless of
17799 * fulfillment or rejection
17800 * @returns {Promise}
17802 Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
17803 if(typeof handler !== 'function') {
17807 return this.then(function(x) {
17808 return runSideEffect(handler, this, identity, x);
17810 return runSideEffect(handler, this, reject, e);
17814 function runSideEffect (handler, thisArg, propagate, value) {
17815 var result = handler.call(thisArg);
17816 return maybeThenable(result)
17817 ? propagateValue(result, propagate, value)
17818 : propagate(value);
17821 function propagateValue (result, propagate, x) {
17822 return resolve(result).then(function () {
17823 return propagate(x);
17828 * Recover from a failure by returning a defaultValue. If defaultValue
17829 * is a promise, it's fulfillment value will be used. If defaultValue is
17830 * a promise that rejects, the returned promise will reject with the
17832 * @param {*} defaultValue
17833 * @returns {Promise} new promise
17835 Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
17836 return this.then(void 0, function() {
17837 return defaultValue;
17842 * Shortcut for .then(function() { return value; })
17844 * @return {Promise} a promise that:
17845 * - is fulfilled if value is not a promise, or
17846 * - if value is a promise, will fulfill with its value, or reject
17849 Promise.prototype['yield'] = function(value) {
17850 return this.then(function() {
17856 * Runs a side effect when this promise fulfills, without changing the
17857 * fulfillment value.
17858 * @param {function} onFulfilledSideEffect
17859 * @returns {Promise}
17861 Promise.prototype.tap = function(onFulfilledSideEffect) {
17862 return this.then(onFulfilledSideEffect)['yield'](this);
17868 function rejectInvalidPredicate() {
17869 throw new TypeError('catch predicate must be a function');
17872 function evaluatePredicate(e, predicate) {
17873 return isError(predicate) ? e instanceof predicate : predicate(e);
17876 function isError(predicate) {
17877 return predicate === Error
17878 || (predicate != null && predicate.prototype instanceof Error);
17881 function maybeThenable(x) {
17882 return (typeof x === 'object' || typeof x === 'function') && x !== null;
17885 function identity(x) {
17890 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17892 },{}],211:[function(require,module,exports){
17893 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17894 /** @author Brian Cavalier */
17895 /** @author John Hann */
17896 /** @author Jeff Escalante */
17898 (function(define) { 'use strict';
17899 define(function() {
17901 return function fold(Promise) {
17903 Promise.prototype.fold = function(f, z) {
17904 var promise = this._beget();
17906 this._handler.fold(function(z, x, to) {
17907 Promise._handler(z).fold(function(x, z, to) {
17908 to.resolve(f.call(this, z, x));
17910 }, z, promise._handler.receiver, promise._handler);
17919 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17921 },{}],212:[function(require,module,exports){
17922 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17923 /** @author Brian Cavalier */
17924 /** @author John Hann */
17926 (function(define) { 'use strict';
17927 define(function(require) {
17929 var inspect = require('../state').inspect;
17931 return function inspection(Promise) {
17933 Promise.prototype.inspect = function() {
17934 return inspect(Promise._handler(this));
17941 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
17943 },{"../state":221}],213:[function(require,module,exports){
17944 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17945 /** @author Brian Cavalier */
17946 /** @author John Hann */
17948 (function(define) { 'use strict';
17949 define(function() {
17951 return function generate(Promise) {
17953 var resolve = Promise.resolve;
17955 Promise.iterate = iterate;
17956 Promise.unfold = unfold;
17961 * @deprecated Use github.com/cujojs/most streams and most.iterate
17962 * Generate a (potentially infinite) stream of promised values:
17963 * x, f(x), f(f(x)), etc. until condition(x) returns true
17964 * @param {function} f function to generate a new x from the previous x
17965 * @param {function} condition function that, given the current x, returns
17966 * truthy when the iterate should stop
17967 * @param {function} handler function to handle the value produced by f
17968 * @param {*|Promise} x starting value, may be a promise
17969 * @return {Promise} the result of the last call to f before
17970 * condition returns true
17972 function iterate(f, condition, handler, x) {
17973 return unfold(function(x) {
17975 }, condition, handler, x);
17979 * @deprecated Use github.com/cujojs/most streams and most.unfold
17980 * Generate a (potentially infinite) stream of promised values
17981 * by applying handler(generator(seed)) iteratively until
17982 * condition(seed) returns true.
17983 * @param {function} unspool function that generates a [value, newSeed]
17985 * @param {function} condition function that, given the current seed, returns
17986 * truthy when the unfold should stop
17987 * @param {function} handler function to handle the value produced by unspool
17988 * @param x {*|Promise} starting value, may be a promise
17989 * @return {Promise} the result of the last value produced by unspool before
17990 * condition returns true
17992 function unfold(unspool, condition, handler, x) {
17993 return resolve(x).then(function(seed) {
17994 return resolve(condition(seed)).then(function(done) {
17995 return done ? seed : resolve(unspool(seed)).spread(next);
17999 function next(item, newSeed) {
18000 return resolve(handler(item)).then(function() {
18001 return unfold(unspool, condition, handler, newSeed);
18008 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18010 },{}],214:[function(require,module,exports){
18011 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18012 /** @author Brian Cavalier */
18013 /** @author John Hann */
18015 (function(define) { 'use strict';
18016 define(function() {
18018 return function progress(Promise) {
18022 * Register a progress handler for this promise
18023 * @param {function} onProgress
18024 * @returns {Promise}
18026 Promise.prototype.progress = function(onProgress) {
18027 return this.then(void 0, void 0, onProgress);
18034 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18036 },{}],215:[function(require,module,exports){
18037 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18038 /** @author Brian Cavalier */
18039 /** @author John Hann */
18041 (function(define) { 'use strict';
18042 define(function(require) {
18044 var env = require('../env');
18045 var TimeoutError = require('../TimeoutError');
18047 function setTimeout(f, ms, x, y) {
18048 return env.setTimer(function() {
18053 return function timed(Promise) {
18055 * Return a new promise whose fulfillment value is revealed only
18056 * after ms milliseconds
18057 * @param {number} ms milliseconds
18058 * @returns {Promise}
18060 Promise.prototype.delay = function(ms) {
18061 var p = this._beget();
18062 this._handler.fold(handleDelay, ms, void 0, p._handler);
18066 function handleDelay(ms, x, h) {
18067 setTimeout(resolveDelay, ms, x, h);
18070 function resolveDelay(x, h) {
18075 * Return a new promise that rejects after ms milliseconds unless
18076 * this promise fulfills earlier, in which case the returned promise
18077 * fulfills with the same value.
18078 * @param {number} ms milliseconds
18079 * @param {Error|*=} reason optional rejection reason to use, defaults
18080 * to a TimeoutError if not provided
18081 * @returns {Promise}
18083 Promise.prototype.timeout = function(ms, reason) {
18084 var p = this._beget();
18085 var h = p._handler;
18087 var t = setTimeout(onTimeout, ms, reason, p._handler);
18089 this._handler.visit(h,
18090 function onFulfill(x) {
18092 this.resolve(x); // this = h
18094 function onReject(x) {
18096 this.reject(x); // this = h
18103 function onTimeout(reason, h, ms) {
18104 var e = typeof reason === 'undefined'
18105 ? new TimeoutError('timed out after ' + ms + 'ms')
18114 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18116 },{"../TimeoutError":207,"../env":218}],216:[function(require,module,exports){
18117 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18118 /** @author Brian Cavalier */
18119 /** @author John Hann */
18121 (function(define) { 'use strict';
18122 define(function(require) {
18124 var setTimer = require('../env').setTimer;
18125 var format = require('../format');
18127 return function unhandledRejection(Promise) {
18129 var logError = noop;
18130 var logInfo = noop;
18133 if(typeof console !== 'undefined') {
18134 // Alias console to prevent things like uglify's drop_console option from
18135 // removing console.log/error. Unhandled rejections fall into the same
18136 // category as uncaught exceptions, and build tools shouldn't silence them.
18137 localConsole = console;
18138 logError = typeof localConsole.error !== 'undefined'
18139 ? function (e) { localConsole.error(e); }
18140 : function (e) { localConsole.log(e); };
18142 logInfo = typeof localConsole.info !== 'undefined'
18143 ? function (e) { localConsole.info(e); }
18144 : function (e) { localConsole.log(e); };
18147 Promise.onPotentiallyUnhandledRejection = function(rejection) {
18148 enqueue(report, rejection);
18151 Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
18152 enqueue(unreport, rejection);
18155 Promise.onFatalRejection = function(rejection) {
18156 enqueue(throwit, rejection.value);
18161 var running = null;
18163 function report(r) {
18166 logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
18170 function unreport(r) {
18171 var i = reported.indexOf(r);
18173 reported.splice(i, 1);
18174 logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
18178 function enqueue(f, x) {
18180 if(running === null) {
18181 running = setTimer(flush, 0);
18187 while(tasks.length > 0) {
18188 tasks.shift()(tasks.shift());
18195 function throwit(e) {
18202 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18204 },{"../env":218,"../format":219}],217:[function(require,module,exports){
18205 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18206 /** @author Brian Cavalier */
18207 /** @author John Hann */
18209 (function(define) { 'use strict';
18210 define(function() {
18212 return function addWith(Promise) {
18214 * Returns a promise whose handlers will be called with `this` set to
18215 * the supplied receiver. Subsequent promises derived from the
18216 * returned promise will also have their handlers called with receiver
18217 * as `this`. Calling `with` with undefined or no arguments will return
18218 * a promise whose handlers will again be called in the usual Promises/A+
18219 * way (no `this`) thus safely undoing any previous `with` in the
18222 * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
18223 * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
18225 * @param {object} receiver `this` value for all handlers attached to
18226 * the returned promise.
18227 * @returns {Promise}
18229 Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
18230 var p = this._beget();
18231 var child = p._handler;
18232 child.receiver = receiver;
18233 this._handler.chain(child, receiver);
18241 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18244 },{}],218:[function(require,module,exports){
18245 (function (process){
18246 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18247 /** @author Brian Cavalier */
18248 /** @author John Hann */
18250 /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
18251 (function(define) { 'use strict';
18252 define(function(require) {
18253 /*jshint maxcomplexity:6*/
18255 // Sniff "best" async scheduling option
18256 // Prefer process.nextTick or MutationObserver, then check for
18257 // setTimeout, and finally vertx, since its the only env that doesn't
18261 var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
18264 var setTimer = function(f, ms) { return setTimeout(f, ms); };
18265 var clearTimer = function(t) { return clearTimeout(t); };
18266 var asap = function (f) { return capturedSetTimeout(f, 0); };
18268 // Detect specific env
18269 if (isNode()) { // Node
18270 asap = function (f) { return process.nextTick(f); };
18272 } else if (MutationObs = hasMutationObserver()) { // Modern browser
18273 asap = initMutationObserver(MutationObs);
18275 } else if (!capturedSetTimeout) { // vert.x
18276 var vertxRequire = require;
18277 var vertx = vertxRequire('vertx');
18278 setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
18279 clearTimer = vertx.cancelTimer;
18280 asap = vertx.runOnLoop || vertx.runOnContext;
18284 setTimer: setTimer,
18285 clearTimer: clearTimer,
18289 function isNode () {
18290 return typeof process !== 'undefined' &&
18291 Object.prototype.toString.call(process) === '[object process]';
18294 function hasMutationObserver () {
18295 return (typeof MutationObserver !== 'undefined' && MutationObserver) ||
18296 (typeof WebKitMutationObserver !== 'undefined' && WebKitMutationObserver);
18299 function initMutationObserver(MutationObserver) {
18301 var node = document.createTextNode('');
18302 var o = new MutationObserver(run);
18303 o.observe(node, { characterData: true });
18307 scheduled = void 0;
18312 return function (f) {
18314 node.data = (i ^= 1);
18318 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18320 }).call(this,require('_process'))
18322 },{"_process":4}],219:[function(require,module,exports){
18323 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18324 /** @author Brian Cavalier */
18325 /** @author John Hann */
18327 (function(define) { 'use strict';
18328 define(function() {
18331 formatError: formatError,
18332 formatObject: formatObject,
18333 tryStringify: tryStringify
18337 * Format an error into a string. If e is an Error and has a stack property,
18338 * it's returned. Otherwise, e is formatted using formatObject, with a
18339 * warning added about e not being a proper Error.
18341 * @returns {String} formatted string, suitable for output to developers
18343 function formatError(e) {
18344 var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
18345 return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
18349 * Format an object, detecting "plain" objects and running them through
18350 * JSON.stringify if possible.
18351 * @param {Object} o
18352 * @returns {string}
18354 function formatObject(o) {
18356 if(s === '[object Object]' && typeof JSON !== 'undefined') {
18357 s = tryStringify(o, s);
18363 * Try to return the result of JSON.stringify(x). If that fails, return
18366 * @param {*} defaultValue
18367 * @returns {String|*} JSON.stringify(x) or defaultValue
18369 function tryStringify(x, defaultValue) {
18371 return JSON.stringify(x);
18373 return defaultValue;
18378 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18380 },{}],220:[function(require,module,exports){
18381 (function (process){
18382 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18383 /** @author Brian Cavalier */
18384 /** @author John Hann */
18386 (function(define) { 'use strict';
18387 define(function() {
18389 return function makePromise(environment) {
18391 var tasks = environment.scheduler;
18392 var emitRejection = initEmitRejection();
18394 var objectCreate = Object.create ||
18396 function Child() {}
18397 Child.prototype = proto;
18398 return new Child();
18402 * Create a promise whose fate is determined by resolver
18404 * @returns {Promise} promise
18407 function Promise(resolver, handler) {
18408 this._handler = resolver === Handler ? handler : init(resolver);
18412 * Run the supplied resolver
18414 * @returns {Pending}
18416 function init(resolver) {
18417 var handler = new Pending();
18420 resolver(promiseResolve, promiseReject, promiseNotify);
18428 * Transition from pre-resolution state to post-resolution state, notifying
18429 * all listeners of the ultimate fulfillment or rejection
18430 * @param {*} x resolution value
18432 function promiseResolve (x) {
18433 handler.resolve(x);
18436 * Reject this promise with reason, which will be used verbatim
18437 * @param {Error|*} reason rejection reason, strongly suggested
18438 * to be an Error type
18440 function promiseReject (reason) {
18441 handler.reject(reason);
18446 * Issue a progress event, notifying all progress listeners
18447 * @param {*} x progress event payload to pass to all listeners
18449 function promiseNotify (x) {
18456 Promise.resolve = resolve;
18457 Promise.reject = reject;
18458 Promise.never = never;
18460 Promise._defer = defer;
18461 Promise._handler = getHandler;
18464 * Returns a trusted promise. If x is already a trusted promise, it is
18465 * returned, otherwise returns a new trusted Promise which follows x.
18467 * @return {Promise} promise
18469 function resolve(x) {
18470 return isPromise(x) ? x
18471 : new Promise(Handler, new Async(getHandler(x)));
18475 * Return a reject promise with x as its reason (x is used verbatim)
18477 * @returns {Promise} rejected promise
18479 function reject(x) {
18480 return new Promise(Handler, new Async(new Rejected(x)));
18484 * Return a promise that remains pending forever
18485 * @returns {Promise} forever-pending promise.
18488 return foreverPendingPromise; // Should be frozen
18492 * Creates an internal {promise, resolver} pair
18494 * @returns {Promise}
18497 return new Promise(Handler, new Pending());
18500 // Transformation and flow control
18503 * Transform this promise's fulfillment value, returning a new Promise
18504 * for the transformed result. If the promise cannot be fulfilled, onRejected
18505 * is called with the reason. onProgress *may* be called with updates toward
18506 * this promise's fulfillment.
18507 * @param {function=} onFulfilled fulfillment handler
18508 * @param {function=} onRejected rejection handler
18509 * @param {function=} onProgress @deprecated progress handler
18510 * @return {Promise} new promise
18512 Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
18513 var parent = this._handler;
18514 var state = parent.join().state();
18516 if ((typeof onFulfilled !== 'function' && state > 0) ||
18517 (typeof onRejected !== 'function' && state < 0)) {
18518 // Short circuit: value will not change, simply share handler
18519 return new this.constructor(Handler, parent);
18522 var p = this._beget();
18523 var child = p._handler;
18525 parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
18531 * If this promise cannot be fulfilled due to an error, call onRejected to
18532 * handle the error. Shortcut for .then(undefined, onRejected)
18533 * @param {function?} onRejected
18534 * @return {Promise}
18536 Promise.prototype['catch'] = function(onRejected) {
18537 return this.then(void 0, onRejected);
18541 * Creates a new, pending promise of the same type as this promise
18543 * @returns {Promise}
18545 Promise.prototype._beget = function() {
18546 return begetFrom(this._handler, this.constructor);
18549 function begetFrom(parent, Promise) {
18550 var child = new Pending(parent.receiver, parent.join().context);
18551 return new Promise(Handler, child);
18554 // Array combinators
18557 Promise.race = race;
18558 Promise._traverse = traverse;
18561 * Return a promise that will fulfill when all promises in the
18562 * input array have fulfilled, or will reject when one of the
18563 * promises rejects.
18564 * @param {array} promises array of promises
18565 * @returns {Promise} promise for array of fulfillment values
18567 function all(promises) {
18568 return traverseWith(snd, null, promises);
18572 * Array<Promise<X>> -> Promise<Array<f(X)>>
18574 * @param {function} f function to apply to each promise's value
18575 * @param {Array} promises array of promises
18576 * @returns {Promise} promise for transformed values
18578 function traverse(f, promises) {
18579 return traverseWith(tryCatch2, f, promises);
18582 function traverseWith(tryMap, f, promises) {
18583 var handler = typeof f === 'function' ? mapAt : settleAt;
18585 var resolver = new Pending();
18586 var pending = promises.length >>> 0;
18587 var results = new Array(pending);
18589 for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
18592 if (x === void 0 && !(i in promises)) {
18597 traverseAt(promises, handler, i, x, resolver);
18600 if(pending === 0) {
18601 resolver.become(new Fulfilled(results));
18604 return new Promise(Handler, resolver);
18606 function mapAt(i, x, resolver) {
18607 if(!resolver.resolved) {
18608 traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
18612 function settleAt(i, x, resolver) {
18614 if(--pending === 0) {
18615 resolver.become(new Fulfilled(results));
18620 function traverseAt(promises, handler, i, x, resolver) {
18621 if (maybeThenable(x)) {
18622 var h = getHandlerMaybeThenable(x);
18626 h.fold(handler, i, void 0, resolver);
18627 } else if (s > 0) {
18628 handler(i, h.value, resolver);
18630 resolver.become(h);
18631 visitRemaining(promises, i+1, h);
18634 handler(i, x, resolver);
18638 Promise._visitRemaining = visitRemaining;
18639 function visitRemaining(promises, start, handler) {
18640 for(var i=start; i<promises.length; ++i) {
18641 markAsHandled(getHandler(promises[i]), handler);
18645 function markAsHandled(h, handler) {
18646 if(h === handler) {
18652 h.visit(h, void 0, h._unreport);
18659 * Fulfill-reject competitive race. Return a promise that will settle
18660 * to the same state as the earliest input promise to settle.
18662 * WARNING: The ES6 Promise spec requires that race()ing an empty array
18663 * must return a promise that is pending forever. This implementation
18664 * returns a singleton forever-pending promise, the same singleton that is
18665 * returned by Promise.never(), thus can be checked with ===
18667 * @param {array} promises array of promises to race
18668 * @returns {Promise} if input is non-empty, a promise that will settle
18669 * to the same outcome as the earliest input promise to settle. if empty
18670 * is empty, returns a promise that will never settle.
18672 function race(promises) {
18673 if(typeof promises !== 'object' || promises === null) {
18674 return reject(new TypeError('non-iterable passed to race()'));
18677 // Sigh, race([]) is untestable unless we return *something*
18678 // that is recognizable without calling .then() on it.
18679 return promises.length === 0 ? never()
18680 : promises.length === 1 ? resolve(promises[0])
18681 : runRace(promises);
18684 function runRace(promises) {
18685 var resolver = new Pending();
18687 for(i=0; i<promises.length; ++i) {
18689 if (x === void 0 && !(i in promises)) {
18694 if(h.state() !== 0) {
18695 resolver.become(h);
18696 visitRemaining(promises, i+1, h);
18699 h.visit(resolver, resolver.resolve, resolver.reject);
18702 return new Promise(Handler, resolver);
18705 // Promise internals
18706 // Below this, everything is @private
18709 * Get an appropriate handler for x, without checking for cycles
18711 * @returns {object} handler
18713 function getHandler(x) {
18715 return x._handler.join();
18717 return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
18721 * Get a handler for thenable x.
18722 * NOTE: You must only call this if maybeThenable(x) == true
18723 * @param {object|function|Promise} x
18724 * @returns {object} handler
18726 function getHandlerMaybeThenable(x) {
18727 return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
18731 * Get a handler for potentially untrusted thenable x
18733 * @returns {object} handler
18735 function getHandlerUntrusted(x) {
18737 var untrustedThen = x.then;
18738 return typeof untrustedThen === 'function'
18739 ? new Thenable(untrustedThen, x)
18740 : new Fulfilled(x);
18742 return new Rejected(e);
18747 * Handler for a promise that is pending forever
18750 function Handler() {}
18752 Handler.prototype.when
18753 = Handler.prototype.become
18754 = Handler.prototype.notify // deprecated
18755 = Handler.prototype.fail
18756 = Handler.prototype._unreport
18757 = Handler.prototype._report
18760 Handler.prototype._state = 0;
18762 Handler.prototype.state = function() {
18763 return this._state;
18767 * Recursively collapse handler chain to find the handler
18768 * nearest to the fully resolved value.
18769 * @returns {object} handler nearest the fully resolved value
18771 Handler.prototype.join = function() {
18773 while(h.handler !== void 0) {
18779 Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
18782 receiver: receiver,
18783 fulfilled: fulfilled,
18784 rejected: rejected,
18789 Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
18790 this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
18793 Handler.prototype.fold = function(f, z, c, to) {
18794 this.when(new Fold(f, z, c, to));
18798 * Handler that invokes fail() on any handler it becomes
18801 function FailIfRejected() {}
18803 inherit(Handler, FailIfRejected);
18805 FailIfRejected.prototype.become = function(h) {
18809 var failIfRejected = new FailIfRejected();
18812 * Handler that manages a queue of consumers waiting on a pending promise
18815 function Pending(receiver, inheritedContext) {
18816 Promise.createContext(this, inheritedContext);
18818 this.consumers = void 0;
18819 this.receiver = receiver;
18820 this.handler = void 0;
18821 this.resolved = false;
18824 inherit(Handler, Pending);
18826 Pending.prototype._state = 0;
18828 Pending.prototype.resolve = function(x) {
18829 this.become(getHandler(x));
18832 Pending.prototype.reject = function(x) {
18833 if(this.resolved) {
18837 this.become(new Rejected(x));
18840 Pending.prototype.join = function() {
18841 if (!this.resolved) {
18847 while (h.handler !== void 0) {
18850 return this.handler = cycle();
18857 Pending.prototype.run = function() {
18858 var q = this.consumers;
18859 var handler = this.handler;
18860 this.handler = this.handler.join();
18861 this.consumers = void 0;
18863 for (var i = 0; i < q.length; ++i) {
18864 handler.when(q[i]);
18868 Pending.prototype.become = function(handler) {
18869 if(this.resolved) {
18873 this.resolved = true;
18874 this.handler = handler;
18875 if(this.consumers !== void 0) {
18876 tasks.enqueue(this);
18879 if(this.context !== void 0) {
18880 handler._report(this.context);
18884 Pending.prototype.when = function(continuation) {
18885 if(this.resolved) {
18886 tasks.enqueue(new ContinuationTask(continuation, this.handler));
18888 if(this.consumers === void 0) {
18889 this.consumers = [continuation];
18891 this.consumers.push(continuation);
18899 Pending.prototype.notify = function(x) {
18900 if(!this.resolved) {
18901 tasks.enqueue(new ProgressTask(x, this));
18905 Pending.prototype.fail = function(context) {
18906 var c = typeof context === 'undefined' ? this.context : context;
18907 this.resolved && this.handler.join().fail(c);
18910 Pending.prototype._report = function(context) {
18911 this.resolved && this.handler.join()._report(context);
18914 Pending.prototype._unreport = function() {
18915 this.resolved && this.handler.join()._unreport();
18919 * Wrap another handler and force it into a future stack
18920 * @param {object} handler
18923 function Async(handler) {
18924 this.handler = handler;
18927 inherit(Handler, Async);
18929 Async.prototype.when = function(continuation) {
18930 tasks.enqueue(new ContinuationTask(continuation, this));
18933 Async.prototype._report = function(context) {
18934 this.join()._report(context);
18937 Async.prototype._unreport = function() {
18938 this.join()._unreport();
18942 * Handler that wraps an untrusted thenable and assimilates it in a future stack
18943 * @param {function} then
18944 * @param {{then: function}} thenable
18947 function Thenable(then, thenable) {
18948 Pending.call(this);
18949 tasks.enqueue(new AssimilateTask(then, thenable, this));
18952 inherit(Pending, Thenable);
18955 * Handler for a fulfilled promise
18956 * @param {*} x fulfillment value
18959 function Fulfilled(x) {
18960 Promise.createContext(this);
18964 inherit(Handler, Fulfilled);
18966 Fulfilled.prototype._state = 1;
18968 Fulfilled.prototype.fold = function(f, z, c, to) {
18969 runContinuation3(f, z, this, c, to);
18972 Fulfilled.prototype.when = function(cont) {
18973 runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
18979 * Handler for a rejected promise
18980 * @param {*} x rejection reason
18983 function Rejected(x) {
18984 Promise.createContext(this);
18986 this.id = ++errorId;
18988 this.handled = false;
18989 this.reported = false;
18994 inherit(Handler, Rejected);
18996 Rejected.prototype._state = -1;
18998 Rejected.prototype.fold = function(f, z, c, to) {
19002 Rejected.prototype.when = function(cont) {
19003 if(typeof cont.rejected === 'function') {
19006 runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
19009 Rejected.prototype._report = function(context) {
19010 tasks.afterQueue(new ReportTask(this, context));
19013 Rejected.prototype._unreport = function() {
19017 this.handled = true;
19018 tasks.afterQueue(new UnreportTask(this));
19021 Rejected.prototype.fail = function(context) {
19022 this.reported = true;
19023 emitRejection('unhandledRejection', this);
19024 Promise.onFatalRejection(this, context === void 0 ? this.context : context);
19027 function ReportTask(rejection, context) {
19028 this.rejection = rejection;
19029 this.context = context;
19032 ReportTask.prototype.run = function() {
19033 if(!this.rejection.handled && !this.rejection.reported) {
19034 this.rejection.reported = true;
19035 emitRejection('unhandledRejection', this.rejection) ||
19036 Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
19040 function UnreportTask(rejection) {
19041 this.rejection = rejection;
19044 UnreportTask.prototype.run = function() {
19045 if(this.rejection.reported) {
19046 emitRejection('rejectionHandled', this.rejection) ||
19047 Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
19051 // Unhandled rejection hooks
19052 // By default, everything is a noop
19054 Promise.createContext
19055 = Promise.enterContext
19056 = Promise.exitContext
19057 = Promise.onPotentiallyUnhandledRejection
19058 = Promise.onPotentiallyUnhandledRejectionHandled
19059 = Promise.onFatalRejection
19062 // Errors and singletons
19064 var foreverPendingHandler = new Handler();
19065 var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
19068 return new Rejected(new TypeError('Promise cycle'));
19074 * Run a single consumer
19077 function ContinuationTask(continuation, handler) {
19078 this.continuation = continuation;
19079 this.handler = handler;
19082 ContinuationTask.prototype.run = function() {
19083 this.handler.join().when(this.continuation);
19087 * Run a queue of progress handlers
19090 function ProgressTask(value, handler) {
19091 this.handler = handler;
19092 this.value = value;
19095 ProgressTask.prototype.run = function() {
19096 var q = this.handler.consumers;
19101 for (var c, i = 0; i < q.length; ++i) {
19103 runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
19108 * Assimilate a thenable, sending it's value to resolver
19109 * @param {function} then
19110 * @param {object|function} thenable
19111 * @param {object} resolver
19114 function AssimilateTask(then, thenable, resolver) {
19116 this.thenable = thenable;
19117 this.resolver = resolver;
19120 AssimilateTask.prototype.run = function() {
19121 var h = this.resolver;
19122 tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
19124 function _resolve(x) { h.resolve(x); }
19125 function _reject(x) { h.reject(x); }
19126 function _notify(x) { h.notify(x); }
19129 function tryAssimilate(then, thenable, resolve, reject, notify) {
19131 then.call(thenable, resolve, reject, notify);
19138 * Fold a handler value with z
19141 function Fold(f, z, c, to) {
19142 this.f = f; this.z = z; this.c = c; this.to = to;
19143 this.resolver = failIfRejected;
19144 this.receiver = this;
19147 Fold.prototype.fulfilled = function(x) {
19148 this.f.call(this.c, this.z, x, this.to);
19151 Fold.prototype.rejected = function(x) {
19155 Fold.prototype.progress = function(x) {
19163 * @returns {boolean} true iff x is a trusted Promise
19165 function isPromise(x) {
19166 return x instanceof Promise;
19170 * Test just enough to rule out primitives, in order to take faster
19171 * paths in some code
19173 * @returns {boolean} false iff x is guaranteed *not* to be a thenable
19175 function maybeThenable(x) {
19176 return (typeof x === 'object' || typeof x === 'function') && x !== null;
19179 function runContinuation1(f, h, receiver, next) {
19180 if(typeof f !== 'function') {
19181 return next.become(h);
19184 Promise.enterContext(h);
19185 tryCatchReject(f, h.value, receiver, next);
19186 Promise.exitContext();
19189 function runContinuation3(f, x, h, receiver, next) {
19190 if(typeof f !== 'function') {
19191 return next.become(h);
19194 Promise.enterContext(h);
19195 tryCatchReject3(f, x, h.value, receiver, next);
19196 Promise.exitContext();
19202 function runNotify(f, x, h, receiver, next) {
19203 if(typeof f !== 'function') {
19204 return next.notify(x);
19207 Promise.enterContext(h);
19208 tryCatchReturn(f, x, receiver, next);
19209 Promise.exitContext();
19212 function tryCatch2(f, a, b) {
19221 * Return f.call(thisArg, x), or if it throws return a rejected promise for
19222 * the thrown exception
19224 function tryCatchReject(f, x, thisArg, next) {
19226 next.become(getHandler(f.call(thisArg, x)));
19228 next.become(new Rejected(e));
19233 * Same as above, but includes the extra argument parameter.
19235 function tryCatchReject3(f, x, y, thisArg, next) {
19237 f.call(thisArg, x, y, next);
19239 next.become(new Rejected(e));
19245 * Return f.call(thisArg, x), or if it throws, *return* the exception
19247 function tryCatchReturn(f, x, thisArg, next) {
19249 next.notify(f.call(thisArg, x));
19255 function inherit(Parent, Child) {
19256 Child.prototype = objectCreate(Parent.prototype);
19257 Child.prototype.constructor = Child;
19260 function snd(x, y) {
19266 function hasCustomEvent() {
19267 if(typeof CustomEvent === 'function') {
19269 var ev = new CustomEvent('unhandledRejection');
19270 return ev instanceof CustomEvent;
19271 } catch (ignoredException) {}
19276 function hasInternetExplorerCustomEvent() {
19277 if(typeof document !== 'undefined' && typeof document.createEvent === 'function') {
19279 // Try to create one event to make sure it's supported
19280 var ev = document.createEvent('CustomEvent');
19281 ev.initCustomEvent('eventType', false, true, {});
19283 } catch (ignoredException) {}
19288 function initEmitRejection() {
19289 /*global process, self, CustomEvent*/
19290 if(typeof process !== 'undefined' && process !== null
19291 && typeof process.emit === 'function') {
19292 // Returning falsy here means to call the default
19293 // onPotentiallyUnhandledRejection API. This is safe even in
19294 // browserify since process.emit always returns falsy in browserify:
19295 // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
19296 return function(type, rejection) {
19297 return type === 'unhandledRejection'
19298 ? process.emit(type, rejection.value, rejection)
19299 : process.emit(type, rejection);
19301 } else if(typeof self !== 'undefined' && hasCustomEvent()) {
19302 return (function (self, CustomEvent) {
19303 return function (type, rejection) {
19304 var ev = new CustomEvent(type, {
19306 reason: rejection.value,
19313 return !self.dispatchEvent(ev);
19315 }(self, CustomEvent));
19316 } else if(typeof self !== 'undefined' && hasInternetExplorerCustomEvent()) {
19317 return (function(self, document) {
19318 return function(type, rejection) {
19319 var ev = document.createEvent('CustomEvent');
19320 ev.initCustomEvent(type, false, true, {
19321 reason: rejection.value,
19325 return !self.dispatchEvent(ev);
19327 }(self, document));
19336 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19338 }).call(this,require('_process'))
19340 },{"_process":4}],221:[function(require,module,exports){
19341 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19342 /** @author Brian Cavalier */
19343 /** @author John Hann */
19345 (function(define) { 'use strict';
19346 define(function() {
19349 pending: toPendingState,
19350 fulfilled: toFulfilledState,
19351 rejected: toRejectedState,
19355 function toPendingState() {
19356 return { state: 'pending' };
19359 function toRejectedState(e) {
19360 return { state: 'rejected', reason: e };
19363 function toFulfilledState(x) {
19364 return { state: 'fulfilled', value: x };
19367 function inspect(handler) {
19368 var state = handler.state();
19369 return state === 0 ? toPendingState()
19370 : state > 0 ? toFulfilledState(handler.value)
19371 : toRejectedState(handler.value);
19375 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19377 },{}],222:[function(require,module,exports){
19378 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19381 * Promises/A+ and when() implementation
19382 * when is part of the cujoJS family of libraries (http://cujojs.com/)
19383 * @author Brian Cavalier
19384 * @author John Hann
19386 (function(define) { 'use strict';
19387 define(function (require) {
19389 var timed = require('./lib/decorators/timed');
19390 var array = require('./lib/decorators/array');
19391 var flow = require('./lib/decorators/flow');
19392 var fold = require('./lib/decorators/fold');
19393 var inspect = require('./lib/decorators/inspect');
19394 var generate = require('./lib/decorators/iterate');
19395 var progress = require('./lib/decorators/progress');
19396 var withThis = require('./lib/decorators/with');
19397 var unhandledRejection = require('./lib/decorators/unhandledRejection');
19398 var TimeoutError = require('./lib/TimeoutError');
19400 var Promise = [array, flow, fold, generate, progress,
19401 inspect, withThis, timed, unhandledRejection]
19402 .reduce(function(Promise, feature) {
19403 return feature(Promise);
19404 }, require('./lib/Promise'));
19406 var apply = require('./lib/apply')(Promise);
19410 when.promise = promise; // Create a pending promise
19411 when.resolve = Promise.resolve; // Create a resolved promise
19412 when.reject = Promise.reject; // Create a rejected promise
19414 when.lift = lift; // lift a function to return promises
19415 when['try'] = attempt; // call a function and return a promise
19416 when.attempt = attempt; // alias for when.try
19418 when.iterate = Promise.iterate; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
19419 when.unfold = Promise.unfold; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
19421 when.join = join; // Join 2 or more promises
19423 when.all = all; // Resolve a list of promises
19424 when.settle = settle; // Settle a list of promises
19426 when.any = lift(Promise.any); // One-winner race
19427 when.some = lift(Promise.some); // Multi-winner race
19428 when.race = lift(Promise.race); // First-to-settle race
19430 when.map = map; // Array.map() for promises
19431 when.filter = filter; // Array.filter() for promises
19432 when.reduce = lift(Promise.reduce); // Array.reduce() for promises
19433 when.reduceRight = lift(Promise.reduceRight); // Array.reduceRight() for promises
19435 when.isPromiseLike = isPromiseLike; // Is something promise-like, aka thenable
19437 when.Promise = Promise; // Promise constructor
19438 when.defer = defer; // Create a {promise, resolve, reject} tuple
19442 when.TimeoutError = TimeoutError;
19445 * Get a trusted promise for x, or by transforming x with onFulfilled
19448 * @param {function?} onFulfilled callback to be called when x is
19449 * successfully fulfilled. If promiseOrValue is an immediate value, callback
19450 * will be invoked immediately.
19451 * @param {function?} onRejected callback to be called when x is
19453 * @param {function?} onProgress callback to be called when progress updates
19454 * are issued for x. @deprecated
19455 * @returns {Promise} a new promise that will fulfill with the return
19456 * value of callback or errback or the completion value of promiseOrValue if
19457 * callback and/or errback is not supplied.
19459 function when(x, onFulfilled, onRejected, onProgress) {
19460 var p = Promise.resolve(x);
19461 if (arguments.length < 2) {
19465 return p.then(onFulfilled, onRejected, onProgress);
19469 * Creates a new promise whose fate is determined by resolver.
19470 * @param {function} resolver function(resolve, reject, notify)
19471 * @returns {Promise} promise whose fate is determine by resolver
19473 function promise(resolver) {
19474 return new Promise(resolver);
19478 * Lift the supplied function, creating a version of f that returns
19479 * promises, and accepts promises as arguments.
19480 * @param {function} f
19481 * @returns {Function} version of f that returns promises
19484 return function() {
19485 for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
19486 a[i] = arguments[i];
19488 return apply(f, this, a);
19493 * Call f in a future turn, with the supplied args, and return a promise
19495 * @param {function} f
19496 * @returns {Promise}
19498 function attempt(f /*, args... */) {
19499 /*jshint validthis:true */
19500 for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
19501 a[i] = arguments[i+1];
19503 return apply(f, this, a);
19507 * Creates a {promise, resolver} pair, either or both of which
19508 * may be given out safely to consumers.
19509 * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
19512 return new Deferred();
19515 function Deferred() {
19516 var p = Promise._defer();
19518 function resolve(x) { p._handler.resolve(x); }
19519 function reject(x) { p._handler.reject(x); }
19520 function notify(x) { p._handler.notify(x); }
19523 this.resolve = resolve;
19524 this.reject = reject;
19525 this.notify = notify;
19526 this.resolver = { resolve: resolve, reject: reject, notify: notify };
19530 * Determines if x is promise-like, i.e. a thenable object
19531 * NOTE: Will return true for *any thenable object*, and isn't truly
19532 * safe, since it may attempt to access the `then` property of x (i.e.
19533 * clever/malicious getters may do weird things)
19534 * @param {*} x anything
19535 * @returns {boolean} true if x is promise-like
19537 function isPromiseLike(x) {
19538 return x && typeof x.then === 'function';
19542 * Return a promise that will resolve only once all the supplied arguments
19543 * have resolved. The resolution value of the returned promise will be an array
19544 * containing the resolution values of each of the arguments.
19545 * @param {...*} arguments may be a mix of promises and values
19546 * @returns {Promise}
19548 function join(/* ...promises */) {
19549 return Promise.all(arguments);
19553 * Return a promise that will fulfill once all input promises have
19554 * fulfilled, or reject when any one input promise rejects.
19555 * @param {array|Promise} promises array (or promise for an array) of promises
19556 * @returns {Promise}
19558 function all(promises) {
19559 return when(promises, Promise.all);
19563 * Return a promise that will always fulfill with an array containing
19564 * the outcome states of all input promises. The returned promise
19565 * will only reject if `promises` itself is a rejected promise.
19566 * @param {array|Promise} promises array (or promise for an array) of promises
19567 * @returns {Promise} promise for array of settled state descriptors
19569 function settle(promises) {
19570 return when(promises, Promise.settle);
19574 * Promise-aware array map function, similar to `Array.prototype.map()`,
19575 * but input array may contain promises or values.
19576 * @param {Array|Promise} promises array of anything, may contain promises and values
19577 * @param {function(x:*, index:Number):*} mapFunc map function which may
19578 * return a promise or value
19579 * @returns {Promise} promise that will fulfill with an array of mapped values
19580 * or reject if any input promise rejects.
19582 function map(promises, mapFunc) {
19583 return when(promises, function(promises) {
19584 return Promise.map(promises, mapFunc);
19589 * Filter the provided array of promises using the provided predicate. Input may
19590 * contain promises and values
19591 * @param {Array|Promise} promises array of promises and values
19592 * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
19593 * Must return truthy (or promise for truthy) for items to retain.
19594 * @returns {Promise} promise that will fulfill with an array containing all items
19595 * for which predicate returned truthy.
19597 function filter(promises, predicate) {
19598 return when(promises, function(promises) {
19599 return Promise.filter(promises, predicate);
19605 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
19607 },{"./lib/Promise":205,"./lib/TimeoutError":207,"./lib/apply":208,"./lib/decorators/array":209,"./lib/decorators/flow":210,"./lib/decorators/fold":211,"./lib/decorators/inspect":212,"./lib/decorators/iterate":213,"./lib/decorators/progress":214,"./lib/decorators/timed":215,"./lib/decorators/unhandledRejection":216,"./lib/decorators/with":217}],223:[function(require,module,exports){
19608 var nativeIsArray = Array.isArray
19609 var toString = Object.prototype.toString
19611 module.exports = nativeIsArray || isArray
19613 function isArray(obj) {
19614 return toString.call(obj) === "[object Array]"
19617 },{}],224:[function(require,module,exports){
19619 var APIv3_1 = require("./api/APIv3");
19620 exports.APIv3 = APIv3_1.APIv3;
19621 var ModelCreator_1 = require("./api/ModelCreator");
19622 exports.ModelCreator = ModelCreator_1.ModelCreator;
19624 },{"./api/APIv3":236,"./api/ModelCreator":237}],225:[function(require,module,exports){
19626 var Component_1 = require("./component/Component");
19627 exports.Component = Component_1.Component;
19628 var ComponentService_1 = require("./component/ComponentService");
19629 exports.ComponentService = ComponentService_1.ComponentService;
19630 var AttributionComponent_1 = require("./component/AttributionComponent");
19631 exports.AttributionComponent = AttributionComponent_1.AttributionComponent;
19632 var BackgroundComponent_1 = require("./component/BackgroundComponent");
19633 exports.BackgroundComponent = BackgroundComponent_1.BackgroundComponent;
19634 var BearingComponent_1 = require("./component/BearingComponent");
19635 exports.BearingComponent = BearingComponent_1.BearingComponent;
19636 var CacheComponent_1 = require("./component/CacheComponent");
19637 exports.CacheComponent = CacheComponent_1.CacheComponent;
19638 var CoverComponent_1 = require("./component/CoverComponent");
19639 exports.CoverComponent = CoverComponent_1.CoverComponent;
19640 var DebugComponent_1 = require("./component/DebugComponent");
19641 exports.DebugComponent = DebugComponent_1.DebugComponent;
19642 var DirectionComponent_1 = require("./component/direction/DirectionComponent");
19643 exports.DirectionComponent = DirectionComponent_1.DirectionComponent;
19644 var DirectionDOMCalculator_1 = require("./component/direction/DirectionDOMCalculator");
19645 exports.DirectionDOMCalculator = DirectionDOMCalculator_1.DirectionDOMCalculator;
19646 var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer");
19647 exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer;
19648 var ImageComponent_1 = require("./component/ImageComponent");
19649 exports.ImageComponent = ImageComponent_1.ImageComponent;
19650 var KeyboardComponent_1 = require("./component/KeyboardComponent");
19651 exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent;
19652 var LoadingComponent_1 = require("./component/LoadingComponent");
19653 exports.LoadingComponent = LoadingComponent_1.LoadingComponent;
19654 var Marker_1 = require("./component/marker/marker/Marker");
19655 exports.Marker = Marker_1.Marker;
19656 var MarkerComponent_1 = require("./component/marker/MarkerComponent");
19657 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
19658 var MarkerScene_1 = require("./component/marker/MarkerScene");
19659 exports.MarkerScene = MarkerScene_1.MarkerScene;
19660 var MarkerSet_1 = require("./component/marker/MarkerSet");
19661 exports.MarkerSet = MarkerSet_1.MarkerSet;
19662 var MouseComponent_1 = require("./component/mouse/MouseComponent");
19663 exports.MouseComponent = MouseComponent_1.MouseComponent;
19664 var MouseHandlerBase_1 = require("./component/mouse/MouseHandlerBase");
19665 exports.MouseHandlerBase = MouseHandlerBase_1.MouseHandlerBase;
19666 var DragPanHandler_1 = require("./component/mouse/DragPanHandler");
19667 exports.DragPanHandler = DragPanHandler_1.DragPanHandler;
19668 var DoubleClickZoomHandler_1 = require("./component/mouse/DoubleClickZoomHandler");
19669 exports.DoubleClickZoomHandler = DoubleClickZoomHandler_1.DoubleClickZoomHandler;
19670 var ScrollZoomHandler_1 = require("./component/mouse/ScrollZoomHandler");
19671 exports.ScrollZoomHandler = ScrollZoomHandler_1.ScrollZoomHandler;
19672 var TouchZoomHandler_1 = require("./component/mouse/TouchZoomHandler");
19673 exports.TouchZoomHandler = TouchZoomHandler_1.TouchZoomHandler;
19674 var NavigationComponent_1 = require("./component/NavigationComponent");
19675 exports.NavigationComponent = NavigationComponent_1.NavigationComponent;
19676 var RouteComponent_1 = require("./component/RouteComponent");
19677 exports.RouteComponent = RouteComponent_1.RouteComponent;
19678 var SequenceComponent_1 = require("./component/sequence/SequenceComponent");
19679 exports.SequenceComponent = SequenceComponent_1.SequenceComponent;
19680 var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer");
19681 exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer;
19682 var SequenceDOMInteraction_1 = require("./component/sequence/SequenceDOMInteraction");
19683 exports.SequenceDOMInteraction = SequenceDOMInteraction_1.SequenceDOMInteraction;
19684 var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent");
19685 exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent;
19686 var ImagePlaneFactory_1 = require("./component/imageplane/ImagePlaneFactory");
19687 exports.ImagePlaneFactory = ImagePlaneFactory_1.ImagePlaneFactory;
19688 var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer");
19689 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer;
19690 var ImagePlaneScene_1 = require("./component/imageplane/ImagePlaneScene");
19691 exports.ImagePlaneScene = ImagePlaneScene_1.ImagePlaneScene;
19692 var ImagePlaneShaders_1 = require("./component/imageplane/ImagePlaneShaders");
19693 exports.ImagePlaneShaders = ImagePlaneShaders_1.ImagePlaneShaders;
19694 var SimpleMarker_1 = require("./component/marker/marker/SimpleMarker");
19695 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
19696 var CircleMarker_1 = require("./component/marker/marker/CircleMarker");
19697 exports.CircleMarker = CircleMarker_1.CircleMarker;
19698 var SliderComponent_1 = require("./component/imageplane/SliderComponent");
19699 exports.SliderComponent = SliderComponent_1.SliderComponent;
19700 var StatsComponent_1 = require("./component/StatsComponent");
19701 exports.StatsComponent = StatsComponent_1.StatsComponent;
19702 var Tag_1 = require("./component/tag/tag/Tag");
19703 exports.Tag = Tag_1.Tag;
19704 var Alignment_1 = require("./component/tag/tag/Alignment");
19705 exports.Alignment = Alignment_1.Alignment;
19706 var OutlineTag_1 = require("./component/tag/tag/OutlineTag");
19707 exports.OutlineTag = OutlineTag_1.OutlineTag;
19708 var RenderTag_1 = require("./component/tag/tag/RenderTag");
19709 exports.RenderTag = RenderTag_1.RenderTag;
19710 var OutlineRenderTag_1 = require("./component/tag/tag/OutlineRenderTag");
19711 exports.OutlineRenderTag = OutlineRenderTag_1.OutlineRenderTag;
19712 var OutlineCreateTag_1 = require("./component/tag/tag/OutlineCreateTag");
19713 exports.OutlineCreateTag = OutlineCreateTag_1.OutlineCreateTag;
19714 var SpotTag_1 = require("./component/tag/tag/SpotTag");
19715 exports.SpotTag = SpotTag_1.SpotTag;
19716 var SpotRenderTag_1 = require("./component/tag/tag/SpotRenderTag");
19717 exports.SpotRenderTag = SpotRenderTag_1.SpotRenderTag;
19718 var TagComponent_1 = require("./component/tag/TagComponent");
19719 exports.TagComponent = TagComponent_1.TagComponent;
19720 var TagCreator_1 = require("./component/tag/TagCreator");
19721 exports.TagCreator = TagCreator_1.TagCreator;
19722 var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer");
19723 exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer;
19724 var TagGLRenderer_1 = require("./component/tag/TagGLRenderer");
19725 exports.TagGLRenderer = TagGLRenderer_1.TagGLRenderer;
19726 var TagOperation_1 = require("./component/tag/TagOperation");
19727 exports.TagOperation = TagOperation_1.TagOperation;
19728 var TagSet_1 = require("./component/tag/TagSet");
19729 exports.TagSet = TagSet_1.TagSet;
19730 var Geometry_1 = require("./component/tag/geometry/Geometry");
19731 exports.Geometry = Geometry_1.Geometry;
19732 var VertexGeometry_1 = require("./component/tag/geometry/VertexGeometry");
19733 exports.VertexGeometry = VertexGeometry_1.VertexGeometry;
19734 var RectGeometry_1 = require("./component/tag/geometry/RectGeometry");
19735 exports.RectGeometry = RectGeometry_1.RectGeometry;
19736 var PointGeometry_1 = require("./component/tag/geometry/PointGeometry");
19737 exports.PointGeometry = PointGeometry_1.PointGeometry;
19738 var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry");
19739 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
19740 var GeometryTagError_1 = require("./component/tag/error/GeometryTagError");
19741 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
19743 },{"./component/AttributionComponent":238,"./component/BackgroundComponent":239,"./component/BearingComponent":240,"./component/CacheComponent":241,"./component/Component":242,"./component/ComponentService":243,"./component/CoverComponent":244,"./component/DebugComponent":245,"./component/ImageComponent":246,"./component/KeyboardComponent":247,"./component/LoadingComponent":248,"./component/NavigationComponent":249,"./component/RouteComponent":250,"./component/StatsComponent":251,"./component/direction/DirectionComponent":252,"./component/direction/DirectionDOMCalculator":253,"./component/direction/DirectionDOMRenderer":254,"./component/imageplane/ImagePlaneComponent":255,"./component/imageplane/ImagePlaneFactory":256,"./component/imageplane/ImagePlaneGLRenderer":257,"./component/imageplane/ImagePlaneScene":258,"./component/imageplane/ImagePlaneShaders":259,"./component/imageplane/SliderComponent":260,"./component/marker/MarkerComponent":262,"./component/marker/MarkerScene":263,"./component/marker/MarkerSet":264,"./component/marker/marker/CircleMarker":265,"./component/marker/marker/Marker":266,"./component/marker/marker/SimpleMarker":267,"./component/mouse/DoubleClickZoomHandler":268,"./component/mouse/DragPanHandler":269,"./component/mouse/MouseComponent":270,"./component/mouse/MouseHandlerBase":271,"./component/mouse/ScrollZoomHandler":272,"./component/mouse/TouchZoomHandler":273,"./component/sequence/SequenceComponent":274,"./component/sequence/SequenceDOMInteraction":275,"./component/sequence/SequenceDOMRenderer":276,"./component/tag/TagComponent":278,"./component/tag/TagCreator":279,"./component/tag/TagDOMRenderer":280,"./component/tag/TagGLRenderer":281,"./component/tag/TagOperation":282,"./component/tag/TagSet":283,"./component/tag/error/GeometryTagError":284,"./component/tag/geometry/Geometry":285,"./component/tag/geometry/PointGeometry":286,"./component/tag/geometry/PolygonGeometry":287,"./component/tag/geometry/RectGeometry":288,"./component/tag/geometry/VertexGeometry":289,"./component/tag/tag/Alignment":290,"./component/tag/tag/OutlineCreateTag":291,"./component/tag/tag/OutlineRenderTag":292,"./component/tag/tag/OutlineTag":293,"./component/tag/tag/RenderTag":294,"./component/tag/tag/SpotRenderTag":295,"./component/tag/tag/SpotTag":296,"./component/tag/tag/Tag":297}],226:[function(require,module,exports){
19745 var EdgeDirection_1 = require("./graph/edge/EdgeDirection");
19746 exports.EdgeDirection = EdgeDirection_1.EdgeDirection;
19747 var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings");
19748 exports.EdgeCalculatorSettings = EdgeCalculatorSettings_1.EdgeCalculatorSettings;
19749 var EdgeCalculatorDirections_1 = require("./graph/edge/EdgeCalculatorDirections");
19750 exports.EdgeCalculatorDirections = EdgeCalculatorDirections_1.EdgeCalculatorDirections;
19751 var EdgeCalculatorCoefficients_1 = require("./graph/edge/EdgeCalculatorCoefficients");
19752 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculatorCoefficients;
19753 var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator");
19754 exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator;
19756 },{"./graph/edge/EdgeCalculator":315,"./graph/edge/EdgeCalculatorCoefficients":316,"./graph/edge/EdgeCalculatorDirections":317,"./graph/edge/EdgeCalculatorSettings":318,"./graph/edge/EdgeDirection":319}],227:[function(require,module,exports){
19758 var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError");
19759 exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError;
19760 var GraphMapillaryError_1 = require("./error/GraphMapillaryError");
19761 exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError;
19762 var MapillaryError_1 = require("./error/MapillaryError");
19763 exports.MapillaryError = MapillaryError_1.MapillaryError;
19765 },{"./error/ArgumentMapillaryError":298,"./error/GraphMapillaryError":299,"./error/MapillaryError":300}],228:[function(require,module,exports){
19767 var Camera_1 = require("./geo/Camera");
19768 exports.Camera = Camera_1.Camera;
19769 var GeoCoords_1 = require("./geo/GeoCoords");
19770 exports.GeoCoords = GeoCoords_1.GeoCoords;
19771 var ViewportCoords_1 = require("./geo/ViewportCoords");
19772 exports.ViewportCoords = ViewportCoords_1.ViewportCoords;
19773 var Spatial_1 = require("./geo/Spatial");
19774 exports.Spatial = Spatial_1.Spatial;
19775 var Transform_1 = require("./geo/Transform");
19776 exports.Transform = Transform_1.Transform;
19778 },{"./geo/Camera":301,"./geo/GeoCoords":302,"./geo/Spatial":303,"./geo/Transform":304,"./geo/ViewportCoords":305}],229:[function(require,module,exports){
19780 var FilterCreator_1 = require("./graph/FilterCreator");
19781 exports.FilterCreator = FilterCreator_1.FilterCreator;
19782 var Graph_1 = require("./graph/Graph");
19783 exports.Graph = Graph_1.Graph;
19784 var GraphCalculator_1 = require("./graph/GraphCalculator");
19785 exports.GraphCalculator = GraphCalculator_1.GraphCalculator;
19786 var GraphService_1 = require("./graph/GraphService");
19787 exports.GraphService = GraphService_1.GraphService;
19788 var ImageLoadingService_1 = require("./graph/ImageLoadingService");
19789 exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService;
19790 var MeshReader_1 = require("./graph/MeshReader");
19791 exports.MeshReader = MeshReader_1.MeshReader;
19792 var Node_1 = require("./graph/Node");
19793 exports.Node = Node_1.Node;
19794 var NodeCache_1 = require("./graph/NodeCache");
19795 exports.NodeCache = NodeCache_1.NodeCache;
19796 var Sequence_1 = require("./graph/Sequence");
19797 exports.Sequence = Sequence_1.Sequence;
19799 },{"./graph/FilterCreator":306,"./graph/Graph":307,"./graph/GraphCalculator":308,"./graph/GraphService":309,"./graph/ImageLoadingService":310,"./graph/MeshReader":311,"./graph/Node":312,"./graph/NodeCache":313,"./graph/Sequence":314}],230:[function(require,module,exports){
19801 * MapillaryJS is a WebGL JavaScript library for exploring street level imagery
19805 var Edge_1 = require("./Edge");
19806 exports.EdgeDirection = Edge_1.EdgeDirection;
19807 var Render_1 = require("./Render");
19808 exports.RenderMode = Render_1.RenderMode;
19809 var Viewer_1 = require("./Viewer");
19810 exports.ImageSize = Viewer_1.ImageSize;
19811 exports.Viewer = Viewer_1.Viewer;
19812 var TagComponent = require("./component/tag/Tag");
19813 exports.TagComponent = TagComponent;
19814 var MarkerComponent = require("./component/marker/Marker");
19815 exports.MarkerComponent = MarkerComponent;
19817 },{"./Edge":226,"./Render":231,"./Viewer":235,"./component/marker/Marker":261,"./component/tag/Tag":277}],231:[function(require,module,exports){
19819 var DOMRenderer_1 = require("./render/DOMRenderer");
19820 exports.DOMRenderer = DOMRenderer_1.DOMRenderer;
19821 var GLRenderer_1 = require("./render/GLRenderer");
19822 exports.GLRenderer = GLRenderer_1.GLRenderer;
19823 var GLRenderStage_1 = require("./render/GLRenderStage");
19824 exports.GLRenderStage = GLRenderStage_1.GLRenderStage;
19825 var RenderCamera_1 = require("./render/RenderCamera");
19826 exports.RenderCamera = RenderCamera_1.RenderCamera;
19827 var RenderMode_1 = require("./render/RenderMode");
19828 exports.RenderMode = RenderMode_1.RenderMode;
19829 var RenderService_1 = require("./render/RenderService");
19830 exports.RenderService = RenderService_1.RenderService;
19832 },{"./render/DOMRenderer":320,"./render/GLRenderStage":321,"./render/GLRenderer":322,"./render/RenderCamera":323,"./render/RenderMode":324,"./render/RenderService":325}],232:[function(require,module,exports){
19834 var State_1 = require("./state/State");
19835 exports.State = State_1.State;
19836 var StateBase_1 = require("./state/states/StateBase");
19837 exports.StateBase = StateBase_1.StateBase;
19838 var StateContext_1 = require("./state/StateContext");
19839 exports.StateContext = StateContext_1.StateContext;
19840 var StateService_1 = require("./state/StateService");
19841 exports.StateService = StateService_1.StateService;
19842 var TraversingState_1 = require("./state/states/TraversingState");
19843 exports.TraversingState = TraversingState_1.TraversingState;
19844 var WaitingState_1 = require("./state/states/WaitingState");
19845 exports.WaitingState = WaitingState_1.WaitingState;
19847 },{"./state/State":326,"./state/StateContext":327,"./state/StateService":328,"./state/states/StateBase":329,"./state/states/TraversingState":330,"./state/states/WaitingState":331}],233:[function(require,module,exports){
19849 var ImageTileLoader_1 = require("./tiles/ImageTileLoader");
19850 exports.ImageTileLoader = ImageTileLoader_1.ImageTileLoader;
19851 var ImageTileStore_1 = require("./tiles/ImageTileStore");
19852 exports.ImageTileStore = ImageTileStore_1.ImageTileStore;
19853 var TextureProvider_1 = require("./tiles/TextureProvider");
19854 exports.TextureProvider = TextureProvider_1.TextureProvider;
19855 var RegionOfInterestCalculator_1 = require("./tiles/RegionOfInterestCalculator");
19856 exports.RegionOfInterestCalculator = RegionOfInterestCalculator_1.RegionOfInterestCalculator;
19858 },{"./tiles/ImageTileLoader":332,"./tiles/ImageTileStore":333,"./tiles/RegionOfInterestCalculator":334,"./tiles/TextureProvider":335}],234:[function(require,module,exports){
19860 var EventEmitter_1 = require("./utils/EventEmitter");
19861 exports.EventEmitter = EventEmitter_1.EventEmitter;
19862 var Settings_1 = require("./utils/Settings");
19863 exports.Settings = Settings_1.Settings;
19864 var Urls_1 = require("./utils/Urls");
19865 exports.Urls = Urls_1.Urls;
19867 },{"./utils/EventEmitter":336,"./utils/Settings":337,"./utils/Urls":338}],235:[function(require,module,exports){
19869 var CacheService_1 = require("./viewer/CacheService");
19870 exports.CacheService = CacheService_1.CacheService;
19871 var ComponentController_1 = require("./viewer/ComponentController");
19872 exports.ComponentController = ComponentController_1.ComponentController;
19873 var Container_1 = require("./viewer/Container");
19874 exports.Container = Container_1.Container;
19875 var Observer_1 = require("./viewer/Observer");
19876 exports.Observer = Observer_1.Observer;
19877 var ImageSize_1 = require("./viewer/ImageSize");
19878 exports.ImageSize = ImageSize_1.ImageSize;
19879 var LoadingService_1 = require("./viewer/LoadingService");
19880 exports.LoadingService = LoadingService_1.LoadingService;
19881 var MouseService_1 = require("./viewer/MouseService");
19882 exports.MouseService = MouseService_1.MouseService;
19883 var Navigator_1 = require("./viewer/Navigator");
19884 exports.Navigator = Navigator_1.Navigator;
19885 var Projection_1 = require("./viewer/Projection");
19886 exports.Projection = Projection_1.Projection;
19887 var SpriteAlignment_1 = require("./viewer/SpriteAlignment");
19888 exports.SpriteAlignment = SpriteAlignment_1.SpriteAlignment;
19889 var SpriteService_1 = require("./viewer/SpriteService");
19890 exports.SpriteService = SpriteService_1.SpriteService;
19891 var TouchService_1 = require("./viewer/TouchService");
19892 exports.TouchService = TouchService_1.TouchService;
19893 var Viewer_1 = require("./viewer/Viewer");
19894 exports.Viewer = Viewer_1.Viewer;
19896 },{"./viewer/CacheService":339,"./viewer/ComponentController":340,"./viewer/Container":341,"./viewer/ImageSize":342,"./viewer/LoadingService":343,"./viewer/MouseService":344,"./viewer/Navigator":345,"./viewer/Observer":346,"./viewer/Projection":347,"./viewer/SpriteAlignment":348,"./viewer/SpriteService":349,"./viewer/TouchService":350,"./viewer/Viewer":351}],236:[function(require,module,exports){
19897 /// <reference path="../../typings/index.d.ts" />
19899 var Observable_1 = require("rxjs/Observable");
19900 require("rxjs/add/observable/defer");
19901 require("rxjs/add/observable/fromPromise");
19902 require("rxjs/add/operator/catch");
19903 require("rxjs/add/operator/map");
19904 var API_1 = require("../API");
19908 * @classdesc Provides methods for access of API v3.
19910 var APIv3 = (function () {
19912 * Create a new api v3 instance.
19914 * @param {number} clientId - Client id for API requests.
19915 * @param {number} [token] - Optional bearer token for API requests of
19916 * protected resources.
19917 * @param {ModelCreator} [creator] - Optional model creator instance.
19919 function APIv3(clientId, token, creator) {
19920 this._clientId = clientId;
19921 this._modelCreator = creator != null ? creator : new API_1.ModelCreator();
19922 this._model = this._modelCreator.createModel(clientId, token);
19923 this._pageCount = 999;
19924 this._pathImageByKey = "imageByKey";
19925 this._pathImageCloseTo = "imageCloseTo";
19926 this._pathImagesByH = "imagesByH";
19927 this._pathImageViewAdd = "imageViewAdd";
19928 this._pathSequenceByKey = "sequenceByKey";
19929 this._pathSequenceViewAdd = "sequenceViewAdd";
19930 this._propertiesCore = [
19935 this._propertiesFill = [
19940 this._propertiesKey = [
19943 this._propertiesSequence = [
19946 this._propertiesSpatial = [
19960 this._propertiesUser = [
19965 APIv3.prototype.imageByKeyFill$ = function (keys) {
19966 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
19967 this._pathImageByKey,
19969 this._propertiesKey
19970 .concat(this._propertiesFill)
19971 .concat(this._propertiesSpatial),
19972 this._propertiesKey
19973 .concat(this._propertiesUser)
19975 .map(function (value) {
19976 return value.json.imageByKey;
19977 }), this._pathImageByKey, keys);
19979 APIv3.prototype.imageByKeyFull$ = function (keys) {
19980 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
19981 this._pathImageByKey,
19983 this._propertiesKey
19984 .concat(this._propertiesCore)
19985 .concat(this._propertiesFill)
19986 .concat(this._propertiesSpatial),
19987 this._propertiesKey
19988 .concat(this._propertiesUser)
19990 .map(function (value) {
19991 return value.json.imageByKey;
19992 }), this._pathImageByKey, keys);
19994 APIv3.prototype.imageCloseTo$ = function (lat, lon) {
19995 var lonLat = lon + ":" + lat;
19996 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
19997 this._pathImageCloseTo,
19999 this._propertiesKey
20000 .concat(this._propertiesCore)
20001 .concat(this._propertiesFill)
20002 .concat(this._propertiesSpatial),
20003 this._propertiesKey
20004 .concat(this._propertiesUser)
20006 .map(function (value) {
20007 return value != null ? value.json.imageCloseTo[lonLat] : null;
20008 }), this._pathImageCloseTo, [lonLat]);
20010 APIv3.prototype.imagesByH$ = function (hs) {
20012 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20013 this._pathImagesByH,
20015 { from: 0, to: this._pageCount },
20016 this._propertiesKey
20017 .concat(this._propertiesCore),
20018 this._propertiesKey
20020 .map(function (value) {
20021 if (value == null) {
20022 value = { json: { imagesByH: {} } };
20023 for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) {
20025 value.json.imagesByH[h] = {};
20026 for (var i = 0; i <= _this._pageCount; i++) {
20027 value.json.imagesByH[h][i] = null;
20031 return value.json.imagesByH;
20032 }), this._pathImagesByH, hs);
20034 APIv3.prototype.imageViewAdd$ = function (keys) {
20035 return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys);
20037 APIv3.prototype.invalidateImageByKey = function (keys) {
20038 this._invalidateGet(this._pathImageByKey, keys);
20040 APIv3.prototype.invalidateImagesByH = function (hs) {
20041 this._invalidateGet(this._pathImagesByH, hs);
20043 APIv3.prototype.invalidateSequenceByKey = function (sKeys) {
20044 this._invalidateGet(this._pathSequenceByKey, sKeys);
20046 APIv3.prototype.setToken = function (token) {
20047 this._model.invalidate([]);
20048 this._model = null;
20049 this._model = this._modelCreator.createModel(this._clientId, token);
20051 APIv3.prototype.sequenceByKey$ = function (sequenceKeys) {
20052 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20053 this._pathSequenceByKey,
20055 this._propertiesKey
20056 .concat(this._propertiesSequence)
20058 .map(function (value) {
20059 return value.json.sequenceByKey;
20060 }), this._pathSequenceByKey, sequenceKeys);
20062 APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) {
20063 return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys);
20065 Object.defineProperty(APIv3.prototype, "clientId", {
20067 return this._clientId;
20072 APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) {
20075 .catch(function (error) {
20076 _this._invalidateGet(path, paths);
20080 APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) {
20083 .catch(function (error) {
20084 _this._invalidateCall(path, paths);
20088 APIv3.prototype._invalidateGet = function (path, paths) {
20089 this._model.invalidate([path, paths]);
20091 APIv3.prototype._invalidateCall = function (path, paths) {
20092 this._model.invalidate([path], [paths]);
20094 APIv3.prototype._wrapPromise$ = function (promise) {
20095 return Observable_1.Observable.defer(function () { return Observable_1.Observable.fromPromise(promise); });
20099 exports.APIv3 = APIv3;
20100 Object.defineProperty(exports, "__esModule", { value: true });
20101 exports.default = APIv3;
20103 },{"../API":224,"rxjs/Observable":28,"rxjs/add/observable/defer":38,"rxjs/add/observable/fromPromise":42,"rxjs/add/operator/catch":51,"rxjs/add/operator/map":64}],237:[function(require,module,exports){
20104 /// <reference path="../../typings/index.d.ts" />
20106 var falcor = require("falcor");
20107 var HttpDataSource = require("falcor-http-datasource");
20108 var Utils_1 = require("../Utils");
20110 * @class ModelCreator
20112 * @classdesc Creates API models.
20114 var ModelCreator = (function () {
20115 function ModelCreator() {
20118 * Creates a Falcor model.
20120 * @description Max cache size will be set to 16 MB. Authorization
20121 * header will be added if bearer token is supplied.
20123 * @param {number} clientId - Client id for API requests.
20124 * @param {number} [token] - Optional bearer token for API requests of
20125 * protected resources.
20126 * @returns {falcor.Model} Falcor model for HTTP requests.
20128 ModelCreator.prototype.createModel = function (clientId, token) {
20129 var configuration = {
20131 withCredentials: false,
20133 if (token != null) {
20134 configuration.headers = { "Authorization": "Bearer " + token };
20136 return new falcor.Model({
20137 maxSize: 16 * 1024 * 1024,
20138 source: new HttpDataSource(Utils_1.Urls.falcorModel(clientId), configuration),
20141 return ModelCreator;
20143 exports.ModelCreator = ModelCreator;
20144 Object.defineProperty(exports, "__esModule", { value: true });
20145 exports.default = ModelCreator;
20147 },{"../Utils":234,"falcor":13,"falcor-http-datasource":8}],238:[function(require,module,exports){
20148 /// <reference path="../../typings/index.d.ts" />
20150 var __extends = (this && this.__extends) || function (d, b) {
20151 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20152 function __() { this.constructor = d; }
20153 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20155 var vd = require("virtual-dom");
20156 var Component_1 = require("../Component");
20157 var AttributionComponent = (function (_super) {
20158 __extends(AttributionComponent, _super);
20159 function AttributionComponent(name, container, navigator) {
20160 return _super.call(this, name, container, navigator) || this;
20162 AttributionComponent.prototype._activate = function () {
20164 this._disposable = this._navigator.stateService.currentNode$
20165 .map(function (node) {
20166 return { name: _this._name, vnode: _this._getAttributionNode(node.username, node.key) };
20168 .subscribe(this._container.domRenderer.render$);
20170 AttributionComponent.prototype._deactivate = function () {
20171 this._disposable.unsubscribe();
20173 AttributionComponent.prototype._getDefaultConfiguration = function () {
20176 AttributionComponent.prototype._getAttributionNode = function (username, photoId) {
20177 return vd.h("div.Attribution", {}, [
20178 vd.h("a", { href: "https://www.mapillary.com/app/user/" + username,
20180 textContent: "@" + username,
20182 vd.h("span", { textContent: "|" }, []),
20183 vd.h("a", { href: "https://www.mapillary.com/app/?pKey=" + photoId + "&focus=photo",
20185 textContent: "mapillary.com",
20189 return AttributionComponent;
20190 }(Component_1.Component));
20191 AttributionComponent.componentName = "attribution";
20192 exports.AttributionComponent = AttributionComponent;
20193 Component_1.ComponentService.register(AttributionComponent);
20194 Object.defineProperty(exports, "__esModule", { value: true });
20195 exports.default = AttributionComponent;
20197 },{"../Component":225,"virtual-dom":181}],239:[function(require,module,exports){
20198 /// <reference path="../../typings/index.d.ts" />
20200 var __extends = (this && this.__extends) || function (d, b) {
20201 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20202 function __() { this.constructor = d; }
20203 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20205 var vd = require("virtual-dom");
20206 var Component_1 = require("../Component");
20207 var BackgroundComponent = (function (_super) {
20208 __extends(BackgroundComponent, _super);
20209 function BackgroundComponent(name, container, navigator) {
20210 return _super.call(this, name, container, navigator) || this;
20212 BackgroundComponent.prototype._activate = function () {
20213 this._container.domRenderer.render$
20214 .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given photo.") });
20216 BackgroundComponent.prototype._deactivate = function () {
20219 BackgroundComponent.prototype._getDefaultConfiguration = function () {
20222 BackgroundComponent.prototype._getBackgroundNode = function (notice) {
20223 // todo: add condition for when to display the DOM node
20224 return vd.h("div.BackgroundWrapper", {}, [
20225 vd.h("p", { textContent: notice }, []),
20228 return BackgroundComponent;
20229 }(Component_1.Component));
20230 BackgroundComponent.componentName = "background";
20231 exports.BackgroundComponent = BackgroundComponent;
20232 Component_1.ComponentService.register(BackgroundComponent);
20233 Object.defineProperty(exports, "__esModule", { value: true });
20234 exports.default = BackgroundComponent;
20236 },{"../Component":225,"virtual-dom":181}],240:[function(require,module,exports){
20237 /// <reference path="../../typings/index.d.ts" />
20239 var __extends = (this && this.__extends) || function (d, b) {
20240 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20241 function __() { this.constructor = d; }
20242 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20244 var vd = require("virtual-dom");
20245 var Observable_1 = require("rxjs/Observable");
20246 var Component_1 = require("../Component");
20247 var Geo_1 = require("../Geo");
20248 var BearingComponent = (function (_super) {
20249 __extends(BearingComponent, _super);
20250 function BearingComponent(name, container, navigator) {
20251 var _this = _super.call(this, name, container, navigator) || this;
20252 _this._spatial = new Geo_1.Spatial();
20253 _this._svgNamespace = "http://www.w3.org/2000/svg";
20254 _this._distinctThreshold = Math.PI / 90;
20257 BearingComponent.prototype._activate = function () {
20259 var nodeBearingFov$ = this._navigator.stateService.currentState$
20260 .distinctUntilChanged(undefined, function (frame) {
20261 return frame.state.currentNode.key;
20263 .map(function (frame) {
20264 var node = frame.state.currentNode;
20265 var transform = frame.state.currentTransform;
20267 var hFov_1 = 2 * Math.PI * node.gpano.CroppedAreaImageWidthPixels / node.gpano.FullPanoWidthPixels;
20268 return [_this._spatial.degToRad(node.ca), hFov_1];
20270 var size = Math.max(transform.basicWidth, transform.basicHeight);
20272 console.warn("Original image size (" + transform.basicWidth + ", " + transform.basicHeight + ") is invalid (" + node.key + ". " +
20273 "Not showing available fov.");
20275 var hFov = size > 0 ?
20276 2 * Math.atan(0.5 * transform.basicWidth / (size * transform.focal)) :
20278 return [_this._spatial.degToRad(node.ca), hFov];
20280 .distinctUntilChanged(function (a1, a2) {
20281 return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
20282 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
20284 var cameraBearingFov$ = this._container.renderService.renderCamera$
20285 .map(function (rc) {
20286 var vFov = _this._spatial.degToRad(rc.perspective.fov);
20287 var hFov = rc.perspective.aspect === Number.POSITIVE_INFINITY ?
20289 Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2;
20290 return [_this._spatial.azimuthalToBearing(rc.rotation.phi), hFov];
20292 .distinctUntilChanged(function (a1, a2) {
20293 return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
20294 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
20296 this._renderSubscription = Observable_1.Observable
20297 .combineLatest(nodeBearingFov$, cameraBearingFov$)
20298 .map(function (args) {
20299 var background = vd.h("div.BearingIndicatorBackground", { oncontextmenu: function (event) { event.preventDefault(); } }, [
20300 vd.h("div.BearingIndicatorBackgroundRectangle", {}, []),
20301 vd.h("div.BearingIndicatorBackgroundCircle", {}, []),
20303 var north = vd.h("div.BearingIndicatorNorth", {}, []);
20304 var nodeSector = _this._createCircleSector(args[0][0], args[0][1], "#000");
20305 var cameraSector = _this._createCircleSector(args[1][0], args[1][1], "#fff");
20306 var compass = _this._createCircleSectorCompass(nodeSector, cameraSector);
20309 vnode: vd.h("div.BearingIndicator", {}, [
20316 .subscribe(this._container.domRenderer.render$);
20318 BearingComponent.prototype._deactivate = function () {
20319 this._renderSubscription.unsubscribe();
20321 BearingComponent.prototype._getDefaultConfiguration = function () {
20324 BearingComponent.prototype._createCircleSectorCompass = function (nodeSector, cameraSector) {
20325 var group = vd.h("g", {
20326 attributes: { transform: "translate(1,1)" },
20327 namespace: this._svgNamespace,
20328 }, [nodeSector, cameraSector]);
20329 var centerCircle = vd.h("circle", {
20336 "stroke-width": "0.0833333",
20338 namespace: this._svgNamespace,
20340 var svg = vd.h("svg", {
20341 attributes: { viewBox: "0 0 2 2" },
20342 namespace: this._svgNamespace,
20347 position: "absolute",
20350 }, [group, centerCircle]);
20353 BearingComponent.prototype._createCircleSector = function (bearing, fov, fill) {
20354 if (fov > 2 * Math.PI - Math.PI / 90) {
20355 return vd.h("circle", {
20356 attributes: { cx: "0", cy: "0", fill: fill, r: "1" },
20357 namespace: this._svgNamespace,
20360 var arcStart = bearing - fov / 2 - Math.PI / 2;
20361 var arcEnd = arcStart + fov;
20362 var startX = Math.cos(arcStart);
20363 var startY = Math.sin(arcStart);
20364 var endX = Math.cos(arcEnd);
20365 var endY = Math.sin(arcEnd);
20366 var largeArc = fov >= Math.PI ? 1 : 0;
20367 var description = "M 0 0 " + startX + " " + startY + " A 1 1 0 " + largeArc + " 1 " + endX + " " + endY;
20368 return vd.h("path", {
20369 attributes: { d: description, fill: fill },
20370 namespace: this._svgNamespace,
20373 return BearingComponent;
20374 }(Component_1.Component));
20375 BearingComponent.componentName = "bearing";
20376 exports.BearingComponent = BearingComponent;
20377 Component_1.ComponentService.register(BearingComponent);
20378 Object.defineProperty(exports, "__esModule", { value: true });
20379 exports.default = BearingComponent;
20381 },{"../Component":225,"../Geo":228,"rxjs/Observable":28,"virtual-dom":181}],241:[function(require,module,exports){
20383 var __extends = (this && this.__extends) || function (d, b) {
20384 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20385 function __() { this.constructor = d; }
20386 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20388 var Observable_1 = require("rxjs/Observable");
20389 require("rxjs/add/observable/combineLatest");
20390 require("rxjs/add/observable/from");
20391 require("rxjs/add/observable/merge");
20392 require("rxjs/add/observable/of");
20393 require("rxjs/add/observable/zip");
20394 require("rxjs/add/operator/catch");
20395 require("rxjs/add/operator/combineLatest");
20396 require("rxjs/add/operator/distinct");
20397 require("rxjs/add/operator/expand");
20398 require("rxjs/add/operator/filter");
20399 require("rxjs/add/operator/map");
20400 require("rxjs/add/operator/merge");
20401 require("rxjs/add/operator/mergeMap");
20402 require("rxjs/add/operator/mergeAll");
20403 require("rxjs/add/operator/skip");
20404 require("rxjs/add/operator/switchMap");
20405 var Edge_1 = require("../Edge");
20406 var Component_1 = require("../Component");
20407 var CacheComponent = (function (_super) {
20408 __extends(CacheComponent, _super);
20409 function CacheComponent(name, container, navigator) {
20410 return _super.call(this, name, container, navigator) || this;
20413 * Set the cache depth.
20415 * Configures the cache depth. The cache depth can be different for
20416 * different edge direction types.
20418 * @param {ICacheDepth} depth - Cache depth structure.
20420 CacheComponent.prototype.setDepth = function (depth) {
20421 this.configure({ depth: depth });
20423 CacheComponent.prototype._activate = function () {
20425 this._sequenceSubscription = Observable_1.Observable
20426 .combineLatest(this._navigator.stateService.currentNode$
20427 .switchMap(function (node) {
20428 return node.sequenceEdges$;
20430 .filter(function (status) {
20431 return status.cached;
20432 }), this._configuration$)
20433 .switchMap(function (nc) {
20434 var status = nc[0];
20435 var configuration = nc[1];
20436 var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence));
20437 var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth);
20438 var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth);
20439 return Observable_1.Observable
20440 .merge(next$, prev$)
20441 .catch(function (error, caught) {
20442 console.error("Failed to cache sequence edges.", error);
20443 return Observable_1.Observable.empty();
20446 .subscribe(function () { });
20447 this._spatialSubscription = this._navigator.stateService.currentNode$
20448 .switchMap(function (node) {
20449 return Observable_1.Observable
20450 .combineLatest(Observable_1.Observable.of(node), node.spatialEdges$
20451 .filter(function (status) {
20452 return status.cached;
20455 .combineLatest(this._configuration$, function (ns, configuration) {
20456 return [ns[0], ns[1], configuration];
20458 .switchMap(function (args) {
20459 var node = args[0];
20460 var edges = args[1].edges;
20461 var depth = args[2].depth;
20462 var panoDepth = Math.max(0, Math.min(2, depth.pano));
20463 var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step));
20464 var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn));
20465 var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth);
20466 var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth);
20467 var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth);
20468 var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth);
20469 var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth);
20470 var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth);
20471 var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth);
20472 var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth);
20473 return Observable_1.Observable
20474 .merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$)
20475 .catch(function (error, caught) {
20476 console.error("Failed to cache spatial edges.", error);
20477 return Observable_1.Observable.empty();
20480 .subscribe(function () { });
20482 CacheComponent.prototype._deactivate = function () {
20483 this._sequenceSubscription.unsubscribe();
20484 this._spatialSubscription.unsubscribe();
20486 CacheComponent.prototype._getDefaultConfiguration = function () {
20487 return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } };
20489 CacheComponent.prototype._cache$ = function (edges, direction, depth) {
20491 return Observable_1.Observable
20492 .zip(Observable_1.Observable.of(edges), Observable_1.Observable.of(depth))
20493 .expand(function (ed) {
20496 var edgesDepths$ = [];
20498 for (var _i = 0, es_1 = es; _i < es_1.length; _i++) {
20499 var edge = es_1[_i];
20500 if (edge.data.direction === direction) {
20501 edgesDepths$.push(Observable_1.Observable
20502 .zip(_this._navigator.graphService.cacheNode$(edge.to)
20503 .mergeMap(function (n) {
20504 return _this._nodeToEdges$(n, direction);
20505 }), Observable_1.Observable.of(d - 1)));
20509 return Observable_1.Observable
20510 .from(edgesDepths$)
20515 CacheComponent.prototype._nodeToEdges$ = function (node, direction) {
20516 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
20517 node.sequenceEdges$ :
20518 node.spatialEdges$)
20519 .first(function (status) {
20520 return status.cached;
20522 .map(function (status) {
20523 return status.edges;
20526 return CacheComponent;
20527 }(Component_1.Component));
20528 CacheComponent.componentName = "cache";
20529 exports.CacheComponent = CacheComponent;
20530 Component_1.ComponentService.register(CacheComponent);
20531 Object.defineProperty(exports, "__esModule", { value: true });
20532 exports.default = CacheComponent;
20534 },{"../Component":225,"../Edge":226,"rxjs/Observable":28,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/from":40,"rxjs/add/observable/merge":43,"rxjs/add/observable/of":44,"rxjs/add/observable/zip":47,"rxjs/add/operator/catch":51,"rxjs/add/operator/combineLatest":52,"rxjs/add/operator/distinct":56,"rxjs/add/operator/expand":59,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/merge":65,"rxjs/add/operator/mergeAll":66,"rxjs/add/operator/mergeMap":67,"rxjs/add/operator/skip":74,"rxjs/add/operator/switchMap":78}],242:[function(require,module,exports){
20536 var __extends = (this && this.__extends) || function (d, b) {
20537 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20538 function __() { this.constructor = d; }
20539 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20541 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
20542 var Subject_1 = require("rxjs/Subject");
20543 require("rxjs/add/operator/publishReplay");
20544 require("rxjs/add/operator/scan");
20545 require("rxjs/add/operator/startWith");
20546 var Utils_1 = require("../Utils");
20547 var Component = (function (_super) {
20548 __extends(Component, _super);
20549 function Component(name, container, navigator) {
20550 var _this = _super.call(this) || this;
20551 _this._activated$ = new BehaviorSubject_1.BehaviorSubject(false);
20552 _this._configurationSubject$ = new Subject_1.Subject();
20553 _this._activated = false;
20554 _this._container = container;
20555 _this._name = name;
20556 _this._navigator = navigator;
20557 _this._configuration$ =
20558 _this._configurationSubject$
20559 .startWith(_this.defaultConfiguration)
20560 .scan(function (conf, newConf) {
20561 for (var key in newConf) {
20562 if (newConf.hasOwnProperty(key)) {
20563 conf[key] = newConf[key];
20570 _this._configuration$.subscribe(function () { });
20573 Object.defineProperty(Component.prototype, "activated", {
20575 return this._activated;
20580 Object.defineProperty(Component.prototype, "activated$", {
20582 return this._activated$;
20587 Object.defineProperty(Component.prototype, "defaultConfiguration", {
20589 * Get default configuration.
20591 * @returns {TConfiguration} Default configuration for component.
20594 return this._getDefaultConfiguration();
20599 Object.defineProperty(Component.prototype, "configuration$", {
20601 return this._configuration$;
20606 Object.defineProperty(Component.prototype, "name", {
20613 Component.prototype.activate = function (conf) {
20614 if (this._activated) {
20617 if (conf !== undefined) {
20618 this._configurationSubject$.next(conf);
20620 this._activated = true;
20622 this._activated$.next(true);
20625 Component.prototype.configure = function (conf) {
20626 this._configurationSubject$.next(conf);
20628 Component.prototype.deactivate = function () {
20629 if (!this._activated) {
20632 this._activated = false;
20633 this._deactivate();
20634 this._container.domRenderer.clear(this._name);
20635 this._container.glRenderer.clear(this._name);
20636 this._activated$.next(false);
20640 * Detect the viewer's new width and height and resize the component's
20641 * rendered elements accordingly if applicable.
20643 Component.prototype.resize = function () { return; };
20645 }(Utils_1.EventEmitter));
20647 * Component name. Used when interacting with component through the Viewer's API.
20649 Component.componentName = "not_worthy";
20650 exports.Component = Component;
20651 Object.defineProperty(exports, "__esModule", { value: true });
20652 exports.default = Component;
20654 },{"../Utils":234,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/startWith":77}],243:[function(require,module,exports){
20655 /// <reference path="../../typings/index.d.ts" />
20657 var _ = require("underscore");
20658 var Error_1 = require("../Error");
20659 var ComponentService = (function () {
20660 function ComponentService(container, navigator) {
20661 this._components = {};
20662 this._container = container;
20663 this._navigator = navigator;
20664 for (var _i = 0, _a = _.values(ComponentService.registeredComponents); _i < _a.length; _i++) {
20665 var component = _a[_i];
20666 this._components[component.componentName] = {
20668 component: new component(component.componentName, container, navigator),
20671 this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator);
20672 this._coverComponent.activate();
20673 this._coverActivated = true;
20675 ComponentService.register = function (component) {
20676 if (ComponentService.registeredComponents[component.componentName] === undefined) {
20677 ComponentService.registeredComponents[component.componentName] = component;
20680 ComponentService.registerCover = function (coverComponent) {
20681 ComponentService.registeredCoverComponent = coverComponent;
20683 ComponentService.prototype.activateCover = function () {
20684 if (this._coverActivated) {
20687 this._coverActivated = true;
20688 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
20689 var component = _a[_i];
20690 if (component.active) {
20691 component.component.deactivate();
20696 ComponentService.prototype.deactivateCover = function () {
20697 if (!this._coverActivated) {
20700 this._coverActivated = false;
20701 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
20702 var component = _a[_i];
20703 if (component.active) {
20704 component.component.activate();
20709 ComponentService.prototype.activate = function (name) {
20710 this._checkName(name);
20711 this._components[name].active = true;
20712 if (!this._coverActivated) {
20713 this.get(name).activate();
20716 ComponentService.prototype.configure = function (name, conf) {
20717 this._checkName(name);
20718 this.get(name).configure(conf);
20720 ComponentService.prototype.deactivate = function (name) {
20721 this._checkName(name);
20722 this._components[name].active = false;
20723 if (!this._coverActivated) {
20724 this.get(name).deactivate();
20727 ComponentService.prototype.resize = function () {
20728 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
20729 var component = _a[_i];
20730 component.component.resize();
20733 ComponentService.prototype.get = function (name) {
20734 return this._components[name].component;
20736 ComponentService.prototype.getCover = function () {
20737 return this._coverComponent;
20739 ComponentService.prototype._checkName = function (name) {
20740 if (!(name in this._components)) {
20741 throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name);
20744 return ComponentService;
20746 ComponentService.registeredComponents = {};
20747 exports.ComponentService = ComponentService;
20748 Object.defineProperty(exports, "__esModule", { value: true });
20749 exports.default = ComponentService;
20751 },{"../Error":227,"underscore":176}],244:[function(require,module,exports){
20752 /// <reference path="../../typings/index.d.ts" />
20754 var __extends = (this && this.__extends) || function (d, b) {
20755 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20756 function __() { this.constructor = d; }
20757 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20759 var vd = require("virtual-dom");
20760 require("rxjs/add/operator/filter");
20761 require("rxjs/add/operator/map");
20762 require("rxjs/add/operator/withLatestFrom");
20763 var Component_1 = require("../Component");
20764 var CoverComponent = (function (_super) {
20765 __extends(CoverComponent, _super);
20766 function CoverComponent(name, container, navigator) {
20767 return _super.call(this, name, container, navigator) || this;
20769 CoverComponent.prototype._activate = function () {
20771 this._keyDisposable = this._navigator.stateService.currentNode$
20772 .withLatestFrom(this._configuration$, function (node, configuration) {
20773 return [node, configuration];
20775 .filter(function (nc) {
20776 return nc[0].key !== nc[1].key;
20778 .map(function (nc) { return nc[0]; })
20779 .map(function (node) {
20780 return { key: node.key, src: node.image.src };
20782 .subscribe(this._configurationSubject$);
20783 this._disposable = this._configuration$
20784 .map(function (conf) {
20786 return { name: _this._name, vnode: vd.h("div", []) };
20788 if (!conf.visible) {
20789 return { name: _this._name, vnode: vd.h("div.Cover.CoverDone", [_this._getCoverBackgroundVNode(conf)]) };
20791 return { name: _this._name, vnode: _this._getCoverButtonVNode(conf) };
20793 .subscribe(this._container.domRenderer.render$);
20795 CoverComponent.prototype._deactivate = function () {
20796 this._disposable.unsubscribe();
20797 this._keyDisposable.unsubscribe();
20799 CoverComponent.prototype._getDefaultConfiguration = function () {
20800 return { "loading": false, "visible": true };
20802 CoverComponent.prototype._getCoverButtonVNode = function (conf) {
20804 var cover = conf.loading ? "div.Cover.CoverLoading" : "div.Cover";
20805 return vd.h(cover, [
20806 this._getCoverBackgroundVNode(conf),
20807 vd.h("button.CoverButton", { onclick: function () { _this.configure({ loading: true }); } }, ["Explore"]),
20808 vd.h("a.CoverLogo", { href: "https://www.mapillary.com", target: "_blank" }, []),
20811 CoverComponent.prototype._getCoverBackgroundVNode = function (conf) {
20812 var url = conf.src != null ?
20813 "url(" + conf.src + ")" :
20814 "url(https://d1cuyjsrcm0gby.cloudfront.net/" + conf.key + "/thumb-640.jpg)";
20815 var properties = { style: { backgroundImage: url } };
20817 if (conf.loading) {
20818 children.push(vd.h("div.Spinner", {}, []));
20820 children.push(vd.h("div.CoverBackgroundGradient", {}, []));
20821 return vd.h("div.CoverBackground", properties, children);
20823 return CoverComponent;
20824 }(Component_1.Component));
20825 CoverComponent.componentName = "cover";
20826 exports.CoverComponent = CoverComponent;
20827 Component_1.ComponentService.registerCover(CoverComponent);
20828 Object.defineProperty(exports, "__esModule", { value: true });
20829 exports.default = CoverComponent;
20831 },{"../Component":225,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/withLatestFrom":82,"virtual-dom":181}],245:[function(require,module,exports){
20832 /// <reference path="../../typings/index.d.ts" />
20834 var __extends = (this && this.__extends) || function (d, b) {
20835 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20836 function __() { this.constructor = d; }
20837 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20839 var _ = require("underscore");
20840 var vd = require("virtual-dom");
20841 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
20842 require("rxjs/add/operator/combineLatest");
20843 var Component_1 = require("../Component");
20844 var DebugComponent = (function (_super) {
20845 __extends(DebugComponent, _super);
20846 function DebugComponent(name, container, navigator) {
20847 var _this = _super.call(this, name, container, navigator) || this;
20848 _this._open$ = new BehaviorSubject_1.BehaviorSubject(false);
20849 _this._displaying = false;
20852 DebugComponent.prototype._activate = function () {
20854 this._disposable = this._navigator.stateService.currentState$
20855 .combineLatest(this._open$, this._navigator.imageLoadingService.loadstatus$, function (frame, open, loadStatus) {
20856 return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) };
20858 .subscribe(this._container.domRenderer.render$);
20860 DebugComponent.prototype._deactivate = function () {
20861 this._disposable.unsubscribe();
20863 DebugComponent.prototype._getDefaultConfiguration = function () {
20866 DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) {
20868 ret.push(vd.h("h2", "Node"));
20869 if (frame.state.currentNode) {
20870 ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key));
20872 if (frame.state.previousNode) {
20873 ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key));
20875 ret.push(vd.h("h2", "Loading"));
20879 for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
20880 var loadStat = _a[_i];
20881 total += loadStat.loaded;
20882 if (loadStat.loaded !== loadStat.total) {
20889 ret.push(vd.h("p", "Loaded Images: " + loaded));
20890 ret.push(vd.h("p", "Loading Images: " + loading));
20891 ret.push(vd.h("p", "Total bytes loaded: " + total));
20892 ret.push(vd.h("h2", "Camera"));
20893 ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x));
20894 ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y));
20895 ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z));
20896 ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x));
20897 ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y));
20898 ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z));
20899 ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x));
20900 ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y));
20901 ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z));
20904 DebugComponent.prototype._getDebugVNode = function (open, info) {
20906 return vd.h("div.Debug", {}, [
20907 vd.h("h2", {}, ["Debug"]),
20908 this._getDebugVNodeButton(open),
20909 vd.h("pre", {}, info),
20913 return this._getDebugVNodeButton(open);
20916 DebugComponent.prototype._getDebugVNodeButton = function (open) {
20917 var buttonText = open ? "Disable Debug" : "D";
20918 var buttonCssClass = open ? "" : ".DebugButtonFixed";
20920 return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]);
20923 return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]);
20926 DebugComponent.prototype._closeDebugElement = function (open) {
20927 this._open$.next(false);
20929 DebugComponent.prototype._openDebugElement = function () {
20930 this._open$.next(true);
20932 return DebugComponent;
20933 }(Component_1.Component));
20934 DebugComponent.componentName = "debug";
20935 exports.DebugComponent = DebugComponent;
20936 Component_1.ComponentService.register(DebugComponent);
20937 Object.defineProperty(exports, "__esModule", { value: true });
20938 exports.default = DebugComponent;
20940 },{"../Component":225,"rxjs/BehaviorSubject":25,"rxjs/add/operator/combineLatest":52,"underscore":176,"virtual-dom":181}],246:[function(require,module,exports){
20941 /// <reference path="../../typings/index.d.ts" />
20943 var __extends = (this && this.__extends) || function (d, b) {
20944 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20945 function __() { this.constructor = d; }
20946 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20948 var vd = require("virtual-dom");
20949 require("rxjs/add/operator/combineLatest");
20950 var Component_1 = require("../Component");
20951 var ImageComponent = (function (_super) {
20952 __extends(ImageComponent, _super);
20953 function ImageComponent(name, container, navigator) {
20954 var _this = _super.call(this, name, container, navigator) || this;
20955 _this._canvasId = container.id + "-" + _this._name;
20958 ImageComponent.prototype._activate = function () {
20960 this.drawSubscription = this._container.domRenderer.element$
20961 .combineLatest(this._navigator.stateService.currentNode$, function (element, node) {
20962 var canvas = document.getElementById(_this._canvasId);
20963 return { canvas: canvas, node: node };
20965 .subscribe(function (canvasNode) {
20966 var canvas = canvasNode.canvas;
20967 var node = canvasNode.node;
20968 if (!node || !canvas) {
20971 var adaptableDomRenderer = canvas.parentElement;
20972 var width = adaptableDomRenderer.offsetWidth;
20973 var height = adaptableDomRenderer.offsetHeight;
20974 canvas.width = width;
20975 canvas.height = height;
20976 var ctx = canvas.getContext("2d");
20977 ctx.drawImage(node.image, 0, 0, width, height);
20979 this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) });
20981 ImageComponent.prototype._deactivate = function () {
20982 this.drawSubscription.unsubscribe();
20984 ImageComponent.prototype._getDefaultConfiguration = function () {
20987 return ImageComponent;
20988 }(Component_1.Component));
20989 ImageComponent.componentName = "image";
20990 exports.ImageComponent = ImageComponent;
20991 Component_1.ComponentService.register(ImageComponent);
20992 Object.defineProperty(exports, "__esModule", { value: true });
20993 exports.default = ImageComponent;
20995 },{"../Component":225,"rxjs/add/operator/combineLatest":52,"virtual-dom":181}],247:[function(require,module,exports){
20997 var __extends = (this && this.__extends) || function (d, b) {
20998 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20999 function __() { this.constructor = d; }
21000 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21002 var Observable_1 = require("rxjs/Observable");
21003 require("rxjs/add/observable/fromEvent");
21004 require("rxjs/add/operator/withLatestFrom");
21005 var Edge_1 = require("../Edge");
21006 var Component_1 = require("../Component");
21007 var Geo_1 = require("../Geo");
21008 var KeyboardComponent = (function (_super) {
21009 __extends(KeyboardComponent, _super);
21010 function KeyboardComponent(name, container, navigator) {
21011 var _this = _super.call(this, name, container, navigator) || this;
21012 _this._spatial = new Geo_1.Spatial();
21013 _this._perspectiveDirections = [
21014 Edge_1.EdgeDirection.StepForward,
21015 Edge_1.EdgeDirection.StepBackward,
21016 Edge_1.EdgeDirection.StepLeft,
21017 Edge_1.EdgeDirection.StepRight,
21018 Edge_1.EdgeDirection.TurnLeft,
21019 Edge_1.EdgeDirection.TurnRight,
21020 Edge_1.EdgeDirection.TurnU,
21024 KeyboardComponent.prototype._activate = function () {
21026 var sequenceEdges$ = this._navigator.stateService.currentNode$
21027 .switchMap(function (node) {
21028 return node.sequenceEdges$;
21030 var spatialEdges$ = this._navigator.stateService.currentNode$
21031 .switchMap(function (node) {
21032 return node.spatialEdges$;
21034 this._disposable = Observable_1.Observable
21035 .fromEvent(document, "keydown")
21036 .withLatestFrom(this._navigator.stateService.currentState$, sequenceEdges$, spatialEdges$, function (event, frame, sequenceEdges, spatialEdges) {
21037 return { event: event, frame: frame, sequenceEdges: sequenceEdges, spatialEdges: spatialEdges };
21039 .subscribe(function (kf) {
21040 if (!kf.frame.state.currentNode.pano) {
21041 _this._navigatePerspective(kf.event, kf.sequenceEdges, kf.spatialEdges);
21044 _this._navigatePanorama(kf.event, kf.sequenceEdges, kf.spatialEdges, kf.frame.state.camera);
21048 KeyboardComponent.prototype._deactivate = function () {
21049 this._disposable.unsubscribe();
21051 KeyboardComponent.prototype._getDefaultConfiguration = function () {
21054 KeyboardComponent.prototype._navigatePanorama = function (event, sequenceEdges, spatialEdges, camera) {
21055 var navigationAngle = 0;
21056 var stepDirection = null;
21057 var sequenceDirection = null;
21058 var phi = this._rotationFromCamera(camera).phi;
21059 switch (event.keyCode) {
21061 if (event.shiftKey || event.altKey) {
21064 navigationAngle = Math.PI / 2 + phi;
21065 stepDirection = Edge_1.EdgeDirection.StepLeft;
21068 if (event.shiftKey) {
21071 if (event.altKey) {
21072 sequenceDirection = Edge_1.EdgeDirection.Next;
21075 navigationAngle = phi;
21076 stepDirection = Edge_1.EdgeDirection.StepForward;
21079 if (event.shiftKey || event.altKey) {
21082 navigationAngle = -Math.PI / 2 + phi;
21083 stepDirection = Edge_1.EdgeDirection.StepRight;
21086 if (event.shiftKey) {
21089 if (event.altKey) {
21090 sequenceDirection = Edge_1.EdgeDirection.Prev;
21093 navigationAngle = Math.PI + phi;
21094 stepDirection = Edge_1.EdgeDirection.StepBackward;
21099 event.preventDefault();
21100 if (sequenceDirection != null) {
21101 this._moveInDir(sequenceDirection, sequenceEdges);
21104 if (stepDirection == null || !spatialEdges.cached) {
21107 navigationAngle = this._spatial.wrapAngle(navigationAngle);
21108 var threshold = Math.PI / 4;
21109 var edges = spatialEdges.edges.filter(function (e) {
21110 return e.data.direction === Edge_1.EdgeDirection.Pano ||
21111 e.data.direction === stepDirection;
21113 var smallestAngle = Number.MAX_VALUE;
21115 for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
21116 var edge = edges_1[_i];
21117 var angle = Math.abs(this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle));
21118 if (angle < Math.min(smallestAngle, threshold)) {
21119 smallestAngle = angle;
21123 if (toKey == null) {
21126 this._navigator.moveToKey$(toKey)
21127 .subscribe(function (n) { return; }, function (e) { console.error(e); });
21129 KeyboardComponent.prototype._rotationFromCamera = function (camera) {
21130 var direction = camera.lookat.clone().sub(camera.position);
21131 var upProjection = direction.clone().dot(camera.up);
21132 var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection));
21133 var phi = Math.atan2(planeProjection.y, planeProjection.x);
21134 var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
21135 return { phi: phi, theta: theta };
21137 KeyboardComponent.prototype._navigatePerspective = function (event, sequenceEdges, spatialEdges) {
21138 var direction = null;
21139 var sequenceDirection = null;
21140 switch (event.keyCode) {
21142 if (event.altKey) {
21145 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft;
21148 if (event.altKey) {
21149 sequenceDirection = Edge_1.EdgeDirection.Next;
21152 direction = event.shiftKey ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward;
21155 if (event.altKey) {
21158 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight;
21161 if (event.altKey) {
21162 sequenceDirection = Edge_1.EdgeDirection.Prev;
21165 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward;
21170 event.preventDefault();
21171 if (sequenceDirection != null) {
21172 this._moveInDir(sequenceDirection, sequenceEdges);
21175 this._moveInDir(direction, spatialEdges);
21177 KeyboardComponent.prototype._moveInDir = function (direction, edgeStatus) {
21178 if (!edgeStatus.cached) {
21181 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
21183 if (edge.data.direction === direction) {
21184 this._navigator.moveToKey$(edge.to)
21185 .subscribe(function (n) { return; }, function (e) { console.error(e); });
21190 return KeyboardComponent;
21191 }(Component_1.Component));
21192 KeyboardComponent.componentName = "keyboard";
21193 exports.KeyboardComponent = KeyboardComponent;
21194 Component_1.ComponentService.register(KeyboardComponent);
21195 Object.defineProperty(exports, "__esModule", { value: true });
21196 exports.default = KeyboardComponent;
21198 },{"../Component":225,"../Edge":226,"../Geo":228,"rxjs/Observable":28,"rxjs/add/observable/fromEvent":41,"rxjs/add/operator/withLatestFrom":82}],248:[function(require,module,exports){
21199 /// <reference path="../../typings/index.d.ts" />
21201 var __extends = (this && this.__extends) || function (d, b) {
21202 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
21203 function __() { this.constructor = d; }
21204 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21206 var _ = require("underscore");
21207 var vd = require("virtual-dom");
21208 require("rxjs/add/operator/combineLatest");
21209 var Component_1 = require("../Component");
21210 var LoadingComponent = (function (_super) {
21211 __extends(LoadingComponent, _super);
21212 function LoadingComponent(name, container, navigator) {
21213 return _super.call(this, name, container, navigator) || this;
21215 LoadingComponent.prototype._activate = function () {
21217 this._loadingSubscription = this._navigator.loadingService.loading$
21218 .combineLatest(this._navigator.imageLoadingService.loadstatus$, function (loading, loadStatus) {
21220 return { name: "loading", vnode: _this._getBarVNode(100) };
21224 for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
21225 var loadStat = _a[_i];
21226 if (loadStat.loaded !== loadStat.total) {
21227 loaded += loadStat.loaded;
21228 total += loadStat.total;
21231 var percentage = 100;
21233 percentage = (loaded / total) * 100;
21235 return { name: _this._name, vnode: _this._getBarVNode(percentage) };
21237 .subscribe(this._container.domRenderer.render$);
21239 LoadingComponent.prototype._deactivate = function () {
21240 this._loadingSubscription.unsubscribe();
21242 LoadingComponent.prototype._getDefaultConfiguration = function () {
21245 LoadingComponent.prototype._getBarVNode = function (percentage) {
21246 var loadingBarStyle = {};
21247 var loadingContainerStyle = {};
21248 if (percentage !== 100) {
21249 loadingBarStyle.width = percentage.toFixed(0) + "%";
21250 loadingBarStyle.opacity = "1";
21253 loadingBarStyle.width = "100%";
21254 loadingBarStyle.opacity = "0";
21256 return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]);
21258 return LoadingComponent;
21259 }(Component_1.Component));
21260 LoadingComponent.componentName = "loading";
21261 exports.LoadingComponent = LoadingComponent;
21262 Component_1.ComponentService.register(LoadingComponent);
21263 Object.defineProperty(exports, "__esModule", { value: true });
21264 exports.default = LoadingComponent;
21266 },{"../Component":225,"rxjs/add/operator/combineLatest":52,"underscore":176,"virtual-dom":181}],249:[function(require,module,exports){
21267 /// <reference path="../../typings/index.d.ts" />
21269 var __extends = (this && this.__extends) || function (d, b) {
21270 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
21271 function __() { this.constructor = d; }
21272 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21274 var vd = require("virtual-dom");
21275 var Observable_1 = require("rxjs/Observable");
21276 require("rxjs/add/operator/map");
21277 require("rxjs/add/operator/first");
21278 var Edge_1 = require("../Edge");
21279 var Component_1 = require("../Component");
21280 var NavigationComponent = (function (_super) {
21281 __extends(NavigationComponent, _super);
21282 function NavigationComponent(name, container, navigator) {
21283 var _this = _super.call(this, name, container, navigator) || this;
21284 _this._dirNames = {};
21285 _this._dirNames[Edge_1.EdgeDirection.StepForward] = "Forward";
21286 _this._dirNames[Edge_1.EdgeDirection.StepBackward] = "Backward";
21287 _this._dirNames[Edge_1.EdgeDirection.StepLeft] = "Left";
21288 _this._dirNames[Edge_1.EdgeDirection.StepRight] = "Right";
21289 _this._dirNames[Edge_1.EdgeDirection.TurnLeft] = "Turnleft";
21290 _this._dirNames[Edge_1.EdgeDirection.TurnRight] = "Turnright";
21291 _this._dirNames[Edge_1.EdgeDirection.TurnU] = "Turnaround";
21294 NavigationComponent.prototype._activate = function () {
21296 this._renderSubscription = this._navigator.stateService.currentNode$
21297 .switchMap(function (node) {
21299 Observable_1.Observable.of([]) :
21300 Observable_1.Observable.combineLatest(node.sequenceEdges$, node.spatialEdges$, function (seq, spa) {
21301 return seq.edges.concat(spa.edges);
21304 .map(function (edges) {
21306 for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
21307 var edge = edges_1[_i];
21308 var direction = edge.data.direction;
21309 var name_1 = _this._dirNames[direction];
21310 if (name_1 == null) {
21313 btns.push(_this._createVNode(direction, name_1));
21315 return { name: _this._name, vnode: vd.h("div.NavigationComponent", btns) };
21317 .subscribe(this._container.domRenderer.render$);
21319 NavigationComponent.prototype._deactivate = function () {
21320 this._renderSubscription.unsubscribe();
21322 NavigationComponent.prototype._getDefaultConfiguration = function () {
21325 NavigationComponent.prototype._createVNode = function (direction, name) {
21327 return vd.h("span.Direction.Direction" + name, {
21328 onclick: function (ev) {
21329 _this._navigator.moveDir$(direction)
21330 .subscribe(function (node) { return; }, function (error) { console.error(error); });
21334 return NavigationComponent;
21335 }(Component_1.Component));
21336 NavigationComponent.componentName = "navigation";
21337 exports.NavigationComponent = NavigationComponent;
21338 Component_1.ComponentService.register(NavigationComponent);
21339 Object.defineProperty(exports, "__esModule", { value: true });
21340 exports.default = NavigationComponent;
21342 },{"../Component":225,"../Edge":226,"rxjs/Observable":28,"rxjs/add/operator/first":62,"rxjs/add/operator/map":64,"virtual-dom":181}],250:[function(require,module,exports){
21343 /// <reference path="../../typings/index.d.ts" />
21345 var __extends = (this && this.__extends) || function (d, b) {
21346 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
21347 function __() { this.constructor = d; }
21348 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21350 var _ = require("underscore");
21351 var vd = require("virtual-dom");
21352 var Observable_1 = require("rxjs/Observable");
21353 require("rxjs/add/observable/fromPromise");
21354 require("rxjs/add/observable/of");
21355 require("rxjs/add/operator/combineLatest");
21356 require("rxjs/add/operator/distinct");
21357 require("rxjs/add/operator/distinctUntilChanged");
21358 require("rxjs/add/operator/filter");
21359 require("rxjs/add/operator/map");
21360 require("rxjs/add/operator/mergeMap");
21361 require("rxjs/add/operator/pluck");
21362 require("rxjs/add/operator/scan");
21363 var Component_1 = require("../Component");
21364 var DescriptionState = (function () {
21365 function DescriptionState() {
21367 return DescriptionState;
21369 var RouteState = (function () {
21370 function RouteState() {
21374 var RouteTrack = (function () {
21375 function RouteTrack() {
21376 this.nodeInstructions = [];
21377 this.nodeInstructionsOrdered = [];
21381 var RouteComponent = (function (_super) {
21382 __extends(RouteComponent, _super);
21383 function RouteComponent(name, container, navigator) {
21384 return _super.call(this, name, container, navigator) || this;
21386 RouteComponent.prototype._activate = function () {
21388 var _slowedStream$;
21389 _slowedStream$ = this._navigator.stateService.currentState$.filter(function (frame) {
21390 return (frame.id % 2) === 0;
21391 }).filter(function (frame) {
21392 return frame.state.nodesAhead < 15;
21393 }).distinctUntilChanged(undefined, function (frame) {
21394 return frame.state.lastNode.key;
21397 _routeTrack$ = this.configuration$.mergeMap(function (conf) {
21398 return Observable_1.Observable.from(conf.paths);
21399 }).distinct(function (p) {
21400 return p.sequenceKey;
21401 }).mergeMap(function (path) {
21402 return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey])
21403 .map(function (sequenceByKey) {
21404 return sequenceByKey[path.sequenceKey];
21406 }).combineLatest(this.configuration$, function (sequence, conf) {
21408 var instructionPlaces = [];
21409 for (var _i = 0, _a = conf.paths; _i < _a.length; _i++) {
21411 if (path.sequenceKey === sequence.key) {
21412 var nodeInstructions = [];
21413 var saveKey = false;
21414 for (var _b = 0, _c = sequence.keys; _b < _c.length; _b++) {
21416 if (path.startKey === key) {
21420 var description = null;
21421 for (var _d = 0, _e = path.infoKeys; _d < _e.length; _d++) {
21422 var infoKey = _e[_d];
21423 if (infoKey.key === key) {
21424 description = infoKey.description;
21427 nodeInstructions.push({ description: description, key: key });
21429 if (path.stopKey === key) {
21433 instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i });
21437 return instructionPlaces;
21438 }).scan(function (routeTrack, instructionPlaces) {
21439 for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) {
21440 var instructionPlace = instructionPlaces_1[_i];
21441 routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions;
21443 routeTrack.nodeInstructions = _.flatten(routeTrack.nodeInstructionsOrdered);
21445 }, new RouteTrack());
21446 this._disposable = _slowedStream$
21447 .combineLatest(_routeTrack$, this.configuration$, function (frame, routeTrack, conf) {
21448 return { conf: conf, frame: frame, routeTrack: routeTrack };
21449 }).scan(function (routeState, rtAndFrame) {
21450 if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) {
21451 routeState.routeTrack = rtAndFrame.routeTrack;
21452 routeState.currentNode = rtAndFrame.frame.state.currentNode;
21453 routeState.lastNode = rtAndFrame.frame.state.lastNode;
21454 routeState.playing = true;
21457 _this._navigator.stateService.cutNodes();
21458 routeState.playing = false;
21461 }, new RouteState())
21462 .filter(function (routeState) {
21463 return routeState.playing;
21464 }).filter(function (routeState) {
21465 for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
21466 var nodeInstruction = _a[_i];
21467 if (!nodeInstruction) {
21470 if (nodeInstruction.key === routeState.lastNode.key) {
21475 }).distinctUntilChanged(undefined, function (routeState) {
21476 return routeState.lastNode.key;
21477 }).mergeMap(function (routeState) {
21479 for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
21480 var nodeInstruction = _a[_i];
21481 if (nodeInstruction.key === routeState.lastNode.key) {
21486 var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1];
21487 if (!nextInstruction) {
21488 return Observable_1.Observable.of(null);
21490 return _this._navigator.graphService.cacheNode$(nextInstruction.key);
21491 }).combineLatest(this.configuration$, function (node, conf) {
21492 return { conf: conf, node: node };
21493 }).filter(function (cAN) {
21494 return cAN.node !== null && cAN.conf.playing;
21495 }).pluck("node").subscribe(this._navigator.stateService.appendNode$);
21496 this._disposableDescription = this._navigator.stateService.currentNode$
21497 .combineLatest(_routeTrack$, this.configuration$, function (node, routeTrack, conf) {
21498 if (conf.playing !== undefined && !conf.playing) {
21501 var description = null;
21502 for (var _i = 0, _a = routeTrack.nodeInstructions; _i < _a.length; _i++) {
21503 var nodeInstruction = _a[_i];
21504 if (nodeInstruction.key === node.key) {
21505 description = nodeInstruction.description;
21509 return description;
21510 }).scan(function (descriptionState, description) {
21511 if (description !== descriptionState.description && description !== null) {
21512 descriptionState.description = description;
21513 descriptionState.showsLeft = 6;
21516 descriptionState.showsLeft--;
21518 if (description === "quit") {
21519 descriptionState.description = null;
21521 return descriptionState;
21522 }, new DescriptionState()).map(function (descriptionState) {
21523 if (descriptionState.showsLeft > 0 && descriptionState.description) {
21524 return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) };
21527 return { name: _this._name, vnode: vd.h("div", []) };
21529 }).subscribe(this._container.domRenderer.render$);
21531 RouteComponent.prototype._deactivate = function () {
21532 this._disposable.unsubscribe();
21533 this._disposableDescription.unsubscribe();
21535 RouteComponent.prototype._getDefaultConfiguration = function () {
21538 RouteComponent.prototype.play = function () {
21539 this.configure({ playing: true });
21541 RouteComponent.prototype.stop = function () {
21542 this.configure({ playing: false });
21544 RouteComponent.prototype._getRouteAnnotationNode = function (description) {
21545 return vd.h("div.RouteFrame", {}, [
21546 vd.h("p", { textContent: description }, []),
21549 return RouteComponent;
21550 }(Component_1.Component));
21551 RouteComponent.componentName = "route";
21552 exports.RouteComponent = RouteComponent;
21553 Component_1.ComponentService.register(RouteComponent);
21554 Object.defineProperty(exports, "__esModule", { value: true });
21555 exports.default = RouteComponent;
21557 },{"../Component":225,"rxjs/Observable":28,"rxjs/add/observable/fromPromise":42,"rxjs/add/observable/of":44,"rxjs/add/operator/combineLatest":52,"rxjs/add/operator/distinct":56,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/mergeMap":67,"rxjs/add/operator/pluck":69,"rxjs/add/operator/scan":72,"underscore":176,"virtual-dom":181}],251:[function(require,module,exports){
21559 var __extends = (this && this.__extends) || function (d, b) {
21560 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
21561 function __() { this.constructor = d; }
21562 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21564 var Observable_1 = require("rxjs/Observable");
21565 require("rxjs/add/operator/buffer");
21566 require("rxjs/add/operator/debounceTime");
21567 require("rxjs/add/operator/filter");
21568 require("rxjs/add/operator/map");
21569 require("rxjs/add/operator/scan");
21570 var Component_1 = require("../Component");
21571 var StatsComponent = (function (_super) {
21572 __extends(StatsComponent, _super);
21573 function StatsComponent(name, container, navigator) {
21574 return _super.call(this, name, container, navigator) || this;
21576 StatsComponent.prototype._activate = function () {
21578 this._sequenceSubscription = this._navigator.stateService.currentNode$
21579 .scan(function (keys, node) {
21580 var sKey = node.sequenceKey;
21582 if (!(sKey in keys.reported)) {
21583 keys.report = [sKey];
21584 keys.reported[sKey] = true;
21587 }, { report: [], reported: {} })
21588 .filter(function (keys) {
21589 return keys.report.length > 0;
21591 .mergeMap(function (keys) {
21592 return _this._navigator.apiV3.sequenceViewAdd$(keys.report)
21593 .catch(function (error, caught) {
21594 console.error("Failed to report sequence stats (" + keys.report + ")", error);
21595 return Observable_1.Observable.empty();
21598 .subscribe(function () { });
21599 this._imageSubscription = this._navigator.stateService.currentNode$
21600 .map(function (node) {
21603 .buffer(this._navigator.stateService.currentNode$.debounceTime(5000))
21604 .scan(function (keys, newKeys) {
21606 for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
21607 var key = newKeys_1[_i];
21608 if (!(key in keys.reported)) {
21609 keys.report.push(key);
21610 keys.reported[key] = true;
21614 }, { report: [], reported: {} })
21615 .filter(function (keys) {
21616 return keys.report.length > 0;
21618 .mergeMap(function (keys) {
21619 return _this._navigator.apiV3.imageViewAdd$(keys.report)
21620 .catch(function (error, caught) {
21621 console.error("Failed to report image stats (" + keys.report + ")", error);
21622 return Observable_1.Observable.empty();
21625 .subscribe(function () { });
21627 StatsComponent.prototype._deactivate = function () {
21628 this._sequenceSubscription.unsubscribe();
21629 this._imageSubscription.unsubscribe();
21631 StatsComponent.prototype._getDefaultConfiguration = function () {
21634 return StatsComponent;
21635 }(Component_1.Component));
21636 StatsComponent.componentName = "stats";
21637 exports.StatsComponent = StatsComponent;
21638 Component_1.ComponentService.register(StatsComponent);
21639 Object.defineProperty(exports, "__esModule", { value: true });
21640 exports.default = StatsComponent;
21642 },{"../Component":225,"rxjs/Observable":28,"rxjs/add/operator/buffer":48,"rxjs/add/operator/debounceTime":54,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/scan":72}],252:[function(require,module,exports){
21643 /// <reference path="../../../typings/index.d.ts" />
21645 var __extends = (this && this.__extends) || function (d, b) {
21646 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
21647 function __() { this.constructor = d; }
21648 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21650 var vd = require("virtual-dom");
21651 var Observable_1 = require("rxjs/Observable");
21652 var Subject_1 = require("rxjs/Subject");
21653 require("rxjs/add/observable/combineLatest");
21654 require("rxjs/add/operator/do");
21655 require("rxjs/add/operator/distinctUntilChanged");
21656 require("rxjs/add/operator/filter");
21657 require("rxjs/add/operator/map");
21658 require("rxjs/add/operator/share");
21659 var Component_1 = require("../../Component");
21661 * @class DirectionComponent
21662 * @classdesc Component showing navigation arrows for steps and turns.
21664 var DirectionComponent = (function (_super) {
21665 __extends(DirectionComponent, _super);
21666 function DirectionComponent(name, container, navigator) {
21667 var _this = _super.call(this, name, container, navigator) || this;
21668 _this._renderer = new Component_1.DirectionDOMRenderer(_this.defaultConfiguration, container.element);
21669 _this._hoveredKeySubject$ = new Subject_1.Subject();
21670 _this._hoveredKey$ = _this._hoveredKeySubject$.share();
21673 Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", {
21675 * Get hovered key observable.
21677 * @description An observable emitting the key of the node for the direction
21678 * arrow that is being hovered. When the mouse leaves a direction arrow null
21681 * @returns {Observable<string>}
21684 return this._hoveredKey$;
21690 * Set highlight key.
21692 * @description The arrow pointing towards the node corresponding to the
21693 * highlight key will be highlighted.
21695 * @param {string} highlightKey Key of node to be highlighted if existing
21698 DirectionComponent.prototype.setHighlightKey = function (highlightKey) {
21699 this.configure({ highlightKey: highlightKey });
21702 * Set min width of container element.
21704 * @description Set min width of the non transformed container element holding
21705 * the navigation arrows. If the min width is larger than the max width the
21706 * min width value will be used.
21708 * The container element is automatically resized when the resize
21709 * method on the Viewer class is called.
21711 * @param {number} minWidth
21713 DirectionComponent.prototype.setMinWidth = function (minWidth) {
21714 this.configure({ minWidth: minWidth });
21717 * Set max width of container element.
21719 * @description Set max width of the non transformed container element holding
21720 * the navigation arrows. If the min width is larger than the max width the
21721 * min width value will be used.
21723 * The container element is automatically resized when the resize
21724 * method on the Viewer class is called.
21726 * @param {number} minWidth
21728 DirectionComponent.prototype.setMaxWidth = function (maxWidth) {
21729 this.configure({ maxWidth: maxWidth });
21732 DirectionComponent.prototype.resize = function () {
21733 this._renderer.resize(this._container.element);
21735 DirectionComponent.prototype._activate = function () {
21737 this._configurationSubscription = this._configuration$
21738 .subscribe(function (configuration) {
21739 _this._renderer.setConfiguration(configuration);
21741 this._nodeSubscription = this._navigator.stateService.currentNode$
21742 .do(function (node) {
21743 _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) });
21744 _this._renderer.setNode(node);
21746 .withLatestFrom(this._configuration$)
21747 .switchMap(function (nc) {
21749 var configuration = nc[1];
21750 return node.spatialEdges$
21751 .withLatestFrom(configuration.distinguishSequence ?
21752 _this._navigator.graphService
21753 .cacheSequence$(node.sequenceKey)
21754 .catch(function (error, caught) {
21755 console.error("Failed to cache sequence (" + node.sequenceKey + ")", error);
21756 return Observable_1.Observable.empty();
21758 Observable_1.Observable.of(null));
21760 .subscribe(function (es) {
21761 _this._renderer.setEdges(es[0], es[1]);
21763 this._renderCameraSubscription = this._container.renderService.renderCameraFrame$
21764 .do(function (renderCamera) {
21765 _this._renderer.setRenderCamera(renderCamera);
21767 .map(function (renderCamera) {
21768 return _this._renderer;
21770 .filter(function (renderer) {
21771 return renderer.needsRender;
21773 .map(function (renderer) {
21774 return { name: _this._name, vnode: renderer.render(_this._navigator) };
21776 .subscribe(this._container.domRenderer.render$);
21777 this._hoveredKeySubscription = Observable_1.Observable
21779 this._container.domRenderer.element$,
21780 this._container.renderService.renderCamera$,
21781 this._container.mouseService.mouseMove$.startWith(null),
21782 this._container.mouseService.mouseUp$.startWith(null),
21783 ], function (e, rc, mm, mu) {
21786 .map(function (element) {
21787 var elements = element.getElementsByClassName("DirectionsPerspective");
21788 for (var i = 0; i < elements.length; i++) {
21789 var hovered = elements.item(i).querySelector(":hover");
21790 if (hovered != null && hovered.hasAttribute("data-key")) {
21791 return hovered.getAttribute("data-key");
21796 .distinctUntilChanged()
21797 .subscribe(this._hoveredKeySubject$);
21799 DirectionComponent.prototype._deactivate = function () {
21800 this._configurationSubscription.unsubscribe();
21801 this._nodeSubscription.unsubscribe();
21802 this._renderCameraSubscription.unsubscribe();
21803 this._hoveredKeySubscription.unsubscribe();
21805 DirectionComponent.prototype._getDefaultConfiguration = function () {
21807 distinguishSequence: false,
21812 return DirectionComponent;
21813 }(Component_1.Component));
21815 DirectionComponent.componentName = "direction";
21816 exports.DirectionComponent = DirectionComponent;
21817 Component_1.ComponentService.register(DirectionComponent);
21818 Object.defineProperty(exports, "__esModule", { value: true });
21819 exports.default = DirectionComponent;
21821 },{"../../Component":225,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/do":58,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/share":73,"virtual-dom":181}],253:[function(require,module,exports){
21823 var Geo_1 = require("../../Geo");
21825 * @class DirectionDOMCalculator
21826 * @classdesc Helper class for calculating DOM CSS properties.
21828 var DirectionDOMCalculator = (function () {
21829 function DirectionDOMCalculator(configuration, element) {
21830 this._spatial = new Geo_1.Spatial();
21831 this._minThresholdWidth = 320;
21832 this._maxThresholdWidth = 1480;
21833 this._minThresholdHeight = 240;
21834 this._maxThresholdHeight = 820;
21835 this._configure(configuration);
21836 this._resize(element);
21839 Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", {
21841 return this._minWidth;
21846 Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", {
21848 return this._maxWidth;
21853 Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", {
21855 return this._containerWidth;
21860 Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", {
21862 return this._containerWidthCss;
21867 Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", {
21869 return this._containerMarginCss;
21874 Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", {
21876 return this._containerLeftCss;
21881 Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", {
21883 return this._containerHeight;
21888 Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", {
21890 return this._containerHeightCss;
21895 Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", {
21897 return this._containerBottomCss;
21902 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", {
21904 return this._stepCircleSize;
21909 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", {
21911 return this._stepCircleSizeCss;
21916 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", {
21918 return this._stepCircleMarginCss;
21923 Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", {
21925 return this._turnCircleSize;
21930 Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", {
21932 return this._turnCircleSizeCss;
21937 Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", {
21939 return this._outerRadius;
21944 Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", {
21946 return this._innerRadius;
21951 Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", {
21953 return this._shadowOffset;
21959 * Configures the min and max width values.
21961 * @param {IDirectionConfiguration} configuration Configuration
21962 * with min and max width values.
21964 DirectionDOMCalculator.prototype.configure = function (configuration) {
21965 this._configure(configuration);
21969 * Resizes all properties according to the width and height
21972 * @param {HTMLElement} element The container element from which to extract
21973 * the width and height.
21975 DirectionDOMCalculator.prototype.resize = function (element) {
21976 this._resize(element);
21980 * Calculates the coordinates on the unit circle for an angle.
21982 * @param {number} angle Angle in radians.
21983 * @returns {Array<number>} The x and y coordinates on the unit circle.
21985 DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) {
21986 return [Math.cos(angle), Math.sin(angle)];
21989 * Calculates the coordinates on the unit circle for the
21990 * relative angle between the first and second angle.
21992 * @param {number} first Angle in radians.
21993 * @param {number} second Angle in radians.
21994 * @returns {Array<number>} The x and y coordinates on the unit circle
21995 * for the relative angle between the first and second angle.
21997 DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) {
21998 var relativeAngle = this._spatial.wrapAngle(first - second);
21999 return this.angleToCoordinates(relativeAngle);
22001 DirectionDOMCalculator.prototype._configure = function (configuration) {
22002 this._minWidth = configuration.minWidth;
22003 this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth);
22005 DirectionDOMCalculator.prototype._resize = function (element) {
22006 this._elementWidth = element.offsetWidth;
22007 this._elementHeight = element.offsetHeight;
22009 DirectionDOMCalculator.prototype._reset = function () {
22010 this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight);
22011 this._containerHeight = this._getContainerHeight(this.containerWidth);
22012 this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight);
22013 this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight);
22014 this._outerRadius = this._getOuterRadius(this._containerHeight);
22015 this._innerRadius = this._getInnerRadius(this._containerHeight);
22016 this._shadowOffset = 3;
22017 this._containerWidthCss = this._numberToCssPixels(this._containerWidth);
22018 this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth);
22019 this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth));
22020 this._containerHeightCss = this._numberToCssPixels(this._containerHeight);
22021 this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight));
22022 this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize);
22023 this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize);
22024 this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize);
22026 DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) {
22027 var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
22028 var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
22029 var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
22030 coeff = 0.04 * Math.round(25 * coeff);
22031 return this._minWidth + coeff * (this._maxWidth - this._minWidth);
22033 DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) {
22034 return 0.77 * containerWidth;
22036 DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) {
22037 return 0.34 * containerHeight;
22039 DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) {
22040 return 0.3 * containerHeight;
22042 DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) {
22043 return 0.31 * containerHeight;
22045 DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) {
22046 return 0.125 * containerHeight;
22048 DirectionDOMCalculator.prototype._numberToCssPixels = function (value) {
22049 return value + "px";
22051 DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) {
22052 return value > minWidth ? value : minWidth;
22054 return DirectionDOMCalculator;
22056 exports.DirectionDOMCalculator = DirectionDOMCalculator;
22057 Object.defineProperty(exports, "__esModule", { value: true });
22058 exports.default = DirectionDOMCalculator;
22060 },{"../../Geo":228}],254:[function(require,module,exports){
22061 /// <reference path="../../../typings/index.d.ts" />
22063 var vd = require("virtual-dom");
22064 var Component_1 = require("../../Component");
22065 var Edge_1 = require("../../Edge");
22066 var Geo_1 = require("../../Geo");
22068 * @class DirectionDOMRenderer
22069 * @classdesc DOM renderer for direction arrows.
22071 var DirectionDOMRenderer = (function () {
22072 function DirectionDOMRenderer(configuration, element) {
22073 this._isEdge = false;
22074 this._spatial = new Geo_1.Spatial();
22075 this._calculator = new Component_1.DirectionDOMCalculator(configuration, element);
22077 this._rotation = { phi: 0, theta: 0 };
22078 this._epsilon = 0.5 * Math.PI / 180;
22079 this._highlightKey = null;
22080 this._distinguishSequence = false;
22081 this._needsRender = false;
22082 this._stepEdges = [];
22083 this._turnEdges = [];
22084 this._panoEdges = [];
22085 this._sequenceEdgeKeys = [];
22086 this._stepDirections = [
22087 Edge_1.EdgeDirection.StepForward,
22088 Edge_1.EdgeDirection.StepBackward,
22089 Edge_1.EdgeDirection.StepLeft,
22090 Edge_1.EdgeDirection.StepRight,
22092 this._turnDirections = [
22093 Edge_1.EdgeDirection.TurnLeft,
22094 Edge_1.EdgeDirection.TurnRight,
22095 Edge_1.EdgeDirection.TurnU,
22097 this._turnNames = {};
22098 this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft";
22099 this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight";
22100 this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround";
22101 // detects IE 8-11, then Edge 20+.
22102 var isIE = !!document.documentMode;
22103 this._isEdge = !isIE && !!window.StyleMedia;
22105 Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", {
22107 * Get needs render.
22109 * @returns {boolean} Value indicating whether render should be called.
22112 return this._needsRender;
22118 * Renders virtual DOM elements.
22120 * @description Calling render resets the needs render property.
22122 DirectionDOMRenderer.prototype.render = function (navigator) {
22123 this._needsRender = false;
22124 var rotation = this._rotation;
22127 if (this._node.pano) {
22128 steps = steps.concat(this._createPanoArrows(navigator, rotation));
22131 steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation));
22132 steps = steps.concat(this._createStepArrows(navigator, rotation));
22133 turns = turns.concat(this._createTurnArrows(navigator));
22135 return this._getContainer(steps, turns, rotation);
22137 DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) {
22138 this._setEdges(edgeStatus, sequence);
22139 this._setNeedsRender();
22142 * Set node for which to show edges.
22144 * @param {Node} node
22146 DirectionDOMRenderer.prototype.setNode = function (node) {
22148 this._clearEdges();
22149 this._setNeedsRender();
22152 * Set the render camera to use for calculating rotations.
22154 * @param {RenderCamera} renderCamera
22156 DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) {
22157 var rotation = renderCamera.rotation;
22158 if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) {
22161 this._rotation = rotation;
22162 this._setNeedsRender();
22165 * Set configuration values.
22167 * @param {IDirectionConfiguration} configuration
22169 DirectionDOMRenderer.prototype.setConfiguration = function (configuration) {
22170 var needsRender = false;
22171 if (this._highlightKey !== configuration.highlightKey ||
22172 this._distinguishSequence !== configuration.distinguishSequence) {
22173 this._highlightKey = configuration.highlightKey;
22174 this._distinguishSequence = configuration.distinguishSequence;
22175 needsRender = true;
22177 if (this._calculator.minWidth !== configuration.minWidth ||
22178 this._calculator.maxWidth !== configuration.maxWidth) {
22179 this._calculator.configure(configuration);
22180 needsRender = true;
22183 this._setNeedsRender();
22187 * Detect the element's width and height and resize
22188 * elements accordingly.
22190 * @param {HTMLElement} element Viewer container element.
22192 DirectionDOMRenderer.prototype.resize = function (element) {
22193 this._calculator.resize(element);
22194 this._setNeedsRender();
22196 DirectionDOMRenderer.prototype._setNeedsRender = function () {
22197 if (this._node != null) {
22198 this._needsRender = true;
22201 DirectionDOMRenderer.prototype._clearEdges = function () {
22202 this._stepEdges = [];
22203 this._turnEdges = [];
22204 this._panoEdges = [];
22205 this._sequenceEdgeKeys = [];
22207 DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) {
22208 this._stepEdges = [];
22209 this._turnEdges = [];
22210 this._panoEdges = [];
22211 this._sequenceEdgeKeys = [];
22212 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
22214 var direction = edge.data.direction;
22215 if (this._stepDirections.indexOf(direction) > -1) {
22216 this._stepEdges.push(edge);
22219 if (this._turnDirections.indexOf(direction) > -1) {
22220 this._turnEdges.push(edge);
22223 if (edge.data.direction === Edge_1.EdgeDirection.Pano) {
22224 this._panoEdges.push(edge);
22227 if (this._distinguishSequence && sequence != null) {
22228 var edges = this._panoEdges
22229 .concat(this._stepEdges)
22230 .concat(this._turnEdges);
22231 for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) {
22232 var edge = edges_1[_b];
22233 var edgeKey = edge.to;
22234 for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
22235 var sequenceKey = _d[_c];
22236 if (sequenceKey === edgeKey) {
22237 this._sequenceEdgeKeys.push(edgeKey);
22244 DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) {
22246 for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
22247 var panoEdge = _a[_i];
22248 arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano"));
22250 for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) {
22251 var stepEdge = _c[_b];
22252 arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
22256 DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) {
22257 var threshold = Math.PI / 8;
22258 var relativePhi = rotation.phi;
22259 switch (direction) {
22260 case Edge_1.EdgeDirection.StepBackward:
22261 relativePhi = rotation.phi - Math.PI;
22263 case Edge_1.EdgeDirection.StepLeft:
22264 relativePhi = rotation.phi + Math.PI / 2;
22266 case Edge_1.EdgeDirection.StepRight:
22267 relativePhi = rotation.phi - Math.PI / 2;
22272 if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) {
22273 return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep");
22275 return this._createVNodeDisabled(key, azimuth, rotation);
22277 DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) {
22279 for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
22280 var panoEdge = _a[_i];
22281 arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true));
22285 DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) {
22287 for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) {
22288 var stepEdge = _a[_i];
22289 arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
22293 DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) {
22295 for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) {
22296 var turnEdge = _a[_i];
22297 var direction = turnEdge.data.direction;
22298 var name_1 = this._turnNames[direction];
22299 turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction));
22303 DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) {
22304 var onClick = function (e) {
22305 navigator.moveToKey$(key)
22306 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22308 return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically);
22310 DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) {
22311 var onClick = function (e) {
22312 navigator.moveDir$(direction)
22313 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22315 return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick);
22317 DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) {
22318 var onClick = function (e) {
22319 navigator.moveDir$(direction)
22320 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22323 height: this._calculator.turnCircleSizeCss,
22324 transform: "rotate(0)",
22325 width: this._calculator.turnCircleSizeCss,
22327 switch (direction) {
22328 case Edge_1.EdgeDirection.TurnLeft:
22329 style.left = "5px";
22332 case Edge_1.EdgeDirection.TurnRight:
22333 style.right = "5px";
22336 case Edge_1.EdgeDirection.TurnU:
22337 style.left = "5px";
22338 style.bottom = "5px";
22343 var circleProperties = {
22350 var circleClassName = "TurnCircle";
22351 if (this._sequenceEdgeKeys.indexOf(key) > -1) {
22352 circleClassName += "Sequence";
22354 if (this._highlightKey === key) {
22355 circleClassName += "Highlight";
22357 var turn = vd.h("div." + className, {}, []);
22358 return vd.h("div." + circleClassName, circleProperties, [turn]);
22360 DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) {
22361 return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled");
22363 DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) {
22364 var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi);
22365 // rotate 90 degrees clockwise and flip over X-axis
22366 var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth);
22367 var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight);
22368 var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi);
22369 var shadowOffset = this._calculator.shadowOffset;
22370 var shadowTranslationX = -shadowOffset * shadowTranslation[1];
22371 var shadowTranslationY = shadowOffset * shadowTranslation[0];
22372 var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))";
22375 "-webkit-filter": filter,
22379 var chevron = vd.h("div." + className, properties, []);
22380 var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi);
22381 var circleTransform = shiftVertically ?
22382 "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" :
22383 "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)";
22384 var circleProperties = {
22385 attributes: { "data-key": key },
22388 height: this._calculator.stepCircleSizeCss,
22389 marginLeft: this._calculator.stepCircleMarginCss,
22390 marginTop: this._calculator.stepCircleMarginCss,
22391 transform: circleTransform,
22392 width: this._calculator.stepCircleSizeCss,
22395 if (this._sequenceEdgeKeys.indexOf(key) > -1) {
22396 circleClassName += "Sequence";
22398 if (this._highlightKey === key) {
22399 circleClassName += "Highlight";
22401 return vd.h("div." + circleClassName, circleProperties, [chevron]);
22403 DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) {
22404 // edge does not handle hover on perspective transforms.
22405 var transform = this._isEdge ?
22407 "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)";
22409 oncontextmenu: function (event) { event.preventDefault(); },
22411 bottom: this._calculator.containerBottomCss,
22412 height: this._calculator.containerHeightCss,
22413 left: this._calculator.containerLeftCss,
22414 marginLeft: this._calculator.containerMarginCss,
22415 transform: transform,
22416 width: this._calculator.containerWidthCss,
22419 return vd.h("div.DirectionsPerspective", properties, turns.concat(steps));
22421 return DirectionDOMRenderer;
22423 exports.DirectionDOMRenderer = DirectionDOMRenderer;
22424 Object.defineProperty(exports, "__esModule", { value: true });
22425 exports.default = DirectionDOMRenderer;
22427 },{"../../Component":225,"../../Edge":226,"../../Geo":228,"virtual-dom":181}],255:[function(require,module,exports){
22429 var __extends = (this && this.__extends) || function (d, b) {
22430 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
22431 function __() { this.constructor = d; }
22432 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22434 var Observable_1 = require("rxjs/Observable");
22435 var Subject_1 = require("rxjs/Subject");
22436 require("rxjs/add/operator/catch");
22437 require("rxjs/add/operator/combineLatest");
22438 require("rxjs/add/operator/debounceTime");
22439 require("rxjs/add/operator/distinctUntilChanged");
22440 require("rxjs/add/operator/filter");
22441 require("rxjs/add/operator/map");
22442 require("rxjs/add/operator/pairwise");
22443 require("rxjs/add/operator/publish");
22444 require("rxjs/add/operator/publishReplay");
22445 require("rxjs/add/operator/scan");
22446 require("rxjs/add/operator/skipWhile");
22447 require("rxjs/add/operator/startWith");
22448 require("rxjs/add/operator/switchMap");
22449 require("rxjs/add/operator/takeUntil");
22450 require("rxjs/add/operator/withLatestFrom");
22451 var Component_1 = require("../../Component");
22452 var Render_1 = require("../../Render");
22453 var Tiles_1 = require("../../Tiles");
22454 var Utils_1 = require("../../Utils");
22455 var ImagePlaneComponent = (function (_super) {
22456 __extends(ImagePlaneComponent, _super);
22457 function ImagePlaneComponent(name, container, navigator) {
22458 var _this = _super.call(this, name, container, navigator) || this;
22459 _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
22460 _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
22461 _this._rendererOperation$ = new Subject_1.Subject();
22462 _this._rendererCreator$ = new Subject_1.Subject();
22463 _this._rendererDisposer$ = new Subject_1.Subject();
22464 _this._renderer$ = _this._rendererOperation$
22465 .scan(function (renderer, operation) {
22466 return operation(renderer);
22468 .filter(function (renderer) {
22469 return renderer != null;
22471 .distinctUntilChanged(undefined, function (renderer) {
22472 return renderer.frameId;
22474 _this._rendererCreator$
22476 return function (renderer) {
22477 if (renderer != null) {
22478 throw new Error("Multiple image plane states can not be created at the same time");
22480 return new Component_1.ImagePlaneGLRenderer();
22483 .subscribe(_this._rendererOperation$);
22484 _this._rendererDisposer$
22486 return function (renderer) {
22487 renderer.dispose();
22491 .subscribe(_this._rendererOperation$);
22494 ImagePlaneComponent.prototype._activate = function () {
22496 this._rendererSubscription = this._renderer$
22497 .map(function (renderer) {
22501 frameId: renderer.frameId,
22502 needsRender: renderer.needsRender,
22503 render: renderer.render.bind(renderer),
22504 stage: Render_1.GLRenderStage.Background,
22507 renderer.clearNeedsRender();
22510 .subscribe(this._container.glRenderer.render$);
22511 this._rendererCreator$.next(null);
22512 this._stateSubscription = this._navigator.stateService.currentState$
22513 .map(function (frame) {
22514 return function (renderer) {
22515 renderer.updateFrame(frame);
22519 .subscribe(this._rendererOperation$);
22520 var textureProvider$ = this._navigator.stateService.currentState$
22521 .distinctUntilChanged(undefined, function (frame) {
22522 return frame.state.currentNode.key;
22524 .combineLatest(this._configuration$)
22525 .filter(function (args) {
22526 return args[1].imageTiling === true;
22528 .map(function (args) {
22531 .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$)
22532 .map(function (args) {
22533 var state = args[0].state;
22534 var renderer = args[1];
22535 var viewportSize = args[2];
22536 var currentNode = state.currentNode;
22537 var currentTransform = state.currentTransform;
22538 var tileSize = Math.max(viewportSize.width, viewportSize.height) > 1024 ? 1024 : 512;
22539 return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
22543 this._textureProviderSubscription = textureProvider$.subscribe(function () { });
22544 this._setTextureProviderSubscription = textureProvider$
22545 .map(function (provider) {
22546 return function (renderer) {
22547 renderer.setTextureProvider(provider.key, provider);
22551 .subscribe(this._rendererOperation$);
22552 this._abortTextureProviderSubscription = textureProvider$
22554 .subscribe(function (pair) {
22555 var previous = pair[0];
22558 var roiTrigger$ = this._container.renderService.renderCameraFrame$
22559 .map(function (renderCamera) {
22561 renderCamera.camera.position.clone(),
22562 renderCamera.camera.lookat.clone(),
22563 renderCamera.zoom.valueOf()
22567 .skipWhile(function (pls) {
22568 return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
22570 .map(function (pls) {
22571 var samePosition = pls[0][0].equals(pls[1][0]);
22572 var sameLookat = pls[0][1].equals(pls[1][1]);
22573 var sameZoom = pls[0][2] === pls[1][2];
22574 return samePosition && sameLookat && sameZoom;
22576 .distinctUntilChanged()
22577 .filter(function (stalled) {
22580 .switchMap(function (stalled) {
22581 return _this._container.renderService.renderCameraFrame$
22584 .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$);
22585 this._setRegionOfInterestSubscription = textureProvider$
22586 .switchMap(function (provider) {
22588 .map(function (args) {
22590 _this._roiCalculator.computeRegionOfInterest(args[0], args[1], args[2]),
22595 .filter(function (args) {
22596 return !args[1].disposed;
22598 .subscribe(function (args) {
22600 var provider = args[1];
22601 provider.setRegionOfInterest(roi);
22603 var hasTexture$ = textureProvider$
22604 .switchMap(function (provider) {
22605 return provider.hasTexture$;
22610 this._hasTextureSubscription = hasTexture$.subscribe(function () { });
22611 var nodeImage$ = this._navigator.stateService.currentNode$
22612 .debounceTime(1000)
22613 .withLatestFrom(hasTexture$)
22614 .filter(function (args) {
22617 .map(function (args) {
22620 .filter(function (node) {
22622 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
22623 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
22625 .switchMap(function (node) {
22626 var baseImageSize = node.pano ?
22627 Utils_1.Settings.basePanoramaSize :
22628 Utils_1.Settings.baseImageSize;
22629 if (Math.max(node.image.width, node.image.height) > baseImageSize) {
22630 return Observable_1.Observable.empty();
22633 .cacheImage$(Utils_1.Settings.maxImageSize)
22634 .map(function (n) {
22635 return [n.image, n];
22638 .takeUntil(hasTexture$
22639 .filter(function (hasTexture) {
22642 .catch(function (error, caught) {
22643 console.error("Failed to fetch high res image (" + node.key + ")", error);
22644 return Observable_1.Observable.empty();
22649 this._updateBackgroundSubscription = nodeImage$
22650 .withLatestFrom(textureProvider$)
22651 .subscribe(function (args) {
22652 if (args[0][1].key !== args[1].key ||
22653 args[1].disposed) {
22656 args[1].updateBackground(args[0][0]);
22658 this._updateTextureImageSubscription = nodeImage$
22659 .map(function (imn) {
22660 return function (renderer) {
22661 renderer.updateTextureImage(imn[0], imn[1]);
22665 .subscribe(this._rendererOperation$);
22667 ImagePlaneComponent.prototype._deactivate = function () {
22668 this._rendererDisposer$.next(null);
22669 this._abortTextureProviderSubscription.unsubscribe();
22670 this._hasTextureSubscription.unsubscribe();
22671 this._rendererSubscription.unsubscribe();
22672 this._setRegionOfInterestSubscription.unsubscribe();
22673 this._setTextureProviderSubscription.unsubscribe();
22674 this._stateSubscription.unsubscribe();
22675 this._textureProviderSubscription.unsubscribe();
22676 this._updateBackgroundSubscription.unsubscribe();
22677 this._updateTextureImageSubscription.unsubscribe();
22679 ImagePlaneComponent.prototype._getDefaultConfiguration = function () {
22680 return { imageTiling: false };
22682 return ImagePlaneComponent;
22683 }(Component_1.Component));
22684 ImagePlaneComponent.componentName = "imagePlane";
22685 exports.ImagePlaneComponent = ImagePlaneComponent;
22686 Component_1.ComponentService.register(ImagePlaneComponent);
22687 Object.defineProperty(exports, "__esModule", { value: true });
22688 exports.default = ImagePlaneComponent;
22690 },{"../../Component":225,"../../Render":231,"../../Tiles":233,"../../Utils":234,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/operator/catch":51,"rxjs/add/operator/combineLatest":52,"rxjs/add/operator/debounceTime":54,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/pairwise":68,"rxjs/add/operator/publish":70,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/skipWhile":76,"rxjs/add/operator/startWith":77,"rxjs/add/operator/switchMap":78,"rxjs/add/operator/takeUntil":80,"rxjs/add/operator/withLatestFrom":82}],256:[function(require,module,exports){
22691 /// <reference path="../../../typings/index.d.ts" />
22693 var THREE = require("three");
22694 var Component_1 = require("../../Component");
22695 var ImagePlaneFactory = (function () {
22696 function ImagePlaneFactory(imagePlaneDepth, imageSphereRadius) {
22697 this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200;
22698 this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200;
22700 ImagePlaneFactory.prototype.createMesh = function (node, transform) {
22701 var mesh = node.pano ?
22702 this._createImageSphere(node, transform) :
22703 this._createImagePlane(node, transform);
22706 ImagePlaneFactory.prototype._createImageSphere = function (node, transform) {
22707 var texture = this._createTexture(node.image);
22708 var materialParameters = this._createSphereMaterialParameters(transform, texture);
22709 var material = new THREE.ShaderMaterial(materialParameters);
22710 var mesh = this._useMesh(transform, node) ?
22711 new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
22712 new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
22715 ImagePlaneFactory.prototype._createImagePlane = function (node, transform) {
22716 var texture = this._createTexture(node.image);
22717 var materialParameters = this._createPlaneMaterialParameters(transform, texture);
22718 var material = new THREE.ShaderMaterial(materialParameters);
22719 var geometry = this._useMesh(transform, node) ?
22720 this._getImagePlaneGeo(transform, node) :
22721 this._getFlatImagePlaneGeo(transform);
22722 return new THREE.Mesh(geometry, material);
22724 ImagePlaneFactory.prototype._createSphereMaterialParameters = function (transform, texture) {
22725 var gpano = transform.gpano;
22726 var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
22727 var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
22728 var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
22729 var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
22730 var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
22731 var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
22732 var materialParameters = {
22734 fragmentShader: Component_1.ImagePlaneShaders.equirectangular.fragment,
22735 side: THREE.DoubleSide,
22752 value: transform.rt,
22760 value: thetaLength,
22767 vertexShader: Component_1.ImagePlaneShaders.equirectangular.vertex,
22769 return materialParameters;
22771 ImagePlaneFactory.prototype._createPlaneMaterialParameters = function (transform, texture) {
22772 var materialParameters = {
22774 fragmentShader: Component_1.ImagePlaneShaders.perspective.fragment,
22775 side: THREE.DoubleSide,
22780 value: new THREE.Vector4(0, 0, 1, 1),
22788 value: transform.projectorMatrix(),
22795 vertexShader: Component_1.ImagePlaneShaders.perspective.vertex,
22797 return materialParameters;
22799 ImagePlaneFactory.prototype._createTexture = function (image) {
22800 var texture = new THREE.Texture(image);
22801 texture.minFilter = THREE.LinearFilter;
22802 texture.needsUpdate = true;
22805 ImagePlaneFactory.prototype._useMesh = function (transform, node) {
22806 return node.mesh.vertices.length && transform.hasValidScale;
22808 ImagePlaneFactory.prototype._getImageSphereGeo = function (transform, node) {
22809 var t = new THREE.Matrix4().getInverse(transform.srt);
22810 // push everything at least 5 meters in front of the camera
22811 var minZ = 5.0 * transform.scale;
22812 var maxZ = this._imageSphereRadius * transform.scale;
22813 var vertices = node.mesh.vertices;
22814 var numVertices = vertices.length / 3;
22815 var positions = new Float32Array(vertices.length);
22816 for (var i = 0; i < numVertices; ++i) {
22818 var x = vertices[index + 0];
22819 var y = vertices[index + 1];
22820 var z = vertices[index + 2];
22821 var l = Math.sqrt(x * x + y * y + z * z);
22822 var boundedL = Math.max(minZ, Math.min(l, maxZ));
22823 var factor = boundedL / l;
22824 var p = new THREE.Vector3(x * factor, y * factor, z * factor);
22826 positions[index + 0] = p.x;
22827 positions[index + 1] = p.y;
22828 positions[index + 2] = p.z;
22830 var faces = node.mesh.faces;
22831 var indices = new Uint16Array(faces.length);
22832 for (var i = 0; i < faces.length; ++i) {
22833 indices[i] = faces[i];
22835 var geometry = new THREE.BufferGeometry();
22836 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
22837 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
22840 ImagePlaneFactory.prototype._getImagePlaneGeo = function (transform, node) {
22841 var t = new THREE.Matrix4().getInverse(transform.srt);
22842 // push everything at least 5 meters in front of the camera
22843 var minZ = 5.0 * transform.scale;
22844 var maxZ = this._imagePlaneDepth * transform.scale;
22845 var vertices = node.mesh.vertices;
22846 var numVertices = vertices.length / 3;
22847 var positions = new Float32Array(vertices.length);
22848 for (var i = 0; i < numVertices; ++i) {
22850 var x = vertices[index + 0];
22851 var y = vertices[index + 1];
22852 var z = vertices[index + 2];
22853 var boundedZ = Math.max(minZ, Math.min(z, maxZ));
22854 var factor = boundedZ / z;
22855 var p = new THREE.Vector3(x * factor, y * factor, boundedZ);
22857 positions[index + 0] = p.x;
22858 positions[index + 1] = p.y;
22859 positions[index + 2] = p.z;
22861 var faces = node.mesh.faces;
22862 var indices = new Uint16Array(faces.length);
22863 for (var i = 0; i < faces.length; ++i) {
22864 indices[i] = faces[i];
22866 var geometry = new THREE.BufferGeometry();
22867 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
22868 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
22871 ImagePlaneFactory.prototype._getFlatImageSphereGeo = function (transform) {
22872 var gpano = transform.gpano;
22873 var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels;
22874 var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
22875 var thetaStart = Math.PI *
22876 (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) /
22877 gpano.FullPanoHeightPixels;
22878 var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
22879 var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength);
22880 geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt));
22883 ImagePlaneFactory.prototype._getFlatImagePlaneGeo = function (transform) {
22884 var width = transform.width;
22885 var height = transform.height;
22886 var size = Math.max(width, height);
22887 var dx = width / 2.0 / size;
22888 var dy = height / 2.0 / size;
22890 vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
22891 vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
22892 vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
22893 vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
22894 var positions = new Float32Array(12);
22895 for (var i = 0; i < vertices.length; i++) {
22897 positions[index + 0] = vertices[i][0];
22898 positions[index + 1] = vertices[i][1];
22899 positions[index + 2] = vertices[i][2];
22901 var indices = new Uint16Array(6);
22908 var geometry = new THREE.BufferGeometry();
22909 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
22910 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
22913 return ImagePlaneFactory;
22915 exports.ImagePlaneFactory = ImagePlaneFactory;
22916 Object.defineProperty(exports, "__esModule", { value: true });
22917 exports.default = ImagePlaneFactory;
22919 },{"../../Component":225,"three":175}],257:[function(require,module,exports){
22920 /// <reference path="../../../typings/index.d.ts" />
22922 var Component_1 = require("../../Component");
22923 var Geo_1 = require("../../Geo");
22924 var ImagePlaneGLRenderer = (function () {
22925 function ImagePlaneGLRenderer() {
22926 this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
22927 this._imagePlaneScene = new Component_1.ImagePlaneScene();
22929 this._alphaOld = 0;
22930 this._fadeOutSpeed = 0.05;
22931 this._lastCamera = new Geo_1.Camera();
22932 this._epsilon = 0.000001;
22933 this._currentKey = null;
22934 this._previousKey = null;
22935 this._providerDisposers = {};
22937 this._needsRender = false;
22939 Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", {
22941 return this._frameId;
22946 Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", {
22948 return this._needsRender;
22953 ImagePlaneGLRenderer.prototype.indicateNeedsRender = function () {
22954 this._needsRender = true;
22956 ImagePlaneGLRenderer.prototype.updateFrame = function (frame) {
22957 this._updateFrameId(frame.id);
22958 this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender;
22959 this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender;
22960 this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender;
22962 ImagePlaneGLRenderer.prototype.setTextureProvider = function (key, provider) {
22964 if (key !== this._currentKey) {
22967 var createdSubscription = provider.textureCreated$
22968 .subscribe(function (texture) {
22969 _this._updateTexture(texture);
22971 var updatedSubscription = provider.textureUpdated$
22972 .subscribe(function (updated) {
22973 _this._needsRender = true;
22975 var dispose = function () {
22976 createdSubscription.unsubscribe();
22977 updatedSubscription.unsubscribe();
22978 provider.dispose();
22980 if (key in this._providerDisposers) {
22981 var disposeProvider = this._providerDisposers[key];
22983 delete this._providerDisposers[key];
22985 this._providerDisposers[key] = dispose;
22987 ImagePlaneGLRenderer.prototype._updateTexture = function (texture) {
22988 this._needsRender = true;
22989 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
22990 var plane = _a[_i];
22991 var material = plane.material;
22992 var oldTexture = material.uniforms.projectorTex.value;
22993 material.uniforms.projectorTex.value = null;
22994 oldTexture.dispose();
22995 material.uniforms.projectorTex.value = texture;
22998 ImagePlaneGLRenderer.prototype.updateTextureImage = function (image, node) {
22999 if (this._currentKey !== node.key) {
23002 this._needsRender = true;
23003 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23004 var plane = _a[_i];
23005 var material = plane.material;
23006 var texture = material.uniforms.projectorTex.value;
23007 texture.image = image;
23008 texture.needsUpdate = true;
23011 ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
23012 var planeAlpha = this._imagePlaneScene.imagePlanesOld.length ? 1 : this._alpha;
23013 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23014 var plane = _a[_i];
23015 plane.material.uniforms.opacity.value = planeAlpha;
23017 for (var _b = 0, _c = this._imagePlaneScene.imagePlanesOld; _b < _c.length; _b++) {
23018 var plane = _c[_b];
23019 plane.material.uniforms.opacity.value = this._alphaOld;
23021 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23022 renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
23023 for (var _d = 0, _e = this._imagePlaneScene.imagePlanes; _d < _e.length; _d++) {
23024 var plane = _e[_d];
23025 plane.material.uniforms.opacity.value = this._alpha;
23027 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23029 ImagePlaneGLRenderer.prototype.clearNeedsRender = function () {
23030 this._needsRender = false;
23032 ImagePlaneGLRenderer.prototype.dispose = function () {
23033 this._imagePlaneScene.clear();
23035 ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) {
23036 this._frameId = frameId;
23038 ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) {
23039 if (alpha === this._alpha) {
23042 this._alpha = alpha;
23045 ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) {
23046 if (alpha < 1 || this._alphaOld === 0) {
23049 this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed);
23052 ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) {
23053 if (state.currentNode == null || state.currentNode.key === this._currentKey) {
23056 var previousKey = state.previousNode != null ? state.previousNode.key : null;
23057 var currentKey = state.currentNode.key;
23058 if (this._previousKey !== previousKey &&
23059 this._previousKey !== currentKey &&
23060 this._previousKey in this._providerDisposers) {
23061 var disposeProvider = this._providerDisposers[this._previousKey];
23063 delete this._providerDisposers[this._previousKey];
23065 if (previousKey != null) {
23066 if (previousKey !== this._currentKey && previousKey !== this._previousKey) {
23067 var previousMesh = this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform);
23068 this._imagePlaneScene.updateImagePlanes([previousMesh]);
23070 this._previousKey = previousKey;
23072 this._currentKey = currentKey;
23073 var currentMesh = this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform);
23074 this._imagePlaneScene.updateImagePlanes([currentMesh]);
23075 this._alphaOld = 1;
23078 return ImagePlaneGLRenderer;
23080 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer;
23081 Object.defineProperty(exports, "__esModule", { value: true });
23082 exports.default = ImagePlaneGLRenderer;
23084 },{"../../Component":225,"../../Geo":228}],258:[function(require,module,exports){
23085 /// <reference path="../../../typings/index.d.ts" />
23087 var THREE = require("three");
23088 var ImagePlaneScene = (function () {
23089 function ImagePlaneScene() {
23090 this.scene = new THREE.Scene();
23091 this.sceneOld = new THREE.Scene();
23092 this.imagePlanes = [];
23093 this.imagePlanesOld = [];
23095 ImagePlaneScene.prototype.updateImagePlanes = function (planes) {
23096 this._dispose(this.imagePlanesOld, this.sceneOld);
23097 for (var _i = 0, _a = this.imagePlanes; _i < _a.length; _i++) {
23098 var plane = _a[_i];
23099 this.scene.remove(plane);
23100 this.sceneOld.add(plane);
23102 for (var _b = 0, planes_1 = planes; _b < planes_1.length; _b++) {
23103 var plane = planes_1[_b];
23104 this.scene.add(plane);
23106 this.imagePlanesOld = this.imagePlanes;
23107 this.imagePlanes = planes;
23109 ImagePlaneScene.prototype.addImagePlanes = function (planes) {
23110 for (var _i = 0, planes_2 = planes; _i < planes_2.length; _i++) {
23111 var plane = planes_2[_i];
23112 this.scene.add(plane);
23113 this.imagePlanes.push(plane);
23116 ImagePlaneScene.prototype.addImagePlanesOld = function (planes) {
23117 for (var _i = 0, planes_3 = planes; _i < planes_3.length; _i++) {
23118 var plane = planes_3[_i];
23119 this.sceneOld.add(plane);
23120 this.imagePlanesOld.push(plane);
23123 ImagePlaneScene.prototype.setImagePlanes = function (planes) {
23125 this.addImagePlanes(planes);
23127 ImagePlaneScene.prototype.setImagePlanesOld = function (planes) {
23129 this.addImagePlanesOld(planes);
23131 ImagePlaneScene.prototype.clear = function () {
23135 ImagePlaneScene.prototype._clear = function () {
23136 this._dispose(this.imagePlanes, this.scene);
23137 this.imagePlanes.length = 0;
23139 ImagePlaneScene.prototype._clearOld = function () {
23140 this._dispose(this.imagePlanesOld, this.sceneOld);
23141 this.imagePlanesOld.length = 0;
23143 ImagePlaneScene.prototype._dispose = function (planes, scene) {
23144 for (var _i = 0, planes_4 = planes; _i < planes_4.length; _i++) {
23145 var plane = planes_4[_i];
23146 scene.remove(plane);
23147 plane.geometry.dispose();
23148 plane.material.dispose();
23149 var texture = plane.material.uniforms.projectorTex.value;
23150 if (texture != null) {
23155 return ImagePlaneScene;
23157 exports.ImagePlaneScene = ImagePlaneScene;
23158 Object.defineProperty(exports, "__esModule", { value: true });
23159 exports.default = ImagePlaneScene;
23161 },{"three":175}],259:[function(require,module,exports){
23162 /// <reference path="../../../typings/index.d.ts" />
23165 var path = require("path");
23166 var ImagePlaneShaders = (function () {
23167 function ImagePlaneShaders() {
23169 return ImagePlaneShaders;
23171 ImagePlaneShaders.equirectangular = {
23172 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}",
23173 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}",
23175 ImagePlaneShaders.perspective = {
23176 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}",
23177 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}",
23179 exports.ImagePlaneShaders = ImagePlaneShaders;
23181 },{"path":21}],260:[function(require,module,exports){
23182 /// <reference path="../../../typings/index.d.ts" />
23184 var __extends = (this && this.__extends) || function (d, b) {
23185 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
23186 function __() { this.constructor = d; }
23187 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23189 var vd = require("virtual-dom");
23190 var Observable_1 = require("rxjs/Observable");
23191 var Subject_1 = require("rxjs/Subject");
23192 require("rxjs/add/observable/combineLatest");
23193 require("rxjs/add/observable/fromEvent");
23194 require("rxjs/add/observable/of");
23195 require("rxjs/add/observable/zip");
23196 require("rxjs/add/operator/distinctUntilChanged");
23197 require("rxjs/add/operator/filter");
23198 require("rxjs/add/operator/first");
23199 require("rxjs/add/operator/map");
23200 require("rxjs/add/operator/merge");
23201 require("rxjs/add/operator/mergeMap");
23202 require("rxjs/add/operator/scan");
23203 require("rxjs/add/operator/switchMap");
23204 require("rxjs/add/operator/withLatestFrom");
23205 require("rxjs/add/operator/zip");
23206 var State_1 = require("../../State");
23207 var Render_1 = require("../../Render");
23208 var Utils_1 = require("../../Utils");
23209 var Component_1 = require("../../Component");
23210 var SliderState = (function () {
23211 function SliderState() {
23212 this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
23213 this._imagePlaneScene = new Component_1.ImagePlaneScene();
23214 this._currentKey = null;
23215 this._previousKey = null;
23216 this._currentPano = false;
23218 this._glNeedsRender = false;
23219 this._domNeedsRender = true;
23222 Object.defineProperty(SliderState.prototype, "frameId", {
23224 return this._frameId;
23229 Object.defineProperty(SliderState.prototype, "curtain", {
23231 return this._curtain;
23236 Object.defineProperty(SliderState.prototype, "glNeedsRender", {
23238 return this._glNeedsRender;
23243 Object.defineProperty(SliderState.prototype, "domNeedsRender", {
23245 return this._domNeedsRender;
23250 Object.defineProperty(SliderState.prototype, "sliderVisible", {
23252 return this._sliderVisible;
23254 set: function (value) {
23255 this._sliderVisible = value;
23256 this._domNeedsRender = true;
23261 Object.defineProperty(SliderState.prototype, "disabled", {
23263 return this._currentKey == null ||
23264 this._previousKey == null ||
23270 SliderState.prototype.update = function (frame) {
23271 this._updateFrameId(frame.id);
23272 var needsRender = this._updateImagePlanes(frame.state);
23273 this._domNeedsRender = needsRender || this._domNeedsRender;
23274 needsRender = this._updateCurtain(frame.state.alpha) || needsRender;
23275 this._glNeedsRender = needsRender || this._glNeedsRender;
23277 SliderState.prototype.updateTexture = function (image, node) {
23278 var imagePlanes = node.key === this._currentKey ?
23279 this._imagePlaneScene.imagePlanes :
23280 node.key === this._previousKey ?
23281 this._imagePlaneScene.imagePlanesOld :
23283 if (imagePlanes.length === 0) {
23286 this._glNeedsRender = true;
23287 for (var _i = 0, imagePlanes_1 = imagePlanes; _i < imagePlanes_1.length; _i++) {
23288 var plane = imagePlanes_1[_i];
23289 var material = plane.material;
23290 var texture = material.uniforms.projectorTex.value;
23291 texture.image = image;
23292 texture.needsUpdate = true;
23295 SliderState.prototype.render = function (perspectiveCamera, renderer) {
23296 if (!this.disabled) {
23297 renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
23299 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23301 SliderState.prototype.dispose = function () {
23302 this._imagePlaneScene.clear();
23304 SliderState.prototype.clearGLNeedsRender = function () {
23305 this._glNeedsRender = false;
23307 SliderState.prototype.clearDomNeedsRender = function () {
23308 this._domNeedsRender = false;
23310 SliderState.prototype._updateFrameId = function (frameId) {
23311 this._frameId = frameId;
23313 SliderState.prototype._updateImagePlanes = function (state) {
23314 if (state.currentNode == null) {
23317 var needsRender = false;
23318 if (state.previousNode != null && this._previousKey !== state.previousNode.key) {
23319 needsRender = true;
23320 this._previousKey = state.previousNode.key;
23321 this._imagePlaneScene.setImagePlanesOld([
23322 this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform),
23325 if (this._currentKey !== state.currentNode.key) {
23326 needsRender = true;
23327 this._currentKey = state.currentNode.key;
23328 this._currentPano = state.currentNode.pano;
23329 this._imagePlaneScene.setImagePlanes([
23330 this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform),
23332 if (!this.disabled) {
23333 this._updateBbox();
23336 return needsRender;
23338 SliderState.prototype._updateCurtain = function (alpha) {
23339 if (this.disabled ||
23340 Math.abs(this._curtain - alpha) < 0.001) {
23343 this._curtain = alpha;
23344 this._updateBbox();
23347 SliderState.prototype._updateBbox = function () {
23348 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23349 var plane = _a[_i];
23350 var shaderMaterial = plane.material;
23351 var bbox = shaderMaterial.uniforms.bbox.value;
23352 bbox.z = this._curtain;
23355 return SliderState;
23357 var SliderComponent = (function (_super) {
23358 __extends(SliderComponent, _super);
23360 * Create a new slider component instance.
23361 * @class SliderComponent
23363 function SliderComponent(name, container, navigator) {
23364 var _this = _super.call(this, name, container, navigator) || this;
23365 _this._sliderStateOperation$ = new Subject_1.Subject();
23366 _this._sliderStateCreator$ = new Subject_1.Subject();
23367 _this._sliderStateDisposer$ = new Subject_1.Subject();
23368 _this._sliderState$ = _this._sliderStateOperation$
23369 .scan(function (sliderState, operation) {
23370 return operation(sliderState);
23372 .filter(function (sliderState) {
23373 return sliderState != null;
23375 .distinctUntilChanged(undefined, function (sliderState) {
23376 return sliderState.frameId;
23378 _this._sliderStateCreator$
23380 return function (sliderState) {
23381 if (sliderState != null) {
23382 throw new Error("Multiple slider states can not be created at the same time");
23384 return new SliderState();
23387 .subscribe(_this._sliderStateOperation$);
23388 _this._sliderStateDisposer$
23390 return function (sliderState) {
23391 sliderState.dispose();
23395 .subscribe(_this._sliderStateOperation$);
23399 * Set the image keys.
23401 * Configures the component to show the image planes for the supplied image keys.
23403 * @param {keys} ISliderKeys - Slider keys object specifying the images to be shown in the foreground and the background.
23405 SliderComponent.prototype.setKeys = function (keys) {
23406 this.configure({ keys: keys });
23409 * Set the initial position.
23411 * Configures the intial position of the slider. The inital position value will be used when the component is activated.
23413 * @param {number} initialPosition - Initial slider position.
23415 SliderComponent.prototype.setInitialPosition = function (initialPosition) {
23416 this.configure({ initialPosition: initialPosition });
23419 * Set the value controlling if the slider is visible.
23421 * @param {boolean} sliderVisible - Value indicating if the slider should be visible or not.
23423 SliderComponent.prototype.setSliderVisible = function (sliderVisible) {
23424 this.configure({ sliderVisible: sliderVisible });
23426 SliderComponent.prototype._activate = function () {
23428 Observable_1.Observable
23429 .combineLatest(this._navigator.stateService.state$, this._configuration$)
23431 .subscribe(function (_a) {
23432 var state = _a[0], configuration = _a[1];
23433 if (state === State_1.State.Traversing) {
23434 _this._navigator.stateService.wait();
23435 var position = configuration.initialPosition;
23436 _this._navigator.stateService.moveTo(position != null ? position : 1);
23439 this._glRenderSubscription = this._sliderState$
23440 .map(function (sliderState) {
23444 frameId: sliderState.frameId,
23445 needsRender: sliderState.glNeedsRender,
23446 render: sliderState.render.bind(sliderState),
23447 stage: Render_1.GLRenderStage.Background,
23450 sliderState.clearGLNeedsRender();
23453 .subscribe(this._container.glRenderer.render$);
23454 this._domRenderSubscription = this._sliderState$
23455 .filter(function (sliderState) {
23456 return sliderState.domNeedsRender;
23458 .map(function (sliderState) {
23459 var sliderInput = vd.h("input.SliderControl", {
23462 oninput: function (e) {
23463 var curtain = Number(e.target.value) / 1000;
23464 _this._navigator.stateService.moveTo(curtain);
23467 value: 1000 * sliderState.curtain,
23469 var vNode = sliderState.disabled || !sliderState.sliderVisible ?
23471 vd.h("div.SliderWrapper", {}, [sliderInput]);
23476 sliderState.clearDomNeedsRender();
23479 .subscribe(this._container.domRenderer.render$);
23480 this._sliderStateCreator$.next(null);
23481 this._stateSubscription = this._navigator.stateService.currentState$
23482 .map(function (frame) {
23483 return function (sliderState) {
23484 sliderState.update(frame);
23485 return sliderState;
23488 .subscribe(this._sliderStateOperation$);
23489 this._setSliderVisibleSubscription = this._configuration$
23490 .map(function (configuration) {
23491 return configuration.sliderVisible == null || configuration.sliderVisible;
23493 .distinctUntilChanged()
23494 .map(function (sliderVisible) {
23495 return function (sliderState) {
23496 sliderState.sliderVisible = sliderVisible;
23497 return sliderState;
23500 .subscribe(this._sliderStateOperation$);
23501 this._setKeysSubscription = this._configuration$
23502 .filter(function (configuration) {
23503 return configuration.keys != null;
23505 .switchMap(function (configuration) {
23506 return Observable_1.Observable
23507 .zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground))
23508 .map(function (nodes) {
23509 return { background: nodes[0], foreground: nodes[1] };
23511 .zip(_this._navigator.stateService.currentState$.first())
23512 .map(function (nf) {
23513 return { nodes: nf[0], state: nf[1].state };
23516 .subscribe(function (co) {
23517 if (co.state.currentNode != null &&
23518 co.state.previousNode != null &&
23519 co.state.currentNode.key === co.nodes.foreground.key &&
23520 co.state.previousNode.key === co.nodes.background.key) {
23523 if (co.state.currentNode.key === co.nodes.background.key) {
23524 _this._navigator.stateService.setNodes([co.nodes.foreground]);
23527 if (co.state.currentNode.key === co.nodes.foreground.key &&
23528 co.state.trajectory.length === 1) {
23529 _this._navigator.stateService.prependNodes([co.nodes.background]);
23532 _this._navigator.stateService.setNodes([co.nodes.background]);
23533 _this._navigator.stateService.setNodes([co.nodes.foreground]);
23537 var previousNode$ = this._navigator.stateService.currentState$
23538 .map(function (frame) {
23539 return frame.state.previousNode;
23541 .filter(function (node) {
23542 return node != null;
23544 .distinctUntilChanged(undefined, function (node) {
23547 this._nodeSubscription = Observable_1.Observable
23548 .merge(previousNode$, this._navigator.stateService.currentNode$)
23549 .filter(function (node) {
23551 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
23552 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
23554 .mergeMap(function (node) {
23555 var baseImageSize = node.pano ?
23556 Utils_1.Settings.basePanoramaSize :
23557 Utils_1.Settings.baseImageSize;
23558 if (Math.max(node.image.width, node.image.height) > baseImageSize) {
23559 return Observable_1.Observable.empty();
23561 return node.cacheImage$(Utils_1.Settings.maxImageSize)
23562 .map(function (n) {
23563 return [n.image, n];
23565 .catch(function (error, caught) {
23566 console.error("Failed to fetch high res slider image (" + node.key + ")", error);
23567 return Observable_1.Observable.empty();
23570 .map(function (_a) {
23571 var element = _a[0], node = _a[1];
23572 return function (sliderState) {
23573 sliderState.updateTexture(element, node);
23574 return sliderState;
23577 .subscribe(this._sliderStateOperation$);
23579 SliderComponent.prototype._deactivate = function () {
23581 this._navigator.stateService.state$
23583 .subscribe(function (state) {
23584 if (state === State_1.State.Waiting) {
23585 _this._navigator.stateService.traverse();
23588 this._sliderStateDisposer$.next(null);
23589 this._setKeysSubscription.unsubscribe();
23590 this._setSliderVisibleSubscription.unsubscribe();
23591 this._stateSubscription.unsubscribe();
23592 this._glRenderSubscription.unsubscribe();
23593 this._domRenderSubscription.unsubscribe();
23594 this._nodeSubscription.unsubscribe();
23595 this.configure({ keys: null });
23597 SliderComponent.prototype._getDefaultConfiguration = function () {
23600 SliderComponent.prototype._catchCacheNode$ = function (key) {
23601 return this._navigator.graphService.cacheNode$(key)
23602 .catch(function (error, caught) {
23603 console.error("Failed to cache slider node (" + key + ")", error);
23604 return Observable_1.Observable.empty();
23607 return SliderComponent;
23608 }(Component_1.Component));
23609 SliderComponent.componentName = "slider";
23610 exports.SliderComponent = SliderComponent;
23611 Component_1.ComponentService.register(SliderComponent);
23612 Object.defineProperty(exports, "__esModule", { value: true });
23613 exports.default = SliderComponent;
23615 },{"../../Component":225,"../../Render":231,"../../State":232,"../../Utils":234,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/fromEvent":41,"rxjs/add/observable/of":44,"rxjs/add/observable/zip":47,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/filter":60,"rxjs/add/operator/first":62,"rxjs/add/operator/map":64,"rxjs/add/operator/merge":65,"rxjs/add/operator/mergeMap":67,"rxjs/add/operator/scan":72,"rxjs/add/operator/switchMap":78,"rxjs/add/operator/withLatestFrom":82,"rxjs/add/operator/zip":83,"virtual-dom":181}],261:[function(require,module,exports){
23617 var MarkerComponent_1 = require("./MarkerComponent");
23618 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
23619 var SimpleMarker_1 = require("./marker/SimpleMarker");
23620 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
23621 var CircleMarker_1 = require("./marker/CircleMarker");
23622 exports.CircleMarker = CircleMarker_1.CircleMarker;
23624 },{"./MarkerComponent":262,"./marker/CircleMarker":265,"./marker/SimpleMarker":267}],262:[function(require,module,exports){
23625 /// <reference path="../../../typings/index.d.ts" />
23627 var __extends = (this && this.__extends) || function (d, b) {
23628 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
23629 function __() { this.constructor = d; }
23630 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23632 var THREE = require("three");
23633 var when = require("when");
23634 var Observable_1 = require("rxjs/Observable");
23635 require("rxjs/add/observable/combineLatest");
23636 require("rxjs/add/operator/distinctUntilChanged");
23637 require("rxjs/add/operator/map");
23638 var Component_1 = require("../../Component");
23639 var Render_1 = require("../../Render");
23640 var Graph_1 = require("../../Graph");
23641 var Geo_1 = require("../../Geo");
23643 * @class MarkerComponent
23645 * @classdesc Component for showing and editing 3D marker objects.
23647 * The `add` method is used for adding new markers or replacing
23648 * markers already in the set.
23650 * If a marker already in the set has the same
23651 * id as one of the markers added, the old marker will be removed
23652 * the added marker will take its place.
23654 * It is not possible to update markers in the set by updating any properties
23655 * directly on the marker object. Markers need to be replaced by
23656 * re-adding them for updates to geographic position or configuration
23659 * Markers added to the marker component can be either interactive
23660 * or non-interactive. Different marker types define their behavior.
23661 * Markers with interaction support can be configured with options
23662 * to respond to dragging inside the viewer and be detected when
23663 * retrieving markers from pixel points with the `getMarkerIdAt` method.
23665 * To retrive and use the marker component
23669 * var markerComponent = viewer.getComponent("marker");
23672 var MarkerComponent = (function (_super) {
23673 __extends(MarkerComponent, _super);
23674 function MarkerComponent(name, container, navigator) {
23675 var _this = _super.call(this, name, container, navigator) || this;
23676 _this._relativeGroundAltitude = -2;
23677 _this._geoCoords = new Geo_1.GeoCoords();
23678 _this._graphCalculator = new Graph_1.GraphCalculator();
23679 _this._markerScene = new Component_1.MarkerScene();
23680 _this._markerSet = new Component_1.MarkerSet();
23681 _this._viewportCoords = new Geo_1.ViewportCoords();
23685 * Add markers to the marker set or replace markers in the marker set.
23687 * @description If a marker already in the set has the same
23688 * id as one of the markers added, the old marker will be removed
23689 * the added marker will take its place.
23691 * Any marker inside the visible bounding bbox
23692 * will be initialized and placed in the viewer.
23694 * @param {Array<Marker>} markers - Markers to add.
23696 * @example ```markerComponent.add([marker1, marker2]);```
23698 MarkerComponent.prototype.add = function (markers) {
23699 this._markerSet.add(markers);
23702 * Check if a marker exist in the marker set.
23704 * @param {string} markerId - Id of the marker.
23706 * @example ```var markerExists = markerComponent.has("markerId");```
23708 MarkerComponent.prototype.has = function (markerId) {
23709 return this._markerSet.has(markerId);
23712 * Returns the marker in the marker set with the specified id, or
23713 * undefined if the id matches no marker.
23715 * @param {string} markerId - Id of the marker.
23717 * @example ```var marker = markerComponent.get("markerId");```
23720 MarkerComponent.prototype.get = function (markerId) {
23721 return this._markerSet.get(markerId);
23724 * Returns an array of all markers.
23726 * @example ```var markers = markerComponent.getAll();```
23728 MarkerComponent.prototype.getAll = function () {
23729 return this._markerSet.getAll();
23732 * Returns the id of the interactive marker closest to the current camera
23733 * position at the specified point.
23735 * @description Notice that the pixelPoint argument requires x, y
23736 * coordinates from pixel space.
23738 * With this function, you can use the coordinates provided by mouse
23739 * events to get information out of the marker component.
23741 * If no interactive geometry of an interactive marker exist at the pixel
23742 * point, `null` will be returned.
23744 * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
23745 * @returns {string} Id of the interactive marker closest to the camera. If no
23746 * interactive marker exist at the pixel point, `null` will be returned.
23750 * markerComponent.getMarkerIdAt([100, 100])
23751 * .then((markerId) => { console.log(markerId); });
23754 MarkerComponent.prototype.getMarkerIdAt = function (pixelPoint) {
23756 return when.promise(function (resolve, reject) {
23757 _this._container.renderService.renderCamera$
23759 .map(function (render) {
23760 var viewport = _this._viewportCoords
23761 .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
23762 var id = _this._markerScene.intersectObjects(viewport, render.perspective);
23765 .subscribe(function (id) {
23767 }, function (error) {
23773 * Remove markers with the specified ids from the marker set.
23775 * @param {Array<string>} markerIds - Ids for markers to remove.
23777 * @example ```markerComponent.remove(["id-1", "id-2"]);```
23779 MarkerComponent.prototype.remove = function (markerIds) {
23780 this._markerSet.remove(markerIds);
23783 * Remove all markers from the marker set.
23785 * @example ```markerComponent.removeAll();```
23787 MarkerComponent.prototype.removeAll = function () {
23788 this._markerSet.removeAll();
23790 MarkerComponent.prototype._activate = function () {
23792 var groundAltitude$ = this._navigator.stateService.currentState$
23793 .map(function (frame) {
23794 return frame.state.camera.position.z + _this._relativeGroundAltitude;
23796 .distinctUntilChanged(function (a1, a2) {
23797 return Math.abs(a1 - a2) < 0.01;
23801 var geoInitiated$ = Observable_1.Observable
23802 .combineLatest(groundAltitude$, this._navigator.stateService.reference$)
23804 .map(function () { })
23807 var clampedConfiguration$ = this._configuration$
23808 .map(function (configuration) {
23809 return { visibleBBoxSize: Math.max(1, Math.min(200, configuration.visibleBBoxSize)) };
23811 var currentlatLon$ = this._navigator.stateService.currentNode$
23812 .map(function (node) { return node.latLon; })
23815 var visibleBBox$ = Observable_1.Observable
23816 .combineLatest(clampedConfiguration$, currentlatLon$)
23817 .map(function (_a) {
23818 var configuration = _a[0], latLon = _a[1];
23819 return _this._graphCalculator
23820 .boundingBoxCorners(latLon, configuration.visibleBBoxSize / 2);
23824 var visibleMarkers$ = Observable_1.Observable
23825 .combineLatest(Observable_1.Observable
23826 .of(this._markerSet)
23827 .concat(this._markerSet.changed$), visibleBBox$)
23828 .map(function (_a) {
23829 var set = _a[0], bbox = _a[1];
23830 return set.search(bbox);
23832 this._setChangedSubscription = geoInitiated$
23833 .switchMap(function () {
23834 return visibleMarkers$
23835 .withLatestFrom(_this._navigator.stateService.reference$, groundAltitude$);
23837 .subscribe(function (_a) {
23838 var markers = _a[0], reference = _a[1], alt = _a[2];
23839 var geoCoords = _this._geoCoords;
23840 var markerScene = _this._markerScene;
23841 var sceneMarkers = markerScene.markers;
23842 var markersToRemove = Object.assign({}, sceneMarkers);
23843 for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
23844 var marker = markers_1[_i];
23845 if (marker.id in sceneMarkers) {
23846 delete markersToRemove[marker.id];
23849 var point3d = geoCoords
23850 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
23851 markerScene.add(marker, point3d);
23854 for (var id in markersToRemove) {
23855 if (!markersToRemove.hasOwnProperty(id)) {
23858 markerScene.remove(id);
23861 this._markersUpdatedSubscription = geoInitiated$
23862 .switchMap(function () {
23863 return _this._markerSet.updated$
23864 .withLatestFrom(visibleBBox$, _this._navigator.stateService.reference$, groundAltitude$);
23866 .subscribe(function (_a) {
23867 var markers = _a[0], _b = _a[1], sw = _b[0], ne = _b[1], reference = _a[2], alt = _a[3];
23868 var geoCoords = _this._geoCoords;
23869 var markerScene = _this._markerScene;
23870 for (var _i = 0, markers_2 = markers; _i < markers_2.length; _i++) {
23871 var marker = markers_2[_i];
23872 var exists = markerScene.has(marker.id);
23873 var visible = marker.latLon.lat > sw.lat &&
23874 marker.latLon.lat < ne.lat &&
23875 marker.latLon.lon > sw.lon &&
23876 marker.latLon.lon < ne.lon;
23878 var point3d = geoCoords
23879 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
23880 markerScene.add(marker, point3d);
23882 else if (!visible && exists) {
23883 markerScene.remove(marker.id);
23887 this._referenceSubscription = this._navigator.stateService.reference$
23889 .withLatestFrom(groundAltitude$)
23890 .subscribe(function (_a) {
23891 var reference = _a[0], alt = _a[1];
23892 var geoCoords = _this._geoCoords;
23893 var markerScene = _this._markerScene;
23894 for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
23895 var marker = _b[_i];
23896 var point3d = geoCoords
23897 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
23898 markerScene.update(marker.id, point3d);
23901 this._adjustHeightSubscription = groundAltitude$
23903 .withLatestFrom(this._navigator.stateService.reference$, currentlatLon$)
23904 .subscribe(function (_a) {
23905 var alt = _a[0], reference = _a[1], latLon = _a[2];
23906 var geoCoords = _this._geoCoords;
23907 var markerScene = _this._markerScene;
23908 var position = geoCoords
23909 .geodeticToEnu(latLon.lat, latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
23910 for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
23911 var marker = _b[_i];
23912 var point3d = geoCoords
23913 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
23914 var distanceX = point3d[0] - position[0];
23915 var distanceY = point3d[1] - position[1];
23916 var groundDistance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
23917 if (groundDistance > 50) {
23920 markerScene.lerpAltitude(marker.id, alt, Math.min(1, Math.max(0, 1.2 - 1.2 * groundDistance / 50)));
23923 this._renderSubscription = this._navigator.stateService.currentState$
23924 .map(function (frame) {
23925 var scene = _this._markerScene;
23930 needsRender: scene.needsRender,
23931 render: scene.render.bind(scene),
23932 stage: Render_1.GLRenderStage.Foreground,
23936 .subscribe(this._container.glRenderer.render$);
23937 var hoveredMarkerId$ = Observable_1.Observable
23938 .combineLatest(this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$)
23939 .map(function (_a) {
23940 var render = _a[0], event = _a[1];
23941 var element = _this._container.element;
23942 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
23943 var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element);
23944 var markerId = _this._markerScene.intersectObjects(viewport, render.perspective);
23949 var draggingStarted$ = this._container.mouseService
23950 .filtered$(this._name, this._container.mouseService.mouseDragStart$)
23951 .map(function (event) {
23954 var draggingStopped$ = this._container.mouseService
23955 .filtered$(this._name, this._container.mouseService.mouseDragEnd$)
23956 .map(function (event) {
23959 var dragging$ = Observable_1.Observable
23960 .merge(draggingStarted$, draggingStopped$)
23962 this._dragEventSubscription = draggingStarted$
23963 .withLatestFrom(hoveredMarkerId$)
23964 .merge(Observable_1.Observable
23965 .combineLatest(draggingStopped$, Observable_1.Observable.of(null)))
23966 .startWith([false, null])
23968 .subscribe(function (_a) {
23969 var previous = _a[0], current = _a[1];
23970 var dragging = current[0];
23971 var eventType = dragging ? MarkerComponent.dragstart : MarkerComponent.dragend;
23972 var id = dragging ? current[1] : previous[1];
23973 var marker = _this._markerScene.get(id);
23974 var markerEvent = { marker: marker, target: _this, type: eventType };
23975 _this.fire(eventType, markerEvent);
23977 this._mouseClaimSubscription = Observable_1.Observable
23978 .combineLatest(this._container.mouseService.active$, hoveredMarkerId$, dragging$)
23979 .map(function (_a) {
23980 var active = _a[0], markerId = _a[1], dragging = _a[2];
23981 return (!active && markerId != null) || dragging;
23983 .distinctUntilChanged()
23984 .subscribe(function (hovered) {
23986 _this._container.mouseService.claimMouse(_this._name, 1);
23989 _this._container.mouseService.unclaimMouse(_this._name);
23992 var offset$ = this._container.mouseService
23993 .filtered$(this._name, this._container.mouseService.mouseDragStart$)
23994 .withLatestFrom(hoveredMarkerId$, this._container.renderService.renderCamera$)
23995 .map(function (_a) {
23996 var e = _a[0], id = _a[1], r = _a[2];
23997 var marker = _this._markerScene.get(id);
23998 var element = _this._container.element;
23999 var _b = _this._viewportCoords.projectToCanvas(marker.geometry.position.toArray(), element, r.perspective), groundCanvasX = _b[0], groundCanvasY = _b[1];
24000 var _c = _this._viewportCoords.canvasPosition(e, element), canvasX = _c[0], canvasY = _c[1];
24001 var offset = [canvasX - groundCanvasX, canvasY - groundCanvasY];
24002 return [marker, offset, r];
24006 this._updateMarkerSubscription = this._container.mouseService
24007 .filtered$(this._name, this._container.mouseService.mouseDrag$)
24008 .withLatestFrom(offset$, this._navigator.stateService.reference$, clampedConfiguration$)
24009 .subscribe(function (_a) {
24010 var event = _a[0], _b = _a[1], marker = _b[0], offset = _b[1], render = _b[2], reference = _a[2], configuration = _a[3];
24011 if (!_this._markerScene.has(marker.id)) {
24014 var element = _this._container.element;
24015 var _c = _this._viewportCoords.canvasPosition(event, element), canvasX = _c[0], canvasY = _c[1];
24016 var groundX = canvasX - offset[0];
24017 var groundY = canvasY - offset[1];
24018 var _d = _this._viewportCoords
24019 .canvasToViewport(groundX, groundY, element), viewportX = _d[0], viewportY = _d[1];
24020 var direction = new THREE.Vector3(viewportX, viewportY, 1)
24021 .unproject(render.perspective)
24022 .sub(render.perspective.position)
24024 var distance = Math.min(_this._relativeGroundAltitude / direction.z, configuration.visibleBBoxSize / 2 - 0.1);
24025 if (distance < 0) {
24028 var intersection = direction
24030 .multiplyScalar(distance)
24031 .add(render.perspective.position);
24032 intersection.z = render.perspective.position.z + _this._relativeGroundAltitude;
24033 var _e = _this._geoCoords
24034 .enuToGeodetic(intersection.x, intersection.y, intersection.z, reference.lat, reference.lon, reference.alt), lat = _e[0], lon = _e[1];
24035 _this._markerScene.update(marker.id, intersection.toArray(), { lat: lat, lon: lon });
24036 _this._markerSet.update(marker);
24037 var markerEvent = { marker: marker, target: _this, type: MarkerComponent.changed };
24038 _this.fire(MarkerComponent.changed, markerEvent);
24041 MarkerComponent.prototype._deactivate = function () {
24042 this._adjustHeightSubscription.unsubscribe();
24043 this._dragEventSubscription.unsubscribe();
24044 this._markersUpdatedSubscription.unsubscribe();
24045 this._mouseClaimSubscription.unsubscribe();
24046 this._referenceSubscription.unsubscribe();
24047 this._renderSubscription.unsubscribe();
24048 this._setChangedSubscription.unsubscribe();
24049 this._updateMarkerSubscription.unsubscribe();
24050 this._markerScene.clear();
24052 MarkerComponent.prototype._getDefaultConfiguration = function () {
24053 return { visibleBBoxSize: 100 };
24055 return MarkerComponent;
24056 }(Component_1.Component));
24057 MarkerComponent.componentName = "marker";
24059 * Fired when the position of a marker is changed.
24061 * @type {IMarkerEvent} markerEvent - Marker event data.
24064 * markerComponent.on("changed", function(e) {
24065 * console.log(e.marker.id, e.marker.latLon);
24069 MarkerComponent.changed = "changed";
24071 * Fired when a marker drag interaction starts.
24073 * @type {IMarkerEvent} markerEvent - Marker event data.
24076 * markerComponent.on("dragstart", function(e) {
24077 * console.log(e.marker.id, e.marker.latLon);
24081 MarkerComponent.dragstart = "dragstart";
24083 * Fired when a marker drag interaction ends.
24085 * @type {IMarkerEvent} markerEvent - Marker event data.
24088 * markerComponent.on("dragend", function(e) {
24089 * console.log(e.marker.id, e.marker.latLon);
24093 MarkerComponent.dragend = "dragend";
24094 exports.MarkerComponent = MarkerComponent;
24095 Component_1.ComponentService.register(MarkerComponent);
24096 Object.defineProperty(exports, "__esModule", { value: true });
24097 exports.default = MarkerComponent;
24099 },{"../../Component":225,"../../Geo":228,"../../Graph":229,"../../Render":231,"rxjs/Observable":28,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/map":64,"three":175,"when":222}],263:[function(require,module,exports){
24100 /// <reference path="../../../typings/index.d.ts" />
24102 var THREE = require("three");
24103 var MarkerScene = (function () {
24104 function MarkerScene(scene, raycaster) {
24105 this._needsRender = false;
24106 this._interactiveObjects = [];
24107 this._markers = {};
24108 this._objectMarkers = {};
24109 this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
24110 this._scene = !!scene ? scene : new THREE.Scene();
24112 Object.defineProperty(MarkerScene.prototype, "markers", {
24114 return this._markers;
24119 Object.defineProperty(MarkerScene.prototype, "needsRender", {
24121 return this._needsRender;
24126 MarkerScene.prototype.add = function (marker, position) {
24127 if (marker.id in this._markers) {
24128 this._dispose(marker.id);
24130 marker.createGeometry(position);
24131 this._scene.add(marker.geometry);
24132 this._markers[marker.id] = marker;
24133 for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
24134 var interactiveObject = _a[_i];
24135 this._interactiveObjects.push(interactiveObject);
24136 this._objectMarkers[interactiveObject.uuid] = marker.id;
24138 this._needsRender = true;
24140 MarkerScene.prototype.clear = function () {
24141 for (var id in this._markers) {
24142 if (!this._markers.hasOwnProperty) {
24147 this._needsRender = true;
24149 MarkerScene.prototype.get = function (id) {
24150 return this._markers[id];
24152 MarkerScene.prototype.getAll = function () {
24155 .keys(this._markers)
24156 .map(function (id) { return _this._markers[id]; });
24158 MarkerScene.prototype.has = function (id) {
24159 return id in this._markers;
24161 MarkerScene.prototype.intersectObjects = function (_a, camera) {
24162 var viewportX = _a[0], viewportY = _a[1];
24163 this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
24164 var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
24165 for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
24166 var intersect = intersects_1[_i];
24167 if (intersect.object.uuid in this._objectMarkers) {
24168 return this._objectMarkers[intersect.object.uuid];
24173 MarkerScene.prototype.lerpAltitude = function (id, alt, alpha) {
24174 if (!(id in this._markers)) {
24177 this._markers[id].lerpAltitude(alt, alpha);
24178 this._needsRender = true;
24180 MarkerScene.prototype.remove = function (id) {
24181 if (!(id in this._markers)) {
24185 this._needsRender = true;
24187 MarkerScene.prototype.render = function (perspectiveCamera, renderer) {
24188 renderer.render(this._scene, perspectiveCamera);
24189 this._needsRender = false;
24191 MarkerScene.prototype.update = function (id, position, latLon) {
24192 if (!(id in this._markers)) {
24195 var marker = this._markers[id];
24196 marker.updatePosition(position, latLon);
24197 this._needsRender = true;
24199 MarkerScene.prototype._dispose = function (id) {
24200 var marker = this._markers[id];
24201 this._scene.remove(marker.geometry);
24202 for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
24203 var interactiveObject = _a[_i];
24204 var index = this._interactiveObjects.indexOf(interactiveObject);
24205 if (index !== -1) {
24206 this._interactiveObjects.splice(index, 1);
24209 console.warn("Object does not exist (" + interactiveObject.id + ") for " + id);
24211 delete this._objectMarkers[interactiveObject.uuid];
24213 marker.disposeGeometry();
24214 delete this._markers[id];
24216 return MarkerScene;
24218 exports.MarkerScene = MarkerScene;
24219 Object.defineProperty(exports, "__esModule", { value: true });
24220 exports.default = MarkerScene;
24222 },{"three":175}],264:[function(require,module,exports){
24223 /// <reference path="../../../typings/index.d.ts" />
24225 var rbush = require("rbush");
24226 var Subject_1 = require("rxjs/Subject");
24227 require("rxjs/add/operator/map");
24228 require("rxjs/add/operator/publishReplay");
24229 require("rxjs/add/operator/scan");
24230 var MarkerSet = (function () {
24231 function MarkerSet() {
24233 this._index = rbush(16, [".lon", ".lat", ".lon", ".lat"]);
24234 this._indexChanged$ = new Subject_1.Subject();
24235 this._updated$ = new Subject_1.Subject();
24237 Object.defineProperty(MarkerSet.prototype, "changed$", {
24239 return this._indexChanged$;
24244 Object.defineProperty(MarkerSet.prototype, "updated$", {
24246 return this._updated$;
24251 MarkerSet.prototype.add = function (markers) {
24253 var hash = this._hash;
24254 var index = this._index;
24255 for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
24256 var marker = markers_1[_i];
24257 var id = marker.id;
24259 index.remove(hash[id]);
24260 updated.push(marker);
24263 lat: marker.latLon.lat,
24264 lon: marker.latLon.lon,
24268 index.insert(item);
24270 if (updated.length > 0) {
24271 this._updated$.next(updated);
24273 if (markers.length > updated.length) {
24274 this._indexChanged$.next(this);
24277 MarkerSet.prototype.has = function (id) {
24278 return id in this._hash;
24280 MarkerSet.prototype.get = function (id) {
24281 return this.has(id) ? this._hash[id].marker : undefined;
24283 MarkerSet.prototype.getAll = function () {
24286 .map(function (indexItem) {
24287 return indexItem.marker;
24290 MarkerSet.prototype.remove = function (ids) {
24291 var hash = this._hash;
24292 var index = this._index;
24293 var changed = false;
24294 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
24295 var id = ids_1[_i];
24296 if (!(id in hash)) {
24299 var item = hash[id];
24300 index.remove(item);
24305 this._indexChanged$.next(this);
24308 MarkerSet.prototype.removeAll = function () {
24310 this._index.clear();
24311 this._indexChanged$.next(this);
24313 MarkerSet.prototype.search = function (_a) {
24314 var sw = _a[0], ne = _a[1];
24316 .search({ maxX: ne.lon, maxY: ne.lat, minX: sw.lon, minY: sw.lat })
24317 .map(function (indexItem) {
24318 return indexItem.marker;
24321 MarkerSet.prototype.update = function (marker) {
24322 var hash = this._hash;
24323 var index = this._index;
24324 var id = marker.id;
24325 if (!(id in hash)) {
24328 index.remove(hash[id]);
24330 lat: marker.latLon.lat,
24331 lon: marker.latLon.lon,
24335 index.insert(item);
24339 exports.MarkerSet = MarkerSet;
24340 Object.defineProperty(exports, "__esModule", { value: true });
24341 exports.default = MarkerSet;
24343 },{"rbush":24,"rxjs/Subject":33,"rxjs/add/operator/map":64,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72}],265:[function(require,module,exports){
24344 /// <reference path="../../../../typings/index.d.ts" />
24346 var __extends = (this && this.__extends) || function (d, b) {
24347 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24348 function __() { this.constructor = d; }
24349 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24351 var THREE = require("three");
24352 var Component_1 = require("../../../Component");
24354 * @class CircleMarker
24356 * @classdesc Non-interactive marker with a flat circle shape. The circle
24357 * marker can not be configured to be interactive.
24359 * Circle marker properties can not be updated after creation.
24361 * To create and add one `CircleMarker` with default configuration
24362 * and one with configuration use
24366 * var defaultMarker = new Mapillary.MarkerComponent.CircleMarker(
24368 * { lat: 0, lon: 0, });
24370 * var configuredMarker = new Mapillary.MarkerComponent.CircleMarker(
24372 * { lat: 0, lon: 0, },
24379 * markerComponent.add([defaultMarker, configuredMarker]);
24382 var CircleMarker = (function (_super) {
24383 __extends(CircleMarker, _super);
24384 function CircleMarker(id, latLon, options) {
24385 var _this = _super.call(this, id, latLon) || this;
24386 options = !!options ? options : {};
24387 _this._color = options.color != null ? options.color : 0xffffff;
24388 _this._opacity = options.opacity != null ? options.opacity : 0.4;
24389 _this._radius = options.radius != null ? options.radius : 1;
24392 CircleMarker.prototype._createGeometry = function (position) {
24393 var circle = new THREE.Mesh(new THREE.CircleGeometry(this._radius, 16), new THREE.MeshBasicMaterial({
24394 color: this._color,
24395 opacity: this._opacity,
24398 circle.up.fromArray([0, 0, 1]);
24399 circle.renderOrder = -1;
24400 var group = new THREE.Object3D();
24402 group.position.fromArray(position);
24403 this._geometry = group;
24405 CircleMarker.prototype._disposeGeometry = function () {
24406 for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
24408 mesh.geometry.dispose();
24409 mesh.material.dispose();
24412 CircleMarker.prototype._getInteractiveObjects = function () {
24415 return CircleMarker;
24416 }(Component_1.Marker));
24417 exports.CircleMarker = CircleMarker;
24418 Object.defineProperty(exports, "__esModule", { value: true });
24419 exports.default = CircleMarker;
24421 },{"../../../Component":225,"three":175}],266:[function(require,module,exports){
24422 /// <reference path="../../../../typings/index.d.ts" />
24427 * @classdesc Represents an abstract marker class that should be extended
24428 * by marker implementations used in the marker component.
24430 var Marker = (function () {
24431 function Marker(id, latLon) {
24433 this._latLon = latLon;
24435 Object.defineProperty(Marker.prototype, "id", {
24438 * @returns {string} The id of the marker.
24446 Object.defineProperty(Marker.prototype, "geometry", {
24448 return this._geometry;
24453 Object.defineProperty(Marker.prototype, "latLon", {
24456 * @returns {ILatLon} The geographic coordinates of the marker.
24459 return this._latLon;
24464 Marker.prototype.createGeometry = function (position) {
24465 if (!!this._geometry) {
24468 this._createGeometry(position);
24469 // update matrix world if raycasting occurs before first render
24470 this._geometry.updateMatrixWorld(true);
24472 Marker.prototype.disposeGeometry = function () {
24473 if (!this._geometry) {
24476 this._disposeGeometry();
24477 this._geometry = undefined;
24479 Marker.prototype.getInteractiveObjects = function () {
24480 if (!this._geometry) {
24483 return this._getInteractiveObjects();
24485 Marker.prototype.lerpAltitude = function (alt, alpha) {
24486 if (!this._geometry) {
24489 this._geometry.position.z = (1 - alpha) * this._geometry.position.z + alpha * alt;
24491 Marker.prototype.updatePosition = function (position, latLon) {
24493 this._latLon.lat = latLon.lat;
24494 this._latLon.lon = latLon.lon;
24496 if (!this._geometry) {
24499 this._geometry.position.fromArray(position);
24500 this._geometry.updateMatrixWorld(true);
24504 exports.Marker = Marker;
24505 Object.defineProperty(exports, "__esModule", { value: true });
24506 exports.default = Marker;
24508 },{}],267:[function(require,module,exports){
24509 /// <reference path="../../../../typings/index.d.ts" />
24511 var __extends = (this && this.__extends) || function (d, b) {
24512 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24513 function __() { this.constructor = d; }
24514 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24516 var THREE = require("three");
24517 var Component_1 = require("../../../Component");
24519 * @class SimpleMarker
24521 * @classdesc Interactive marker with ice cream shape. The sphere
24522 * inside the ice cream can be configured to be interactive.
24524 * Simple marker properties can not be updated after creation.
24526 * To create and add one `SimpleMarker` with default configuration
24527 * (non-interactive) and one interactive with configuration use
24531 * var defaultMarker = new Mapillary.MarkerComponent.SimpleMarker(
24533 * { lat: 0, lon: 0, });
24535 * var interactiveMarker = new Mapillary.MarkerComponent.SimpleMarker(
24537 * { lat: 0, lon: 0, },
24539 * ballColor: "#00f",
24540 * ballOpacity: 0.5,
24542 * interactive: true,
24547 * markerComponent.add([defaultMarker, interactiveMarker]);
24550 var SimpleMarker = (function (_super) {
24551 __extends(SimpleMarker, _super);
24552 function SimpleMarker(id, latLon, options) {
24553 var _this = _super.call(this, id, latLon) || this;
24554 options = !!options ? options : {};
24555 _this._ballColor = options.ballColor != null ? options.ballColor : 0xff0000;
24556 _this._ballOpacity = options.ballOpacity != null ? options.ballOpacity : 0.8;
24557 _this._circleToRayAngle = 2;
24558 _this._color = options.color != null ? options.color : 0xff0000;
24559 _this._interactive = !!options.interactive;
24560 _this._opacity = options.opacity != null ? options.opacity : 0.4;
24561 _this._radius = options.radius != null ? options.radius : 1;
24564 SimpleMarker.prototype._createGeometry = function (position) {
24565 var radius = this._radius;
24566 var cone = new THREE.Mesh(this._markerGeometry(radius, 8, 8), new THREE.MeshBasicMaterial({
24567 color: this._color,
24568 opacity: this._opacity,
24569 shading: THREE.SmoothShading,
24572 cone.renderOrder = 1;
24573 var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 8, 8), new THREE.MeshBasicMaterial({
24574 color: this._ballColor,
24575 opacity: this._ballOpacity,
24576 shading: THREE.SmoothShading,
24579 ball.position.z = this._markerHeight(radius);
24580 var group = new THREE.Object3D();
24583 group.position.fromArray(position);
24584 this._geometry = group;
24586 SimpleMarker.prototype._disposeGeometry = function () {
24587 for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
24589 mesh.geometry.dispose();
24590 mesh.material.dispose();
24593 SimpleMarker.prototype._getInteractiveObjects = function () {
24594 return this._interactive ? [this._geometry.children[0]] : [];
24596 SimpleMarker.prototype._markerHeight = function (radius) {
24597 var t = Math.tan(Math.PI - this._circleToRayAngle);
24598 return radius * Math.sqrt(1 + t * t);
24600 SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) {
24601 var geometry = new THREE.Geometry();
24602 widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
24603 heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
24604 var height = this._markerHeight(radius);
24606 for (var y = 0; y <= heightSegments; ++y) {
24607 var verticesRow = [];
24608 for (var x = 0; x <= widthSegments; ++x) {
24609 var u = x / widthSegments * Math.PI * 2;
24610 var v = y / heightSegments * Math.PI;
24612 if (v < this._circleToRayAngle) {
24616 var t = Math.tan(v - this._circleToRayAngle);
24617 r = radius * Math.sqrt(1 + t * t);
24619 var vertex = new THREE.Vector3();
24620 vertex.x = r * Math.cos(u) * Math.sin(v);
24621 vertex.y = r * Math.sin(u) * Math.sin(v);
24622 vertex.z = r * Math.cos(v) + height;
24623 geometry.vertices.push(vertex);
24624 verticesRow.push(geometry.vertices.length - 1);
24626 vertices.push(verticesRow);
24628 for (var y = 0; y < heightSegments; ++y) {
24629 for (var x = 0; x < widthSegments; ++x) {
24630 var v1 = vertices[y][x + 1];
24631 var v2 = vertices[y][x];
24632 var v3 = vertices[y + 1][x];
24633 var v4 = vertices[y + 1][x + 1];
24634 var n1 = geometry.vertices[v1].clone().normalize();
24635 var n2 = geometry.vertices[v2].clone().normalize();
24636 var n3 = geometry.vertices[v3].clone().normalize();
24637 var n4 = geometry.vertices[v4].clone().normalize();
24638 geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4]));
24639 geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()]));
24642 geometry.computeFaceNormals();
24643 geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height);
24646 return SimpleMarker;
24647 }(Component_1.Marker));
24648 exports.SimpleMarker = SimpleMarker;
24649 Object.defineProperty(exports, "__esModule", { value: true });
24650 exports.default = SimpleMarker;
24652 },{"../../../Component":225,"three":175}],268:[function(require,module,exports){
24654 var __extends = (this && this.__extends) || function (d, b) {
24655 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24656 function __() { this.constructor = d; }
24657 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24659 var Observable_1 = require("rxjs/Observable");
24660 var Component_1 = require("../../Component");
24662 * The `DoubleClickZoomHandler` allows the user to zoom the viewer photo at a point by double clicking.
24666 * var mouseComponent = viewer.getComponent("mouse");
24668 * mouseComponent.doubleClickZoom.disable();
24669 * mouseComponent.doubleClickZoom.enable();
24671 * var isEnabled = mouseComponent.doubleClickZoom.isEnabled;
24674 var DoubleClickZoomHandler = (function (_super) {
24675 __extends(DoubleClickZoomHandler, _super);
24676 function DoubleClickZoomHandler() {
24677 return _super !== null && _super.apply(this, arguments) || this;
24679 DoubleClickZoomHandler.prototype._enable = function () {
24681 this._zoomSubscription = Observable_1.Observable
24682 .merge(this._container.mouseService
24683 .filtered$(this._component.name, this._container.mouseService.dblClick$), this._container.touchService.doubleTap$
24684 .map(function (e) {
24685 var touch = e.touches[0];
24686 return { clientX: touch.clientX, clientY: touch.clientY, shiftKey: e.shiftKey };
24688 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
24689 .subscribe(function (_a) {
24690 var event = _a[0], render = _a[1], transform = _a[2];
24691 var element = _this._container.element;
24692 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
24693 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
24694 var reference = transform.projectBasic(unprojected.toArray());
24695 var delta = !!event.shiftKey ? -1 : 1;
24696 _this._navigator.stateService.zoomIn(delta, reference);
24699 DoubleClickZoomHandler.prototype._disable = function () {
24700 this._zoomSubscription.unsubscribe();
24702 DoubleClickZoomHandler.prototype._getConfiguration = function (enable) {
24703 return { doubleClickZoom: enable };
24705 return DoubleClickZoomHandler;
24706 }(Component_1.MouseHandlerBase));
24707 exports.DoubleClickZoomHandler = DoubleClickZoomHandler;
24708 Object.defineProperty(exports, "__esModule", { value: true });
24709 exports.default = DoubleClickZoomHandler;
24711 },{"../../Component":225,"rxjs/Observable":28}],269:[function(require,module,exports){
24712 /// <reference path="../../../typings/index.d.ts" />
24714 var __extends = (this && this.__extends) || function (d, b) {
24715 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24716 function __() { this.constructor = d; }
24717 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24719 var THREE = require("three");
24720 var Observable_1 = require("rxjs/Observable");
24721 var Component_1 = require("../../Component");
24723 * The `DragPanHandler` allows the user to pan the viewer photo by clicking and dragging the cursor.
24727 * var mouseComponent = viewer.getComponent("mouse");
24729 * mouseComponent.dragPan.disable();
24730 * mouseComponent.dragPan.enable();
24732 * var isEnabled = mouseComponent.dragPan.isEnabled;
24735 var DragPanHandler = (function (_super) {
24736 __extends(DragPanHandler, _super);
24737 function DragPanHandler(component, container, navigator, viewportCoords, spatial) {
24738 var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
24739 _this._spatial = spatial;
24740 _this._basicRotationThreshold = 5e-2;
24741 _this._forceCoeff = 2e-1;
24744 DragPanHandler.prototype._enable = function () {
24746 this._preventDefaultSubscription = Observable_1.Observable.merge(this._container.mouseService.mouseDragStart$, this._container.mouseService.mouseDrag$, this._container.touchService.touchMove$)
24747 .subscribe(function (event) {
24748 event.preventDefault(); // prevent selection of content outside the viewer
24750 var draggingStarted$ = this._container.mouseService
24751 .filtered$(this._component.name, this._container.mouseService.mouseDragStart$)
24752 .map(function (event) {
24755 var draggingStopped$ = this._container.mouseService
24756 .filtered$(this._component.name, this._container.mouseService.mouseDragEnd$)
24757 .map(function (event) {
24760 this._activeMouseSubscription = Observable_1.Observable
24761 .merge(draggingStarted$, draggingStopped$)
24762 .subscribe(this._container.mouseService.activate$);
24763 var touchMovingStarted$ = this._container.touchService.singleTouchDragStart$
24764 .map(function (event) {
24767 var touchMovingStopped$ = this._container.touchService.singleTouchDragEnd$
24768 .map(function (event) {
24771 this._activeTouchSubscription = Observable_1.Observable
24772 .merge(touchMovingStarted$, touchMovingStopped$)
24773 .subscribe(this._container.touchService.activate$);
24774 this._rotateBasicSubscription = this._navigator.stateService.currentState$
24775 .map(function (frame) {
24776 return frame.state.currentNode.fullPano || frame.state.nodesAhead < 1;
24778 .distinctUntilChanged()
24779 .switchMap(function (enable) {
24781 return Observable_1.Observable.empty();
24783 var mouseDrag$ = Observable_1.Observable
24784 .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$)
24785 .map(function (e) { return null; }))
24787 .filter(function (pair) {
24788 return pair[0] != null && pair[1] != null;
24790 var singleTouchDrag$ = Observable_1.Observable
24791 .merge(_this._container.touchService.singleTouchDragStart$, _this._container.touchService.singleTouchDrag$, _this._container.touchService.singleTouchDragEnd$.map(function (t) { return null; }))
24792 .map(function (event) {
24793 return event != null && event.touches.length > 0 ?
24794 event.touches[0] : null;
24797 .filter(function (pair) {
24798 return pair[0] != null && pair[1] != null;
24800 return Observable_1.Observable
24801 .merge(mouseDrag$, singleTouchDrag$);
24803 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.stateService.currentCamera$)
24804 .map(function (_a) {
24805 var events = _a[0], render = _a[1], transform = _a[2], c = _a[3];
24806 var camera = c.clone();
24807 var previousEvent = events[0];
24808 var event = events[1];
24809 var movementX = event.clientX - previousEvent.clientX;
24810 var movementY = event.clientY - previousEvent.clientY;
24811 var element = _this._container.element;
24812 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
24813 var currentDirection = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective)
24814 .sub(render.perspective.position);
24815 var directionX = _this._viewportCoords.unprojectFromCanvas(canvasX - movementX, canvasY, element, render.perspective)
24816 .sub(render.perspective.position);
24817 var directionY = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY - movementY, element, render.perspective)
24818 .sub(render.perspective.position);
24819 var deltaPhi = (movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection);
24820 var deltaTheta = (movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection);
24821 var upQuaternion = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
24822 var upQuaternionInverse = upQuaternion.clone().inverse();
24823 var offset = new THREE.Vector3();
24824 offset.copy(camera.lookat).sub(camera.position);
24825 offset.applyQuaternion(upQuaternion);
24826 var length = offset.length();
24827 var phi = Math.atan2(offset.y, offset.x);
24829 var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
24830 theta += deltaTheta;
24831 theta = Math.max(0.01, Math.min(Math.PI - 0.01, theta));
24832 offset.x = Math.sin(theta) * Math.cos(phi);
24833 offset.y = Math.sin(theta) * Math.sin(phi);
24834 offset.z = Math.cos(theta);
24835 offset.applyQuaternion(upQuaternionInverse);
24836 var lookat = new THREE.Vector3().copy(camera.position).add(offset.multiplyScalar(length));
24837 var basic = transform.projectBasic(lookat.toArray());
24838 var original = transform.projectBasic(camera.lookat.toArray());
24839 var x = basic[0] - original[0];
24840 var y = basic[1] - original[1];
24841 if (Math.abs(x) > 1) {
24844 else if (x > 0.5) {
24847 else if (x < -0.5) {
24850 var rotationThreshold = _this._basicRotationThreshold;
24851 x = _this._spatial.clamp(x, -rotationThreshold, rotationThreshold);
24852 y = _this._spatial.clamp(y, -rotationThreshold, rotationThreshold);
24853 if (transform.fullPano) {
24856 var pixelDistances = _this._viewportCoords.getPixelDistances(_this._container.element, transform, render.perspective);
24857 var coeff = _this._forceCoeff;
24858 if (pixelDistances[0] > 0 && y < 0 && basic[1] < 0.5) {
24859 y /= Math.max(1, coeff * pixelDistances[0]);
24861 if (pixelDistances[1] > 0 && x > 0 && basic[0] > 0.5) {
24862 x /= Math.max(1, coeff * pixelDistances[1]);
24864 if (pixelDistances[2] > 0 && y > 0 && basic[1] > 0.5) {
24865 y /= Math.max(1, coeff * pixelDistances[2]);
24867 if (pixelDistances[3] > 0 && x < 0 && basic[0] < 0.5) {
24868 x /= Math.max(1, coeff * pixelDistances[3]);
24872 .subscribe(function (basicRotation) {
24873 _this._navigator.stateService.rotateBasic(basicRotation);
24876 DragPanHandler.prototype._disable = function () {
24877 this._activeMouseSubscription.unsubscribe();
24878 this._activeTouchSubscription.unsubscribe();
24879 this._preventDefaultSubscription.unsubscribe();
24880 this._rotateBasicSubscription.unsubscribe();
24881 this._activeMouseSubscription = null;
24882 this._activeTouchSubscription = null;
24883 this._rotateBasicSubscription = null;
24885 DragPanHandler.prototype._getConfiguration = function (enable) {
24886 return { dragPan: enable };
24888 return DragPanHandler;
24889 }(Component_1.MouseHandlerBase));
24890 exports.DragPanHandler = DragPanHandler;
24891 Object.defineProperty(exports, "__esModule", { value: true });
24892 exports.default = DragPanHandler;
24894 },{"../../Component":225,"rxjs/Observable":28,"three":175}],270:[function(require,module,exports){
24895 /// <reference path="../../../typings/index.d.ts" />
24897 var __extends = (this && this.__extends) || function (d, b) {
24898 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24899 function __() { this.constructor = d; }
24900 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24902 var Observable_1 = require("rxjs/Observable");
24903 require("rxjs/add/observable/merge");
24904 require("rxjs/add/operator/filter");
24905 require("rxjs/add/operator/map");
24906 require("rxjs/add/operator/withLatestFrom");
24907 var Component_1 = require("../../Component");
24908 var Geo_1 = require("../../Geo");
24910 * @class MouseComponent
24912 * @classdesc Component handling mouse and touch events for camera movement.
24914 var MouseComponent = (function (_super) {
24915 __extends(MouseComponent, _super);
24916 function MouseComponent(name, container, navigator) {
24917 var _this = _super.call(this, name, container, navigator) || this;
24918 _this._basicDistanceThreshold = 1e-3;
24919 _this._basicRotationThreshold = 5e-2;
24920 _this._bounceCoeff = 1e-1;
24921 var spatial = new Geo_1.Spatial();
24922 var viewportCoords = new Geo_1.ViewportCoords();
24923 _this._spatial = spatial;
24924 _this._viewportCoords = viewportCoords;
24925 _this._doubleClickZoomHandler = new Component_1.DoubleClickZoomHandler(_this, container, navigator, viewportCoords);
24926 _this._dragPanHandler = new Component_1.DragPanHandler(_this, container, navigator, viewportCoords, spatial);
24927 _this._scrollZoomHandler = new Component_1.ScrollZoomHandler(_this, container, navigator, viewportCoords);
24928 _this._touchZoomHandler = new Component_1.TouchZoomHandler(_this, container, navigator, viewportCoords);
24931 Object.defineProperty(MouseComponent.prototype, "doubleClickZoom", {
24933 * Get double click zoom.
24935 * @returns {DoubleClickZoomHandler} The double click zoom handler.
24938 return this._doubleClickZoomHandler;
24943 Object.defineProperty(MouseComponent.prototype, "dragPan", {
24947 * @returns {DragPanHandler} The drag pan handler.
24950 return this._dragPanHandler;
24955 Object.defineProperty(MouseComponent.prototype, "scrollZoom", {
24959 * @returns {ScrollZoomHandler} The scroll zoom handler.
24962 return this._scrollZoomHandler;
24967 Object.defineProperty(MouseComponent.prototype, "touchZoom", {
24971 * @returns {TouchZoomHandler} The touch zoom handler.
24974 return this._touchZoomHandler;
24979 MouseComponent.prototype._activate = function () {
24981 this._configurationSubscription = this._configuration$
24982 .subscribe(function (configuration) {
24983 if (configuration.doubleClickZoom) {
24984 _this._doubleClickZoomHandler.enable();
24987 _this._doubleClickZoomHandler.disable();
24989 if (configuration.dragPan) {
24990 _this._dragPanHandler.enable();
24993 _this._dragPanHandler.disable();
24995 if (configuration.scrollZoom) {
24996 _this._scrollZoomHandler.enable();
24999 _this._scrollZoomHandler.disable();
25001 if (configuration.touchZoom) {
25002 _this._touchZoomHandler.enable();
25005 _this._touchZoomHandler.disable();
25008 var inTransition$ = this._navigator.stateService.currentState$
25009 .map(function (frame) {
25010 return frame.state.alpha < 1;
25012 this._bounceSubscription = Observable_1.Observable
25013 .combineLatest(inTransition$, this._navigator.stateService.inTranslation$, this._container.mouseService.active$, this._container.touchService.active$)
25014 .map(function (noForce) {
25015 return noForce[0] || noForce[1] || noForce[2] || noForce[3];
25017 .distinctUntilChanged()
25018 .switchMap(function (noForce) {
25020 Observable_1.Observable.empty() :
25021 Observable_1.Observable.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$.first());
25023 .subscribe(function (args) {
25024 var renderCamera = args[0];
25025 var perspectiveCamera = renderCamera.perspective;
25026 var transform = args[1];
25027 if (!transform.hasValidScale && renderCamera.camera.focal < 0.1) {
25030 if (renderCamera.perspective.aspect === 0 || renderCamera.perspective.aspect === Number.POSITIVE_INFINITY) {
25033 var distanceThreshold = _this._basicDistanceThreshold / Math.pow(2, renderCamera.zoom);
25034 var basicCenter = _this._viewportCoords.viewportToBasic(0, 0, transform, perspectiveCamera);
25035 if (Math.abs(basicCenter[0] - 0.5) < distanceThreshold && Math.abs(basicCenter[1] - 0.5) < distanceThreshold) {
25038 var basicDistances = _this._viewportCoords.getBasicDistances(transform, perspectiveCamera);
25041 if (basicDistances[0] < distanceThreshold && basicDistances[1] < distanceThreshold &&
25042 basicDistances[2] < distanceThreshold && basicDistances[3] < distanceThreshold) {
25045 if (Math.abs(basicDistances[0] - basicDistances[2]) < distanceThreshold &&
25046 Math.abs(basicDistances[1] - basicDistances[3]) < distanceThreshold) {
25049 var coeff = _this._bounceCoeff;
25050 if (basicDistances[1] > 0 && basicDistances[3] === 0) {
25051 basicX = -coeff * basicDistances[1];
25053 else if (basicDistances[1] === 0 && basicDistances[3] > 0) {
25054 basicX = coeff * basicDistances[3];
25056 else if (basicDistances[1] > 0 && basicDistances[3] > 0) {
25057 basicX = coeff * (basicDistances[3] - basicDistances[1]) / 2;
25059 if (basicDistances[0] > 0 && basicDistances[2] === 0) {
25060 basicY = coeff * basicDistances[0];
25062 else if (basicDistances[0] === 0 && basicDistances[2] > 0) {
25063 basicY = -coeff * basicDistances[2];
25065 else if (basicDistances[0] > 0 && basicDistances[2] > 0) {
25066 basicY = coeff * (basicDistances[0] - basicDistances[2]) / 2;
25068 var rotationThreshold = _this._basicRotationThreshold;
25069 basicX = _this._spatial.clamp(basicX, -rotationThreshold, rotationThreshold);
25070 basicY = _this._spatial.clamp(basicY, -rotationThreshold, rotationThreshold);
25071 _this._navigator.stateService.rotateBasicUnbounded([basicX, basicY]);
25073 this._container.mouseService.claimMouse(this._name, 0);
25075 MouseComponent.prototype._deactivate = function () {
25076 this._container.mouseService.unclaimMouse(this._name);
25077 this._bounceSubscription.unsubscribe();
25078 this._configurationSubscription.unsubscribe();
25079 this._doubleClickZoomHandler.disable();
25080 this._dragPanHandler.disable();
25081 this._scrollZoomHandler.disable();
25082 this._touchZoomHandler.disable();
25084 MouseComponent.prototype._getDefaultConfiguration = function () {
25085 return { doubleClickZoom: true, dragPan: true, scrollZoom: true, touchZoom: true };
25087 return MouseComponent;
25088 }(Component_1.Component));
25090 MouseComponent.componentName = "mouse";
25091 exports.MouseComponent = MouseComponent;
25092 Component_1.ComponentService.register(MouseComponent);
25093 Object.defineProperty(exports, "__esModule", { value: true });
25094 exports.default = MouseComponent;
25096 },{"../../Component":225,"../../Geo":228,"rxjs/Observable":28,"rxjs/add/observable/merge":43,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/withLatestFrom":82}],271:[function(require,module,exports){
25098 var MouseHandlerBase = (function () {
25099 function MouseHandlerBase(component, container, navigator, viewportCoords) {
25100 this._component = component;
25101 this._container = container;
25102 this._navigator = navigator;
25103 this._viewportCoords = viewportCoords;
25104 this._enabled = false;
25106 Object.defineProperty(MouseHandlerBase.prototype, "isEnabled", {
25108 * Returns a Boolean indicating whether the interaction is enabled.
25110 * @returns {boolean} `true` if the interaction is enabled.
25113 return this._enabled;
25119 * Enables the interaction.
25121 * @example ```mouseComponent.<handler-name>.enable();```
25123 MouseHandlerBase.prototype.enable = function () {
25124 if (this._enabled || !this._component.activated) {
25128 this._enabled = true;
25129 this._component.configure(this._getConfiguration(true));
25132 * Disables the interaction.
25134 * @example ```mouseComponent.<handler-name>.disable();```
25136 MouseHandlerBase.prototype.disable = function () {
25137 if (!this._enabled) {
25141 this._enabled = false;
25142 if (this._component.activated) {
25143 this._component.configure(this._getConfiguration(false));
25146 return MouseHandlerBase;
25148 exports.MouseHandlerBase = MouseHandlerBase;
25149 Object.defineProperty(exports, "__esModule", { value: true });
25150 exports.default = MouseHandlerBase;
25152 },{}],272:[function(require,module,exports){
25154 var __extends = (this && this.__extends) || function (d, b) {
25155 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25156 function __() { this.constructor = d; }
25157 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25159 var Component_1 = require("../../Component");
25161 * The `ScrollZoomHandler` allows the user to zoom the viewer photo by scrolling.
25165 * var mouseComponent = viewer.getComponent("mouse");
25167 * mouseComponent.scrollZoom.disable();
25168 * mouseComponent.scrollZoom.enable();
25170 * var isEnabled = mouseComponent.scrollZoom.isEnabled;
25173 var ScrollZoomHandler = (function (_super) {
25174 __extends(ScrollZoomHandler, _super);
25175 function ScrollZoomHandler() {
25176 return _super !== null && _super.apply(this, arguments) || this;
25178 ScrollZoomHandler.prototype._enable = function () {
25180 this._preventDefaultSubscription = this._container.mouseService.mouseWheel$
25181 .subscribe(function (event) {
25182 event.preventDefault();
25184 this._zoomSubscription = this._container.mouseService
25185 .filtered$(this._component.name, this._container.mouseService.mouseWheel$)
25186 .withLatestFrom(this._navigator.stateService.currentState$, function (w, f) {
25189 .filter(function (args) {
25190 var state = args[1].state;
25191 return state.currentNode.fullPano || state.nodesAhead < 1;
25193 .map(function (args) {
25196 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) {
25199 .subscribe(function (args) {
25200 var event = args[0];
25201 var render = args[1];
25202 var transform = args[2];
25203 var element = _this._container.element;
25204 var _a = _this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
25205 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
25206 var reference = transform.projectBasic(unprojected.toArray());
25207 var deltaY = event.deltaY;
25208 if (event.deltaMode === 1) {
25209 deltaY = 40 * deltaY;
25211 else if (event.deltaMode === 2) {
25212 deltaY = 800 * deltaY;
25214 var canvasSize = _this._viewportCoords.containerToCanvas(element);
25215 var zoom = -3 * deltaY / canvasSize[1];
25216 _this._navigator.stateService.zoomIn(zoom, reference);
25219 ScrollZoomHandler.prototype._disable = function () {
25220 this._preventDefaultSubscription.unsubscribe();
25221 this._zoomSubscription.unsubscribe();
25222 this._preventDefaultSubscription = null;
25223 this._zoomSubscription = null;
25225 ScrollZoomHandler.prototype._getConfiguration = function (enable) {
25226 return { scrollZoom: enable };
25228 return ScrollZoomHandler;
25229 }(Component_1.MouseHandlerBase));
25230 exports.ScrollZoomHandler = ScrollZoomHandler;
25231 Object.defineProperty(exports, "__esModule", { value: true });
25232 exports.default = ScrollZoomHandler;
25234 },{"../../Component":225}],273:[function(require,module,exports){
25235 /// <reference path="../../../typings/index.d.ts" />
25237 var __extends = (this && this.__extends) || function (d, b) {
25238 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25239 function __() { this.constructor = d; }
25240 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25242 var Observable_1 = require("rxjs/Observable");
25243 var Component_1 = require("../../Component");
25245 * The `TouchZoomHandler` allows the user to zoom the viewer photo by pinching on a touchscreen.
25249 * var mouseComponent = viewer.getComponent("mouse");
25251 * mouseComponent.touchZoom.disable();
25252 * mouseComponent.touchZoom.enable();
25254 * var isEnabled = mouseComponent.touchZoom.isEnabled;
25257 var TouchZoomHandler = (function (_super) {
25258 __extends(TouchZoomHandler, _super);
25259 function TouchZoomHandler() {
25260 return _super !== null && _super.apply(this, arguments) || this;
25262 TouchZoomHandler.prototype._enable = function () {
25264 this._preventDefaultSubscription = this._container.touchService.pinch$
25265 .subscribe(function (pinch) {
25266 pinch.originalEvent.preventDefault();
25268 var pinchStarted$ = this._container.touchService.pinchStart$
25269 .map(function (event) {
25272 var pinchStopped$ = this._container.touchService.pinchEnd$
25273 .map(function (event) {
25276 this._activeSubscription = Observable_1.Observable
25277 .merge(pinchStarted$, pinchStopped$)
25278 .subscribe(this._container.touchService.activate$);
25279 this._zoomSubscription = this._container.touchService.pinch$
25280 .withLatestFrom(this._navigator.stateService.currentState$)
25281 .filter(function (args) {
25282 var state = args[1].state;
25283 return state.currentNode.fullPano || state.nodesAhead < 1;
25285 .map(function (args) {
25288 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
25289 .subscribe(function (_a) {
25290 var pinch = _a[0], render = _a[1], transform = _a[2];
25291 var element = _this._container.element;
25292 var _b = _this._viewportCoords.canvasPosition(pinch, element), canvasX = _b[0], canvasY = _b[1];
25293 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
25294 var reference = transform.projectBasic(unprojected.toArray());
25295 var _c = _this._viewportCoords.containerToCanvas(element), canvasWidth = _c[0], canvasHeight = _c[1];
25296 var zoom = 3 * pinch.distanceChange / Math.min(canvasWidth, canvasHeight);
25297 _this._navigator.stateService.zoomIn(zoom, reference);
25300 TouchZoomHandler.prototype._disable = function () {
25301 this._activeSubscription.unsubscribe();
25302 this._preventDefaultSubscription.unsubscribe();
25303 this._zoomSubscription.unsubscribe();
25304 this._preventDefaultSubscription = null;
25305 this._zoomSubscription = null;
25307 TouchZoomHandler.prototype._getConfiguration = function (enable) {
25308 return { touchZoom: enable };
25310 return TouchZoomHandler;
25311 }(Component_1.MouseHandlerBase));
25312 exports.TouchZoomHandler = TouchZoomHandler;
25313 Object.defineProperty(exports, "__esModule", { value: true });
25314 exports.default = TouchZoomHandler;
25316 },{"../../Component":225,"rxjs/Observable":28}],274:[function(require,module,exports){
25317 /// <reference path="../../../typings/index.d.ts" />
25319 var __extends = (this && this.__extends) || function (d, b) {
25320 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25321 function __() { this.constructor = d; }
25322 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25324 var Observable_1 = require("rxjs/Observable");
25325 var Subject_1 = require("rxjs/Subject");
25326 require("rxjs/add/observable/combineLatest");
25327 require("rxjs/add/observable/of");
25328 require("rxjs/add/operator/bufferCount");
25329 require("rxjs/add/operator/concat");
25330 require("rxjs/add/operator/distinctUntilChanged");
25331 require("rxjs/add/operator/filter");
25332 require("rxjs/add/operator/finally");
25333 require("rxjs/add/operator/first");
25334 require("rxjs/add/operator/map");
25335 require("rxjs/add/operator/publishReplay");
25336 require("rxjs/add/operator/scan");
25337 require("rxjs/add/operator/share");
25338 require("rxjs/add/operator/switchMap");
25339 require("rxjs/add/operator/takeUntil");
25340 require("rxjs/add/operator/withLatestFrom");
25341 var Component_1 = require("../../Component");
25342 var Edge_1 = require("../../Edge");
25344 * @class SequenceComponent
25345 * @classdesc Component showing navigation arrows for sequence directions
25346 * as well as playing button. Exposes an API to start and stop play.
25348 var SequenceComponent = (function (_super) {
25349 __extends(SequenceComponent, _super);
25350 function SequenceComponent(name, container, navigator) {
25351 var _this = _super.call(this, name, container, navigator) || this;
25352 _this._nodesAhead = 5;
25353 _this._configurationOperation$ = new Subject_1.Subject();
25354 _this._sequenceDOMRenderer = new Component_1.SequenceDOMRenderer(container.element);
25355 _this._sequenceDOMInteraction = new Component_1.SequenceDOMInteraction();
25356 _this._containerWidth$ = new Subject_1.Subject();
25357 _this._hoveredKeySubject$ = new Subject_1.Subject();
25358 _this._hoveredKey$ = _this._hoveredKeySubject$.share();
25359 _this._edgeStatus$ = _this._navigator.stateService.currentNode$
25360 .switchMap(function (node) {
25361 return node.sequenceEdges$;
25367 Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", {
25369 * Get hovered key observable.
25371 * @description An observable emitting the key of the node for the direction
25372 * arrow that is being hovered. When the mouse leaves a direction arrow null
25375 * @returns {Observable<string>}
25378 return this._hoveredKey$;
25386 * @fires PlayerComponent#playingchanged
25388 SequenceComponent.prototype.play = function () {
25389 this.configure({ playing: true });
25394 * @fires PlayerComponent#playingchanged
25396 SequenceComponent.prototype.stop = function () {
25397 this.configure({ playing: false });
25400 * Set the direction to follow when playing.
25402 * @param {EdgeDirection} direction - The direction that will be followed when playing.
25404 SequenceComponent.prototype.setDirection = function (direction) {
25405 this.configure({ direction: direction });
25408 * Set highlight key.
25410 * @description The arrow pointing towards the node corresponding to the
25411 * highlight key will be highlighted.
25413 * @param {string} highlightKey Key of node to be highlighted if existing.
25415 SequenceComponent.prototype.setHighlightKey = function (highlightKey) {
25416 this.configure({ highlightKey: highlightKey });
25419 * Set max width of container element.
25421 * @description Set max width of the container element holding
25422 * the sequence navigation elements. If the min width is larger than the
25423 * max width the min width value will be used.
25425 * The container element is automatically resized when the resize
25426 * method on the Viewer class is called.
25428 * @param {number} minWidth
25430 SequenceComponent.prototype.setMaxWidth = function (maxWidth) {
25431 this.configure({ maxWidth: maxWidth });
25434 * Set min width of container element.
25436 * @description Set min width of the container element holding
25437 * the sequence navigation elements. If the min width is larger than the
25438 * max width the min width value will be used.
25440 * The container element is automatically resized when the resize
25441 * method on the Viewer class is called.
25443 * @param {number} minWidth
25445 SequenceComponent.prototype.setMinWidth = function (minWidth) {
25446 this.configure({ minWidth: minWidth });
25449 * Set the value indicating whether the sequence UI elements should be visible.
25451 * @param {boolean} visible
25453 SequenceComponent.prototype.setVisible = function (visible) {
25454 this.configure({ visible: visible });
25457 SequenceComponent.prototype.resize = function () {
25459 this._configuration$
25461 .map(function (configuration) {
25462 return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
25464 .subscribe(function (containerWidth) {
25465 _this._containerWidth$.next(containerWidth);
25468 SequenceComponent.prototype._activate = function () {
25470 this._renderSubscription = Observable_1.Observable
25471 .combineLatest(this._edgeStatus$, this._configuration$, this._containerWidth$)
25472 .map(function (ec) {
25473 var edgeStatus = ec[0];
25474 var configuration = ec[1];
25475 var containerWidth = ec[2];
25476 var vNode = _this._sequenceDOMRenderer
25477 .render(edgeStatus, configuration, containerWidth, _this, _this._sequenceDOMInteraction, _this._navigator);
25478 return { name: _this._name, vnode: vNode };
25480 .subscribe(this._container.domRenderer.render$);
25481 this._containerWidthSubscription = this._configuration$
25482 .distinctUntilChanged(function (value1, value2) {
25483 return value1[0] === value2[0] && value1[1] === value2[1];
25484 }, function (configuration) {
25485 return [configuration.minWidth, configuration.maxWidth];
25487 .map(function (configuration) {
25488 return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
25490 .subscribe(this._containerWidth$);
25491 this._configurationSubscription = this._configurationOperation$
25492 .scan(function (configuration, operation) {
25493 return operation(configuration);
25494 }, { playing: false })
25495 .finally(function () {
25496 if (_this._playingSubscription != null) {
25497 _this._navigator.stateService.cutNodes();
25501 .subscribe(function () { });
25502 this._configuration$
25503 .map(function (newConfiguration) {
25504 return function (configuration) {
25505 if (newConfiguration.playing !== configuration.playing) {
25506 _this._navigator.stateService.cutNodes();
25507 if (newConfiguration.playing) {
25514 configuration.playing = newConfiguration.playing;
25515 return configuration;
25518 .subscribe(this._configurationOperation$);
25519 this._stopSubscription = this._configuration$
25520 .switchMap(function (configuration) {
25521 var edgeStatus$ = configuration.playing ?
25522 _this._edgeStatus$ :
25523 Observable_1.Observable.empty();
25524 var edgeDirection$ = Observable_1.Observable
25525 .of(configuration.direction);
25526 return Observable_1.Observable
25527 .combineLatest(edgeStatus$, edgeDirection$);
25529 .map(function (ne) {
25530 var edgeStatus = ne[0];
25531 var direction = ne[1];
25532 if (!edgeStatus.cached) {
25535 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
25537 if (edge.data.direction === direction) {
25543 .filter(function (hasEdge) {
25546 .map(function (hasEdge) {
25547 return { playing: false };
25549 .subscribe(this._configurationSubject$);
25550 this._hoveredKeySubscription = this._sequenceDOMInteraction.mouseEnterDirection$
25551 .switchMap(function (direction) {
25552 return _this._edgeStatus$
25553 .map(function (edgeStatus) {
25554 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
25556 if (edge.data.direction === direction) {
25562 .takeUntil(_this._sequenceDOMInteraction.mouseLeaveDirection$)
25563 .concat(Observable_1.Observable.of(null));
25565 .distinctUntilChanged()
25566 .subscribe(this._hoveredKeySubject$);
25568 SequenceComponent.prototype._deactivate = function () {
25569 this._stopSubscription.unsubscribe();
25570 this._renderSubscription.unsubscribe();
25571 this._configurationSubscription.unsubscribe();
25572 this._containerWidthSubscription.unsubscribe();
25573 this._hoveredKeySubscription.unsubscribe();
25576 SequenceComponent.prototype._getDefaultConfiguration = function () {
25578 direction: Edge_1.EdgeDirection.Next,
25585 SequenceComponent.prototype._play = function () {
25587 this._playingSubscription = this._navigator.stateService.currentState$
25588 .filter(function (frame) {
25589 return frame.state.nodesAhead < _this._nodesAhead;
25591 .map(function (frame) {
25592 return frame.state.lastNode;
25594 .distinctUntilChanged(undefined, function (lastNode) {
25595 return lastNode.key;
25597 .withLatestFrom(this._configuration$, function (lastNode, configuration) {
25598 return [lastNode, configuration.direction];
25600 .switchMap(function (nd) {
25601 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(nd[1]) > -1 ?
25602 nd[0].sequenceEdges$ :
25603 nd[0].spatialEdges$)
25604 .filter(function (status) {
25605 return status.cached;
25607 .zip(Observable_1.Observable.of(nd[1]), function (status, direction) {
25608 return [status, direction];
25611 .map(function (ed) {
25612 var direction = ed[1];
25613 for (var _i = 0, _a = ed[0].edges; _i < _a.length; _i++) {
25615 if (edge.data.direction === direction) {
25621 .filter(function (key) {
25622 return key != null;
25624 .switchMap(function (key) {
25625 return _this._navigator.graphService.cacheNode$(key);
25627 .subscribe(function (node) {
25628 _this._navigator.stateService.appendNodes([node]);
25629 }, function (error) {
25630 console.error(error);
25633 this._clearSubscription = this._navigator.stateService.currentNode$
25635 .subscribe(function (nodes) {
25636 _this._navigator.stateService.clearPriorNodes();
25638 this.fire(SequenceComponent.playingchanged, true);
25640 SequenceComponent.prototype._stop = function () {
25641 this._playingSubscription.unsubscribe();
25642 this._playingSubscription = null;
25643 this._clearSubscription.unsubscribe();
25644 this._clearSubscription = null;
25645 this.fire(SequenceComponent.playingchanged, false);
25647 return SequenceComponent;
25648 }(Component_1.Component));
25650 SequenceComponent.componentName = "sequence";
25652 * Event fired when playing starts or stops.
25654 * @event PlayerComponent#playingchanged
25655 * @type {boolean} Indicates whether the player is playing.
25657 SequenceComponent.playingchanged = "playingchanged";
25658 exports.SequenceComponent = SequenceComponent;
25659 Component_1.ComponentService.register(SequenceComponent);
25660 Object.defineProperty(exports, "__esModule", { value: true });
25661 exports.default = SequenceComponent;
25663 },{"../../Component":225,"../../Edge":226,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/of":44,"rxjs/add/operator/bufferCount":49,"rxjs/add/operator/concat":53,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/filter":60,"rxjs/add/operator/finally":61,"rxjs/add/operator/first":62,"rxjs/add/operator/map":64,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/share":73,"rxjs/add/operator/switchMap":78,"rxjs/add/operator/takeUntil":80,"rxjs/add/operator/withLatestFrom":82}],275:[function(require,module,exports){
25665 var Subject_1 = require("rxjs/Subject");
25666 var SequenceDOMInteraction = (function () {
25667 function SequenceDOMInteraction() {
25668 this._mouseEnterDirection$ = new Subject_1.Subject();
25669 this._mouseLeaveDirection$ = new Subject_1.Subject();
25671 Object.defineProperty(SequenceDOMInteraction.prototype, "mouseEnterDirection$", {
25673 return this._mouseEnterDirection$;
25678 Object.defineProperty(SequenceDOMInteraction.prototype, "mouseLeaveDirection$", {
25680 return this._mouseLeaveDirection$;
25685 return SequenceDOMInteraction;
25687 exports.SequenceDOMInteraction = SequenceDOMInteraction;
25688 Object.defineProperty(exports, "__esModule", { value: true });
25689 exports.default = SequenceDOMInteraction;
25691 },{"rxjs/Subject":33}],276:[function(require,module,exports){
25692 /// <reference path="../../../typings/index.d.ts" />
25694 var vd = require("virtual-dom");
25695 var Edge_1 = require("../../Edge");
25696 var SequenceDOMRenderer = (function () {
25697 function SequenceDOMRenderer(element) {
25698 this._minThresholdWidth = 320;
25699 this._maxThresholdWidth = 1480;
25700 this._minThresholdHeight = 240;
25701 this._maxThresholdHeight = 820;
25703 SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, component, interaction, navigator) {
25704 if (configuration.visible === false) {
25705 return vd.h("div.SequenceContainer", {}, []);
25707 var nextKey = null;
25708 var prevKey = null;
25709 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
25711 if (edge.data.direction === Edge_1.EdgeDirection.Next) {
25714 if (edge.data.direction === Edge_1.EdgeDirection.Prev) {
25718 var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component);
25719 var arrows = this._createSequenceArrows(nextKey, prevKey, configuration, interaction, navigator);
25720 var containerProperties = {
25721 oncontextmenu: function (event) { event.preventDefault(); },
25722 style: { height: (0.27 * containerWidth) + "px", width: containerWidth + "px" },
25724 return vd.h("div.SequenceContainer", containerProperties, arrows.concat([playingButton]));
25726 SequenceDOMRenderer.prototype.getContainerWidth = function (element, configuration) {
25727 var elementWidth = element.offsetWidth;
25728 var elementHeight = element.offsetHeight;
25729 var minWidth = configuration.minWidth;
25730 var maxWidth = configuration.maxWidth;
25731 if (maxWidth < minWidth) {
25732 maxWidth = minWidth;
25734 var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
25735 var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
25736 var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
25737 return minWidth + coeff * (maxWidth - minWidth);
25739 SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) {
25740 var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null ||
25741 configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null;
25742 var onclick = configuration.playing ?
25743 function (e) { component.stop(); } :
25744 canPlay ? function (e) { component.play(); } : null;
25745 var buttonProperties = {
25749 var iconClass = configuration.playing ?
25751 canPlay ? "Play" : "PlayDisabled";
25752 var icon = vd.h("div.SequenceComponentIcon", { className: iconClass }, []);
25753 var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled";
25754 return vd.h("div." + buttonClass, buttonProperties, [icon]);
25756 SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, configuration, interaction, navigator) {
25757 var nextProperties = {
25758 onclick: nextKey != null ?
25760 navigator.moveDir$(Edge_1.EdgeDirection.Next)
25761 .subscribe(function (node) { return; }, function (error) { console.error(error); });
25764 onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); },
25765 onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); },
25768 var prevProperties = {
25769 onclick: prevKey != null ?
25771 navigator.moveDir$(Edge_1.EdgeDirection.Prev)
25772 .subscribe(function (node) { return; }, function (error) { console.error(error); });
25775 onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); },
25776 onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); },
25779 var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey);
25780 var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey);
25781 var nextIcon = vd.h("div.SequenceComponentIcon", []);
25782 var prevIcon = vd.h("div.SequenceComponentIcon", []);
25784 vd.h("div." + nextClass, nextProperties, [nextIcon]),
25785 vd.h("div." + prevClass, prevProperties, [prevIcon]),
25788 SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) {
25789 var className = direction === Edge_1.EdgeDirection.Next ?
25790 "SequenceStepNext" :
25791 "SequenceStepPrev";
25793 className += "Disabled";
25796 if (highlightKey === key) {
25797 className += "Highlight";
25802 return SequenceDOMRenderer;
25804 exports.SequenceDOMRenderer = SequenceDOMRenderer;
25805 Object.defineProperty(exports, "__esModule", { value: true });
25806 exports.default = SequenceDOMRenderer;
25808 },{"../../Edge":226,"virtual-dom":181}],277:[function(require,module,exports){
25810 var GeometryTagError_1 = require("./error/GeometryTagError");
25811 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
25812 var PointGeometry_1 = require("./geometry/PointGeometry");
25813 exports.PointGeometry = PointGeometry_1.PointGeometry;
25814 var RectGeometry_1 = require("./geometry/RectGeometry");
25815 exports.RectGeometry = RectGeometry_1.RectGeometry;
25816 var PolygonGeometry_1 = require("./geometry/PolygonGeometry");
25817 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
25818 var OutlineTag_1 = require("./tag/OutlineTag");
25819 exports.OutlineTag = OutlineTag_1.OutlineTag;
25820 var SpotTag_1 = require("./tag/SpotTag");
25821 exports.SpotTag = SpotTag_1.SpotTag;
25822 var Alignment_1 = require("./tag/Alignment");
25823 exports.Alignment = Alignment_1.Alignment;
25824 var TagComponent_1 = require("./TagComponent");
25825 exports.TagComponent = TagComponent_1.TagComponent;
25827 },{"./TagComponent":278,"./error/GeometryTagError":284,"./geometry/PointGeometry":286,"./geometry/PolygonGeometry":287,"./geometry/RectGeometry":288,"./tag/Alignment":290,"./tag/OutlineTag":293,"./tag/SpotTag":296}],278:[function(require,module,exports){
25828 /// <reference path="../../../typings/index.d.ts" />
25830 var __extends = (this && this.__extends) || function (d, b) {
25831 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25832 function __() { this.constructor = d; }
25833 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25835 var Observable_1 = require("rxjs/Observable");
25836 var Subject_1 = require("rxjs/Subject");
25837 require("rxjs/add/observable/combineLatest");
25838 require("rxjs/add/observable/empty");
25839 require("rxjs/add/observable/from");
25840 require("rxjs/add/observable/merge");
25841 require("rxjs/add/observable/of");
25842 require("rxjs/add/operator/combineLatest");
25843 require("rxjs/add/operator/concat");
25844 require("rxjs/add/operator/distinctUntilChanged");
25845 require("rxjs/add/operator/do");
25846 require("rxjs/add/operator/filter");
25847 require("rxjs/add/operator/map");
25848 require("rxjs/add/operator/merge");
25849 require("rxjs/add/operator/mergeMap");
25850 require("rxjs/add/operator/publishReplay");
25851 require("rxjs/add/operator/scan");
25852 require("rxjs/add/operator/share");
25853 require("rxjs/add/operator/skip");
25854 require("rxjs/add/operator/skipUntil");
25855 require("rxjs/add/operator/startWith");
25856 require("rxjs/add/operator/switchMap");
25857 require("rxjs/add/operator/take");
25858 require("rxjs/add/operator/takeUntil");
25859 require("rxjs/add/operator/withLatestFrom");
25860 var Component_1 = require("../../Component");
25861 var Geo_1 = require("../../Geo");
25862 var Render_1 = require("../../Render");
25864 * @class TagComponent
25865 * @classdesc Component for showing and editing 2D tags with different geometries.
25867 var TagComponent = (function (_super) {
25868 __extends(TagComponent, _super);
25869 function TagComponent(name, container, navigator) {
25870 var _this = _super.call(this, name, container, navigator) || this;
25871 _this._tagDomRenderer = new Component_1.TagDOMRenderer();
25872 _this._tagSet = new Component_1.TagSet();
25873 _this._tagCreator = new Component_1.TagCreator();
25874 _this._viewportCoords = new Geo_1.ViewportCoords();
25875 _this._tagGlRendererOperation$ = new Subject_1.Subject();
25876 _this._tagGlRenderer$ = _this._tagGlRendererOperation$
25877 .startWith(function (renderer) {
25880 .scan(function (renderer, operation) {
25881 return operation(renderer);
25882 }, new Component_1.TagGLRenderer());
25883 _this._tags$ = _this._tagSet.tagData$
25884 .map(function (tagData) {
25886 // ensure that tags are always rendered in the same order
25887 // to avoid hover tracking problems on first resize.
25888 for (var _i = 0, _a = Object.keys(tagData).sort(); _i < _a.length; _i++) {
25890 tags.push(tagData[key]);
25895 _this._renderTags$ = _this.tags$
25896 .withLatestFrom(_this._navigator.stateService.currentTransform$)
25897 .map(function (args) {
25898 var tags = args[0];
25899 var transform = args[1];
25900 var renderTags = tags
25901 .map(function (tag) {
25902 if (tag instanceof Component_1.OutlineTag) {
25903 return new Component_1.OutlineRenderTag(tag, transform);
25905 else if (tag instanceof Component_1.SpotTag) {
25906 return new Component_1.SpotRenderTag(tag, transform);
25908 throw new Error("Tag type not supported");
25913 _this._tagChanged$ = _this._tags$
25914 .switchMap(function (tags) {
25915 return Observable_1.Observable
25917 .mergeMap(function (tag) {
25918 return Observable_1.Observable
25919 .merge(tag.changed$, tag.geometryChanged$);
25923 _this._renderTagGLChanged$ = _this._renderTags$
25924 .switchMap(function (tags) {
25925 return Observable_1.Observable
25927 .mergeMap(function (tag) {
25928 return tag.glObjectsChanged$;
25932 _this._tagInterationInitiated$ = _this._renderTags$
25933 .switchMap(function (tags) {
25934 return Observable_1.Observable
25936 .mergeMap(function (tag) {
25937 return tag.interact$
25938 .map(function (interaction) {
25939 return interaction.tag.id;
25944 _this._tagInteractionAbort$ = Observable_1.Observable
25945 .merge(_this._container.mouseService.documentMouseUp$)
25946 .map(function (e) { })
25948 _this._activeTag$ = _this._renderTags$
25949 .switchMap(function (tags) {
25950 return Observable_1.Observable
25952 .mergeMap(function (tag) {
25953 return tag.interact$;
25956 .merge(_this._tagInteractionAbort$
25958 return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null };
25961 _this._createGeometryChanged$ = _this._tagCreator.tag$
25962 .switchMap(function (tag) {
25963 return tag != null ?
25964 tag.geometryChanged$ :
25965 Observable_1.Observable.empty();
25968 _this._tagCreated$ = _this._tagCreator.tag$
25969 .switchMap(function (tag) {
25970 return tag != null ?
25972 Observable_1.Observable.empty();
25975 _this._vertexGeometryCreated$ = _this._tagCreated$
25976 .map(function (tag) {
25977 return tag.geometry;
25980 _this._pointGeometryCreated$ = new Subject_1.Subject();
25981 _this._geometryCreated$ = Observable_1.Observable
25982 .merge(_this._vertexGeometryCreated$, _this._pointGeometryCreated$)
25984 _this._basicClick$ = _this._container.mouseService.staticClick$
25985 .withLatestFrom(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$, function (event, renderCamera, transform) {
25986 return [event, renderCamera, transform];
25988 .map(function (ert) {
25989 var event = ert[0];
25990 var camera = ert[1];
25991 var transform = ert[2];
25992 var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
25996 _this._validBasicClick$ = _this._basicClick$
25997 .filter(function (basic) {
26000 return 0 <= x && x <= 1 && 0 <= y && y <= 1;
26003 _this._creatingConfiguration$ = _this._configuration$
26004 .distinctUntilChanged(function (c1, c2) {
26005 return c1.creating === c2.creating && c1.createType === c2.createType;
26006 }, function (configuration) {
26008 createColor: configuration.createColor,
26009 createType: configuration.createType,
26010 creating: configuration.creating,
26015 _this._creating$ = _this._creatingConfiguration$
26016 .map(function (configuration) {
26017 return configuration.creating;
26022 .subscribe(function (creating) {
26023 _this.fire(TagComponent.creatingchanged, creating);
26027 Object.defineProperty(TagComponent.prototype, "tags$", {
26029 * Get tags observable.
26031 * @description An observable emitting every time the items in the
26032 * tag array changes.
26034 * @returns {Observable<Tag[]>}
26037 return this._tags$;
26042 Object.defineProperty(TagComponent.prototype, "geometryCreated$", {
26044 * Get geometry created observable.
26046 * @description An observable emitting every time a geometry
26047 * has been created.
26049 * @returns {Observable<Geometry>}
26052 return this._geometryCreated$;
26058 * Set the tags to display.
26060 * @param {Tag[]} tags - The tags.
26062 TagComponent.prototype.setTags = function (tags) {
26063 this._tagSet.set$.next(tags);
26066 * Configure the component to enter create mode for
26067 * creating a geometry of a certain type.
26069 * @description Supported geometry types are: rect
26071 * @param {string} geometryType - String specifying the geometry type.
26073 TagComponent.prototype.startCreate = function (geometryType) {
26074 this.configure({ createType: geometryType, creating: true });
26077 * Configure the component to leave create mode.
26079 * @description A non completed geometry will be removed.
26081 TagComponent.prototype.stopCreate = function () {
26082 this.configure({ createType: null, creating: false });
26084 TagComponent.prototype._activate = function () {
26086 this._preventDefaultSubscription = Observable_1.Observable.merge(this._container.mouseService.documentCanvasMouseDown$, this._container.mouseService.documentCanvasMouseMove$)
26087 .subscribe(function (event) {
26088 event.preventDefault(); // prevent selection of content outside the viewer
26090 this._geometryCreatedEventSubscription = this._geometryCreated$
26091 .subscribe(function (geometry) {
26092 _this.fire(TagComponent.geometrycreated, geometry);
26094 this._tagsChangedEventSubscription = this._tags$
26095 .subscribe(function (tags) {
26096 _this.fire(TagComponent.tagschanged, tags);
26098 var nodeChanged$ = this.configuration$
26099 .switchMap(function (configuration) {
26100 return configuration.creating ?
26101 _this._navigator.stateService.currentNode$
26104 .map(function (n) { return null; }) :
26105 Observable_1.Observable.empty();
26107 var tagAborted$ = this._tagCreator.tag$
26108 .switchMap(function (tag) {
26109 return tag != null ?
26111 .map(function (t) { return null; }) :
26112 Observable_1.Observable.empty();
26114 var tagCreated$ = this._tagCreated$
26115 .map(function (t) { return null; });
26116 var pointGeometryCreated$ = this._pointGeometryCreated$
26117 .map(function (p) { return null; });
26118 this._stopCreateSubscription = Observable_1.Observable
26119 .merge(nodeChanged$, tagAborted$, tagCreated$, pointGeometryCreated$)
26120 .subscribe(function () { _this.stopCreate(); });
26121 this._creatorConfigurationSubscription = this._configuration$
26122 .subscribe(this._tagCreator.configuration$);
26123 this._createSubscription = this._creatingConfiguration$
26124 .switchMap(function (configuration) {
26125 return configuration.creating &&
26126 configuration.createType === "rect" ||
26127 configuration.createType === "polygon" ?
26128 _this._validBasicClick$.take(1) :
26129 Observable_1.Observable.empty();
26131 .subscribe(this._tagCreator.create$);
26132 this._createPointSubscription = this._creatingConfiguration$
26133 .switchMap(function (configuration) {
26134 return configuration.creating &&
26135 configuration.createType === "point" ?
26136 _this._validBasicClick$.take(1) :
26137 Observable_1.Observable.empty();
26139 .map(function (basic) {
26140 return new Component_1.PointGeometry(basic);
26142 .subscribe(this._pointGeometryCreated$);
26143 this._setCreateVertexSubscription = Observable_1.Observable
26144 .combineLatest(this._container.mouseService.documentCanvasMouseMove$, this._tagCreator.tag$, this._container.renderService.renderCamera$)
26145 .filter(function (etr) {
26146 return etr[1] != null;
26148 .withLatestFrom(this._navigator.stateService.currentTransform$, function (etr, transform) {
26149 return [etr[0], etr[1], etr[2], transform];
26151 .subscribe(function (etrt) {
26152 var event = etrt[0];
26154 var camera = etrt[2];
26155 var transform = etrt[3];
26156 var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
26157 if (tag.geometry instanceof Component_1.RectGeometry) {
26158 tag.geometry.setVertex2d(3, basic, transform);
26160 else if (tag.geometry instanceof Component_1.PolygonGeometry) {
26161 tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basic, transform);
26164 this._addPointSubscription = this._creatingConfiguration$
26165 .switchMap(function (configuration) {
26166 var createType = configuration.createType;
26167 return configuration.creating &&
26168 (createType === "rect" || createType === "polygon") ?
26169 _this._basicClick$.skipUntil(_this._validBasicClick$).skip(1) :
26170 Observable_1.Observable.empty();
26172 .withLatestFrom(this._tagCreator.tag$, function (basic, tag) {
26173 return [basic, tag];
26175 .subscribe(function (bt) {
26178 tag.addPoint(basic);
26180 this._containerClassListSubscription = this._creating$
26181 .subscribe(function (creating) {
26183 _this._container.element.classList.add("component-tag-create");
26186 _this._container.element.classList.remove("component-tag-create");
26189 this._deleteCreatedSubscription = this._creating$
26190 .subscribe(function (creating) {
26191 _this._tagCreator.delete$.next(null);
26193 this._setGLCreateTagSubscription = Observable_1.Observable
26194 .merge(this._tagCreator.tag$, this._createGeometryChanged$)
26195 .withLatestFrom(this._navigator.stateService.currentTransform$, function (tag, transform) {
26196 return [tag, transform];
26198 .map(function (tt) {
26199 return function (renderer) {
26201 var transform = tt[1];
26203 renderer.removeCreateTag();
26206 renderer.setCreateTag(tag, transform);
26211 .subscribe(this._tagGlRendererOperation$);
26212 this._claimMouseSubscription = this._tagInterationInitiated$
26213 .switchMap(function (id) {
26214 return _this._container.mouseService.documentCanvasMouseMove$
26215 .takeUntil(_this._tagInteractionAbort$)
26218 .subscribe(function (e) {
26219 _this._container.mouseService.claimMouse(_this._name, 1);
26221 this._mouseDragSubscription = this._activeTag$
26222 .withLatestFrom(this._container.mouseService.documentCanvasMouseMove$, function (a, e) {
26225 .switchMap(function (args) {
26226 var activeTag = args[0];
26227 var mouseMove = args[1];
26228 if (activeTag.operation === Component_1.TagOperation.None) {
26229 return Observable_1.Observable.empty();
26231 var mouseDrag$ = Observable_1.Observable
26233 .concat(_this._container.mouseService.filtered$(_this._name, _this._container.mouseService.documentCanvasMouseDrag$));
26234 return Observable_1.Observable
26235 .combineLatest(mouseDrag$, _this._container.renderService.renderCamera$)
26236 .withLatestFrom(Observable_1.Observable.of(activeTag), _this._navigator.stateService.currentTransform$, function (ec, a, t) {
26237 return [ec[0], ec[1], a, t];
26240 .subscribe(function (args) {
26241 var mouseEvent = args[0];
26242 var renderCamera = args[1];
26243 var activeTag = args[2];
26244 var transform = args[3];
26245 if (activeTag.operation === Component_1.TagOperation.None) {
26248 var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, activeTag.offsetX, activeTag.offsetY);
26249 if (activeTag.operation === Component_1.TagOperation.Centroid) {
26250 activeTag.tag.geometry.setCentroid2d(basic, transform);
26252 else if (activeTag.operation === Component_1.TagOperation.Vertex) {
26253 var vertexGeometry = activeTag.tag.geometry;
26254 vertexGeometry.setVertex2d(activeTag.vertexIndex, basic, transform);
26257 this._unclaimMouseSubscription = this._container.mouseService
26258 .filtered$(this._name, this._container.mouseService.documentCanvasMouseDragEnd$)
26259 .subscribe(function (e) {
26260 _this._container.mouseService.unclaimMouse(_this._name);
26262 this._setTagsSubscription = this._renderTags$
26263 .map(function (tags) {
26264 return function (renderer) {
26265 renderer.setTags(tags);
26269 .subscribe(this._tagGlRendererOperation$);
26270 this._updateGLTagSubscription = this._renderTagGLChanged$
26271 .map(function (tag) {
26272 return function (renderer) {
26273 renderer.updateTag(tag);
26277 .subscribe(this._tagGlRendererOperation$);
26278 this._setNeedsRenderSubscription = this._tagChanged$
26279 .map(function (tag) {
26280 return function (renderer) {
26281 renderer.setNeedsRender();
26285 .subscribe(this._tagGlRendererOperation$);
26286 this._domSubscription = this._renderTags$
26288 .do(function (tags) {
26289 _this._container.domRenderer.render$.next({
26291 vnode: _this._tagDomRenderer.clear(),
26294 .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) {
26295 return [rc, atlas, renderTags, tag, ct];
26297 .withLatestFrom(this._navigator.stateService.currentTransform$, function (args, transform) {
26298 return [args[0], args[1], args[2], args[3], args[4], transform];
26300 .map(function (args) {
26303 vnode: _this._tagDomRenderer.render(args[2], args[4], args[1], args[0].perspective, args[5]),
26306 .subscribe(this._container.domRenderer.render$);
26307 this._glSubscription = this._navigator.stateService.currentState$
26308 .withLatestFrom(this._tagGlRenderer$, function (frame, renderer) {
26309 return [frame, renderer];
26311 .map(function (fr) {
26313 var renderer = fr[1];
26318 needsRender: renderer.needsRender,
26319 render: renderer.render.bind(renderer),
26320 stage: Render_1.GLRenderStage.Foreground,
26324 .subscribe(this._container.glRenderer.render$);
26326 TagComponent.prototype._deactivate = function () {
26327 this._tagGlRendererOperation$
26328 .next(function (renderer) {
26329 renderer.dispose();
26332 this._tagSet.set$.next([]);
26333 this._tagCreator.delete$.next(null);
26334 this._claimMouseSubscription.unsubscribe();
26335 this._mouseDragSubscription.unsubscribe();
26336 this._unclaimMouseSubscription.unsubscribe();
26337 this._setTagsSubscription.unsubscribe();
26338 this._updateGLTagSubscription.unsubscribe();
26339 this._setNeedsRenderSubscription.unsubscribe();
26340 this._stopCreateSubscription.unsubscribe();
26341 this._creatorConfigurationSubscription.unsubscribe();
26342 this._createSubscription.unsubscribe();
26343 this._createPointSubscription.unsubscribe();
26344 this._setCreateVertexSubscription.unsubscribe();
26345 this._addPointSubscription.unsubscribe();
26346 this._deleteCreatedSubscription.unsubscribe();
26347 this._setGLCreateTagSubscription.unsubscribe();
26348 this._preventDefaultSubscription.unsubscribe();
26349 this._containerClassListSubscription.unsubscribe();
26350 this._domSubscription.unsubscribe();
26351 this._glSubscription.unsubscribe();
26352 this._geometryCreatedEventSubscription.unsubscribe();
26353 this._tagsChangedEventSubscription.unsubscribe();
26355 TagComponent.prototype._getDefaultConfiguration = function () {
26357 createColor: 0xFFFFFF,
26361 TagComponent.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) {
26362 offsetX = offsetX != null ? offsetX : 0;
26363 offsetY = offsetY != null ? offsetY : 0;
26364 var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
26365 var basic = this._viewportCoords.canvasToBasic(canvasX - offsetX, canvasY - offsetY, element, transform, camera.perspective);
26368 return TagComponent;
26369 }(Component_1.Component));
26371 TagComponent.componentName = "tag";
26373 * Event fired when creation starts and stops.
26375 * @event TagComponent#creatingchanged
26376 * @type {boolean} Indicates whether the component is creating a tag.
26378 TagComponent.creatingchanged = "creatingchanged";
26380 * Event fired when a geometry has been created.
26382 * @event TagComponent#geometrycreated
26383 * @type {Geometry} Created geometry.
26385 TagComponent.geometrycreated = "geometrycreated";
26387 * Event fired when the tags collection has changed.
26389 * @event TagComponent#tagschanged
26390 * @type {Array<Tag>} Current array of tags.
26392 TagComponent.tagschanged = "tagschanged";
26393 exports.TagComponent = TagComponent;
26394 Component_1.ComponentService.register(TagComponent);
26395 Object.defineProperty(exports, "__esModule", { value: true });
26396 exports.default = TagComponent;
26398 },{"../../Component":225,"../../Geo":228,"../../Render":231,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/empty":39,"rxjs/add/observable/from":40,"rxjs/add/observable/merge":43,"rxjs/add/observable/of":44,"rxjs/add/operator/combineLatest":52,"rxjs/add/operator/concat":53,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/do":58,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/merge":65,"rxjs/add/operator/mergeMap":67,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/share":73,"rxjs/add/operator/skip":74,"rxjs/add/operator/skipUntil":75,"rxjs/add/operator/startWith":77,"rxjs/add/operator/switchMap":78,"rxjs/add/operator/take":79,"rxjs/add/operator/takeUntil":80,"rxjs/add/operator/withLatestFrom":82}],279:[function(require,module,exports){
26400 var Subject_1 = require("rxjs/Subject");
26401 require("rxjs/add/operator/map");
26402 require("rxjs/add/operator/scan");
26403 require("rxjs/add/operator/share");
26404 require("rxjs/add/operator/withLatestFrom");
26405 var Component_1 = require("../../Component");
26406 var TagCreator = (function () {
26407 function TagCreator() {
26408 this._tagOperation$ = new Subject_1.Subject();
26409 this._create$ = new Subject_1.Subject();
26410 this._delete$ = new Subject_1.Subject();
26411 this._configuration$ = new Subject_1.Subject();
26412 this._tag$ = this._tagOperation$
26413 .scan(function (tag, operation) {
26414 return operation(tag);
26418 .withLatestFrom(this._configuration$, function (coordinate, type) {
26419 return [coordinate, type];
26421 .map(function (ct) {
26422 return function (tag) {
26423 var coordinate = ct[0];
26424 var configuration = ct[1];
26425 if (configuration.createType === "rect") {
26426 var geometry = new Component_1.RectGeometry([
26432 return new Component_1.OutlineCreateTag(geometry, { color: configuration.createColor });
26434 else if (configuration.createType === "polygon") {
26435 var geometry = new Component_1.PolygonGeometry([
26436 [coordinate[0], coordinate[1]],
26437 [coordinate[0], coordinate[1]],
26438 [coordinate[0], coordinate[1]],
26440 return new Component_1.OutlineCreateTag(geometry, { color: configuration.createColor });
26445 .subscribe(this._tagOperation$);
26448 return function (tag) {
26452 .subscribe(this._tagOperation$);
26454 Object.defineProperty(TagCreator.prototype, "create$", {
26456 return this._create$;
26461 Object.defineProperty(TagCreator.prototype, "delete$", {
26463 return this._delete$;
26468 Object.defineProperty(TagCreator.prototype, "configuration$", {
26470 return this._configuration$;
26475 Object.defineProperty(TagCreator.prototype, "tag$", {
26484 exports.TagCreator = TagCreator;
26485 Object.defineProperty(exports, "__esModule", { value: true });
26486 exports.default = TagCreator;
26488 },{"../../Component":225,"rxjs/Subject":33,"rxjs/add/operator/map":64,"rxjs/add/operator/scan":72,"rxjs/add/operator/share":73,"rxjs/add/operator/withLatestFrom":82}],280:[function(require,module,exports){
26489 /// <reference path="../../../typings/index.d.ts" />
26491 var THREE = require("three");
26492 var vd = require("virtual-dom");
26493 var TagDOMRenderer = (function () {
26494 function TagDOMRenderer() {
26496 TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, transform) {
26497 var matrixWorldInverse = new THREE.Matrix4().getInverse(camera.matrixWorld);
26498 var projectionMatrix = camera.projectionMatrix;
26500 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
26501 var tag = tags_1[_i];
26502 vNodes = vNodes.concat(tag.getDOMObjects(atlas, matrixWorldInverse, projectionMatrix));
26504 if (createTag != null) {
26505 vNodes = vNodes.concat(createTag.getDOMObjects(transform, matrixWorldInverse, projectionMatrix));
26507 return vd.h("div.TagContainer", {}, vNodes);
26509 TagDOMRenderer.prototype.clear = function () {
26510 return vd.h("div", {}, []);
26512 return TagDOMRenderer;
26514 exports.TagDOMRenderer = TagDOMRenderer;
26516 },{"three":175,"virtual-dom":181}],281:[function(require,module,exports){
26517 /// <reference path="../../../typings/index.d.ts" />
26519 var THREE = require("three");
26520 var TagGLRenderer = (function () {
26521 function TagGLRenderer() {
26522 this._scene = new THREE.Scene();
26524 this._createTag = null;
26525 this._needsRender = false;
26527 Object.defineProperty(TagGLRenderer.prototype, "needsRender", {
26529 return this._needsRender;
26534 TagGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
26535 renderer.render(this._scene, perspectiveCamera);
26536 this._needsRender = false;
26538 TagGLRenderer.prototype.setCreateTag = function (tag, transform) {
26539 this._disposeCreateTag();
26540 this._addCreateTag(tag, transform);
26541 this._needsRender = true;
26543 TagGLRenderer.prototype.removeCreateTag = function () {
26544 this._disposeCreateTag();
26545 this._needsRender = true;
26547 TagGLRenderer.prototype.setTags = function (tags) {
26548 this._disposeTags();
26549 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
26550 var tag = tags_1[_i];
26553 this._needsRender = true;
26555 TagGLRenderer.prototype.updateTag = function (tag) {
26556 for (var _i = 0, _a = this._tags[tag.tag.id][1]; _i < _a.length; _i++) {
26557 var object3d = _a[_i];
26558 this._scene.remove(object3d);
26562 TagGLRenderer.prototype.setNeedsRender = function () {
26563 this._needsRender = true;
26565 TagGLRenderer.prototype.dispose = function () {
26566 this._disposeTags();
26567 this._disposeCreateTag();
26568 this._needsRender = false;
26570 TagGLRenderer.prototype._addTag = function (tag) {
26571 var objects = tag.glObjects;
26572 this._tags[tag.tag.id] = [tag, []];
26573 for (var _i = 0, objects_1 = objects; _i < objects_1.length; _i++) {
26574 var object = objects_1[_i];
26575 this._tags[tag.tag.id][1].push(object);
26576 this._scene.add(object);
26579 TagGLRenderer.prototype._addCreateTag = function (tag, transform) {
26580 var object = tag.getGLObject(transform);
26581 this._createTag = object;
26582 this._scene.add(object);
26584 TagGLRenderer.prototype._disposeTags = function () {
26585 for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
26587 for (var _b = 0, _c = this._tags[id][1]; _b < _c.length; _b++) {
26588 var object = _c[_b];
26589 this._scene.remove(object);
26591 this._tags[id][0].dispose();
26592 delete this._tags[id];
26595 TagGLRenderer.prototype._disposeCreateTag = function () {
26596 if (this._createTag == null) {
26599 var mesh = this._createTag;
26600 this._scene.remove(mesh);
26601 mesh.geometry.dispose();
26602 mesh.material.dispose();
26603 this._createTag = null;
26605 return TagGLRenderer;
26607 exports.TagGLRenderer = TagGLRenderer;
26609 },{"three":175}],282:[function(require,module,exports){
26612 (function (TagOperation) {
26613 TagOperation[TagOperation["None"] = 0] = "None";
26614 TagOperation[TagOperation["Centroid"] = 1] = "Centroid";
26615 TagOperation[TagOperation["Vertex"] = 2] = "Vertex";
26616 })(TagOperation = exports.TagOperation || (exports.TagOperation = {}));
26617 Object.defineProperty(exports, "__esModule", { value: true });
26618 exports.default = TagOperation;
26620 },{}],283:[function(require,module,exports){
26622 var Subject_1 = require("rxjs/Subject");
26623 require("rxjs/add/operator/map");
26624 require("rxjs/add/operator/scan");
26625 require("rxjs/add/operator/share");
26626 var TagSet = (function () {
26627 function TagSet() {
26628 this._tagDataOperation$ = new Subject_1.Subject();
26629 this._set$ = new Subject_1.Subject();
26630 this._tagData$ = this._tagDataOperation$
26631 .scan(function (tagData, operation) {
26632 return operation(tagData);
26636 .map(function (tags) {
26637 return function (tagData) {
26638 for (var _i = 0, _a = Object.keys(tagData); _i < _a.length; _i++) {
26640 delete tagData[key];
26642 for (var _b = 0, tags_1 = tags; _b < tags_1.length; _b++) {
26643 var tag = tags_1[_b];
26644 tagData[tag.id] = tag;
26649 .subscribe(this._tagDataOperation$);
26651 Object.defineProperty(TagSet.prototype, "tagData$", {
26653 return this._tagData$;
26658 Object.defineProperty(TagSet.prototype, "set$", {
26667 exports.TagSet = TagSet;
26668 Object.defineProperty(exports, "__esModule", { value: true });
26669 exports.default = TagSet;
26671 },{"rxjs/Subject":33,"rxjs/add/operator/map":64,"rxjs/add/operator/scan":72,"rxjs/add/operator/share":73}],284:[function(require,module,exports){
26673 var __extends = (this && this.__extends) || function (d, b) {
26674 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
26675 function __() { this.constructor = d; }
26676 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26678 var Error_1 = require("../../../Error");
26679 var GeometryTagError = (function (_super) {
26680 __extends(GeometryTagError, _super);
26681 function GeometryTagError(message) {
26682 var _this = _super.call(this, message != null ? message : "The provided geometry value is incorrect") || this;
26683 _this.name = "GeometryTagError";
26686 return GeometryTagError;
26687 }(Error_1.MapillaryError));
26688 exports.GeometryTagError = GeometryTagError;
26689 Object.defineProperty(exports, "__esModule", { value: true });
26690 exports.default = Error_1.MapillaryError;
26692 },{"../../../Error":227}],285:[function(require,module,exports){
26694 var Subject_1 = require("rxjs/Subject");
26698 * @classdesc Represents a geometry.
26700 var Geometry = (function () {
26702 * Create a geometry.
26706 function Geometry() {
26707 this._notifyChanged$ = new Subject_1.Subject();
26709 Object.defineProperty(Geometry.prototype, "changed$", {
26711 * Get changed observable.
26713 * @description Emits the geometry itself every time the geometry
26716 * @returns {Observable<Geometry>} Observable emitting the geometry instance.
26719 return this._notifyChanged$;
26726 exports.Geometry = Geometry;
26727 Object.defineProperty(exports, "__esModule", { value: true });
26728 exports.default = Geometry;
26730 },{"rxjs/Subject":33}],286:[function(require,module,exports){
26732 var __extends = (this && this.__extends) || function (d, b) {
26733 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
26734 function __() { this.constructor = d; }
26735 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26737 var Component_1 = require("../../../Component");
26739 * @class PointGeometry
26740 * @classdesc Represents a point geometry in the basic coordinate system.
26742 var PointGeometry = (function (_super) {
26743 __extends(PointGeometry, _super);
26745 * Create a point geometry.
26748 * @param {Array<number>} point - An array representing the basic coordinates of
26751 * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
26753 function PointGeometry(point) {
26754 var _this = _super.call(this) || this;
26757 if (x < 0 || x > 1 || y < 0 || y > 1) {
26758 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
26760 _this._point = point.slice();
26763 Object.defineProperty(PointGeometry.prototype, "point", {
26765 * Get point property.
26766 * @returns {Array<number>} Array representing the basic coordinates of the point.
26769 return this._point;
26775 * Get the 3D world coordinates for the centroid of the point, i.e. the 3D
26776 * world coordinates of the point itself.
26778 * @param {Transform} transform - The transform of the node related to the point.
26779 * @returns {Array<number>} 3D world coordinates representing the centroid.
26781 PointGeometry.prototype.getCentroid3d = function (transform) {
26782 return transform.unprojectBasic(this._point, 200);
26785 * Set the centroid of the point, i.e. the point coordinates.
26787 * @param {Array<number>} value - The new value of the centroid.
26788 * @param {Transform} transform - The transform of the node related to the point.
26790 PointGeometry.prototype.setCentroid2d = function (value, transform) {
26792 Math.max(0, Math.min(1, value[0])),
26793 Math.max(0, Math.min(1, value[1])),
26795 this._point[0] = changed[0];
26796 this._point[1] = changed[1];
26797 this._notifyChanged$.next(this);
26799 return PointGeometry;
26800 }(Component_1.Geometry));
26801 exports.PointGeometry = PointGeometry;
26803 },{"../../../Component":225}],287:[function(require,module,exports){
26805 var __extends = (this && this.__extends) || function (d, b) {
26806 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
26807 function __() { this.constructor = d; }
26808 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26810 var Component_1 = require("../../../Component");
26812 * @class PolygonGeometry
26813 * @classdesc Represents a polygon geometry in the basic coordinate system.
26815 var PolygonGeometry = (function (_super) {
26816 __extends(PolygonGeometry, _super);
26818 * Create a polygon geometry.
26821 * @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
26822 * @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
26823 * Each array of holes vertices must be closed.
26825 * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
26827 function PolygonGeometry(polygon, holes) {
26828 var _this = _super.call(this) || this;
26829 var polygonLength = polygon.length;
26830 if (polygonLength < 3) {
26831 throw new Component_1.GeometryTagError("A polygon must have three or more positions.");
26833 if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
26834 polygon[0][1] !== polygon[polygonLength - 1][1]) {
26835 throw new Component_1.GeometryTagError("First and last positions must be equivalent.");
26837 _this._polygon = [];
26838 for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) {
26839 var vertex = polygon_1[_i];
26840 if (vertex[0] < 0 || vertex[0] > 1 ||
26841 vertex[1] < 0 || vertex[1] > 1) {
26842 throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
26844 _this._polygon.push(vertex.slice());
26847 if (holes == null) {
26850 for (var i = 0; i < holes.length; i++) {
26851 var hole = holes[i];
26852 var holeLength = hole.length;
26853 if (holeLength < 3) {
26854 throw new Component_1.GeometryTagError("A polygon hole must have three or more positions.");
26856 if (hole[0][0] !== hole[holeLength - 1][0] ||
26857 hole[0][1] !== hole[holeLength - 1][1]) {
26858 throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent.");
26860 _this._holes.push([]);
26861 for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) {
26862 var vertex = hole_1[_a];
26863 if (vertex[0] < 0 || vertex[0] > 1 ||
26864 vertex[1] < 0 || vertex[1] > 1) {
26865 throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
26867 _this._holes[i].push(vertex.slice());
26872 Object.defineProperty(PolygonGeometry.prototype, "polygon", {
26874 * Get polygon property.
26875 * @returns {Array<Array<number>>} Closed 2d polygon.
26878 return this._polygon;
26883 Object.defineProperty(PolygonGeometry.prototype, "holes", {
26885 * Get holes property.
26886 * @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
26889 return this._holes;
26895 * Add a vertex to the polygon by appending it after the last vertex.
26897 * @param {Array<number>} vertex - Vertex to add.
26899 PolygonGeometry.prototype.addVertex2d = function (vertex) {
26901 Math.max(0, Math.min(1, vertex[0])),
26902 Math.max(0, Math.min(1, vertex[1])),
26904 this._polygon.splice(this._polygon.length - 1, 0, clamped);
26905 this._notifyChanged$.next(this);
26908 * Remove a vertex from the polygon.
26910 * @param {number} index - The index of the vertex to remove.
26912 PolygonGeometry.prototype.removeVertex2d = function (index) {
26914 index >= this._polygon.length ||
26915 this._polygon.length < 4) {
26916 throw new Component_1.GeometryTagError("Index for removed vertex must be valid.");
26918 if (index > 0 && index < this._polygon.length - 1) {
26919 this._polygon.splice(index, 1);
26922 this._polygon.splice(0, 1);
26923 this._polygon.pop();
26924 var closing = this._polygon[0].slice();
26925 this._polygon.push(closing);
26927 this._notifyChanged$.next(this);
26930 PolygonGeometry.prototype.setVertex2d = function (index, value, transform) {
26932 Math.max(0, Math.min(1, value[0])),
26933 Math.max(0, Math.min(1, value[1])),
26935 if (index === 0 || index === this._polygon.length - 1) {
26936 this._polygon[0] = changed.slice();
26937 this._polygon[this._polygon.length - 1] = changed.slice();
26940 this._polygon[index] = changed.slice();
26942 this._notifyChanged$.next(this);
26945 PolygonGeometry.prototype.setCentroid2d = function (value, transform) {
26946 var xs = this._polygon.map(function (point) { return point[0]; });
26947 var ys = this._polygon.map(function (point) { return point[1]; });
26948 var minX = Math.min.apply(Math, xs);
26949 var maxX = Math.max.apply(Math, xs);
26950 var minY = Math.min.apply(Math, ys);
26951 var maxY = Math.max.apply(Math, ys);
26952 var centroid = this._getCentroid2d();
26953 var minTranslationX = -minX;
26954 var maxTranslationX = 1 - maxX;
26955 var minTranslationY = -minY;
26956 var maxTranslationY = 1 - maxY;
26957 var translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
26958 var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
26959 for (var _i = 0, _a = this._polygon; _i < _a.length; _i++) {
26960 var point = _a[_i];
26961 point[0] += translationX;
26962 point[1] += translationY;
26964 this._notifyChanged$.next(this);
26967 PolygonGeometry.prototype.getPoints3d = function (transform) {
26968 return this.getVertices3d(transform);
26971 PolygonGeometry.prototype.getVertex3d = function (index, transform) {
26972 return transform.unprojectBasic(this._polygon[index], 200);
26975 PolygonGeometry.prototype.getVertices3d = function (transform) {
26976 return this._polygon
26977 .map(function (point) {
26978 return transform.unprojectBasic(point, 200);
26982 * Get a polygon representation of the 3D coordinates for the vertices of each hole
26985 * @param {Transform} transform - The transform of the node related to the geometry.
26986 * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
26987 * representing the vertices of each hole of the geometry.
26989 PolygonGeometry.prototype.getHoleVertices3d = function (transform) {
26991 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
26994 .map(function (point) {
26995 return transform.unprojectBasic(point, 200);
26997 holes3d.push(hole3d);
27002 PolygonGeometry.prototype.getCentroid3d = function (transform) {
27003 var centroid2d = this._getCentroid2d();
27004 return transform.unprojectBasic(centroid2d, 200);
27007 PolygonGeometry.prototype.getTriangles3d = function (transform) {
27008 return this._triangulate(this._polygon, this.getPoints3d(transform), this._holes, this.getHoleVertices3d(transform));
27010 PolygonGeometry.prototype._getCentroid2d = function () {
27011 var polygon = this._polygon;
27015 for (var i = 0; i < polygon.length - 1; i++) {
27016 var xi = polygon[i][0];
27017 var yi = polygon[i][1];
27018 var xi1 = polygon[i + 1][0];
27019 var yi1 = polygon[i + 1][1];
27020 var a = xi * yi1 - xi1 * yi;
27022 centroidX += (xi + xi1) * a;
27023 centroidY += (yi + yi1) * a;
27026 centroidX /= 6 * area;
27027 centroidY /= 6 * area;
27028 return [centroidX, centroidY];
27030 return PolygonGeometry;
27031 }(Component_1.VertexGeometry));
27032 exports.PolygonGeometry = PolygonGeometry;
27033 Object.defineProperty(exports, "__esModule", { value: true });
27034 exports.default = PolygonGeometry;
27036 },{"../../../Component":225}],288:[function(require,module,exports){
27038 var __extends = (this && this.__extends) || function (d, b) {
27039 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
27040 function __() { this.constructor = d; }
27041 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27043 var Component_1 = require("../../../Component");
27045 * @class RectGeometry
27046 * @classdesc Represents a rectangle geometry in the basic coordinate system.
27048 var RectGeometry = (function (_super) {
27049 __extends(RectGeometry, _super);
27051 * Create a rectangle geometry.
27054 * @param {Array<number>} rect - An array representing the top-left and bottom-right
27055 * corners of the rectangle in basic coordinates. Ordered according to [x0, y0, x1, y1].
27057 * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates.
27059 function RectGeometry(rect) {
27060 var _this = _super.call(this) || this;
27061 if (rect[1] > rect[3]) {
27062 throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted.");
27064 for (var _i = 0, rect_1 = rect; _i < rect_1.length; _i++) {
27065 var coord = rect_1[_i];
27066 if (coord < 0 || coord > 1) {
27067 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
27070 _this._rect = rect.slice(0, 4);
27071 if (_this._rect[0] > _this._rect[2]) {
27072 _this._inverted = true;
27076 Object.defineProperty(RectGeometry.prototype, "rect", {
27078 * Get rect property.
27079 * @returns {Array<number>} Array representing the top-left and bottom-right
27080 * corners of the rectangle in basic coordinates.
27089 * Set the value of a vertex in the polygon representation of the rectangle.
27091 * @description The polygon is defined to have the first vertex at the
27092 * bottom-left corner with the rest of the vertices following in clockwise order.
27094 * @param {number} index - The index of the vertex to be set.
27095 * @param {Array<number>} value - The new value of the vertex.
27096 * @param {Transform} transform - The transform of the node related to the rectangle.
27098 RectGeometry.prototype.setVertex2d = function (index, value, transform) {
27099 var original = this._rect.slice();
27101 Math.max(0, Math.min(1, value[0])),
27102 Math.max(0, Math.min(1, value[1])),
27106 rect[0] = changed[0];
27107 rect[1] = original[1];
27108 rect[2] = original[2];
27109 rect[3] = changed[1];
27111 else if (index === 1) {
27112 rect[0] = changed[0];
27113 rect[1] = changed[1];
27114 rect[2] = original[2];
27115 rect[3] = original[3];
27117 else if (index === 2) {
27118 rect[0] = original[0];
27119 rect[1] = changed[1];
27120 rect[2] = changed[0];
27121 rect[3] = original[3];
27123 else if (index === 3) {
27124 rect[0] = original[0];
27125 rect[1] = original[1];
27126 rect[2] = changed[0];
27127 rect[3] = changed[1];
27129 if (transform.gpano) {
27130 var passingBoundaryLeft = index < 2 && changed[0] > 0.75 && original[0] < 0.25 ||
27131 index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25;
27132 var passingBoundaryRight = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 ||
27133 index >= 2 && changed[0] < 0.25 && original[2] > 0.75;
27134 if (passingBoundaryLeft || passingBoundaryRight) {
27135 this._inverted = !this._inverted;
27138 if (rect[0] - original[0] < -0.25) {
27139 rect[0] = original[0];
27141 if (rect[2] - original[2] > 0.25) {
27142 rect[2] = original[2];
27145 if (!this._inverted && rect[0] > rect[2] ||
27146 this._inverted && rect[0] < rect[2]) {
27147 rect[0] = original[0];
27148 rect[2] = original[2];
27152 if (rect[0] > rect[2]) {
27153 rect[0] = original[0];
27154 rect[2] = original[2];
27157 if (rect[1] > rect[3]) {
27158 rect[1] = original[1];
27159 rect[3] = original[3];
27161 this._rect[0] = rect[0];
27162 this._rect[1] = rect[1];
27163 this._rect[2] = rect[2];
27164 this._rect[3] = rect[3];
27165 this._notifyChanged$.next(this);
27168 RectGeometry.prototype.setCentroid2d = function (value, transform) {
27169 var original = this._rect.slice();
27170 var x0 = original[0];
27171 var x1 = this._inverted ? original[2] + 1 : original[2];
27172 var y0 = original[1];
27173 var y1 = original[3];
27174 var centerX = x0 + (x1 - x0) / 2;
27175 var centerY = y0 + (y1 - y0) / 2;
27176 var translationX = 0;
27177 if (transform.gpano != null &&
27178 transform.gpano.CroppedAreaImageWidthPixels === transform.gpano.FullPanoWidthPixels) {
27179 translationX = this._inverted ? value[0] + 1 - centerX : value[0] - centerX;
27182 var minTranslationX = -x0;
27183 var maxTranslationX = 1 - x1;
27184 translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centerX));
27186 var minTranslationY = -y0;
27187 var maxTranslationY = 1 - y1;
27188 var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centerY));
27189 this._rect[0] = original[0] + translationX;
27190 this._rect[1] = original[1] + translationY;
27191 this._rect[2] = original[2] + translationX;
27192 this._rect[3] = original[3] + translationY;
27193 if (this._rect[0] < 0) {
27194 this._rect[0] += 1;
27195 this._inverted = !this._inverted;
27197 else if (this._rect[0] > 1) {
27198 this._rect[0] -= 1;
27199 this._inverted = !this._inverted;
27201 if (this._rect[2] < 0) {
27202 this._rect[2] += 1;
27203 this._inverted = !this._inverted;
27205 else if (this._rect[2] > 1) {
27206 this._rect[2] -= 1;
27207 this._inverted = !this._inverted;
27209 this._notifyChanged$.next(this);
27212 * Get the 3D coordinates for the vertices of the rectangle with
27213 * interpolated points along the lines.
27215 * @param {Transform} transform - The transform of the node related to
27217 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates
27218 * representing the rectangle.
27220 RectGeometry.prototype.getPoints3d = function (transform) {
27221 return this._getPoints2d(transform)
27222 .map(function (point) {
27223 return transform.unprojectBasic(point, 200);
27227 * Get a vertex from the polygon representation of the 3D coordinates for the
27228 * vertices of the geometry.
27230 * @description The first vertex represents the bottom-left corner with the rest of
27231 * the vertices following in clockwise order.
27233 * @param {number} index - Vertex index.
27234 * @param {Transform} transform - The transform of the node related to the geometry.
27235 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
27236 * the vertices of the geometry.
27238 RectGeometry.prototype.getVertex3d = function (index, transform) {
27239 return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200);
27242 * Get a polygon representation of the 3D coordinates for the vertices of the rectangle.
27244 * @description The first vertex represents the bottom-left corner with the rest of
27245 * the vertices following in clockwise order.
27247 * @param {Transform} transform - The transform of the node related to the rectangle.
27248 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
27249 * the rectangle vertices.
27251 RectGeometry.prototype.getVertices3d = function (transform) {
27252 return this._rectToVertices2d(this._rect)
27253 .map(function (vertex) {
27254 return transform.unprojectBasic(vertex, 200);
27258 RectGeometry.prototype.getCentroid3d = function (transform) {
27259 var rect = this._rect;
27261 var x1 = this._inverted ? rect[2] + 1 : rect[2];
27264 var centroidX = x0 + (x1 - x0) / 2;
27265 var centroidY = y0 + (y1 - y0) / 2;
27266 return transform.unprojectBasic([centroidX, centroidY], 200);
27269 RectGeometry.prototype.getTriangles3d = function (transform) {
27270 return this._triangulate(this._rectToVertices2d(this._rect), this.getVertices3d(transform));
27273 * Check if a particular bottom-right value is valid according to the current
27274 * rectangle coordinates.
27276 * @param {Array<number>} bottomRight - The bottom-right coordinates to validate
27277 * @returns {boolean} Value indicating whether the provided bottom-right coordinates
27280 RectGeometry.prototype.validate = function (bottomRight) {
27281 var rect = this._rect;
27282 if (!this._inverted && bottomRight[0] < rect[0] ||
27283 bottomRight[0] - rect[2] > 0.25 ||
27284 bottomRight[1] < rect[1]) {
27290 * Get the 2D coordinates for the vertices of the rectangle with
27291 * interpolated points along the lines.
27293 * @param {Transform} transform - The transform of the node related to
27295 * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates
27296 * representing the rectangle.
27298 RectGeometry.prototype._getPoints2d = function (transform) {
27299 var vertices2d = this._rectToVertices2d(this._rect);
27300 var sides = vertices2d.length - 1;
27303 for (var i = 0; i < sides; ++i) {
27304 var startX = vertices2d[i][0];
27305 var startY = vertices2d[i][1];
27306 var endX = vertices2d[i + 1][0];
27307 var endY = vertices2d[i + 1][1];
27308 var intervalX = (endX - startX) / (sections - 1);
27309 var intervalY = (endY - startY) / (sections - 1);
27310 for (var j = 0; j < sections; ++j) {
27312 startX + j * intervalX,
27313 startY + j * intervalY,
27315 points2d.push(point);
27321 * Convert the top-left, bottom-right representation of a rectangle to a polygon
27322 * representation of the vertices starting at the bottom-right corner going
27325 * @param {Array<number>} rect - Top-left, bottom-right representation of a
27327 * @returns {Array<Array<number>>} Polygon representation of the vertices of the
27330 RectGeometry.prototype._rectToVertices2d = function (rect) {
27332 [rect[0], rect[3]],
27333 [rect[0], rect[1]],
27334 [this._inverted ? rect[2] + 1 : rect[2], rect[1]],
27335 [this._inverted ? rect[2] + 1 : rect[2], rect[3]],
27336 [rect[0], rect[3]],
27339 return RectGeometry;
27340 }(Component_1.VertexGeometry));
27341 exports.RectGeometry = RectGeometry;
27342 Object.defineProperty(exports, "__esModule", { value: true });
27343 exports.default = RectGeometry;
27345 },{"../../../Component":225}],289:[function(require,module,exports){
27346 /// <reference path="../../../../typings/index.d.ts" />
27348 var __extends = (this && this.__extends) || function (d, b) {
27349 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
27350 function __() { this.constructor = d; }
27351 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27353 var earcut = require("earcut");
27354 var Component_1 = require("../../../Component");
27356 * @class VertexGeometry
27358 * @classdesc Represents a vertex geometry.
27360 var VertexGeometry = (function (_super) {
27361 __extends(VertexGeometry, _super);
27363 * Create a vertex geometry.
27367 function VertexGeometry() {
27368 return _super.call(this) || this;
27371 * Triangulates a 2d polygon and returns the triangle
27372 * representation as a flattened array of 3d points.
27374 * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
27375 * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points.
27376 * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate.
27377 * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points.
27378 * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles.
27380 VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) {
27381 var data = [points2d.slice(0, -1)];
27382 for (var _i = 0, _a = holes2d != null ? holes2d : []; _i < _a.length; _i++) {
27383 var hole2d = _a[_i];
27384 data.push(hole2d.slice(0, -1));
27386 var points = points3d.slice(0, -1);
27387 for (var _b = 0, _c = holes3d != null ? holes3d : []; _b < _c.length; _b++) {
27388 var hole3d = _c[_b];
27389 points = points.concat(hole3d.slice(0, -1));
27391 var flattened = earcut.flatten(data);
27392 var indices = earcut(flattened.vertices, flattened.holes, flattened.dimensions);
27393 var triangles = [];
27394 for (var i = 0; i < indices.length; ++i) {
27395 var point = points[indices[i]];
27396 triangles.push(point[0]);
27397 triangles.push(point[1]);
27398 triangles.push(point[2]);
27402 return VertexGeometry;
27403 }(Component_1.Geometry));
27404 exports.VertexGeometry = VertexGeometry;
27405 Object.defineProperty(exports, "__esModule", { value: true });
27406 exports.default = VertexGeometry;
27408 },{"../../../Component":225,"earcut":6}],290:[function(require,module,exports){
27411 (function (Alignment) {
27412 Alignment[Alignment["Center"] = 0] = "Center";
27413 Alignment[Alignment["Outer"] = 1] = "Outer";
27414 })(Alignment = exports.Alignment || (exports.Alignment = {}));
27415 Object.defineProperty(exports, "__esModule", { value: true });
27416 exports.default = Alignment;
27418 },{}],291:[function(require,module,exports){
27419 /// <reference path="../../../../typings/index.d.ts" />
27421 var THREE = require("three");
27422 var vd = require("virtual-dom");
27423 var Subject_1 = require("rxjs/Subject");
27424 var Component_1 = require("../../../Component");
27425 var OutlineCreateTag = (function () {
27426 function OutlineCreateTag(geometry, options) {
27427 this._geometry = geometry;
27428 this._options = { color: options.color == null ? 0xFFFFFF : options.color };
27429 this._created$ = new Subject_1.Subject();
27430 this._aborted$ = new Subject_1.Subject();
27432 Object.defineProperty(OutlineCreateTag.prototype, "geometry", {
27434 return this._geometry;
27439 Object.defineProperty(OutlineCreateTag.prototype, "created$", {
27441 return this._created$;
27446 Object.defineProperty(OutlineCreateTag.prototype, "aborted$", {
27448 return this._aborted$;
27453 Object.defineProperty(OutlineCreateTag.prototype, "geometryChanged$", {
27456 return this._geometry.changed$
27457 .map(function (geometry) {
27464 OutlineCreateTag.prototype.getGLObject = function (transform) {
27465 var polygon3d = this._geometry.getPoints3d(transform);
27466 var positions = this._getPositions(polygon3d);
27467 var geometry = new THREE.BufferGeometry();
27468 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
27469 var material = new THREE.LineBasicMaterial({
27470 color: this._options.color,
27473 return new THREE.Line(geometry, material);
27475 OutlineCreateTag.prototype.getDOMObjects = function (transform, matrixWorldInverse, projectionMatrix) {
27478 var abort = function (e) {
27479 e.stopPropagation();
27480 _this._aborted$.next(_this);
27482 if (this._geometry instanceof Component_1.RectGeometry) {
27483 var topLeftPoint3d = this._geometry.getVertex3d(1, transform);
27484 var topLeftCameraSpace = this._convertToCameraSpace(topLeftPoint3d, matrixWorldInverse);
27485 if (topLeftCameraSpace.z < 0) {
27486 var centerCanvas = this._projectToCanvas(topLeftCameraSpace, projectionMatrix);
27487 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
27488 var pointProperties = {
27490 background: "#" + ("000000" + this._options.color.toString(16)).substr(-6),
27491 left: centerCss[0],
27492 position: "absolute",
27496 var completerProperties = {
27498 style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
27500 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
27501 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
27504 else if (this._geometry instanceof Component_1.PolygonGeometry) {
27505 var polygonGeometry_1 = this._geometry;
27506 var firstVertex3d = this._geometry.getVertex3d(0, transform);
27507 var firstCameraSpace = this._convertToCameraSpace(firstVertex3d, matrixWorldInverse);
27508 if (firstCameraSpace.z < 0) {
27509 var centerCanvas = this._projectToCanvas(firstCameraSpace, projectionMatrix);
27510 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
27511 var firstOnclick = polygonGeometry_1.polygon.length > 4 ?
27513 e.stopPropagation();
27514 polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 2);
27515 _this._created$.next(_this);
27518 var completerProperties = {
27519 onclick: firstOnclick,
27520 style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
27522 var firstClass = polygonGeometry_1.polygon.length > 4 ?
27525 vNodes.push(vd.h("div." + firstClass, completerProperties, []));
27527 if (polygonGeometry_1.polygon.length > 3) {
27528 var lastVertex3d = this._geometry.getVertex3d(polygonGeometry_1.polygon.length - 3, transform);
27529 var lastCameraSpace = this._convertToCameraSpace(lastVertex3d, matrixWorldInverse);
27530 if (lastCameraSpace.z < 0) {
27531 var centerCanvas = this._projectToCanvas(lastCameraSpace, projectionMatrix);
27532 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
27533 var remove = function (e) {
27534 e.stopPropagation();
27535 polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3);
27537 var completerProperties = {
27539 style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
27541 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
27544 var vertices3d = this._geometry.getVertices3d(transform);
27545 vertices3d.splice(-2, 2);
27546 for (var _i = 0, vertices3d_1 = vertices3d; _i < vertices3d_1.length; _i++) {
27547 var vertex = vertices3d_1[_i];
27548 var vertexCameraSpace = this._convertToCameraSpace(vertex, matrixWorldInverse);
27549 if (vertexCameraSpace.z < 0) {
27550 var centerCanvas = this._projectToCanvas(vertexCameraSpace, projectionMatrix);
27551 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
27552 var pointProperties = {
27554 background: "#" + ("000000" + this._options.color.toString(16)).substr(-6),
27555 left: centerCss[0],
27556 position: "absolute",
27560 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
27566 OutlineCreateTag.prototype.addPoint = function (point) {
27567 if (this._geometry instanceof Component_1.RectGeometry) {
27568 var rectGeometry = this._geometry;
27569 if (!rectGeometry.validate(point)) {
27572 this._created$.next(this);
27574 else if (this._geometry instanceof Component_1.PolygonGeometry) {
27575 var polygonGeometry = this._geometry;
27576 polygonGeometry.addVertex2d(point);
27579 OutlineCreateTag.prototype._getPositions = function (polygon3d) {
27580 var length = polygon3d.length;
27581 var positions = new Float32Array(length * 3);
27582 for (var i = 0; i < length; ++i) {
27584 var position = polygon3d[i];
27585 positions[index] = position[0];
27586 positions[index + 1] = position[1];
27587 positions[index + 2] = position[2];
27591 OutlineCreateTag.prototype._projectToCanvas = function (point, projectionMatrix) {
27592 var projected = new THREE.Vector3(point.x, point.y, point.z)
27593 .applyProjection(projectionMatrix);
27594 return [(projected.x + 1) / 2, (-projected.y + 1) / 2];
27596 OutlineCreateTag.prototype._convertToCameraSpace = function (point, matrixWorldInverse) {
27597 return new THREE.Vector3(point[0], point[1], point[2]).applyMatrix4(matrixWorldInverse);
27599 return OutlineCreateTag;
27601 exports.OutlineCreateTag = OutlineCreateTag;
27602 Object.defineProperty(exports, "__esModule", { value: true });
27603 exports.default = OutlineCreateTag;
27605 },{"../../../Component":225,"rxjs/Subject":33,"three":175,"virtual-dom":181}],292:[function(require,module,exports){
27606 /// <reference path="../../../../typings/index.d.ts" />
27608 var __extends = (this && this.__extends) || function (d, b) {
27609 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
27610 function __() { this.constructor = d; }
27611 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27613 var THREE = require("three");
27614 var vd = require("virtual-dom");
27615 var Component_1 = require("../../../Component");
27616 var Viewer_1 = require("../../../Viewer");
27618 * @class OutlineRenderTag
27619 * @classdesc Tag visualizing the properties of an OutlineTag.
27621 var OutlineRenderTag = (function (_super) {
27622 __extends(OutlineRenderTag, _super);
27623 function OutlineRenderTag(tag, transform) {
27624 var _this = _super.call(this, tag, transform) || this;
27625 _this._fill = _this._tag.fillOpacity > 0 && !transform.gpano ?
27626 _this._createFill() :
27628 _this._holes = _this._tag.lineWidth >= 1 ?
27629 _this._createHoles() :
27631 _this._outline = _this._tag.lineWidth >= 1 ?
27632 _this._createOutline() :
27634 _this._glObjects = _this._createGLObjects();
27635 _this._tag.geometry.changed$
27636 .subscribe(function (geometry) {
27637 if (_this._fill != null) {
27638 _this._updateFillGeometry();
27640 if (_this._holes.length > 0) {
27641 _this._updateHoleGeometries();
27643 if (_this._outline != null) {
27644 _this._updateOulineGeometry();
27647 _this._tag.changed$
27648 .subscribe(function (changedTag) {
27649 var glObjectsChanged = false;
27650 if (_this._fill == null) {
27651 if (_this._tag.fillOpacity > 0 && !_this._transform.gpano) {
27652 _this._fill = _this._createFill();
27653 glObjectsChanged = true;
27657 _this._updateFillMaterial();
27659 if (_this._outline == null) {
27660 if (_this._tag.lineWidth > 0) {
27661 _this._holes = _this._createHoles();
27662 _this._outline = _this._createOutline();
27663 glObjectsChanged = true;
27667 _this._updateHoleMaterials();
27668 _this._updateOutlineMaterial();
27670 if (glObjectsChanged) {
27671 _this._glObjects = _this._createGLObjects();
27672 _this._glObjectsChanged$.next(_this);
27677 OutlineRenderTag.prototype.dispose = function () {
27678 this._disposeFill();
27679 this._disposeHoles();
27680 this._disposeOutline();
27682 OutlineRenderTag.prototype.getDOMObjects = function (atlas, matrixWorldInverse, projectionMatrix) {
27685 if (this._tag.geometry instanceof Component_1.RectGeometry) {
27686 if (this._tag.icon != null) {
27687 var iconVertex = this._tag.geometry.getVertex3d(this._tag.iconIndex, this._transform);
27688 var iconCameraSpace = this._convertToCameraSpace(iconVertex, matrixWorldInverse);
27689 if (iconCameraSpace.z < 0) {
27690 var interact = function (e) {
27691 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
27693 if (atlas.loaded) {
27694 var spriteAlignments = this._getSpriteAlignment(this._tag.iconIndex, this._tag.iconAlignment);
27695 var sprite = atlas.getDOMSprite(this._tag.icon, spriteAlignments[0], spriteAlignments[1]);
27696 var click = function (e) {
27697 e.stopPropagation();
27698 _this._tag.click$.next(_this._tag);
27700 var iconCanvas = this._projectToCanvas(iconCameraSpace, projectionMatrix);
27701 var iconCss = iconCanvas.map(function (coord) { return (100 * coord) + "%"; });
27704 onmousedown: interact,
27707 pointerEvents: "all",
27708 position: "absolute",
27712 vNodes.push(vd.h("div.TagSymbol", properties, [sprite]));
27716 else if (this._tag.text != null) {
27717 var textVertex = this._tag.geometry.getVertex3d(3, this._transform);
27718 var textCameraSpace = this._convertToCameraSpace(textVertex, matrixWorldInverse);
27719 if (textCameraSpace.z < 0) {
27720 var interact = function (e) {
27721 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
27723 var labelCanvas = this._projectToCanvas(textCameraSpace, projectionMatrix);
27724 var labelCss = labelCanvas.map(function (coord) { return (100 * coord) + "%"; });
27726 onmousedown: interact,
27728 color: "#" + ("000000" + this._tag.textColor.toString(16)).substr(-6),
27730 pointerEvents: "all",
27731 position: "absolute",
27734 textContent: this._tag.text,
27736 vNodes.push(vd.h("span.TagSymbol", properties, []));
27740 if (!this._tag.editable) {
27743 var lineColor = "#" + ("000000" + this._tag.lineColor.toString(16)).substr(-6);
27744 if (this._tag.geometry instanceof Component_1.RectGeometry) {
27745 var centroid3d = this._tag.geometry.getCentroid3d(this._transform);
27746 var centroidCameraSpace = this._convertToCameraSpace(centroid3d, matrixWorldInverse);
27747 if (centroidCameraSpace.z < 0) {
27748 var interact = this._interact(Component_1.TagOperation.Centroid);
27749 var centerCanvas = this._projectToCanvas(centroidCameraSpace, projectionMatrix);
27750 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
27752 onmousedown: interact,
27753 style: { background: lineColor, left: centerCss[0], position: "absolute", top: centerCss[1] },
27755 vNodes.push(vd.h("div.TagMover", properties, []));
27758 var vertices3d = this._tag.geometry.getVertices3d(this._transform);
27759 for (var i = 0; i < vertices3d.length - 1; i++) {
27760 var isRectGeometry = this._tag.geometry instanceof Component_1.RectGeometry;
27761 if (isRectGeometry &&
27762 ((this._tag.icon != null && i === this._tag.iconIndex) ||
27763 (this._tag.icon == null && this._tag.text != null && i === 3))) {
27766 var vertexCameraSpace = this._convertToCameraSpace(vertices3d[i], matrixWorldInverse);
27767 if (vertexCameraSpace.z > 0) {
27770 var interact = this._interact(Component_1.TagOperation.Vertex, i);
27771 var vertexCanvas = this._projectToCanvas(vertexCameraSpace, projectionMatrix);
27772 var vertexCss = vertexCanvas.map(function (coord) { return (100 * coord) + "%"; });
27774 onmousedown: interact,
27776 background: lineColor,
27777 left: vertexCss[0],
27778 position: "absolute",
27782 if (isRectGeometry) {
27783 properties.style.cursor = i % 2 === 0 ? "nesw-resize" : "nwse-resize";
27785 vNodes.push(vd.h("div.TagResizer", properties, []));
27786 if (!this._tag.indicateVertices) {
27789 var pointProperties = {
27791 background: lineColor,
27792 left: vertexCss[0],
27793 position: "absolute",
27797 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
27801 OutlineRenderTag.prototype._createFill = function () {
27802 var triangles = this._tag.geometry.getTriangles3d(this._transform);
27803 var positions = new Float32Array(triangles);
27804 var geometry = new THREE.BufferGeometry();
27805 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
27806 geometry.computeBoundingSphere();
27807 var material = new THREE.MeshBasicMaterial({
27808 color: this._tag.fillColor,
27809 opacity: this._tag.fillOpacity,
27810 side: THREE.DoubleSide,
27813 return new THREE.Mesh(geometry, material);
27815 OutlineRenderTag.prototype._createGLObjects = function () {
27816 var glObjects = [];
27817 if (this._fill != null) {
27818 glObjects.push(this._fill);
27820 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
27822 glObjects.push(hole);
27824 if (this._outline != null) {
27825 glObjects.push(this._outline);
27829 OutlineRenderTag.prototype._createHoles = function () {
27831 if (this._tag.geometry instanceof Component_1.PolygonGeometry) {
27832 var polygonGeometry = this._tag.geometry;
27833 var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
27834 for (var _i = 0, holes3d_1 = holes3d; _i < holes3d_1.length; _i++) {
27835 var holePoints3d = holes3d_1[_i];
27836 var hole = this._createLine(holePoints3d);
27842 OutlineRenderTag.prototype._createLine = function (points3d) {
27843 var positions = this._getLinePositions(points3d);
27844 var geometry = new THREE.BufferGeometry();
27845 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
27846 geometry.computeBoundingSphere();
27847 var material = new THREE.LineBasicMaterial({
27848 color: this._tag.lineColor,
27849 linewidth: this._tag.lineWidth,
27851 return new THREE.Line(geometry, material);
27853 OutlineRenderTag.prototype._createOutline = function () {
27854 var points3d = this._tag.geometry.getPoints3d(this._transform);
27855 return this._createLine(points3d);
27857 OutlineRenderTag.prototype._disposeFill = function () {
27858 if (this._fill == null) {
27861 this._fill.geometry.dispose();
27862 this._fill.material.dispose();
27865 OutlineRenderTag.prototype._disposeHoles = function () {
27866 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
27868 hole.geometry.dispose();
27869 hole.material.dispose();
27873 OutlineRenderTag.prototype._disposeOutline = function () {
27874 if (this._outline == null) {
27877 this._outline.geometry.dispose();
27878 this._outline.material.dispose();
27879 this._outline = null;
27881 OutlineRenderTag.prototype._getLinePositions = function (points3d) {
27882 var length = points3d.length;
27883 var positions = new Float32Array(length * 3);
27884 for (var i = 0; i < length; ++i) {
27886 var position = points3d[i];
27887 positions[index + 0] = position[0];
27888 positions[index + 1] = position[1];
27889 positions[index + 2] = position[2];
27893 OutlineRenderTag.prototype._getSpriteAlignment = function (index, alignment) {
27894 var horizontalAlignment = Viewer_1.SpriteAlignment.Center;
27895 var verticalAlignment = Viewer_1.SpriteAlignment.Center;
27896 if (alignment === Component_1.Alignment.Outer) {
27899 horizontalAlignment = Viewer_1.SpriteAlignment.End;
27900 verticalAlignment = Viewer_1.SpriteAlignment.Start;
27903 horizontalAlignment = Viewer_1.SpriteAlignment.End;
27904 verticalAlignment = Viewer_1.SpriteAlignment.End;
27907 horizontalAlignment = Viewer_1.SpriteAlignment.Start;
27908 verticalAlignment = Viewer_1.SpriteAlignment.End;
27911 horizontalAlignment = Viewer_1.SpriteAlignment.Start;
27912 verticalAlignment = Viewer_1.SpriteAlignment.Start;
27918 return [horizontalAlignment, verticalAlignment];
27920 OutlineRenderTag.prototype._interact = function (operation, vertexIndex) {
27922 return function (e) {
27923 var offsetX = e.offsetX - e.target.offsetWidth / 2;
27924 var offsetY = e.offsetY - e.target.offsetHeight / 2;
27925 _this._interact$.next({
27928 operation: operation,
27930 vertexIndex: vertexIndex,
27934 OutlineRenderTag.prototype._updateFillGeometry = function () {
27935 var triangles = this._tag.geometry.getTriangles3d(this._transform);
27936 var positions = new Float32Array(triangles);
27937 var geometry = this._fill.geometry;
27938 var attribute = geometry.getAttribute("position");
27939 if (attribute.array.length === positions.length) {
27940 attribute.set(positions);
27941 attribute.needsUpdate = true;
27944 geometry.removeAttribute("position");
27945 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
27947 geometry.computeBoundingSphere();
27949 OutlineRenderTag.prototype._updateFillMaterial = function () {
27950 var material = this._fill.material;
27951 material.color = new THREE.Color(this._tag.fillColor);
27952 material.opacity = this._tag.fillOpacity;
27953 material.needsUpdate = true;
27955 OutlineRenderTag.prototype._updateHoleGeometries = function () {
27956 var polygonGeometry = this._tag.geometry;
27957 var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
27958 if (holes3d.length !== this._holes.length) {
27959 throw new Error("Changing the number of holes is not supported.");
27961 for (var i = 0; i < this._holes.length; i++) {
27962 var holePoints3d = holes3d[i];
27963 var hole = this._holes[i];
27964 this._updateLine(hole, holePoints3d);
27967 OutlineRenderTag.prototype._updateHoleMaterials = function () {
27968 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
27970 var material = hole.material;
27971 this._updateLineBasicMaterial(material);
27974 OutlineRenderTag.prototype._updateLine = function (line, points3d) {
27975 var positions = this._getLinePositions(points3d);
27976 var geometry = line.geometry;
27977 var attribute = geometry.getAttribute("position");
27978 attribute.set(positions);
27979 attribute.needsUpdate = true;
27980 geometry.computeBoundingSphere();
27982 OutlineRenderTag.prototype._updateOulineGeometry = function () {
27983 var points3d = this._tag.geometry.getPoints3d(this._transform);
27984 this._updateLine(this._outline, points3d);
27986 OutlineRenderTag.prototype._updateOutlineMaterial = function () {
27987 var material = this._outline.material;
27988 this._updateLineBasicMaterial(material);
27990 OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) {
27991 material.color = new THREE.Color(this._tag.lineColor);
27992 material.linewidth = Math.max(this._tag.lineWidth, 1);
27993 material.opacity = this._tag.lineWidth >= 1 ? 1 : 0;
27994 material.transparent = this._tag.lineWidth <= 0;
27995 material.needsUpdate = true;
27997 return OutlineRenderTag;
27998 }(Component_1.RenderTag));
27999 exports.OutlineRenderTag = OutlineRenderTag;
28001 },{"../../../Component":225,"../../../Viewer":235,"three":175,"virtual-dom":181}],293:[function(require,module,exports){
28003 var __extends = (this && this.__extends) || function (d, b) {
28004 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
28005 function __() { this.constructor = d; }
28006 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28008 var Subject_1 = require("rxjs/Subject");
28009 var Component_1 = require("../../../Component");
28011 * @class OutlineTag
28012 * @classdesc Tag holding properties for visualizing a geometry outline.
28014 var OutlineTag = (function (_super) {
28015 __extends(OutlineTag, _super);
28017 * Create an outline tag.
28021 * @param {string} id
28022 * @param {Geometry} geometry
28023 * @param {IOutlineTagOptions} options - Options defining the visual appearance and
28024 * behavior of the outline tag.
28026 function OutlineTag(id, geometry, options) {
28027 var _this = _super.call(this, id, geometry) || this;
28028 _this._editable = options.editable == null ? false : options.editable;
28029 _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
28030 _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
28031 _this._icon = options.icon === undefined ? null : options.icon;
28032 _this._iconAlignment = options.iconAlignment == null ? Component_1.Alignment.Outer : options.iconAlignment;
28033 _this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
28034 _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
28035 _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
28036 _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
28037 _this._text = options.text === undefined ? null : options.text;
28038 _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
28039 _this._click$ = new Subject_1.Subject();
28041 .subscribe(function (t) {
28042 _this.fire(OutlineTag.click, _this);
28046 Object.defineProperty(OutlineTag.prototype, "click$", {
28048 * Click observable.
28050 * @description An observable emitting the tag when the icon of the
28051 * tag has been clicked.
28053 * @returns {Observable<Tag>}
28056 return this._click$;
28061 Object.defineProperty(OutlineTag.prototype, "editable", {
28063 * Get editable property.
28064 * @returns {boolean} Value indicating if tag is editable.
28067 return this._editable;
28070 * Set editable property.
28073 * @fires Tag#changed
28075 set: function (value) {
28076 this._editable = value;
28077 this._notifyChanged$.next(this);
28082 Object.defineProperty(OutlineTag.prototype, "fillColor", {
28084 * Get fill color property.
28085 * @returns {number}
28088 return this._fillColor;
28091 * Set fill color property.
28094 * @fires Tag#changed
28096 set: function (value) {
28097 this._fillColor = value;
28098 this._notifyChanged$.next(this);
28103 Object.defineProperty(OutlineTag.prototype, "fillOpacity", {
28105 * Get fill opacity property.
28106 * @returns {number}
28109 return this._fillOpacity;
28112 * Set fill opacity property.
28115 * @fires Tag#changed
28117 set: function (value) {
28118 this._fillOpacity = value;
28119 this._notifyChanged$.next(this);
28124 Object.defineProperty(OutlineTag.prototype, "geometry", {
28126 return this._geometry;
28131 Object.defineProperty(OutlineTag.prototype, "icon", {
28133 * Get icon property.
28134 * @returns {string}
28140 * Set icon property.
28143 * @fires Tag#changed
28145 set: function (value) {
28146 this._icon = value;
28147 this._notifyChanged$.next(this);
28152 Object.defineProperty(OutlineTag.prototype, "iconAlignment", {
28154 * Get icon alignment property.
28155 * @returns {Alignment}
28158 return this._iconAlignment;
28161 * Set icon alignment property.
28162 * @param {Alignment}
28164 * @fires Tag#changed
28166 set: function (value) {
28167 this._iconAlignment = value;
28168 this._notifyChanged$.next(this);
28173 Object.defineProperty(OutlineTag.prototype, "iconIndex", {
28175 * Get icon index property.
28176 * @returns {number}
28179 return this._iconIndex;
28182 * Set icon index property.
28185 * @fires Tag#changed
28187 set: function (value) {
28188 this._iconIndex = value;
28189 this._notifyChanged$.next(this);
28194 Object.defineProperty(OutlineTag.prototype, "indicateVertices", {
28196 * Get indicate vertices property.
28197 * @returns {boolean} Value indicating if vertices should be indicated
28198 * when tag is editable.
28201 return this._indicateVertices;
28204 * Set indicate vertices property.
28207 * @fires Tag#changed
28209 set: function (value) {
28210 this._indicateVertices = value;
28211 this._notifyChanged$.next(this);
28216 Object.defineProperty(OutlineTag.prototype, "lineColor", {
28218 * Get line color property.
28219 * @returns {number}
28222 return this._lineColor;
28225 * Set line color property.
28228 * @fires Tag#changed
28230 set: function (value) {
28231 this._lineColor = value;
28232 this._notifyChanged$.next(this);
28237 Object.defineProperty(OutlineTag.prototype, "lineWidth", {
28239 * Get line width property.
28240 * @returns {number}
28243 return this._lineWidth;
28246 * Set line width property.
28249 * @fires Tag#changed
28251 set: function (value) {
28252 this._lineWidth = value;
28253 this._notifyChanged$.next(this);
28258 Object.defineProperty(OutlineTag.prototype, "text", {
28260 * Get text property.
28261 * @returns {string}
28267 * Set text property.
28270 * @fires Tag#changed
28272 set: function (value) {
28273 this._text = value;
28274 this._notifyChanged$.next(this);
28279 Object.defineProperty(OutlineTag.prototype, "textColor", {
28281 * Get text color property.
28282 * @returns {number}
28285 return this._textColor;
28288 * Set text color property.
28291 * @fires Tag#changed
28293 set: function (value) {
28294 this._textColor = value;
28295 this._notifyChanged$.next(this);
28301 * Set options for tag.
28303 * @description Sets all the option properties provided and keps
28304 * the rest of the values as is.
28306 * @param {IOutlineTagOptions} options - Outline tag options
28308 * @fires {Tag#changed}
28310 OutlineTag.prototype.setOptions = function (options) {
28311 this._editable = options.editable == null ? this._editable : options.editable;
28312 this._icon = options.icon === undefined ? this._icon : options.icon;
28313 this._iconAlignment = options.iconAlignment == null ? this._iconAlignment : options.iconAlignment;
28314 this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
28315 this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
28316 this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
28317 this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
28318 this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
28319 this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
28320 this._text = options.text === undefined ? this._text : options.text;
28321 this._textColor = options.textColor == null ? this._textColor : options.textColor;
28322 this._notifyChanged$.next(this);
28325 }(Component_1.Tag));
28327 * Event fired when the icon of the outline tag is clicked.
28329 * @event OutlineTag#click
28330 * @type {OutlineTag} The tag instance that was clicked.
28332 OutlineTag.click = "click";
28333 exports.OutlineTag = OutlineTag;
28334 Object.defineProperty(exports, "__esModule", { value: true });
28335 exports.default = OutlineTag;
28337 },{"../../../Component":225,"rxjs/Subject":33}],294:[function(require,module,exports){
28338 /// <reference path="../../../../typings/index.d.ts" />
28340 var THREE = require("three");
28341 var Subject_1 = require("rxjs/Subject");
28342 var RenderTag = (function () {
28343 function RenderTag(tag, transform) {
28345 this._transform = transform;
28346 this._glObjects = [];
28347 this._glObjectsChanged$ = new Subject_1.Subject();
28348 this._interact$ = new Subject_1.Subject();
28350 Object.defineProperty(RenderTag.prototype, "glObjects", {
28352 * Get the GL objects for rendering of the tag.
28353 * @return {Array<Object3D>}
28356 return this._glObjects;
28361 Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", {
28363 return this._glObjectsChanged$;
28368 Object.defineProperty(RenderTag.prototype, "interact$", {
28370 return this._interact$;
28375 Object.defineProperty(RenderTag.prototype, "tag", {
28382 RenderTag.prototype._projectToCanvas = function (point3d, projectionMatrix) {
28383 var projected = new THREE.Vector3(point3d.x, point3d.y, point3d.z)
28384 .applyProjection(projectionMatrix);
28385 return [(projected.x + 1) / 2, (-projected.y + 1) / 2];
28387 RenderTag.prototype._convertToCameraSpace = function (point3d, matrixWorldInverse) {
28388 return new THREE.Vector3(point3d[0], point3d[1], point3d[2]).applyMatrix4(matrixWorldInverse);
28392 exports.RenderTag = RenderTag;
28393 Object.defineProperty(exports, "__esModule", { value: true });
28394 exports.default = RenderTag;
28396 },{"rxjs/Subject":33,"three":175}],295:[function(require,module,exports){
28397 /// <reference path="../../../../typings/index.d.ts" />
28399 var __extends = (this && this.__extends) || function (d, b) {
28400 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
28401 function __() { this.constructor = d; }
28402 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28404 var vd = require("virtual-dom");
28405 var Component_1 = require("../../../Component");
28406 var Viewer_1 = require("../../../Viewer");
28408 * @class SpotRenderTag
28409 * @classdesc Tag visualizing the properties of a SpotTag.
28411 var SpotRenderTag = (function (_super) {
28412 __extends(SpotRenderTag, _super);
28413 function SpotRenderTag() {
28414 return _super !== null && _super.apply(this, arguments) || this;
28416 SpotRenderTag.prototype.dispose = function () { return; };
28417 SpotRenderTag.prototype.getDOMObjects = function (atlas, matrixWorldInverse, projectionMatrix) {
28420 var centroid3d = this._tag.geometry.getCentroid3d(this._transform);
28421 var centroidCameraSpace = this._convertToCameraSpace(centroid3d, matrixWorldInverse);
28422 if (centroidCameraSpace.z < 0) {
28423 var centroidCanvas = this._projectToCanvas(centroidCameraSpace, projectionMatrix);
28424 var centroidCss = centroidCanvas.map(function (coord) { return (100 * coord) + "%"; });
28425 var interactNone = function (e) {
28426 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
28428 if (this._tag.icon != null) {
28429 if (atlas.loaded) {
28430 var sprite = atlas.getDOMSprite(this._tag.icon, Viewer_1.SpriteAlignment.Center, Viewer_1.SpriteAlignment.End);
28432 onmousedown: interactNone,
28434 bottom: 100 * (1 - centroidCanvas[1]) + "%",
28435 left: centroidCss[0],
28436 pointerEvents: "all",
28437 position: "absolute",
28438 transform: "translate(0px, -8px)",
28441 vNodes.push(vd.h("div", properties, [sprite]));
28444 else if (this._tag.text != null) {
28446 onmousedown: interactNone,
28448 bottom: 100 * (1 - centroidCanvas[1]) + "%",
28449 color: "#" + ("000000" + this._tag.textColor.toString(16)).substr(-6),
28450 left: centroidCss[0],
28451 pointerEvents: "all",
28452 position: "absolute",
28453 transform: "translate(-50%, -7px)",
28455 textContent: this._tag.text,
28457 vNodes.push(vd.h("span.TagSymbol", properties, []));
28459 var interact = this._interact(Component_1.TagOperation.Centroid);
28460 var background = "#" + ("000000" + this._tag.color.toString(16)).substr(-6);
28461 if (this._tag.editable) {
28462 var interactorProperties = {
28463 onmousedown: interact,
28465 background: background,
28466 left: centroidCss[0],
28467 pointerEvents: "all",
28468 position: "absolute",
28469 top: centroidCss[1],
28472 vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, []));
28474 var pointProperties = {
28476 background: background,
28477 left: centroidCss[0],
28478 position: "absolute",
28479 top: centroidCss[1],
28482 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
28486 SpotRenderTag.prototype._interact = function (operation, vertexIndex) {
28488 return function (e) {
28489 var offsetX = e.offsetX - e.target.offsetWidth / 2;
28490 var offsetY = e.offsetY - e.target.offsetHeight / 2;
28491 _this._interact$.next({
28494 operation: operation,
28496 vertexIndex: vertexIndex,
28500 return SpotRenderTag;
28501 }(Component_1.RenderTag));
28502 exports.SpotRenderTag = SpotRenderTag;
28504 },{"../../../Component":225,"../../../Viewer":235,"virtual-dom":181}],296:[function(require,module,exports){
28506 var __extends = (this && this.__extends) || function (d, b) {
28507 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
28508 function __() { this.constructor = d; }
28509 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28511 var Component_1 = require("../../../Component");
28514 * @classdesc Tag holding properties for visualizing the centroid of a geometry.
28516 var SpotTag = (function (_super) {
28517 __extends(SpotTag, _super);
28519 * Create a spot tag.
28523 * @param {string} id
28524 * @param {Geometry} geometry
28525 * @param {IOutlineTagOptions} options - Options defining the visual appearance and
28526 * behavior of the spot tag.
28528 function SpotTag(id, geometry, options) {
28529 var _this = _super.call(this, id, geometry) || this;
28530 _this._color = options.color == null ? 0xFFFFFF : options.color;
28531 _this._editable = options.editable == null ? false : options.editable;
28532 _this._icon = options.icon === undefined ? null : options.icon;
28533 _this._text = options.text === undefined ? null : options.text;
28534 _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
28537 Object.defineProperty(SpotTag.prototype, "color", {
28539 * Get color property.
28540 * @returns {number} The color of the spot as a hexagonal number;
28543 return this._color;
28546 * Set color property.
28549 * @fires Tag#changed
28551 set: function (value) {
28552 this._color = value;
28553 this._notifyChanged$.next(this);
28558 Object.defineProperty(SpotTag.prototype, "editable", {
28560 * Get editable property.
28561 * @returns {boolean} Value indicating if tag is editable.
28564 return this._editable;
28567 * Set editable property.
28570 * @fires Tag#changed
28572 set: function (value) {
28573 this._editable = value;
28574 this._notifyChanged$.next(this);
28579 Object.defineProperty(SpotTag.prototype, "icon", {
28581 * Get icon property.
28582 * @returns {string}
28588 * Set icon property.
28591 * @fires Tag#changed
28593 set: function (value) {
28594 this._icon = value;
28595 this._notifyChanged$.next(this);
28600 Object.defineProperty(SpotTag.prototype, "text", {
28602 * Get text property.
28603 * @returns {string}
28609 * Set text property.
28612 * @fires Tag#changed
28614 set: function (value) {
28615 this._text = value;
28616 this._notifyChanged$.next(this);
28621 Object.defineProperty(SpotTag.prototype, "textColor", {
28623 * Get text color property.
28624 * @returns {number}
28627 return this._textColor;
28630 * Set text color property.
28633 * @fires Tag#changed
28635 set: function (value) {
28636 this._textColor = value;
28637 this._notifyChanged$.next(this);
28643 * Set options for tag.
28645 * @description Sets all the option properties provided and keps
28646 * the rest of the values as is.
28648 * @param {ISpotTagOptions} options - Spot tag options
28650 * @fires {Tag#changed}
28652 SpotTag.prototype.setOptions = function (options) {
28653 this._color = options.color == null ? this._color : options.color;
28654 this._editable = options.editable == null ? this._editable : options.editable;
28655 this._icon = options.icon === undefined ? this._icon : options.icon;
28656 this._text = options.text === undefined ? this._text : options.text;
28657 this._textColor = options.textColor == null ? this._textColor : options.textColor;
28658 this._notifyChanged$.next(this);
28661 }(Component_1.Tag));
28662 exports.SpotTag = SpotTag;
28663 Object.defineProperty(exports, "__esModule", { value: true });
28664 exports.default = SpotTag;
28666 },{"../../../Component":225}],297:[function(require,module,exports){
28668 var __extends = (this && this.__extends) || function (d, b) {
28669 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
28670 function __() { this.constructor = d; }
28671 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28673 var Subject_1 = require("rxjs/Subject");
28674 require("rxjs/add/operator/map");
28675 require("rxjs/add/operator/share");
28676 var Utils_1 = require("../../../Utils");
28680 * @classdesc Abstract class representing the basic functionality of for a tag.
28682 var Tag = (function (_super) {
28683 __extends(Tag, _super);
28688 * @param {string} id
28689 * @param {Geometry} geometry
28691 function Tag(id, geometry) {
28692 var _this = _super.call(this) || this;
28694 _this._geometry = geometry;
28695 _this._notifyChanged$ = new Subject_1.Subject();
28696 _this._notifyChanged$
28697 .subscribe(function (t) {
28698 _this.fire(Tag.changed, _this);
28700 _this._geometry.changed$
28701 .subscribe(function (g) {
28702 _this.fire(Tag.geometrychanged, _this);
28706 Object.defineProperty(Tag.prototype, "id", {
28709 * @returns {string}
28717 Object.defineProperty(Tag.prototype, "geometry", {
28719 * Get geometry property.
28720 * @returns {Geometry}
28723 return this._geometry;
28728 Object.defineProperty(Tag.prototype, "changed$", {
28730 * Get changed observable.
28731 * @returns {Observable<Tag>}
28734 return this._notifyChanged$;
28739 Object.defineProperty(Tag.prototype, "geometryChanged$", {
28741 * Get geometry changed observable.
28742 * @returns {Observable<Tag>}
28746 return this._geometry.changed$
28747 .map(function (geometry) {
28756 }(Utils_1.EventEmitter));
28758 * Event fired when a property related to the visual appearance of the
28761 * @event Tag#changed
28762 * @type {Tag} The tag instance that has changed.
28764 Tag.changed = "changed";
28766 * Event fired when the geometry of the tag has changed.
28768 * @event Tag#geometrychanged
28769 * @type {Tag} The tag instance whose geometry has changed.
28771 Tag.geometrychanged = "geometrychanged";
28773 Object.defineProperty(exports, "__esModule", { value: true });
28774 exports.default = Tag;
28776 },{"../../../Utils":234,"rxjs/Subject":33,"rxjs/add/operator/map":64,"rxjs/add/operator/share":73}],298:[function(require,module,exports){
28778 var __extends = (this && this.__extends) || function (d, b) {
28779 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
28780 function __() { this.constructor = d; }
28781 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28783 var MapillaryError_1 = require("./MapillaryError");
28784 var ArgumentMapillaryError = (function (_super) {
28785 __extends(ArgumentMapillaryError, _super);
28786 function ArgumentMapillaryError(message) {
28787 var _this = _super.call(this, message != null ? message : "The argument is not valid.") || this;
28788 _this.name = "ArgumentMapillaryError";
28791 return ArgumentMapillaryError;
28792 }(MapillaryError_1.MapillaryError));
28793 exports.ArgumentMapillaryError = ArgumentMapillaryError;
28794 Object.defineProperty(exports, "__esModule", { value: true });
28795 exports.default = ArgumentMapillaryError;
28797 },{"./MapillaryError":300}],299:[function(require,module,exports){
28799 var __extends = (this && this.__extends) || function (d, b) {
28800 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
28801 function __() { this.constructor = d; }
28802 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28804 var MapillaryError_1 = require("./MapillaryError");
28805 var GraphMapillaryError = (function (_super) {
28806 __extends(GraphMapillaryError, _super);
28807 function GraphMapillaryError(message) {
28808 var _this = _super.call(this, message) || this;
28809 _this.name = "GraphMapillaryError";
28812 return GraphMapillaryError;
28813 }(MapillaryError_1.MapillaryError));
28814 exports.GraphMapillaryError = GraphMapillaryError;
28815 Object.defineProperty(exports, "__esModule", { value: true });
28816 exports.default = GraphMapillaryError;
28818 },{"./MapillaryError":300}],300:[function(require,module,exports){
28820 var __extends = (this && this.__extends) || function (d, b) {
28821 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
28822 function __() { this.constructor = d; }
28823 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28825 var MapillaryError = (function (_super) {
28826 __extends(MapillaryError, _super);
28827 function MapillaryError(message) {
28828 var _this = _super.call(this, message) || this;
28829 _this.name = "MapillaryError";
28832 return MapillaryError;
28834 exports.MapillaryError = MapillaryError;
28835 Object.defineProperty(exports, "__esModule", { value: true });
28836 exports.default = MapillaryError;
28838 },{}],301:[function(require,module,exports){
28839 /// <reference path="../../typings/index.d.ts" />
28841 var THREE = require("three");
28845 * @classdesc Holds information about a camera.
28847 var Camera = (function () {
28849 * Create a new camera instance.
28850 * @param {Transform} [transform] - Optional transform instance.
28852 function Camera(transform) {
28853 if (transform != null) {
28854 this._position = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0));
28855 this._lookat = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10));
28856 this._up = transform.upVector();
28857 this._focal = this._getFocal(transform);
28860 this._position = new THREE.Vector3(0, 0, 0);
28861 this._lookat = new THREE.Vector3(0, 0, 1);
28862 this._up = new THREE.Vector3(0, -1, 0);
28866 Object.defineProperty(Camera.prototype, "position", {
28869 * @returns {THREE.Vector3} The position vector.
28872 return this._position;
28877 Object.defineProperty(Camera.prototype, "lookat", {
28880 * @returns {THREE.Vector3} The lookat vector.
28883 return this._lookat;
28888 Object.defineProperty(Camera.prototype, "up", {
28891 * @returns {THREE.Vector3} The up vector.
28899 Object.defineProperty(Camera.prototype, "focal", {
28902 * @returns {number} The focal length.
28905 return this._focal;
28910 set: function (value) {
28911 this._focal = value;
28917 * Update this camera to the linearly interpolated value of two other cameras.
28919 * @param {Camera} a - First camera.
28920 * @param {Camera} b - Second camera.
28921 * @param {number} alpha - Interpolation value on the interval [0, 1].
28923 Camera.prototype.lerpCameras = function (a, b, alpha) {
28924 this._position.subVectors(b.position, a.position).multiplyScalar(alpha).add(a.position);
28925 this._lookat.subVectors(b.lookat, a.lookat).multiplyScalar(alpha).add(a.lookat);
28926 this._up.subVectors(b.up, a.up).multiplyScalar(alpha).add(a.up);
28927 this._focal = (1 - alpha) * a.focal + alpha * b.focal;
28930 * Copy the properties of another camera to this camera.
28932 * @param {Camera} other - Another camera.
28934 Camera.prototype.copy = function (other) {
28935 this._position.copy(other.position);
28936 this._lookat.copy(other.lookat);
28937 this._up.copy(other.up);
28938 this._focal = other.focal;
28941 * Clone this camera.
28943 * @returns {Camera} A camera with cloned properties equal to this camera.
28945 Camera.prototype.clone = function () {
28946 var camera = new Camera();
28947 camera.position.copy(this._position);
28948 camera.lookat.copy(this._lookat);
28949 camera.up.copy(this._up);
28950 camera.focal = this._focal;
28954 * Determine the distance between this camera and another camera.
28956 * @param {Camera} other - Another camera.
28957 * @returns {number} The distance between the cameras.
28959 Camera.prototype.diff = function (other) {
28960 var pd = this._position.distanceToSquared(other.position);
28961 var ld = this._lookat.distanceToSquared(other.lookat);
28962 var ud = this._up.distanceToSquared(other.up);
28963 var fd = 100 * Math.abs(this._focal - other.focal);
28964 return Math.max(pd, ld, ud, fd);
28967 * Get the focal length based on the transform.
28969 * @description Returns the focal length of the transform if gpano info is not available.
28970 * Returns a focal length corresponding to a vertical fov clamped to [45, 90] degrees based on
28971 * the gpano information if available.
28973 * @returns {number} Focal length.
28975 Camera.prototype._getFocal = function (transform) {
28976 if (transform.gpano == null) {
28977 return transform.focal;
28979 var vFov = Math.PI * transform.gpano.CroppedAreaImageHeightPixels / transform.gpano.FullPanoHeightPixels;
28980 var focal = 0.5 / Math.tan(vFov / 2);
28981 return Math.min(1 / (2 * (Math.sqrt(2) - 1)), Math.max(0.5, focal));
28985 exports.Camera = Camera;
28987 },{"three":175}],302:[function(require,module,exports){
28992 * @classdesc Converts coordinates between the geodetic (WGS84),
28993 * Earth-Centered, Earth-Fixed (ECEF) and local topocentric
28994 * East, North, Up (ENU) reference frames.
28996 * The WGS84 has latitude (degrees), longitude (degrees) and
28997 * altitude (meters) values.
28999 * The ECEF Z-axis pierces the north pole and the
29000 * XY-axis defines the equatorial plane. The X-axis extends
29001 * from the geocenter to the intersection of the Equator and
29002 * the Greenwich Meridian. All values in meters.
29004 * The WGS84 parameters are:
29008 * f = 1 / 298.257223563
29009 * e = Math.sqrt((a^2 - b^2) / a^2)
29010 * e' = Math.sqrt((a^2 - b^2) / b^2)
29012 * The WGS84 to ECEF conversion is performed using the following:
29014 * X = (N - h) * cos(phi) * cos(lambda)
29015 * Y = (N + h) * cos(phi) * sin(lambda)
29016 * Z = (b^2 * N / a^2 + h) * sin(phi)
29021 * lambda = longitude
29022 * h = height above ellipsoid (altitude)
29023 * N = Radius of curvature (meters)
29024 * = a / Math.sqrt(1 - e^2 * sin(phi)^2)
29026 * The ECEF to WGS84 conversion is performed using the following:
29028 * phi = arctan((Z + e'^2 * b * sin(theta)^3) / (p - e^2 * a * cos(theta)^3))
29029 * lambda = arctan(Y / X)
29030 * h = p / cos(phi) - N
29034 * p = Math.sqrt(X^2 + Y^2)
29035 * theta = arctan(Z * a / p * b)
29037 * In the ENU reference frame the x-axis points to the
29038 * East, the y-axis to the North and the z-axis Up. All values
29041 * The ECEF to ENU conversion is performed using the following:
29043 * | x | | -sin(lambda_r) cos(lambda_r) 0 | | X - X_r |
29044 * | y | = | -sin(phi_r) * cos(lambda_r) -sin(phi_r) * sin(lambda_r) cos(phi_r) | | Y - Y_r |
29045 * | z | | cos(phi_r) * cos(lambda_r) cos(phi_r) * sin(lambda_r) sin(phi_r) | | Z - Z_r |
29049 * phi_r = latitude of reference
29050 * lambda_r = longitude of reference
29051 * X_r, Y_r, Z_r = ECEF coordinates of reference
29053 * The ENU to ECEF conversion is performed by solving the above equation for X, Y, Z.
29055 * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in
29056 * the first step for both conversions.
29058 var GeoCoords = (function () {
29059 function GeoCoords() {
29060 this._wgs84a = 6378137.0;
29061 this._wgs84b = 6356752.31424518;
29064 * Convert coordinates from geodetic (WGS84) reference to local topocentric
29067 * @param {number} lat Latitude in degrees.
29068 * @param {number} lon Longitude in degrees.
29069 * @param {number} alt Altitude in meters.
29070 * @param {number} refLat Reference latitude in degrees.
29071 * @param {number} refLon Reference longitude in degrees.
29072 * @param {number} refAlt Reference altitude in meters.
29073 * @returns {Array<number>} The x, y, z local topocentric ENU coordinates.
29075 GeoCoords.prototype.geodeticToEnu = function (lat, lon, alt, refLat, refLon, refAlt) {
29076 var ecef = this.geodeticToEcef(lat, lon, alt);
29077 return this.ecefToEnu(ecef[0], ecef[1], ecef[2], refLat, refLon, refAlt);
29080 * Convert coordinates from local topocentric (ENU) reference to
29081 * geodetic (WGS84) reference.
29083 * @param {number} x Topocentric ENU coordinate in East direction.
29084 * @param {number} y Topocentric ENU coordinate in North direction.
29085 * @param {number} z Topocentric ENU coordinate in Up direction.
29086 * @param {number} refLat Reference latitude in degrees.
29087 * @param {number} refLon Reference longitude in degrees.
29088 * @param {number} refAlt Reference altitude in meters.
29089 * @returns {Array<number>} The latitude and longitude in degrees
29090 * as well as altitude in meters.
29092 GeoCoords.prototype.enuToGeodetic = function (x, y, z, refLat, refLon, refAlt) {
29093 var ecef = this.enuToEcef(x, y, z, refLat, refLon, refAlt);
29094 return this.ecefToGeodetic(ecef[0], ecef[1], ecef[2]);
29097 * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
29098 * to local topocentric (ENU) reference.
29100 * @param {number} X ECEF X-value.
29101 * @param {number} Y ECEF Y-value.
29102 * @param {number} Z ECEF Z-value.
29103 * @param {number} refLat Reference latitude in degrees.
29104 * @param {number} refLon Reference longitude in degrees.
29105 * @param {number} refAlt Reference altitude in meters.
29106 * @returns {Array<number>} The x, y, z topocentric ENU coordinates in East, North
29107 * and Up directions respectively.
29109 GeoCoords.prototype.ecefToEnu = function (X, Y, Z, refLat, refLon, refAlt) {
29110 var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
29111 var V = [X - refEcef[0], Y - refEcef[1], Z - refEcef[2]];
29112 refLat = refLat * Math.PI / 180.0;
29113 refLon = refLon * Math.PI / 180.0;
29114 var cosLat = Math.cos(refLat);
29115 var sinLat = Math.sin(refLat);
29116 var cosLon = Math.cos(refLon);
29117 var sinLon = Math.sin(refLon);
29118 var x = -sinLon * V[0] + cosLon * V[1];
29119 var y = -sinLat * cosLon * V[0] - sinLat * sinLon * V[1] + cosLat * V[2];
29120 var z = cosLat * cosLon * V[0] + cosLat * sinLon * V[1] + sinLat * V[2];
29124 * Convert coordinates from local topocentric (ENU) reference
29125 * to Earth-Centered, Earth-Fixed (ECEF) reference.
29127 * @param {number} x Topocentric ENU coordinate in East direction.
29128 * @param {number} y Topocentric ENU coordinate in North direction.
29129 * @param {number} z Topocentric ENU coordinate in Up direction.
29130 * @param {number} refLat Reference latitude in degrees.
29131 * @param {number} refLon Reference longitude in degrees.
29132 * @param {number} refAlt Reference altitude in meters.
29133 * @returns {Array<number>} The X, Y, Z ECEF coordinates.
29135 GeoCoords.prototype.enuToEcef = function (x, y, z, refLat, refLon, refAlt) {
29136 var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
29137 refLat = refLat * Math.PI / 180.0;
29138 refLon = refLon * Math.PI / 180.0;
29139 var cosLat = Math.cos(refLat);
29140 var sinLat = Math.sin(refLat);
29141 var cosLon = Math.cos(refLon);
29142 var sinLon = Math.sin(refLon);
29143 var X = -sinLon * x - sinLat * cosLon * y + cosLat * cosLon * z + refEcef[0];
29144 var Y = cosLon * x - sinLat * sinLon * y + cosLat * sinLon * z + refEcef[1];
29145 var Z = cosLat * y + sinLat * z + refEcef[2];
29149 * Convert coordinates from geodetic reference (WGS84) to Earth-Centered,
29150 * Earth-Fixed (ECEF) reference.
29152 * @param {number} lat Latitude in degrees.
29153 * @param {number} lon Longitude in degrees.
29154 * @param {number} alt Altitude in meters.
29155 * @returns {Array<number>} The X, Y, Z ECEF coordinates.
29157 GeoCoords.prototype.geodeticToEcef = function (lat, lon, alt) {
29158 var a = this._wgs84a;
29159 var b = this._wgs84b;
29160 lat = lat * Math.PI / 180.0;
29161 lon = lon * Math.PI / 180.0;
29162 var cosLat = Math.cos(lat);
29163 var sinLat = Math.sin(lat);
29164 var cosLon = Math.cos(lon);
29165 var sinLon = Math.sin(lon);
29168 var L = 1.0 / Math.sqrt(a2 * cosLat * cosLat + b2 * sinLat * sinLat);
29169 var nhcl = (a2 * L + alt) * cosLat;
29170 var X = nhcl * cosLon;
29171 var Y = nhcl * sinLon;
29172 var Z = (b2 * L + alt) * sinLat;
29176 * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
29177 * to geodetic reference (WGS84).
29179 * @param {number} X ECEF X-value.
29180 * @param {number} Y ECEF Y-value.
29181 * @param {number} Z ECEF Z-value.
29182 * @returns {Array<number>} The latitude and longitude in degrees
29183 * as well as altitude in meters.
29185 GeoCoords.prototype.ecefToGeodetic = function (X, Y, Z) {
29186 var a = this._wgs84a;
29187 var b = this._wgs84b;
29190 var a2mb2 = a2 - b2;
29191 var ea = Math.sqrt(a2mb2 / a2);
29192 var eb = Math.sqrt(a2mb2 / b2);
29193 var p = Math.sqrt(X * X + Y * Y);
29194 var theta = Math.atan2(Z * a, p * b);
29195 var sinTheta = Math.sin(theta);
29196 var cosTheta = Math.cos(theta);
29197 var lon = Math.atan2(Y, X);
29198 var lat = Math.atan2(Z + eb * eb * b * sinTheta * sinTheta * sinTheta, p - ea * ea * a * cosTheta * cosTheta * cosTheta);
29199 var sinLat = Math.sin(lat);
29200 var cosLat = Math.cos(lat);
29201 var N = a / Math.sqrt(1 - ea * ea * sinLat * sinLat);
29202 var alt = p / cosLat - N;
29203 return [lat * 180.0 / Math.PI, lon * 180.0 / Math.PI, alt];
29207 exports.GeoCoords = GeoCoords;
29208 Object.defineProperty(exports, "__esModule", { value: true });
29209 exports.default = GeoCoords;
29211 },{}],303:[function(require,module,exports){
29212 /// <reference path="../../typings/index.d.ts" />
29214 var THREE = require("three");
29218 * @classdesc Provides methods for scalar, vector and matrix calculations.
29220 var Spatial = (function () {
29221 function Spatial() {
29222 this._epsilon = 1e-9;
29225 * Converts azimuthal phi rotation (counter-clockwise with origin on X-axis) to
29226 * bearing (clockwise with origin at north or Y-axis).
29228 * @param {number} phi - Azimuthal phi angle in radians.
29229 * @returns {number} Bearing in radians.
29231 Spatial.prototype.azimuthalToBearing = function (phi) {
29232 return -phi + Math.PI / 2;
29235 * Converts degrees to radians.
29237 * @param {number} deg - Degrees.
29238 * @returns {number} Radians.
29240 Spatial.prototype.degToRad = function (deg) {
29241 return Math.PI * deg / 180;
29244 * Converts radians to degrees.
29246 * @param {number} rad - Radians.
29247 * @returns {number} Degrees.
29249 Spatial.prototype.radToDeg = function (rad) {
29250 return 180 * rad / Math.PI;
29253 * Creates a rotation matrix from an angle-axis vector.
29255 * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
29256 * @returns {THREE.Matrix4} Rotation matrix.
29258 Spatial.prototype.rotationMatrix = function (angleAxis) {
29259 var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]);
29260 var angle = axis.length();
29262 return new THREE.Matrix4().makeRotationAxis(axis, angle);
29265 * Rotates a vector according to a angle-axis rotation vector.
29267 * @param {Array<number>} vector - Vector to rotate.
29268 * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
29269 * @returns {THREE.Vector3} Rotated vector.
29271 Spatial.prototype.rotate = function (vector, angleAxis) {
29272 var v = new THREE.Vector3(vector[0], vector[1], vector[2]);
29273 var rotationMatrix = this.rotationMatrix(angleAxis);
29274 v.applyMatrix4(rotationMatrix);
29278 * Calculates the optical center from a rotation vector
29279 * on the angle-axis representation and a translation vector
29280 * according to C = -R^T t.
29282 * @param {Array<number>} rotation - Angle-axis representation of a rotation.
29283 * @param {Array<number>} translation - Translation vector.
29284 * @returns {THREE.Vector3} Optical center.
29286 Spatial.prototype.opticalCenter = function (rotation, translation) {
29287 var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
29288 var vector = [-translation[0], -translation[1], -translation[2]];
29289 return this.rotate(vector, angleAxis);
29292 * Calculates the viewing direction from a rotation vector
29293 * on the angle-axis representation.
29295 * @param {number[]} rotation - Angle-axis representation of a rotation.
29296 * @returns {THREE.Vector3} Viewing direction.
29298 Spatial.prototype.viewingDirection = function (rotation) {
29299 var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
29300 return this.rotate([0, 0, 1], angleAxis);
29303 * Wrap a number on the interval [min, max].
29305 * @param {number} value - Value to wrap.
29306 * @param {number} min - Lower endpoint of interval.
29307 * @param {number} max - Upper endpoint of interval.
29308 * @returns {number} The wrapped number.
29310 Spatial.prototype.wrap = function (value, min, max) {
29312 throw new Error("Invalid arguments: max must be larger than min.");
29314 var interval = (max - min);
29315 while (value > max || value < min) {
29317 value = value - interval;
29319 else if (value < min) {
29320 value = value + interval;
29326 * Wrap an angle on the interval [-Pi, Pi].
29328 * @param {number} angle - Value to wrap.
29329 * @returns {number} Wrapped angle.
29331 Spatial.prototype.wrapAngle = function (angle) {
29332 return this.wrap(angle, -Math.PI, Math.PI);
29335 * Limit the value to the interval [min, max] by changing the value to
29336 * the nearest available one when it is outside the interval.
29338 * @param {number} value - Value to clamp.
29339 * @param {number} min - Minimum of the interval.
29340 * @param {number} max - Maximum of the interval.
29341 * @returns {number} Clamped value.
29343 Spatial.prototype.clamp = function (value, min, max) {
29353 * Calculates the counter-clockwise angle from the first
29354 * vector (x1, y1)^T to the second (x2, y2)^T.
29356 * @param {number} x1 - X coordinate of first vector.
29357 * @param {number} y1 - Y coordinate of first vector.
29358 * @param {number} x2 - X coordinate of second vector.
29359 * @param {number} y2 - Y coordinate of second vector.
29360 * @returns {number} Counter clockwise angle between the vectors.
29362 Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) {
29363 var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1);
29364 return this.wrapAngle(angle);
29367 * Calculates the minimum (absolute) angle change for rotation
29368 * from one angle to another on the [-Pi, Pi] interval.
29370 * @param {number} angle1 - Start angle.
29371 * @param {number} angle2 - Destination angle.
29372 * @returns {number} Absolute angle change between angles.
29374 Spatial.prototype.angleDifference = function (angle1, angle2) {
29375 var angle = angle2 - angle1;
29376 return this.wrapAngle(angle);
29379 * Calculates the relative rotation angle between two
29380 * angle-axis vectors.
29382 * @param {number} rotation1 - First angle-axis vector.
29383 * @param {number} rotation2 - Second angle-axis vector.
29384 * @returns {number} Relative rotation angle.
29386 Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) {
29387 var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]);
29388 var R2 = this.rotationMatrix(rotation2);
29389 var R = R1T.multiply(R2);
29390 var elements = R.elements;
29391 // from Tr(R) = 1 + 2*cos(theta)
29392 var theta = Math.acos((elements[0] + elements[5] + elements[10] - 1) / 2);
29396 * Calculates the angle from a vector to a plane.
29398 * @param {Array<number>} vector - The vector.
29399 * @param {Array<number>} planeNormal - Normal of the plane.
29400 * @returns {number} Angle from between plane and vector.
29402 Spatial.prototype.angleToPlane = function (vector, planeNormal) {
29403 var v = new THREE.Vector3().fromArray(vector);
29404 var norm = v.length();
29405 if (norm < this._epsilon) {
29408 var projection = v.dot(new THREE.Vector3().fromArray(planeNormal));
29409 return Math.asin(projection / norm);
29412 * Calculates the distance between two coordinates
29413 * (latitude longitude pairs) in meters according to
29414 * the haversine formula.
29416 * @param {number} lat1 - Latitude of the first coordinate.
29417 * @param {number} lon1 - Longitude of the first coordinate.
29418 * @param {number} lat2 - Latitude of the second coordinate.
29419 * @param {number} lon2 - Longitude of the second coordinate.
29420 * @returns {number} Distance between lat lon positions.
29422 Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) {
29424 var dLat = this.degToRad(lat2 - lat1);
29425 var dLon = this.degToRad(lon2 - lon1);
29426 var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
29427 Math.cos(lat1) * Math.cos(lat2) *
29428 Math.sin(dLon / 2) * Math.sin(dLon / 2);
29429 var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav));
29434 exports.Spatial = Spatial;
29435 Object.defineProperty(exports, "__esModule", { value: true });
29436 exports.default = Spatial;
29438 },{"three":175}],304:[function(require,module,exports){
29439 /// <reference path="../../typings/index.d.ts" />
29441 var THREE = require("three");
29445 * @classdesc Class used for calculating coordinate transformations
29448 var Transform = (function () {
29450 * Create a new transform instance.
29451 * @param {Node} apiNavImIm - Node properties.
29452 * @param {HTMLImageElement} image - Node image.
29453 * @param {Array<number>} translation - Node translation vector in three dimensions.
29455 function Transform(node, image, translation) {
29456 this._orientation = this._getValue(node.orientation, 1);
29457 var imageWidth = image != null ? image.width : 4;
29458 var imageHeight = image != null ? image.height : 3;
29459 var keepOrientation = this._orientation < 5;
29460 this._width = this._getValue(node.width, keepOrientation ? imageWidth : imageHeight);
29461 this._height = this._getValue(node.height, keepOrientation ? imageHeight : imageWidth);
29462 this._basicAspect = keepOrientation ?
29463 this._width / this._height :
29464 this._height / this._width;
29465 this._basicWidth = keepOrientation ? node.width : node.height;
29466 this._basicHeight = keepOrientation ? node.height : node.width;
29467 this._focal = this._getValue(node.focal, 1);
29468 this._scale = this._getValue(node.scale, 0);
29469 this._gpano = node.gpano != null ? node.gpano : null;
29470 this._rt = this._getRt(node.rotation, translation);
29471 this._srt = this._getSrt(this._rt, this._scale);
29473 Object.defineProperty(Transform.prototype, "basicAspect", {
29475 * Get basic aspect.
29476 * @returns {number} The orientation adjusted aspect ratio.
29479 return this._basicAspect;
29484 Object.defineProperty(Transform.prototype, "basicHeight", {
29486 * Get basic height.
29488 * @description Does not fall back to node image height but
29489 * uses original value from API so can be faulty.
29491 * @returns {number} The height of the basic version image
29492 * (adjusted for orientation).
29495 return this._basicHeight;
29500 Object.defineProperty(Transform.prototype, "basicWidth", {
29504 * @description Does not fall back to node image width but
29505 * uses original value from API so can be faulty.
29507 * @returns {number} The width of the basic version image
29508 * (adjusted for orientation).
29511 return this._basicWidth;
29516 Object.defineProperty(Transform.prototype, "focal", {
29519 * @returns {number} The node focal length.
29522 return this._focal;
29527 Object.defineProperty(Transform.prototype, "fullPano", {
29531 * @returns {boolean} Value indicating whether the node is a complete
29535 return this._gpano != null &&
29536 this._gpano.CroppedAreaLeftPixels === 0 &&
29537 this._gpano.CroppedAreaTopPixels === 0 &&
29538 this._gpano.CroppedAreaImageWidthPixels === this._gpano.FullPanoWidthPixels &&
29539 this._gpano.CroppedAreaImageHeightPixels === this._gpano.FullPanoHeightPixels;
29544 Object.defineProperty(Transform.prototype, "gpano", {
29547 * @returns {number} The node gpano information.
29550 return this._gpano;
29555 Object.defineProperty(Transform.prototype, "height", {
29559 * @description Falls back to the node image height if
29560 * the API data is faulty.
29562 * @returns {number} The orientation adjusted image height.
29565 return this._height;
29570 Object.defineProperty(Transform.prototype, "orientation", {
29573 * @returns {number} The image orientation.
29576 return this._orientation;
29581 Object.defineProperty(Transform.prototype, "rt", {
29584 * @returns {THREE.Matrix4} The extrinsic camera matrix.
29592 Object.defineProperty(Transform.prototype, "srt", {
29595 * @returns {THREE.Matrix4} The scaled extrinsic camera matrix.
29603 Object.defineProperty(Transform.prototype, "scale", {
29606 * @returns {number} The node atomic reconstruction scale.
29609 return this._scale;
29614 Object.defineProperty(Transform.prototype, "hasValidScale", {
29616 * Get has valid scale.
29617 * @returns {boolean} Value indicating if the scale of the transform is valid.
29620 return this._scale > 1e-2 && this._scale < 50;
29625 Object.defineProperty(Transform.prototype, "width", {
29629 * @description Falls back to the node image width if
29630 * the API data is faulty.
29632 * @returns {number} The orientation adjusted image width.
29635 return this._width;
29641 * Calculate the up vector for the node transform.
29643 * @returns {THREE.Vector3} Normalized and orientation adjusted up vector.
29645 Transform.prototype.upVector = function () {
29646 var rte = this._rt.elements;
29647 switch (this._orientation) {
29649 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
29651 return new THREE.Vector3(rte[1], rte[5], rte[9]);
29653 return new THREE.Vector3(-rte[0], -rte[4], -rte[8]);
29655 return new THREE.Vector3(rte[0], rte[4], rte[8]);
29657 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
29661 * Calculate projector matrix for projecting 3D points to texture map
29662 * coordinates (u and v).
29664 * @returns {THREE.Matrix4} Projection matrix for 3D point to texture
29665 * map coordinate calculations.
29667 Transform.prototype.projectorMatrix = function () {
29668 var projector = this._normalizedToTextureMatrix();
29669 var f = this._focal;
29670 var projection = new THREE.Matrix4().set(f, 0, 0, 0, 0, f, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
29671 projector.multiply(projection);
29672 projector.multiply(this._rt);
29676 * Project 3D world coordinates to basic coordinates.
29678 * @param {Array<number>} point3d - 3D world coordinates.
29679 * @return {Array<number>} 2D basic coordinates.
29681 Transform.prototype.projectBasic = function (point3d) {
29682 var sfm = this.projectSfM(point3d);
29683 return this._sfmToBasic(sfm);
29686 * Unproject basic coordinates to 3D world coordinates.
29688 * @param {Array<number>} basic - 2D basic coordinates.
29689 * @param {Array<number>} distance - Depth to unproject from camera center.
29690 * @returns {Array<number>} Unprojected 3D world coordinates.
29692 Transform.prototype.unprojectBasic = function (basic, distance) {
29693 var sfm = this._basicToSfm(basic);
29694 return this.unprojectSfM(sfm, distance);
29697 * Project 3D world coordinates to SfM coordinates.
29699 * @param {Array<number>} point3d - 3D world coordinates.
29700 * @return {Array<number>} 2D SfM coordinates.
29702 Transform.prototype.projectSfM = function (point3d) {
29703 var v = new THREE.Vector4(point3d[0], point3d[1], point3d[2], 1);
29704 v.applyMatrix4(this._rt);
29705 return this._bearingToSfm([v.x, v.y, v.z]);
29708 * Unproject SfM coordinates to a 3D world coordinates.
29710 * @param {Array<number>} sfm - 2D SfM coordinates.
29711 * @param {Array<number>} distance - Depth to unproject from camera center.
29712 * @returns {Array<number>} Unprojected 3D world coordinates.
29714 Transform.prototype.unprojectSfM = function (sfm, distance) {
29715 var bearing = this._sfmToBearing(sfm);
29716 var v = new THREE.Vector4(distance * bearing[0], distance * bearing[1], distance * bearing[2], 1);
29717 v.applyMatrix4(new THREE.Matrix4().getInverse(this._rt));
29718 return [v.x / v.w, v.y / v.w, v.z / v.w];
29721 * Transform SfM coordinates to bearing vector (3D cartesian
29722 * coordinates on the unit sphere).
29724 * @param {Array<number>} sfm - 2D SfM coordinates.
29725 * @returns {Array<number>} Bearing vector (3D cartesian coordinates
29726 * on the unit sphere).
29728 Transform.prototype._sfmToBearing = function (sfm) {
29729 if (this._fullPano()) {
29730 var lon = sfm[0] * 2 * Math.PI;
29731 var lat = -sfm[1] * 2 * Math.PI;
29732 var x = Math.cos(lat) * Math.sin(lon);
29733 var y = -Math.sin(lat);
29734 var z = Math.cos(lat) * Math.cos(lon);
29737 else if (this._gpano) {
29738 var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
29739 var fullPanoPixel = [
29740 sfm[0] * size + this.gpano.CroppedAreaImageWidthPixels / 2 + this.gpano.CroppedAreaLeftPixels,
29741 sfm[1] * size + this.gpano.CroppedAreaImageHeightPixels / 2 + this.gpano.CroppedAreaTopPixels,
29743 var lon = 2 * Math.PI * (fullPanoPixel[0] / this.gpano.FullPanoWidthPixels - 0.5);
29744 var lat = -Math.PI * (fullPanoPixel[1] / this.gpano.FullPanoHeightPixels - 0.5);
29745 var x = Math.cos(lat) * Math.sin(lon);
29746 var y = -Math.sin(lat);
29747 var z = Math.cos(lat) * Math.cos(lon);
29751 var v = new THREE.Vector3(sfm[0], sfm[1], this._focal);
29753 return [v.x, v.y, v.z];
29757 * Transform bearing vector (3D cartesian coordiantes on the unit sphere) to
29760 * @param {Array<number>} bearing - Bearing vector (3D cartesian coordinates on the
29762 * @returns {Array<number>} 2D SfM coordinates.
29764 Transform.prototype._bearingToSfm = function (bearing) {
29765 if (this._fullPano()) {
29766 var x = bearing[0];
29767 var y = bearing[1];
29768 var z = bearing[2];
29769 var lon = Math.atan2(x, z);
29770 var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
29771 return [lon / (2 * Math.PI), -lat / (2 * Math.PI)];
29773 else if (this._gpano) {
29774 var x = bearing[0];
29775 var y = bearing[1];
29776 var z = bearing[2];
29777 var lon = Math.atan2(x, z);
29778 var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
29779 var fullPanoPixel = [
29780 (lon / (2 * Math.PI) + 0.5) * this.gpano.FullPanoWidthPixels,
29781 (-lat / Math.PI + 0.5) * this.gpano.FullPanoHeightPixels,
29783 var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
29785 (fullPanoPixel[0] - this.gpano.CroppedAreaLeftPixels - this.gpano.CroppedAreaImageWidthPixels / 2) / size,
29786 (fullPanoPixel[1] - this.gpano.CroppedAreaTopPixels - this.gpano.CroppedAreaImageHeightPixels / 2) / size,
29790 if (bearing[2] > 0) {
29792 bearing[0] * this._focal / bearing[2],
29793 bearing[1] * this._focal / bearing[2],
29798 bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
29799 bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
29805 * Convert basic coordinates to SfM coordinates.
29807 * @param {Array<number>} basic - 2D basic coordinates.
29808 * @returns {Array<number>} 2D SfM coordinates.
29810 Transform.prototype._basicToSfm = function (basic) {
29813 switch (this._orientation) {
29815 rotatedX = basic[0];
29816 rotatedY = basic[1];
29819 rotatedX = 1 - basic[0];
29820 rotatedY = 1 - basic[1];
29823 rotatedX = basic[1];
29824 rotatedY = 1 - basic[0];
29827 rotatedX = 1 - basic[1];
29828 rotatedY = basic[0];
29831 rotatedX = basic[0];
29832 rotatedY = basic[1];
29835 var w = this._width;
29836 var h = this._height;
29837 var s = Math.max(w, h);
29838 var sfmX = rotatedX * w / s - w / s / 2;
29839 var sfmY = rotatedY * h / s - h / s / 2;
29840 return [sfmX, sfmY];
29843 * Convert SfM coordinates to basic coordinates.
29845 * @param {Array<number>} sfm - 2D SfM coordinates.
29846 * @returns {Array<number>} 2D basic coordinates.
29848 Transform.prototype._sfmToBasic = function (sfm) {
29849 var w = this._width;
29850 var h = this._height;
29851 var s = Math.max(w, h);
29852 var rotatedX = (sfm[0] + w / s / 2) / w * s;
29853 var rotatedY = (sfm[1] + h / s / 2) / h * s;
29856 switch (this._orientation) {
29862 basicX = 1 - rotatedX;
29863 basicY = 1 - rotatedY;
29866 basicX = 1 - rotatedY;
29871 basicY = 1 - rotatedX;
29878 return [basicX, basicY];
29881 * Determines if the gpano information indicates a full panorama.
29883 * @returns {boolean} Value determining if the gpano information indicates
29886 Transform.prototype._fullPano = function () {
29887 return this.gpano != null &&
29888 this.gpano.CroppedAreaLeftPixels === 0 &&
29889 this.gpano.CroppedAreaTopPixels === 0 &&
29890 this.gpano.CroppedAreaImageWidthPixels === this.gpano.FullPanoWidthPixels &&
29891 this.gpano.CroppedAreaImageHeightPixels === this.gpano.FullPanoHeightPixels;
29894 * Checks a value and returns it if it exists and is larger than 0.
29895 * Fallbacks if it is null.
29897 * @param {number} value - Value to check.
29898 * @param {number} fallback - Value to fall back to.
29899 * @returns {number} The value or its fallback value if it is not defined or negative.
29901 Transform.prototype._getValue = function (value, fallback) {
29902 return value != null && value > 0 ? value : fallback;
29905 * Creates the extrinsic camera matrix [ R | t ].
29907 * @param {Array<number>} rotation - Rotation vector in angle axis representation.
29908 * @param {Array<number>} translation - Translation vector.
29909 * @returns {THREE.Matrix4} Extrisic camera matrix.
29911 Transform.prototype._getRt = function (rotation, translation) {
29912 var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]);
29913 var angle = axis.length();
29915 var rt = new THREE.Matrix4();
29916 rt.makeRotationAxis(axis, angle);
29917 rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2]));
29921 * Calculates the scaled extrinsic camera matrix scale * [ R | t ].
29923 * @param {THREE.Matrix4} rt - Extrisic camera matrix.
29924 * @param {number} scale - Scale factor.
29925 * @returns {THREE.Matrix4} Scaled extrisic camera matrix.
29927 Transform.prototype._getSrt = function (rt, scale) {
29928 var srt = rt.clone();
29929 var elements = srt.elements;
29930 elements[12] = scale * elements[12];
29931 elements[13] = scale * elements[13];
29932 elements[14] = scale * elements[14];
29933 srt.scale(new THREE.Vector3(scale, scale, scale));
29937 * Calculate a transformation matrix from normalized coordinates for
29938 * texture map coordinates.
29940 * @returns {THREE.Matrix4} Normalized coordinates to texture map
29941 * coordinates transformation matrix.
29943 Transform.prototype._normalizedToTextureMatrix = function () {
29944 var size = Math.max(this._width, this._height);
29945 var w = size / this._width;
29946 var h = size / this._height;
29947 switch (this._orientation) {
29949 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
29951 return new THREE.Matrix4().set(-w, 0, 0, 0.5, 0, h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
29953 return new THREE.Matrix4().set(0, -h, 0, 0.5, -w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
29955 return new THREE.Matrix4().set(0, h, 0, 0.5, w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
29957 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
29962 exports.Transform = Transform;
29964 },{"three":175}],305:[function(require,module,exports){
29965 /// <reference path="../../typings/index.d.ts" />
29967 var THREE = require("three");
29969 * @class ViewportCoords
29971 * @classdesc Provides methods for calculating 2D coordinate conversions
29972 * as well as 3D projection and unprojection.
29974 * Basic coordinates are 2D coordinates on the [0, 1] interval and
29975 * have the origin point, (0, 0), at the top left corner and the
29976 * maximum value, (1, 1), at the bottom right corner of the original
29979 * Viewport coordinates are 2D coordinates on the [-1, 1] interval and
29980 * have the origin point in the center. The bottom left corner point is
29981 * (-1, -1) and the top right corner point is (1, 1).
29983 * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and
29984 * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left
29985 * corner and the maximum value is (canvasWidth, canvasHeight) is in the
29986 * bottom right corner.
29988 * 3D coordinates are in the topocentric world reference frame.
29990 var ViewportCoords = (function () {
29991 function ViewportCoords() {
29992 this._unprojectDepth = 200;
29995 * Convert basic coordinates to canvas coordinates.
29997 * @description Transform origin and perspective camera position needs to be the
29998 * equal for reliable return value.
30000 * @param {number} basicX - Basic X coordinate.
30001 * @param {number} basicY - Basic Y coordinate.
30002 * @param {HTMLElement} container - The viewer container.
30003 * @param {Transform} transform - Transform of the node to unproject from.
30004 * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
30005 * @returns {Array<number>} 2D canvas coordinates.
30007 ViewportCoords.prototype.basicToCanvas = function (basicX, basicY, container, transform, perspectiveCamera) {
30008 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
30009 var canvas = this.projectToCanvas(point3d, container, perspectiveCamera);
30013 * Convert basic coordinates to viewport coordinates.
30015 * @description Transform origin and perspective camera position needs to be the
30016 * equal for reliable return value.
30018 * @param {number} basicX - Basic X coordinate.
30019 * @param {number} basicY - Basic Y coordinate.
30020 * @param {Transform} transform - Transform of the node to unproject from.
30021 * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
30022 * @returns {Array<number>} 2D viewport coordinates.
30024 ViewportCoords.prototype.basicToViewport = function (basicX, basicY, transform, perspectiveCamera) {
30025 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
30026 var viewport = this.projectToViewport(point3d, perspectiveCamera);
30030 * Get canvas pixel position from event.
30032 * @param {Event} event - Event containing clientX and clientY properties.
30033 * @param {HTMLElement} element - HTML element.
30034 * @returns {Array<number>} 2D canvas coordinates.
30036 ViewportCoords.prototype.canvasPosition = function (event, element) {
30037 var clientRect = element.getBoundingClientRect();
30038 var canvasX = event.clientX - clientRect.left - element.clientLeft;
30039 var canvasY = event.clientY - clientRect.top - element.clientTop;
30040 return [canvasX, canvasY];
30043 * Convert canvas coordinates to basic coordinates.
30045 * @description Transform origin and perspective camera position needs to be the
30046 * equal for reliable return value.
30048 * @param {number} canvasX - Canvas X coordinate.
30049 * @param {number} canvasY - Canvas Y coordinate.
30050 * @param {HTMLElement} container - The viewer container.
30051 * @param {Transform} transform - Transform of the node to unproject from.
30052 * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
30053 * @returns {Array<number>} 2D basic coordinates.
30055 ViewportCoords.prototype.canvasToBasic = function (canvasX, canvasY, container, transform, perspectiveCamera) {
30056 var point3d = this.unprojectFromCanvas(canvasX, canvasY, container, perspectiveCamera)
30058 var basic = transform.projectBasic(point3d);
30062 * Convert canvas coordinates to viewport coordinates.
30064 * @param {number} canvasX - Canvas X coordinate.
30065 * @param {number} canvasY - Canvas Y coordinate.
30066 * @param {HTMLElement} container - The viewer container.
30067 * @returns {Array<number>} 2D viewport coordinates.
30069 ViewportCoords.prototype.canvasToViewport = function (canvasX, canvasY, container) {
30070 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
30071 var viewportX = 2 * canvasX / canvasWidth - 1;
30072 var viewportY = 1 - 2 * canvasY / canvasHeight;
30073 return [viewportX, viewportY];
30076 * Determines the width and height of the container in canvas coordinates.
30078 * @param {HTMLElement} container - The viewer container.
30079 * @returns {Array<number>} 2D canvas coordinates.
30081 ViewportCoords.prototype.containerToCanvas = function (container) {
30082 return [container.offsetWidth, container.offsetHeight];
30085 * Determine basic distances from image to canvas corners.
30087 * @description Transform origin and perspective camera position needs to be the
30088 * equal for reliable return value.
30090 * Determines the smallest basic distance for every side of the canvas.
30092 * @param {Transform} transform - Transform of the node to unproject from.
30093 * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
30094 * @returns {Array<number>} Array of basic distances as [top, right, bottom, left].
30096 ViewportCoords.prototype.getBasicDistances = function (transform, perspectiveCamera) {
30097 var topLeftBasic = this.viewportToBasic(-1, 1, transform, perspectiveCamera);
30098 var topRightBasic = this.viewportToBasic(1, 1, transform, perspectiveCamera);
30099 var bottomRightBasic = this.viewportToBasic(1, -1, transform, perspectiveCamera);
30100 var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, perspectiveCamera);
30101 var topBasicDistance = 0;
30102 var rightBasicDistance = 0;
30103 var bottomBasicDistance = 0;
30104 var leftBasicDistance = 0;
30105 if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
30106 topBasicDistance = topLeftBasic[1] > topRightBasic[1] ?
30110 if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
30111 rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ?
30112 topRightBasic[0] - 1 :
30113 bottomRightBasic[0] - 1;
30115 if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
30116 bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ?
30117 bottomRightBasic[1] - 1 :
30118 bottomLeftBasic[1] - 1;
30120 if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
30121 leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ?
30122 -bottomLeftBasic[0] :
30125 return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance];
30128 * Determine pixel distances from image to canvas corners.
30130 * @description Transform origin and perspective camera position needs to be the
30131 * equal for reliable return value.
30133 * Determines the smallest pixel distance for every side of the canvas.
30135 * @param {HTMLElement} container - The viewer container.
30136 * @param {Transform} transform - Transform of the node to unproject from.
30137 * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
30138 * @returns {Array<number>} Array of pixel distances as [top, right, bottom, left].
30140 ViewportCoords.prototype.getPixelDistances = function (container, transform, perspectiveCamera) {
30141 var topLeftBasic = this.viewportToBasic(-1, 1, transform, perspectiveCamera);
30142 var topRightBasic = this.viewportToBasic(1, 1, transform, perspectiveCamera);
30143 var bottomRightBasic = this.viewportToBasic(1, -1, transform, perspectiveCamera);
30144 var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, perspectiveCamera);
30145 var topPixelDistance = 0;
30146 var rightPixelDistance = 0;
30147 var bottomPixelDistance = 0;
30148 var leftPixelDistance = 0;
30149 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
30150 if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
30151 var basicX = topLeftBasic[1] > topRightBasic[1] ?
30154 var canvas = this.basicToCanvas(basicX, 0, container, transform, perspectiveCamera);
30155 topPixelDistance = canvas[1] > 0 ? canvas[1] : 0;
30157 if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
30158 var basicY = topRightBasic[0] < bottomRightBasic[0] ?
30160 bottomRightBasic[1];
30161 var canvas = this.basicToCanvas(1, basicY, container, transform, perspectiveCamera);
30162 rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0;
30164 if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
30165 var basicX = bottomRightBasic[1] < bottomLeftBasic[1] ?
30166 bottomRightBasic[0] :
30167 bottomLeftBasic[0];
30168 var canvas = this.basicToCanvas(basicX, 1, container, transform, perspectiveCamera);
30169 bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0;
30171 if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
30172 var basicY = bottomLeftBasic[0] > topLeftBasic[0] ?
30173 bottomLeftBasic[1] :
30175 var canvas = this.basicToCanvas(0, basicY, container, transform, perspectiveCamera);
30176 leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0;
30178 return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance];
30181 * Determine if an event occured inside an element.
30183 * @param {Event} event - Event containing clientX and clientY properties.
30184 * @param {HTMLElement} element - HTML element.
30185 * @returns {boolean} Value indicating if the event occured inside the element or not.
30187 ViewportCoords.prototype.insideElement = function (event, element) {
30188 var clientRect = element.getBoundingClientRect();
30189 var minX = clientRect.left + element.clientLeft;
30190 var maxX = minX + element.clientWidth;
30191 var minY = clientRect.top + element.clientTop;
30192 var maxY = minY + element.clientHeight;
30193 return event.clientX > minX &&
30194 event.clientX < maxX &&
30195 event.clientY > minY &&
30196 event.clientY < maxY;
30199 * Project 3D world coordinates to canvas coordinates.
30201 * @param {Array<number>} point3D - 3D world coordinates.
30202 * @param {HTMLElement} container - The viewer container.
30203 * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
30204 * @returns {Array<number>} 2D canvas coordinates.
30206 ViewportCoords.prototype.projectToCanvas = function (point3d, container, perspectiveCamera) {
30207 var viewport = this.projectToViewport(point3d, perspectiveCamera);
30208 var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
30212 * Project 3D world coordinates to viewport coordinates.
30214 * @param {Array<number>} point3D - 3D world coordinates.
30215 * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
30216 * @returns {Array<number>} 2D viewport coordinates.
30218 ViewportCoords.prototype.projectToViewport = function (point3d, perspectiveCamera) {
30219 var viewport = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
30220 .project(perspectiveCamera);
30221 return [viewport.x, viewport.y];
30224 * Uproject canvas coordinates to 3D world coordinates.
30226 * @param {number} canvasX - Canvas X coordinate.
30227 * @param {number} canvasY - Canvas Y coordinate.
30228 * @param {HTMLElement} container - The viewer container.
30229 * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
30230 * @returns {Array<number>} 3D world coordinates.
30232 ViewportCoords.prototype.unprojectFromCanvas = function (canvasX, canvasY, container, perspectiveCamera) {
30233 var viewport = this.canvasToViewport(canvasX, canvasY, container);
30234 var point3d = this.unprojectFromViewport(viewport[0], viewport[1], perspectiveCamera);
30238 * Unproject viewport coordinates to 3D world coordinates.
30240 * @param {number} viewportX - Viewport X coordinate.
30241 * @param {number} viewportY - Viewport Y coordinate.
30242 * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
30243 * @returns {Array<number>} 3D world coordinates.
30245 ViewportCoords.prototype.unprojectFromViewport = function (viewportX, viewportY, perspectiveCamera) {
30246 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
30247 .unproject(perspectiveCamera);
30251 * Convert viewport coordinates to basic coordinates.
30253 * @description Transform origin and perspective camera position needs to be the
30254 * equal for reliable return value.
30256 * @param {number} viewportX - Viewport X coordinate.
30257 * @param {number} viewportY - Viewport Y coordinate.
30258 * @param {Transform} transform - Transform of the node to unproject from.
30259 * @param {THREE.PerspectiveCamera} perspectiveCamera - Perspective camera used in rendering.
30260 * @returns {Array<number>} 2D basic coordinates.
30262 ViewportCoords.prototype.viewportToBasic = function (viewportX, viewportY, transform, perspectiveCamera) {
30263 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
30264 .unproject(perspectiveCamera)
30266 var basic = transform.projectBasic(point3d);
30270 * Convert viewport coordinates to canvas coordinates.
30272 * @param {number} viewportX - Viewport X coordinate.
30273 * @param {number} viewportY - Viewport Y coordinate.
30274 * @param {HTMLElement} container - The viewer container.
30275 * @returns {Array<number>} 2D canvas coordinates.
30277 ViewportCoords.prototype.viewportToCanvas = function (viewportX, viewportY, container) {
30278 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
30279 var canvasX = canvasWidth * (viewportX + 1) / 2;
30280 var canvasY = -canvasHeight * (viewportY - 1) / 2;
30281 return [canvasX, canvasY];
30283 return ViewportCoords;
30285 exports.ViewportCoords = ViewportCoords;
30286 Object.defineProperty(exports, "__esModule", { value: true });
30287 exports.default = ViewportCoords;
30289 },{"three":175}],306:[function(require,module,exports){
30294 * @classdesc Represents a class for creating node filters. Implementation and
30295 * definitions based on https://github.com/mapbox/feature-filter.
30297 var FilterCreator = (function () {
30298 function FilterCreator() {
30301 * Create a filter from a filter expression.
30303 * @description The following filters are supported:
30320 * @param {FilterExpression} filter - Comparison, set membership or combinding filter
30322 * @returns {FilterFunction} Function taking a node and returning a boolean that
30323 * indicates whether the node passed the test or not.
30325 FilterCreator.prototype.createFilter = function (filter) {
30326 return new Function("node", "return " + this._compile(filter) + ";");
30328 FilterCreator.prototype._compile = function (filter) {
30329 if (filter == null || filter.length <= 1) {
30332 var operator = filter[0];
30333 var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) :
30334 operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) :
30335 operator === ">" ||
30336 operator === ">=" ||
30337 operator === "<" ||
30338 operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) :
30339 operator === "in" ?
30340 this._compileInOp(filter[1], filter.slice(2)) :
30341 operator === "!in" ?
30342 this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) :
30343 operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") :
30345 return "(" + operation + ")";
30347 FilterCreator.prototype._compare = function (a, b) {
30348 return a < b ? -1 : a > b ? 1 : 0;
30350 FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) {
30351 var left = this._compilePropertyReference(property);
30352 var right = JSON.stringify(value);
30353 return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right;
30355 FilterCreator.prototype._compileInOp = function (property, values) {
30356 var compare = this._compare;
30357 var left = JSON.stringify(values.sort(compare));
30358 var right = this._compilePropertyReference(property);
30359 return left + ".indexOf(" + right + ")!==-1";
30361 FilterCreator.prototype._compileLogicalOp = function (filters, operator) {
30362 var compile = this._compile.bind(this);
30363 return filters.map(compile).join(operator);
30365 FilterCreator.prototype._compileNegation = function (expression) {
30366 return "!(" + expression + ")";
30368 FilterCreator.prototype._compilePropertyReference = function (property) {
30369 return "node[" + JSON.stringify(property) + "]";
30371 return FilterCreator;
30373 exports.FilterCreator = FilterCreator;
30374 Object.defineProperty(exports, "__esModule", { value: true });
30375 exports.default = FilterCreator;
30377 },{}],307:[function(require,module,exports){
30378 /// <reference path="../../typings/index.d.ts" />
30380 var rbush = require("rbush");
30381 var Subject_1 = require("rxjs/Subject");
30382 require("rxjs/add/observable/from");
30383 require("rxjs/add/operator/catch");
30384 require("rxjs/add/operator/do");
30385 require("rxjs/add/operator/finally");
30386 require("rxjs/add/operator/map");
30387 require("rxjs/add/operator/publish");
30388 var Edge_1 = require("../Edge");
30389 var Error_1 = require("../Error");
30390 var Graph_1 = require("../Graph");
30394 * @classdesc Represents a graph of nodes with edges.
30396 var Graph = (function () {
30398 * Create a new graph instance.
30400 * @param {APIv3} [apiV3] - API instance for retrieving data.
30401 * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival.
30402 * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations.
30403 * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations.
30404 * @param {FilterCreator} [filterCreator] - Instance for filter creation.
30405 * @param {IGraphConfiguration} [configuration] - Configuration struct.
30407 function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator, configuration) {
30408 this._apiV3 = apiV3;
30409 this._cachedNodes = {};
30410 this._cachedNodeTiles = {};
30411 this._cachedSpatialEdges = {};
30412 this._cachedTiles = {};
30413 this._cachingFill$ = {};
30414 this._cachingFull$ = {};
30415 this._cachingSequences$ = {};
30416 this._cachingSpatialArea$ = {};
30417 this._cachingTiles$ = {};
30418 this._changed$ = new Subject_1.Subject();
30419 this._defaultAlt = 2;
30420 this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator();
30421 this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator();
30422 this._filter = this._filterCreator.createFilter(undefined);
30423 this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator();
30424 this._configuration = configuration != null ?
30428 maxUnusedNodes: 100,
30429 maxUnusedTiles: 20,
30432 this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lat", ".lon", ".lat", ".lon"]);
30433 this._nodeIndexTiles = {};
30434 this._nodeToTile = {};
30435 this._preStored = {};
30436 this._requiredNodeTiles = {};
30437 this._requiredSpatialArea = {};
30438 this._sequences = {};
30439 this._tilePrecision = 7;
30440 this._tileThreshold = 20;
30442 Object.defineProperty(Graph.prototype, "changed$", {
30446 * @returns {Observable<Graph>} Observable emitting
30447 * the graph every time it has changed.
30450 return this._changed$;
30456 * Retrieve and cache node fill properties.
30458 * @param {string} key - Key of node to fill.
30459 * @returns {Observable<Graph>} Observable emitting the graph
30460 * when the node has been updated.
30461 * @throws {GraphMapillaryError} When the operation is not valid on the
30464 Graph.prototype.cacheFill$ = function (key) {
30466 if (key in this._cachingFull$) {
30467 throw new Error_1.GraphMapillaryError("Cannot fill node while caching full (" + key + ").");
30469 if (!this.hasNode(key)) {
30470 throw new Error_1.GraphMapillaryError("Cannot fill node that does not exist in graph (" + key + ").");
30472 if (key in this._cachingFill$) {
30473 return this._cachingFill$[key];
30475 var node = this.getNode(key);
30477 throw new Error_1.GraphMapillaryError("Cannot fill node that is already full (" + key + ").");
30479 this._cachingFill$[key] = this._apiV3.imageByKeyFill$([key])
30480 .do(function (imageByKeyFill) {
30482 _this._makeFull(node, imageByKeyFill[key]);
30484 delete _this._cachingFill$[key];
30486 .map(function (imageByKeyFill) {
30489 .finally(function () {
30490 if (key in _this._cachingFill$) {
30491 delete _this._cachingFill$[key];
30493 _this._changed$.next(_this);
30497 return this._cachingFill$[key];
30500 * Retrieve and cache full node properties.
30502 * @param {string} key - Key of node to fill.
30503 * @returns {Observable<Graph>} Observable emitting the graph
30504 * when the node has been updated.
30505 * @throws {GraphMapillaryError} When the operation is not valid on the
30508 Graph.prototype.cacheFull$ = function (key) {
30510 if (key in this._cachingFull$) {
30511 return this._cachingFull$[key];
30513 if (this.hasNode(key)) {
30514 throw new Error_1.GraphMapillaryError("Cannot cache full node that already exist in graph (" + key + ").");
30516 this._cachingFull$[key] = this._apiV3.imageByKeyFull$([key])
30517 .do(function (imageByKeyFull) {
30518 var fn = imageByKeyFull[key];
30519 if (_this.hasNode(key)) {
30520 var node = _this.getNode(key);
30522 _this._makeFull(node, fn);
30526 if (fn.sequence == null || fn.sequence.key == null) {
30527 throw new Error_1.GraphMapillaryError("Node has no sequence (" + key + ").");
30529 var node = new Graph_1.Node(fn);
30530 _this._makeFull(node, fn);
30531 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
30532 _this._preStore(h, node);
30533 _this._setNode(node);
30534 delete _this._cachingFull$[key];
30537 .map(function (imageByKeyFull) {
30540 .finally(function () {
30541 if (key in _this._cachingFull$) {
30542 delete _this._cachingFull$[key];
30544 _this._changed$.next(_this);
30548 return this._cachingFull$[key];
30551 * Retrieve and cache a node sequence.
30553 * @param {string} key - Key of node for which to retrieve sequence.
30554 * @returns {Observable<Graph>} Observable emitting the graph
30555 * when the sequence has been retrieved.
30556 * @throws {GraphMapillaryError} When the operation is not valid on the
30559 Graph.prototype.cacheNodeSequence$ = function (key) {
30560 if (!this.hasNode(key)) {
30561 throw new Error_1.GraphMapillaryError("Cannot cache sequence edges of node that does not exist in graph (" + key + ").");
30563 var node = this.getNode(key);
30564 if (node.sequenceKey in this._sequences) {
30565 throw new Error_1.GraphMapillaryError("Sequence already cached (" + key + "), (" + node.sequenceKey + ").");
30567 return this._cacheSequence$(node.sequenceKey);
30570 * Retrieve and cache a sequence.
30572 * @param {string} sequenceKey - Key of sequence to cache.
30573 * @returns {Observable<Graph>} Observable emitting the graph
30574 * when the sequence has been retrieved.
30575 * @throws {GraphMapillaryError} When the operation is not valid on the
30578 Graph.prototype.cacheSequence$ = function (sequenceKey) {
30579 if (sequenceKey in this._sequences) {
30580 throw new Error_1.GraphMapillaryError("Sequence already cached (" + sequenceKey + ")");
30582 return this._cacheSequence$(sequenceKey);
30585 * Cache sequence edges for a node.
30587 * @param {string} key - Key of node.
30588 * @throws {GraphMapillaryError} When the operation is not valid on the
30591 Graph.prototype.cacheSequenceEdges = function (key) {
30592 var node = this.getNode(key);
30593 if (!(node.sequenceKey in this._sequences)) {
30594 throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")");
30596 var sequence = this._sequences[node.sequenceKey].sequence;
30597 var edges = this._edgeCalculator.computeSequenceEdges(node, sequence);
30598 node.cacheSequenceEdges(edges);
30601 * Retrieve and cache full nodes for a node spatial area.
30603 * @param {string} key - Key of node for which to retrieve sequence.
30604 * @returns {Observable<Graph>} Observable emitting the graph
30605 * when the nodes in the spatial area has been made full.
30606 * @throws {GraphMapillaryError} When the operation is not valid on the
30609 Graph.prototype.cacheSpatialArea$ = function (key) {
30611 if (!this.hasNode(key)) {
30612 throw new Error_1.GraphMapillaryError("Cannot cache spatial area of node that does not exist in graph (" + key + ").");
30614 if (key in this._cachedSpatialEdges) {
30615 throw new Error_1.GraphMapillaryError("Node already spatially cached (" + key + ").");
30617 if (!(key in this._requiredSpatialArea)) {
30618 throw new Error_1.GraphMapillaryError("Spatial area not determined (" + key + ").");
30620 var spatialArea = this._requiredSpatialArea[key];
30621 if (Object.keys(spatialArea.cacheNodes).length === 0) {
30622 throw new Error_1.GraphMapillaryError("Spatial nodes already cached (" + key + ").");
30624 if (key in this._cachingSpatialArea$) {
30625 return this._cachingSpatialArea$[key];
30628 while (spatialArea.cacheKeys.length > 0) {
30629 batches.push(spatialArea.cacheKeys.splice(0, 200));
30631 var batchesToCache = batches.length;
30632 var spatialNodes$ = [];
30633 var _loop_1 = function (batch) {
30634 var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch)
30635 .do(function (imageByKeyFill) {
30636 for (var fillKey in imageByKeyFill) {
30637 if (!imageByKeyFill.hasOwnProperty(fillKey)) {
30640 var spatialNode = spatialArea.cacheNodes[fillKey];
30641 if (spatialNode.full) {
30642 delete spatialArea.cacheNodes[fillKey];
30645 var fillNode = imageByKeyFill[fillKey];
30646 _this._makeFull(spatialNode, fillNode);
30647 delete spatialArea.cacheNodes[fillKey];
30649 if (--batchesToCache === 0) {
30650 delete _this._cachingSpatialArea$[key];
30653 .map(function (imageByKeyFill) {
30656 .catch(function (error) {
30657 for (var _i = 0, batch_1 = batch; _i < batch_1.length; _i++) {
30658 var batchKey = batch_1[_i];
30659 if (batchKey in spatialArea.all) {
30660 delete spatialArea.all[batchKey];
30662 if (batchKey in spatialArea.cacheNodes) {
30663 delete spatialArea.cacheNodes[batchKey];
30666 if (--batchesToCache === 0) {
30667 delete _this._cachingSpatialArea$[key];
30671 .finally(function () {
30672 if (Object.keys(spatialArea.cacheNodes).length === 0) {
30673 _this._changed$.next(_this);
30678 spatialNodes$.push(spatialNodeBatch$);
30681 for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {
30682 var batch = batches_1[_i];
30685 this._cachingSpatialArea$[key] = spatialNodes$;
30686 return spatialNodes$;
30689 * Cache spatial edges for a node.
30691 * @param {string} key - Key of node.
30692 * @throws {GraphMapillaryError} When the operation is not valid on the
30695 Graph.prototype.cacheSpatialEdges = function (key) {
30696 if (key in this._cachedSpatialEdges) {
30697 throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ").");
30699 var node = this.getNode(key);
30700 var sequence = this._sequences[node.sequenceKey].sequence;
30701 var fallbackKeys = [];
30702 var prevKey = sequence.findPrevKey(node.key);
30703 if (prevKey != null) {
30704 fallbackKeys.push(prevKey);
30706 var nextKey = sequence.findNextKey(node.key);
30707 if (nextKey != null) {
30708 fallbackKeys.push(nextKey);
30710 var allSpatialNodes = this._requiredSpatialArea[key].all;
30711 var potentialNodes = [];
30712 var filter = this._filter;
30713 for (var spatialNodeKey in allSpatialNodes) {
30714 if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) {
30717 var spatialNode = allSpatialNodes[spatialNodeKey];
30718 if (filter(spatialNode)) {
30719 potentialNodes.push(spatialNode);
30722 var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys);
30723 var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey);
30724 edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges));
30725 edges = edges.concat(this._edgeCalculator.computePanoEdges(node, potentialEdges));
30726 edges = edges.concat(this._edgeCalculator.computePerspectiveToPanoEdges(node, potentialEdges));
30727 edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges));
30728 node.cacheSpatialEdges(edges);
30729 this._cachedSpatialEdges[key] = node;
30730 delete this._requiredSpatialArea[key];
30731 delete this._cachedNodeTiles[key];
30734 * Retrieve and cache geohash tiles for a node.
30736 * @param {string} key - Key of node for which to retrieve tiles.
30737 * @returns {Observable<Graph>} Observable emitting the graph
30738 * when the tiles required for the node has been cached.
30739 * @throws {GraphMapillaryError} When the operation is not valid on the
30742 Graph.prototype.cacheTiles$ = function (key) {
30744 if (key in this._cachedNodeTiles) {
30745 throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
30747 if (key in this._cachedSpatialEdges) {
30748 throw new Error_1.GraphMapillaryError("Spatial edges already cached so tiles considered cached (" + key + ").");
30750 if (!(key in this._requiredNodeTiles)) {
30751 throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ").");
30753 var nodeTiles = this._requiredNodeTiles[key];
30754 if (nodeTiles.cache.length === 0 &&
30755 nodeTiles.caching.length === 0) {
30756 throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
30758 if (!this.hasNode(key)) {
30759 throw new Error_1.GraphMapillaryError("Cannot cache tiles of node that does not exist in graph (" + key + ").");
30761 var hs = nodeTiles.cache.slice();
30762 nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs);
30763 nodeTiles.cache = [];
30764 var cacheTiles$ = [];
30765 var _loop_2 = function (h) {
30766 var cacheTile$ = null;
30767 if (h in this_2._cachingTiles$) {
30768 cacheTile$ = this_2._cachingTiles$[h];
30771 cacheTile$ = this_2._apiV3.imagesByH$([h])
30772 .do(function (imagesByH) {
30773 var coreNodes = imagesByH[h];
30774 if (h in _this._cachedTiles) {
30777 _this._nodeIndexTiles[h] = [];
30778 _this._cachedTiles[h] = { accessed: new Date().getTime(), nodes: [] };
30779 var hCache = _this._cachedTiles[h].nodes;
30780 var preStored = _this._removeFromPreStore(h);
30781 for (var index in coreNodes) {
30782 if (!coreNodes.hasOwnProperty(index)) {
30785 var coreNode = coreNodes[index];
30786 if (coreNode == null) {
30789 if (coreNode.sequence == null ||
30790 coreNode.sequence.key == null) {
30791 console.warn("Sequence missing, discarding (" + coreNode.key + ")");
30794 if (preStored != null && coreNode.key in preStored) {
30795 var node_1 = preStored[coreNode.key];
30796 delete preStored[coreNode.key];
30797 hCache.push(node_1);
30798 var nodeIndexItem_1 = {
30799 lat: node_1.latLon.lat,
30800 lon: node_1.latLon.lon,
30803 _this._nodeIndex.insert(nodeIndexItem_1);
30804 _this._nodeIndexTiles[h].push(nodeIndexItem_1);
30805 _this._nodeToTile[node_1.key] = h;
30808 var node = new Graph_1.Node(coreNode);
30810 var nodeIndexItem = {
30811 lat: node.latLon.lat,
30812 lon: node.latLon.lon,
30815 _this._nodeIndex.insert(nodeIndexItem);
30816 _this._nodeIndexTiles[h].push(nodeIndexItem);
30817 _this._nodeToTile[node.key] = h;
30818 _this._setNode(node);
30820 delete _this._cachingTiles$[h];
30822 .map(function (imagesByH) {
30825 .catch(function (error) {
30826 delete _this._cachingTiles$[h];
30831 this_2._cachingTiles$[h] = cacheTile$;
30833 cacheTiles$.push(cacheTile$
30834 .do(function (graph) {
30835 var index = nodeTiles.caching.indexOf(h);
30837 nodeTiles.caching.splice(index, 1);
30839 if (nodeTiles.caching.length === 0 &&
30840 nodeTiles.cache.length === 0) {
30841 delete _this._requiredNodeTiles[key];
30842 _this._cachedNodeTiles[key] = true;
30845 .catch(function (error) {
30846 var index = nodeTiles.caching.indexOf(h);
30848 nodeTiles.caching.splice(index, 1);
30850 if (nodeTiles.caching.length === 0 &&
30851 nodeTiles.cache.length === 0) {
30852 delete _this._requiredNodeTiles[key];
30853 _this._cachedNodeTiles[key] = true;
30857 .finally(function () {
30858 _this._changed$.next(_this);
30864 for (var _i = 0, _a = nodeTiles.caching; _i < _a.length; _i++) {
30868 return cacheTiles$;
30871 * Initialize the cache for a node.
30873 * @param {string} key - Key of node.
30874 * @throws {GraphMapillaryError} When the operation is not valid on the
30877 Graph.prototype.initializeCache = function (key) {
30878 if (key in this._cachedNodes) {
30879 throw new Error_1.GraphMapillaryError("Node already in cache (" + key + ").");
30881 var node = this.getNode(key);
30882 node.initializeCache(new Graph_1.NodeCache());
30883 var accessed = new Date().getTime();
30884 this._cachedNodes[key] = { accessed: accessed, node: node };
30885 this._updateCachedTileAccess(key, accessed);
30888 * Get a value indicating if the graph is fill caching a node.
30890 * @param {string} key - Key of node.
30891 * @returns {boolean} Value indicating if the node is being fill cached.
30893 Graph.prototype.isCachingFill = function (key) {
30894 return key in this._cachingFill$;
30897 * Get a value indicating if the graph is fully caching a node.
30899 * @param {string} key - Key of node.
30900 * @returns {boolean} Value indicating if the node is being fully cached.
30902 Graph.prototype.isCachingFull = function (key) {
30903 return key in this._cachingFull$;
30906 * Get a value indicating if the graph is caching a sequence of a node.
30908 * @param {string} key - Key of node.
30909 * @returns {boolean} Value indicating if the sequence of a node is
30912 Graph.prototype.isCachingNodeSequence = function (key) {
30913 var node = this.getNode(key);
30914 return node.sequenceKey in this._cachingSequences$;
30917 * Get a value indicating if the graph is caching a sequence.
30919 * @param {string} sequenceKey - Key of sequence.
30920 * @returns {boolean} Value indicating if the sequence is
30923 Graph.prototype.isCachingSequence = function (sequenceKey) {
30924 return sequenceKey in this._cachingSequences$;
30927 * Get a value indicating if the graph is caching the tiles
30928 * required for calculating spatial edges of a node.
30930 * @param {string} key - Key of node.
30931 * @returns {boolean} Value indicating if the tiles of
30932 * a node are being cached.
30934 Graph.prototype.isCachingTiles = function (key) {
30935 return key in this._requiredNodeTiles &&
30936 this._requiredNodeTiles[key].cache.length === 0 &&
30937 this._requiredNodeTiles[key].caching.length > 0;
30940 * Get a value indicating if the cache has been initialized
30943 * @param {string} key - Key of node.
30944 * @returns {boolean} Value indicating if the cache has been
30945 * initialized for a node.
30947 Graph.prototype.hasInitializedCache = function (key) {
30948 return key in this._cachedNodes;
30951 * Get a value indicating if a node exist in the graph.
30953 * @param {string} key - Key of node.
30954 * @returns {boolean} Value indicating if a node exist in the graph.
30956 Graph.prototype.hasNode = function (key) {
30957 var accessed = new Date().getTime();
30958 this._updateCachedNodeAccess(key, accessed);
30959 this._updateCachedTileAccess(key, accessed);
30960 return key in this._nodes;
30963 * Get a value indicating if a node sequence exist in the graph.
30965 * @param {string} key - Key of node.
30966 * @returns {boolean} Value indicating if a node sequence exist
30969 Graph.prototype.hasNodeSequence = function (key) {
30970 var node = this.getNode(key);
30971 var sequenceKey = node.sequenceKey;
30972 var hasNodeSequence = sequenceKey in this._sequences;
30973 if (hasNodeSequence) {
30974 this._sequences[sequenceKey].accessed = new Date().getTime();
30976 return hasNodeSequence;
30979 * Get a value indicating if a sequence exist in the graph.
30981 * @param {string} sequenceKey - Key of sequence.
30982 * @returns {boolean} Value indicating if a sequence exist
30985 Graph.prototype.hasSequence = function (sequenceKey) {
30986 var hasSequence = sequenceKey in this._sequences;
30988 this._sequences[sequenceKey].accessed = new Date().getTime();
30990 return hasSequence;
30993 * Get a value indicating if the graph has fully cached
30994 * all nodes in the spatial area of a node.
30996 * @param {string} key - Key of node.
30997 * @returns {boolean} Value indicating if the spatial area
30998 * of a node has been cached.
31000 Graph.prototype.hasSpatialArea = function (key) {
31001 if (!this.hasNode(key)) {
31002 throw new Error_1.GraphMapillaryError("Spatial area nodes cannot be determined if node not in graph (" + key + ").");
31004 if (key in this._cachedSpatialEdges) {
31007 if (key in this._requiredSpatialArea) {
31008 return Object.keys(this._requiredSpatialArea[key].cacheNodes).length === 0;
31010 var node = this.getNode(key);
31011 var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold);
31012 var spatialItems = this._nodeIndex.search({
31018 var spatialNodes = {
31023 for (var _i = 0, spatialItems_1 = spatialItems; _i < spatialItems_1.length; _i++) {
31024 var spatialItem = spatialItems_1[_i];
31025 spatialNodes.all[spatialItem.node.key] = spatialItem.node;
31026 if (!spatialItem.node.full) {
31027 spatialNodes.cacheKeys.push(spatialItem.node.key);
31028 spatialNodes.cacheNodes[spatialItem.node.key] = spatialItem.node;
31031 this._requiredSpatialArea[key] = spatialNodes;
31032 return spatialNodes.cacheKeys.length === 0;
31035 * Get a value indicating if the graph has a tiles required
31038 * @param {string} key - Key of node.
31039 * @returns {boolean} Value indicating if the the tiles required
31040 * by a node has been cached.
31042 Graph.prototype.hasTiles = function (key) {
31044 if (key in this._cachedNodeTiles) {
31047 if (key in this._cachedSpatialEdges) {
31050 if (!this.hasNode(key)) {
31051 throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ").");
31053 var nodeTiles = { cache: [], caching: [] };
31054 if (!(key in this._requiredNodeTiles)) {
31055 var node = this.getNode(key);
31056 nodeTiles.cache = this._graphCalculator
31057 .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold)
31058 .filter(function (h) {
31059 return !(h in _this._cachedTiles);
31061 if (nodeTiles.cache.length > 0) {
31062 this._requiredNodeTiles[key] = nodeTiles;
31066 nodeTiles = this._requiredNodeTiles[key];
31068 return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0;
31073 * @param {string} key - Key of node.
31074 * @returns {Node} Retrieved node.
31076 Graph.prototype.getNode = function (key) {
31077 var accessed = new Date().getTime();
31078 this._updateCachedNodeAccess(key, accessed);
31079 this._updateCachedTileAccess(key, accessed);
31080 return this._nodes[key];
31085 * @param {string} sequenceKey - Key of sequence.
31086 * @returns {Node} Retrieved sequence.
31088 Graph.prototype.getSequence = function (sequenceKey) {
31089 var sequenceAccess = this._sequences[sequenceKey];
31090 sequenceAccess.accessed = new Date().getTime();
31091 return sequenceAccess.sequence;
31094 * Reset all spatial edges of the graph nodes.
31096 Graph.prototype.resetSpatialEdges = function () {
31097 var cachedKeys = Object.keys(this._cachedSpatialEdges);
31098 for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) {
31099 var cachedKey = cachedKeys_1[_i];
31100 var node = this._cachedSpatialEdges[cachedKey];
31101 node.resetSpatialEdges();
31102 delete this._cachedSpatialEdges[cachedKey];
31106 * Reset the complete graph but keep the nodes corresponding
31107 * to the supplied keys. All other nodes will be disposed.
31109 * @param {Array<string>} keepKeys - Keys for nodes to keep
31110 * in graph after reset.
31112 Graph.prototype.reset = function (keepKeys) {
31114 for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) {
31115 var key = keepKeys_1[_i];
31116 if (!this.hasNode(key)) {
31117 throw new Error("Node does not exist " + key);
31119 var node = this.getNode(key);
31120 node.resetSequenceEdges();
31121 node.resetSpatialEdges();
31124 for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) {
31125 var cachedKey = _b[_a];
31126 if (keepKeys.indexOf(cachedKey) !== -1) {
31129 this._cachedNodes[cachedKey].node.dispose();
31130 delete this._cachedNodes[cachedKey];
31132 this._cachedNodeTiles = {};
31133 this._cachedSpatialEdges = {};
31134 this._cachedTiles = {};
31135 this._cachingFill$ = {};
31136 this._cachingFull$ = {};
31137 this._cachingSequences$ = {};
31138 this._cachingSpatialArea$ = {};
31139 this._cachingTiles$ = {};
31141 this._nodeToTile = {};
31142 this._preStored = {};
31143 for (var _c = 0, nodes_1 = nodes; _c < nodes_1.length; _c++) {
31144 var node = nodes_1[_c];
31145 this._nodes[node.key] = node;
31146 var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision);
31147 this._preStore(h, node);
31149 this._requiredNodeTiles = {};
31150 this._requiredSpatialArea = {};
31151 this._sequences = {};
31152 this._nodeIndexTiles = {};
31153 this._nodeIndex.clear();
31156 * Set the spatial node filter.
31158 * @param {FilterExpression} filter - Filter expression to be applied
31159 * when calculating spatial edges.
31161 Graph.prototype.setFilter = function (filter) {
31162 this._filter = this._filterCreator.createFilter(filter);
31165 * Uncache the graph according to the graph configuration.
31167 * @description Uncaches unused tiles, unused nodes and
31168 * sequences according to the numbers specified in the
31169 * graph configuration. Sequences does not have a direct
31170 * reference to either tiles or nodes and may be uncached
31171 * even if they are related to the nodes that should be kept.
31173 * @param {Array<string>} keepKeys - Keys of nodes to keep in
31174 * graph unrelated to last access. Tiles related to those keys
31175 * will also be kept in graph.
31177 Graph.prototype.uncache = function (keepKeys) {
31178 var keysInUse = {};
31179 this._addNewKeys(keysInUse, this._cachingFull$);
31180 this._addNewKeys(keysInUse, this._cachingFill$);
31181 this._addNewKeys(keysInUse, this._cachingTiles$);
31182 this._addNewKeys(keysInUse, this._cachingSpatialArea$);
31183 this._addNewKeys(keysInUse, this._requiredNodeTiles);
31184 this._addNewKeys(keysInUse, this._requiredSpatialArea);
31185 for (var _i = 0, keepKeys_2 = keepKeys; _i < keepKeys_2.length; _i++) {
31186 var key = keepKeys_2[_i];
31187 if (key in keysInUse) {
31190 keysInUse[key] = true;
31193 for (var key in keysInUse) {
31194 if (!keysInUse.hasOwnProperty(key)) {
31197 var node = this._nodes[key];
31198 var nodeHs = this._graphCalculator.encodeHs(node.latLon);
31199 for (var _a = 0, nodeHs_1 = nodeHs; _a < nodeHs_1.length; _a++) {
31200 var nodeH = nodeHs_1[_a];
31201 if (!(nodeH in keepHs)) {
31202 keepHs[nodeH] = true;
31206 var potentialHs = [];
31207 for (var h in this._cachedTiles) {
31208 if (!this._cachedTiles.hasOwnProperty(h) || h in keepHs) {
31211 potentialHs.push([h, this._cachedTiles[h]]);
31213 var uncacheHs = potentialHs
31214 .sort(function (h1, h2) {
31215 return h2[1].accessed - h1[1].accessed;
31217 .slice(this._configuration.maxUnusedTiles)
31218 .map(function (h) {
31221 for (var _b = 0, uncacheHs_1 = uncacheHs; _b < uncacheHs_1.length; _b++) {
31222 var uncacheH = uncacheHs_1[_b];
31223 this._uncacheTile(uncacheH);
31225 var potentialNodes = [];
31226 for (var key in this._cachedNodes) {
31227 if (!this._cachedNodes.hasOwnProperty(key) || key in keysInUse) {
31230 potentialNodes.push(this._cachedNodes[key]);
31232 var uncacheNodes = potentialNodes
31233 .sort(function (n1, n2) {
31234 return n2.accessed - n1.accessed;
31236 .slice(this._configuration.maxUnusedNodes);
31237 for (var _c = 0, uncacheNodes_1 = uncacheNodes; _c < uncacheNodes_1.length; _c++) {
31238 var nodeAccess = uncacheNodes_1[_c];
31239 nodeAccess.node.uncache();
31240 var key = nodeAccess.node.key;
31241 delete this._cachedNodes[key];
31242 if (key in this._cachedNodeTiles) {
31243 delete this._cachedNodeTiles[key];
31245 if (key in this._cachedSpatialEdges) {
31246 delete this._cachedSpatialEdges[key];
31249 var potentialSequences = [];
31250 for (var sequenceKey in this._sequences) {
31251 if (!this._sequences.hasOwnProperty(sequenceKey) ||
31252 sequenceKey in this._cachingSequences$) {
31255 potentialSequences.push(this._sequences[sequenceKey]);
31257 var uncacheSequences = potentialSequences
31258 .sort(function (s1, s2) {
31259 return s2.accessed - s1.accessed;
31261 .slice(this._configuration.maxSequences);
31262 for (var _d = 0, uncacheSequences_1 = uncacheSequences; _d < uncacheSequences_1.length; _d++) {
31263 var sequenceAccess = uncacheSequences_1[_d];
31264 var sequenceKey = sequenceAccess.sequence.key;
31265 delete this._sequences[sequenceKey];
31266 sequenceAccess.sequence.dispose();
31269 Graph.prototype._addNewKeys = function (keys, dict) {
31270 for (var key in dict) {
31271 if (!dict.hasOwnProperty(key) || !this.hasNode(key)) {
31274 if (!(key in keys)) {
31279 Graph.prototype._cacheSequence$ = function (sequenceKey) {
31281 if (sequenceKey in this._cachingSequences$) {
31282 return this._cachingSequences$[sequenceKey];
31284 this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey])
31285 .do(function (sequenceByKey) {
31286 if (!(sequenceKey in _this._sequences)) {
31287 _this._sequences[sequenceKey] = {
31288 accessed: new Date().getTime(),
31289 sequence: new Graph_1.Sequence(sequenceByKey[sequenceKey]),
31292 delete _this._cachingSequences$[sequenceKey];
31294 .map(function (sequenceByKey) {
31297 .finally(function () {
31298 if (sequenceKey in _this._cachingSequences$) {
31299 delete _this._cachingSequences$[sequenceKey];
31301 _this._changed$.next(_this);
31305 return this._cachingSequences$[sequenceKey];
31307 Graph.prototype._makeFull = function (node, fillNode) {
31308 if (fillNode.calt == null) {
31309 fillNode.calt = this._defaultAlt;
31311 if (fillNode.c_rotation == null) {
31312 fillNode.c_rotation = this._graphCalculator.rotationFromCompass(fillNode.ca, fillNode.orientation);
31314 node.makeFull(fillNode);
31316 Graph.prototype._preStore = function (h, node) {
31317 if (!(h in this._preStored)) {
31318 this._preStored[h] = {};
31320 this._preStored[h][node.key] = node;
31322 Graph.prototype._removeFromPreStore = function (h) {
31323 var preStored = null;
31324 if (h in this._preStored) {
31325 preStored = this._preStored[h];
31326 delete this._preStored[h];
31330 Graph.prototype._setNode = function (node) {
31331 var key = node.key;
31332 if (this.hasNode(key)) {
31333 throw new Error_1.GraphMapillaryError("Node already exist (" + key + ").");
31335 this._nodes[key] = node;
31337 Graph.prototype._uncacheTile = function (h) {
31338 for (var _i = 0, _a = this._cachedTiles[h].nodes; _i < _a.length; _i++) {
31340 var key = node.key;
31341 delete this._nodes[key];
31342 delete this._nodeToTile[key];
31343 if (key in this._cachedNodes) {
31344 delete this._cachedNodes[key];
31346 if (key in this._cachedNodeTiles) {
31347 delete this._cachedNodeTiles[key];
31349 if (key in this._cachedSpatialEdges) {
31350 delete this._cachedSpatialEdges[key];
31354 for (var _b = 0, _c = this._nodeIndexTiles[h]; _b < _c.length; _b++) {
31355 var nodeIndexItem = _c[_b];
31356 this._nodeIndex.remove(nodeIndexItem);
31358 delete this._nodeIndexTiles[h];
31359 delete this._cachedTiles[h];
31361 Graph.prototype._updateCachedTileAccess = function (key, accessed) {
31362 if (key in this._nodeToTile) {
31363 this._cachedTiles[this._nodeToTile[key]].accessed = accessed;
31366 Graph.prototype._updateCachedNodeAccess = function (key, accessed) {
31367 if (key in this._cachedNodes) {
31368 this._cachedNodes[key].accessed = accessed;
31373 exports.Graph = Graph;
31374 Object.defineProperty(exports, "__esModule", { value: true });
31375 exports.default = Graph;
31377 },{"../Edge":226,"../Error":227,"../Graph":229,"rbush":24,"rxjs/Subject":33,"rxjs/add/observable/from":40,"rxjs/add/operator/catch":51,"rxjs/add/operator/do":58,"rxjs/add/operator/finally":61,"rxjs/add/operator/map":64,"rxjs/add/operator/publish":70}],308:[function(require,module,exports){
31378 /// <reference path="../../typings/index.d.ts" />
31380 var geohash = require("latlon-geohash");
31381 var THREE = require("three");
31382 var Geo_1 = require("../Geo");
31383 var GeoHashDirections = (function () {
31384 function GeoHashDirections() {
31386 return GeoHashDirections;
31388 GeoHashDirections.n = "n";
31389 GeoHashDirections.nw = "nw";
31390 GeoHashDirections.w = "w";
31391 GeoHashDirections.sw = "sw";
31392 GeoHashDirections.s = "s";
31393 GeoHashDirections.se = "se";
31394 GeoHashDirections.e = "e";
31395 GeoHashDirections.ne = "ne";
31397 * @class GraphCalculator
31399 * @classdesc Represents a calculator for graph entities.
31401 var GraphCalculator = (function () {
31403 * Create a new graph calculator instance.
31405 * @param {GeoCoords} geoCoords - Geo coords instance.
31407 function GraphCalculator(geoCoords) {
31408 this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords();
31411 * Encode the geohash tile for geodetic coordinates.
31413 * @param {ILatLon} latlon - Latitude and longitude to encode.
31414 * @param {number} precision - Precision of the encoding.
31416 * @returns {string} The geohash tile for the lat, lon and precision.
31418 GraphCalculator.prototype.encodeH = function (latLon, precision) {
31419 if (precision === void 0) { precision = 7; }
31420 return geohash.encode(latLon.lat, latLon.lon, precision);
31423 * Encode the geohash tiles within a threshold from a position
31424 * using Manhattan distance.
31426 * @param {ILatLon} latlon - Latitude and longitude to encode.
31427 * @param {number} precision - Precision of the encoding.
31428 * @param {number} threshold - Threshold of the encoding in meters.
31430 * @returns {string} The geohash tiles reachable within the threshold.
31432 GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) {
31433 if (precision === void 0) { precision = 7; }
31434 if (threshold === void 0) { threshold = 20; }
31435 var h = geohash.encode(latLon.lat, latLon.lon, precision);
31436 var bounds = geohash.bounds(h);
31437 var ne = bounds.ne;
31438 var sw = bounds.sw;
31439 var neighbours = geohash.neighbours(h);
31440 var bl = [0, 0, 0];
31441 var tr = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, sw.lat, sw.lon, 0);
31442 var position = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, sw.lat, sw.lon, 0);
31443 var left = position[0] - bl[0];
31444 var right = tr[0] - position[0];
31445 var bottom = position[1] - bl[1];
31446 var top = tr[1] - position[1];
31447 var l = left < threshold;
31448 var r = right < threshold;
31449 var b = bottom < threshold;
31450 var t = top < threshold;
31453 hs.push(neighbours[GeoHashDirections.n]);
31456 hs.push(neighbours[GeoHashDirections.nw]);
31459 hs.push(neighbours[GeoHashDirections.w]);
31462 hs.push(neighbours[GeoHashDirections.sw]);
31465 hs.push(neighbours[GeoHashDirections.s]);
31468 hs.push(neighbours[GeoHashDirections.se]);
31471 hs.push(neighbours[GeoHashDirections.e]);
31474 hs.push(neighbours[GeoHashDirections.ne]);
31479 * Get the bounding box corners for a circle with radius of a threshold
31480 * with center in a geodetic position.
31482 * @param {ILatLon} latlon - Latitude and longitude to encode.
31483 * @param {number} threshold - Threshold distance from the position in meters.
31485 * @returns {Array<ILatLon>} The south west and north east corners of the
31488 GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) {
31489 var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0);
31490 var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0);
31492 { lat: bl[0], lon: bl[1] },
31493 { lat: tr[0], lon: tr[1] },
31497 * Convert a compass angle to an angle axis rotation vector.
31499 * @param {number} compassAngle - The compass angle in degrees.
31500 * @param {number} orientation - The orientation of the original image.
31502 * @returns {Array<number>} Angle axis rotation vector.
31504 GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) {
31508 switch (orientation) {
31527 var rz = new THREE.Matrix4().makeRotationZ(z);
31528 var euler = new THREE.Euler(x, y, compassAngle * Math.PI / 180, "XYZ");
31529 var re = new THREE.Matrix4().makeRotationFromEuler(euler);
31530 var rotation = new THREE.Vector4().setAxisAngleFromRotationMatrix(re.multiply(rz));
31531 return rotation.multiplyScalar(rotation.w).toArray().slice(0, 3);
31533 return GraphCalculator;
31535 exports.GraphCalculator = GraphCalculator;
31536 Object.defineProperty(exports, "__esModule", { value: true });
31537 exports.default = GraphCalculator;
31539 },{"../Geo":228,"latlon-geohash":20,"three":175}],309:[function(require,module,exports){
31541 var Observable_1 = require("rxjs/Observable");
31542 var Subject_1 = require("rxjs/Subject");
31543 require("rxjs/add/operator/catch");
31544 require("rxjs/add/operator/concat");
31545 require("rxjs/add/operator/do");
31546 require("rxjs/add/operator/expand");
31547 require("rxjs/add/operator/finally");
31548 require("rxjs/add/operator/first");
31549 require("rxjs/add/operator/last");
31550 require("rxjs/add/operator/map");
31551 require("rxjs/add/operator/mergeMap");
31552 require("rxjs/add/operator/publishReplay");
31554 * @class GraphService
31556 * @classdesc Represents a service for graph operations.
31558 var GraphService = (function () {
31560 * Create a new graph service instance.
31562 * @param {Graph} graph - Graph instance to be operated on.
31564 function GraphService(graph, imageLoadingService) {
31565 this._graph$ = Observable_1.Observable
31567 .concat(graph.changed$)
31570 this._graph$.subscribe(function () { });
31571 this._imageLoadingService = imageLoadingService;
31572 this._firstGraphSubjects$ = [];
31573 this._initializeCacheSubscriptions = [];
31574 this._sequenceSubscriptions = [];
31575 this._spatialSubscriptions = [];
31578 * Cache a node in the graph and retrieve it.
31580 * @description When called, the full properties of
31581 * the node are retrieved and the node cache is initialized.
31582 * After that the node assets are cached and the node
31583 * is emitted to the observable when.
31584 * In parallel to caching the node assets, the sequence and
31585 * spatial edges of the node are cached. For this, the sequence
31586 * of the node and the required tiles and spatial nodes are
31587 * retrieved. The sequence and spatial edges may be set before
31588 * or after the node is returned.
31590 * @param {string} key - Key of the node to cache.
31591 * @return {Observable<Node>} Observable emitting a single item,
31592 * the node, when it has been retrieved and its assets are cached.
31593 * @throws {Error} Propagates any IO node caching errors to the caller.
31595 GraphService.prototype.cacheNode$ = function (key) {
31597 var firstGraphSubject$ = new Subject_1.Subject();
31598 this._firstGraphSubjects$.push(firstGraphSubject$);
31599 var firstGraph$ = firstGraphSubject$
31602 var node$ = firstGraph$
31603 .map(function (graph) {
31604 return graph.getNode(key);
31606 .mergeMap(function (node) {
31607 return node.assetsCached ?
31608 Observable_1.Observable.of(node) :
31609 node.cacheAssets$();
31613 node$.subscribe(function (node) {
31614 _this._imageLoadingService.loadnode$.next(node);
31615 }, function (error) {
31616 console.error("Failed to cache node (" + key + ")", error);
31618 var initializeCacheSubscription = this._graph$
31620 .mergeMap(function (graph) {
31621 if (graph.isCachingFull(key) || !graph.hasNode(key)) {
31622 return graph.cacheFull$(key);
31624 if (graph.isCachingFill(key) || !graph.getNode(key).full) {
31625 return graph.cacheFill$(key);
31627 return Observable_1.Observable.of(graph);
31629 .do(function (graph) {
31630 if (!graph.hasInitializedCache(key)) {
31631 graph.initializeCache(key);
31634 .finally(function () {
31635 if (initializeCacheSubscription == null) {
31638 _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions);
31639 _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$);
31641 .subscribe(function (graph) {
31642 firstGraphSubject$.next(graph);
31643 firstGraphSubject$.complete();
31644 }, function (error) {
31645 firstGraphSubject$.error(error);
31647 if (!initializeCacheSubscription.closed) {
31648 this._initializeCacheSubscriptions.push(initializeCacheSubscription);
31650 var sequenceSubscription = firstGraph$
31651 .mergeMap(function (graph) {
31652 if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) {
31653 return graph.cacheNodeSequence$(key);
31655 return Observable_1.Observable.of(graph);
31657 .do(function (graph) {
31658 if (!graph.getNode(key).sequenceEdges.cached) {
31659 graph.cacheSequenceEdges(key);
31662 .finally(function () {
31663 if (sequenceSubscription == null) {
31666 _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions);
31668 .subscribe(function (graph) { return; }, function (error) {
31669 console.error("Failed to cache sequence edges (" + key + ").", error);
31671 if (!sequenceSubscription.closed) {
31672 this._sequenceSubscriptions.push(sequenceSubscription);
31674 var spatialSubscription = firstGraph$
31675 .expand(function (graph) {
31676 if (graph.hasTiles(key)) {
31677 return Observable_1.Observable.empty();
31679 return Observable_1.Observable
31680 .from(graph.cacheTiles$(key))
31681 .mergeMap(function (graph$) {
31683 .mergeMap(function (g) {
31684 if (g.isCachingTiles(key)) {
31685 return Observable_1.Observable.empty();
31687 return Observable_1.Observable.of(g);
31689 .catch(function (error, caught$) {
31690 console.error("Failed to cache tile data (" + key + ").", error);
31691 return Observable_1.Observable.empty();
31696 .mergeMap(function (graph) {
31697 if (graph.hasSpatialArea(key)) {
31698 return Observable_1.Observable.of(graph);
31700 return Observable_1.Observable
31701 .from(graph.cacheSpatialArea$(key))
31702 .mergeMap(function (graph$) {
31704 .catch(function (error, caught$) {
31705 console.error("Failed to cache spatial nodes (" + key + ").", error);
31706 return Observable_1.Observable.empty();
31711 .mergeMap(function (graph) {
31712 return graph.hasNodeSequence(key) ?
31713 Observable_1.Observable.of(graph) :
31714 graph.cacheNodeSequence$(key);
31716 .do(function (graph) {
31717 if (!graph.getNode(key).spatialEdges.cached) {
31718 graph.cacheSpatialEdges(key);
31721 .finally(function () {
31722 if (spatialSubscription == null) {
31725 _this._removeFromArray(spatialSubscription, _this._spatialSubscriptions);
31727 .subscribe(function (graph) { return; }, function (error) {
31728 console.error("Failed to cache spatial edges (" + key + ").", error);
31730 if (!spatialSubscription.closed) {
31731 this._spatialSubscriptions.push(spatialSubscription);
31734 .first(function (node) {
31735 return node.assetsCached;
31739 * Cache a sequence in the graph and retrieve it.
31741 * @param {string} sequenceKey - Sequence key.
31742 * @returns {Observable<Sequence>} Observable emitting a single item,
31743 * the sequence, when it has been retrieved and its assets are cached.
31744 * @throws {Error} Propagates any IO node caching errors to the caller.
31746 GraphService.prototype.cacheSequence$ = function (sequenceKey) {
31747 return this._graph$
31749 .mergeMap(function (graph) {
31750 if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
31751 return graph.cacheSequence$(sequenceKey);
31753 return Observable_1.Observable.of(graph);
31755 .map(function (graph) {
31756 return graph.getSequence(sequenceKey);
31760 * Set a spatial edge filter on the graph.
31762 * @description Resets the spatial edges of all cached nodes.
31764 * @param {FilterExpression} filter - Filter expression to be applied.
31765 * @return {Observable<Graph>} Observable emitting a single item,
31766 * the graph, when the spatial edges have been reset.
31768 GraphService.prototype.setFilter$ = function (filter) {
31769 this._resetSubscriptions(this._spatialSubscriptions);
31770 return this._graph$
31772 .do(function (graph) {
31773 graph.resetSpatialEdges();
31774 graph.setFilter(filter);
31780 * @description Resets the graph but keeps the nodes of the
31783 * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
31784 * @return {Observable<Node>} Observable emitting a single item,
31785 * the graph, when it has been reset.
31787 GraphService.prototype.reset$ = function (keepKeys) {
31788 this._abortSubjects(this._firstGraphSubjects$);
31789 this._resetSubscriptions(this._initializeCacheSubscriptions);
31790 this._resetSubscriptions(this._sequenceSubscriptions);
31791 this._resetSubscriptions(this._spatialSubscriptions);
31792 return this._graph$
31794 .do(function (graph) {
31795 graph.reset(keepKeys);
31799 * Uncache the graph.
31801 * @description Uncaches the graph by removing tiles, nodes and
31802 * sequences. Keeps the nodes of the supplied keys and the tiles
31803 * related to those nodes.
31805 * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
31806 * @return {Observable<Graph>} Observable emitting a single item,
31807 * the graph, when the graph has been uncached.
31809 GraphService.prototype.uncache$ = function (keepKeys) {
31810 return this._graph$
31812 .do(function (graph) {
31813 graph.uncache(keepKeys);
31816 GraphService.prototype._abortSubjects = function (subjects) {
31817 for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) {
31818 var subject = _a[_i];
31819 this._removeFromArray(subject, subjects);
31820 subject.error(new Error("Cache node request was aborted."));
31823 GraphService.prototype._removeFromArray = function (object, objects) {
31824 var index = objects.indexOf(object);
31825 if (index !== -1) {
31826 objects.splice(index, 1);
31829 GraphService.prototype._resetSubscriptions = function (subscriptions) {
31830 for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) {
31831 var subscription = _a[_i];
31832 this._removeFromArray(subscription, subscriptions);
31833 if (!subscription.closed) {
31834 subscription.unsubscribe();
31838 return GraphService;
31840 exports.GraphService = GraphService;
31841 Object.defineProperty(exports, "__esModule", { value: true });
31842 exports.default = GraphService;
31844 },{"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/operator/catch":51,"rxjs/add/operator/concat":53,"rxjs/add/operator/do":58,"rxjs/add/operator/expand":59,"rxjs/add/operator/finally":61,"rxjs/add/operator/first":62,"rxjs/add/operator/last":63,"rxjs/add/operator/map":64,"rxjs/add/operator/mergeMap":67,"rxjs/add/operator/publishReplay":71}],310:[function(require,module,exports){
31845 /// <reference path="../../typings/index.d.ts" />
31847 var Subject_1 = require("rxjs/Subject");
31848 var ImageLoadingService = (function () {
31849 function ImageLoadingService() {
31850 this._loadnode$ = new Subject_1.Subject();
31851 this._loadstatus$ = this._loadnode$
31852 .scan(function (nodes, node) {
31853 nodes[node.key] = node.loadStatus;
31858 this._loadstatus$.subscribe(function () { });
31860 Object.defineProperty(ImageLoadingService.prototype, "loadnode$", {
31862 return this._loadnode$;
31867 Object.defineProperty(ImageLoadingService.prototype, "loadstatus$", {
31869 return this._loadstatus$;
31874 return ImageLoadingService;
31876 exports.ImageLoadingService = ImageLoadingService;
31878 },{"rxjs/Subject":33}],311:[function(require,module,exports){
31879 /// <reference path="../../typings/index.d.ts" />
31881 var Pbf = require("pbf");
31882 var MeshReader = (function () {
31883 function MeshReader() {
31885 MeshReader.read = function (buffer) {
31886 var pbf = new Pbf(buffer);
31887 return pbf.readFields(MeshReader._readMeshField, { faces: [], vertices: [] });
31889 MeshReader._readMeshField = function (tag, mesh, pbf) {
31891 mesh.vertices.push(pbf.readFloat());
31893 else if (tag === 2) {
31894 mesh.faces.push(pbf.readVarint());
31899 exports.MeshReader = MeshReader;
31901 },{"pbf":22}],312:[function(require,module,exports){
31903 require("rxjs/add/observable/combineLatest");
31904 require("rxjs/add/operator/map");
31908 * @classdesc Represents a node in the navigation graph.
31910 var Node = (function () {
31912 * Create a new node instance.
31914 * @description Nodes are always created internally by the library.
31915 * Nodes can not be added to the library through any API method.
31917 * @param {ICoreNode} coreNode - Raw core node data.
31919 function Node(core) {
31920 this._cache = null;
31924 Object.defineProperty(Node.prototype, "assetsCached", {
31926 * Get assets cached.
31928 * @description The assets that need to be cached for this property
31929 * to report true are the following: fill properties, image and mesh.
31930 * The library ensures that the current node will always have the
31933 * @returns {boolean} Value indicating whether all assets have been
31937 return this._core != null &&
31938 this._fill != null &&
31939 this._cache != null &&
31940 this._cache.image != null &&
31941 this._cache.mesh != null;
31946 Object.defineProperty(Node.prototype, "alt", {
31950 * @description If SfM has not been run the computed altitude is
31951 * set to a default value of two meters.
31953 * @returns {number} Altitude, in meters.
31956 return this._fill.calt;
31961 Object.defineProperty(Node.prototype, "ca", {
31965 * @description If the SfM computed compass angle exists it will
31966 * be returned, otherwise the original EXIF compass angle.
31968 * @returns {number} Compass angle, measured in degrees.
31971 return this._fill.cca != null ? this._fill.cca : this._fill.ca;
31976 Object.defineProperty(Node.prototype, "capturedAt", {
31980 * @returns {number} Timestamp when the image was captured.
31983 return this._fill.captured_at;
31988 Object.defineProperty(Node.prototype, "computedCA", {
31992 * @description Will not be set if SfM has not been run.
31994 * @returns {number} SfM computed compass angle, measured in degrees.
31997 return this._fill.cca;
32002 Object.defineProperty(Node.prototype, "computedLatLon", {
32004 * Get computedLatLon.
32006 * @description Will not be set if SfM has not been run.
32008 * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum,
32009 * measured in degrees.
32012 return this._core.cl;
32017 Object.defineProperty(Node.prototype, "focal", {
32021 * @description Will not be set if SfM has not been run.
32023 * @returns {number} SfM computed focal length.
32026 return this._fill.cfocal;
32031 Object.defineProperty(Node.prototype, "full", {
32035 * @description The library ensures that the current node will
32038 * @returns {boolean} Value indicating whether the node has all
32039 * properties filled.
32042 return this._fill != null;
32047 Object.defineProperty(Node.prototype, "fullPano", {
32051 * @returns {boolean} Value indicating whether the node is a complete
32055 return this._fill.gpano != null &&
32056 this._fill.gpano.CroppedAreaLeftPixels === 0 &&
32057 this._fill.gpano.CroppedAreaTopPixels === 0 &&
32058 this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels &&
32059 this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels;
32064 Object.defineProperty(Node.prototype, "gpano", {
32068 * @description Will not be set for non panoramic images.
32070 * @returns {IGPano} Panorama information for panorama images.
32073 return this._fill.gpano;
32078 Object.defineProperty(Node.prototype, "height", {
32082 * @returns {number} Height of original image, not adjusted
32086 return this._fill.height;
32091 Object.defineProperty(Node.prototype, "image", {
32095 * @description The image will always be set on the current node.
32097 * @returns {HTMLImageElement} Cached image element of the node.
32100 return this._cache.image;
32105 Object.defineProperty(Node.prototype, "key", {
32109 * @returns {string} Unique key of the node.
32112 return this._core.key;
32117 Object.defineProperty(Node.prototype, "latLon", {
32121 * @description If the SfM computed latitude longitude exist
32122 * it will be returned, otherwise the original EXIF latitude
32125 * @returns {ILatLon} Latitude longitude in WGS84 datum,
32126 * measured in degrees.
32129 return this._core.cl != null ? this._core.cl : this._core.l;
32134 Object.defineProperty(Node.prototype, "loadStatus", {
32138 * @returns {ILoadStatus} Value indicating the load status
32139 * of the mesh and image.
32142 return this._cache.loadStatus;
32147 Object.defineProperty(Node.prototype, "merged", {
32151 * @returns {boolean} Value indicating whether SfM has been
32152 * run on the node and the node has been merged into a
32153 * connected component.
32156 return this._fill != null &&
32157 this._fill.merge_version != null &&
32158 this._fill.merge_version > 0;
32163 Object.defineProperty(Node.prototype, "mergeCC", {
32167 * @description Will not be set if SfM has not yet been run on
32170 * @returns {number} SfM connected component key to which
32174 return this._fill.merge_cc;
32179 Object.defineProperty(Node.prototype, "mergeVersion", {
32181 * Get mergeVersion.
32183 * @returns {number} Version for which SfM was run and image was merged.
32186 return this._fill.merge_version;
32191 Object.defineProperty(Node.prototype, "mesh", {
32195 * @description The mesh will always be set on the current node.
32197 * @returns {IMesh} SfM triangulated mesh of reconstructed
32198 * atomic 3D points.
32201 return this._cache.mesh;
32206 Object.defineProperty(Node.prototype, "orientation", {
32210 * @returns {number} EXIF orientation of original image.
32213 return this._fill.orientation;
32218 Object.defineProperty(Node.prototype, "originalCA", {
32222 * @returns {number} Original EXIF compass angle, measured in
32226 return this._fill.ca;
32231 Object.defineProperty(Node.prototype, "originalLatLon", {
32233 * Get originalLatLon.
32235 * @returns {ILatLon} Original EXIF latitude longitude in
32236 * WGS84 datum, measured in degrees.
32239 return this._core.l;
32244 Object.defineProperty(Node.prototype, "pano", {
32248 * @returns {boolean} Value indicating whether the node is a panorama.
32249 * It could be a cropped or full panorama.
32252 return this._fill.gpano != null &&
32253 this._fill.gpano.FullPanoWidthPixels != null;
32258 Object.defineProperty(Node.prototype, "projectKey", {
32262 * @returns {string} Unique key of the project to which
32263 * the node belongs.
32266 return this._fill.project != null ?
32267 this._fill.project.key :
32273 Object.defineProperty(Node.prototype, "rotation", {
32277 * @description Will not be set if SfM has not been run.
32279 * @returns {Array<number>} Rotation vector in angle axis representation.
32282 return this._fill.c_rotation;
32287 Object.defineProperty(Node.prototype, "scale", {
32291 * @description Will not be set if SfM has not been run.
32293 * @returns {number} Scale of atomic reconstruction.
32296 return this._fill.atomic_scale;
32301 Object.defineProperty(Node.prototype, "sequenceKey", {
32305 * @returns {string} Unique key of the sequence to which
32306 * the node belongs.
32309 return this._core.sequence.key;
32314 Object.defineProperty(Node.prototype, "sequenceEdges", {
32316 * Get sequenceEdges.
32318 * @returns {IEdgeStatus} Value describing the status of the
32322 return this._cache.sequenceEdges;
32327 Object.defineProperty(Node.prototype, "sequenceEdges$", {
32329 * Get sequenceEdges$.
32331 * @returns {Observable<IEdgeStatus>} Observable emitting
32332 * values describing the status of the sequence edges.
32335 return this._cache.sequenceEdges$;
32340 Object.defineProperty(Node.prototype, "spatialEdges", {
32342 * Get spatialEdges.
32344 * @returns {IEdgeStatus} Value describing the status of the
32348 return this._cache.spatialEdges;
32353 Object.defineProperty(Node.prototype, "spatialEdges$", {
32355 * Get spatialEdges$.
32357 * @returns {Observable<IEdgeStatus>} Observable emitting
32358 * values describing the status of the spatial edges.
32361 return this._cache.spatialEdges$;
32366 Object.defineProperty(Node.prototype, "userKey", {
32370 * @returns {string} Unique key of the user who uploaded
32374 return this._fill.user.key;
32379 Object.defineProperty(Node.prototype, "username", {
32383 * @returns {string} Username of the user who uploaded
32387 return this._fill.user.username;
32392 Object.defineProperty(Node.prototype, "width", {
32396 * @returns {number} Width of original image, not
32397 * adjusted for orientation.
32400 return this._fill.width;
32406 * Cache the image and mesh assets.
32408 * @description The assets are always cached internally by the
32409 * library prior to setting a node as the current node.
32411 * @returns {Observable<Node>} Observable emitting this node whenever the
32412 * load status has changed and when the mesh or image has been fully loaded.
32414 Node.prototype.cacheAssets$ = function () {
32416 return this._cache.cacheAssets$(this.key, this.pano, this.merged)
32417 .map(function (cache) {
32421 Node.prototype.cacheImage$ = function (imageSize) {
32423 return this._cache.cacheImage$(this.key, imageSize)
32424 .map(function (cache) {
32429 * Cache the sequence edges.
32431 * @description The sequence edges are cached asynchronously
32432 * internally by the library.
32434 * @param {Array<IEdge>} edges - Sequence edges to cache.
32436 Node.prototype.cacheSequenceEdges = function (edges) {
32437 this._cache.cacheSequenceEdges(edges);
32440 * Cache the spatial edges.
32442 * @description The spatial edges are cached asynchronously
32443 * internally by the library.
32445 * @param {Array<IEdge>} edges - Spatial edges to cache.
32447 Node.prototype.cacheSpatialEdges = function (edges) {
32448 this._cache.cacheSpatialEdges(edges);
32451 * Dispose the node.
32453 * @description Disposes all cached assets.
32455 Node.prototype.dispose = function () {
32456 if (this._cache != null) {
32457 this._cache.dispose();
32458 this._cache = null;
32464 * Initialize the node cache.
32466 * @description The node cache is initialized internally by
32469 * @param {NodeCache} cache - The node cache to set as cache.
32471 Node.prototype.initializeCache = function (cache) {
32472 if (this._cache != null) {
32473 throw new Error("Node cache already initialized (" + this.key + ").");
32475 this._cache = cache;
32478 * Fill the node with all properties.
32480 * @description The node is filled internally by
32483 * @param {IFillNode} fill - The fill node struct.
32485 Node.prototype.makeFull = function (fill) {
32486 if (fill == null) {
32487 throw new Error("Fill can not be null.");
32492 * Reset the sequence edges.
32494 Node.prototype.resetSequenceEdges = function () {
32495 this._cache.resetSequenceEdges();
32498 * Reset the spatial edges.
32500 Node.prototype.resetSpatialEdges = function () {
32501 this._cache.resetSpatialEdges();
32504 * Clears the image and mesh assets, aborts
32505 * any outstanding requests and resets edges.
32507 Node.prototype.uncache = function () {
32508 if (this._cache == null) {
32511 this._cache.dispose();
32512 this._cache = null;
32516 exports.Node = Node;
32517 Object.defineProperty(exports, "__esModule", { value: true });
32518 exports.default = Node;
32520 },{"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/map":64}],313:[function(require,module,exports){
32521 (function (Buffer){
32523 var Subject_1 = require("rxjs/Subject");
32524 var Observable_1 = require("rxjs/Observable");
32525 require("rxjs/add/observable/combineLatest");
32526 require("rxjs/add/operator/publishReplay");
32527 var Graph_1 = require("../Graph");
32528 var Utils_1 = require("../Utils");
32532 * @classdesc Represents the cached properties of a node.
32534 var NodeCache = (function () {
32536 * Create a new node cache instance.
32538 function NodeCache() {
32539 this._disposed = false;
32540 this._image = null;
32541 this._loadStatus = { loaded: 0, total: 0 };
32543 this._sequenceEdges = { cached: false, edges: [] };
32544 this._spatialEdges = { cached: false, edges: [] };
32545 this._sequenceEdgesChanged$ = new Subject_1.Subject();
32546 this._sequenceEdges$ = this._sequenceEdgesChanged$
32547 .startWith(this._sequenceEdges)
32550 this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(function () { });
32551 this._spatialEdgesChanged$ = new Subject_1.Subject();
32552 this._spatialEdges$ = this._spatialEdgesChanged$
32553 .startWith(this._spatialEdges)
32556 this._spatialEdgesSubscription = this._spatialEdges$.subscribe(function () { });
32557 this._cachingAssets$ = null;
32559 Object.defineProperty(NodeCache.prototype, "image", {
32563 * @description Will not be set when assets have not been cached
32564 * or when the object has been disposed.
32566 * @returns {HTMLImageElement} Cached image element of the node.
32569 return this._image;
32574 Object.defineProperty(NodeCache.prototype, "loadStatus", {
32578 * @returns {ILoadStatus} Value indicating the load status
32579 * of the mesh and image.
32582 return this._loadStatus;
32587 Object.defineProperty(NodeCache.prototype, "mesh", {
32591 * @description Will not be set when assets have not been cached
32592 * or when the object has been disposed.
32594 * @returns {IMesh} SfM triangulated mesh of reconstructed
32595 * atomic 3D points.
32603 Object.defineProperty(NodeCache.prototype, "sequenceEdges", {
32605 * Get sequenceEdges.
32607 * @returns {IEdgeStatus} Value describing the status of the
32611 return this._sequenceEdges;
32616 Object.defineProperty(NodeCache.prototype, "sequenceEdges$", {
32618 * Get sequenceEdges$.
32620 * @returns {Observable<IEdgeStatus>} Observable emitting
32621 * values describing the status of the sequence edges.
32624 return this._sequenceEdges$;
32629 Object.defineProperty(NodeCache.prototype, "spatialEdges", {
32631 * Get spatialEdges.
32633 * @returns {IEdgeStatus} Value describing the status of the
32637 return this._spatialEdges;
32642 Object.defineProperty(NodeCache.prototype, "spatialEdges$", {
32644 * Get spatialEdges$.
32646 * @returns {Observable<IEdgeStatus>} Observable emitting
32647 * values describing the status of the spatial edges.
32650 return this._spatialEdges$;
32656 * Cache the image and mesh assets.
32658 * @param {string} key - Key of the node to cache.
32659 * @param {boolean} pano - Value indicating whether node is a panorama.
32660 * @param {boolean} merged - Value indicating whether node is merged.
32661 * @returns {Observable<NodeCache>} Observable emitting this node
32662 * cache whenever the load status has changed and when the mesh or image
32663 * has been fully loaded.
32665 NodeCache.prototype.cacheAssets$ = function (key, pano, merged) {
32667 if (this._cachingAssets$ != null) {
32668 return this._cachingAssets$;
32670 var imageSize = pano ?
32671 Utils_1.Settings.basePanoramaSize :
32672 Utils_1.Settings.baseImageSize;
32673 this._cachingAssets$ = Observable_1.Observable
32674 .combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged), function (imageStatus, meshStatus) {
32675 _this._loadStatus.loaded = 0;
32676 _this._loadStatus.total = 0;
32678 _this._mesh = meshStatus.object;
32679 _this._loadStatus.loaded += meshStatus.loaded.loaded;
32680 _this._loadStatus.total += meshStatus.loaded.total;
32683 _this._image = imageStatus.object;
32684 _this._loadStatus.loaded += imageStatus.loaded.loaded;
32685 _this._loadStatus.total += imageStatus.loaded.total;
32689 .finally(function () {
32690 _this._cachingAssets$ = null;
32694 return this._cachingAssets$;
32697 * Cache an image with a higher resolution than the current one.
32699 * @param {string} key - Key of the node to cache.
32700 * @param {ImageSize} imageSize - The size to cache.
32701 * @returns {Observable<NodeCache>} Observable emitting a single item,
32702 * the node cache, when the image has been cached. If supplied image
32703 * size is not larger than the current image size the node cache is
32704 * returned immediately.
32706 NodeCache.prototype.cacheImage$ = function (key, imageSize) {
32708 if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) {
32709 return Observable_1.Observable.of(this);
32711 return this._cacheImage$(key, imageSize)
32712 .first(function (status) {
32713 return status.object != null;
32715 .do(function (status) {
32716 _this._disposeImage();
32717 _this._image = status.object;
32719 .map(function (imageStatus) {
32724 * Cache the sequence edges.
32726 * @param {Array<IEdge>} edges - Sequence edges to cache.
32728 NodeCache.prototype.cacheSequenceEdges = function (edges) {
32729 this._sequenceEdges = { cached: true, edges: edges };
32730 this._sequenceEdgesChanged$.next(this._sequenceEdges);
32733 * Cache the spatial edges.
32735 * @param {Array<IEdge>} edges - Spatial edges to cache.
32737 NodeCache.prototype.cacheSpatialEdges = function (edges) {
32738 this._spatialEdges = { cached: true, edges: edges };
32739 this._spatialEdgesChanged$.next(this._spatialEdges);
32742 * Dispose the node cache.
32744 * @description Disposes all cached assets and unsubscribes to
32747 NodeCache.prototype.dispose = function () {
32748 this._sequenceEdgesSubscription.unsubscribe();
32749 this._spatialEdgesSubscription.unsubscribe();
32750 this._disposeImage();
32752 this._loadStatus.loaded = 0;
32753 this._loadStatus.total = 0;
32754 this._sequenceEdges = { cached: false, edges: [] };
32755 this._spatialEdges = { cached: false, edges: [] };
32756 this._sequenceEdgesChanged$.next(this._sequenceEdges);
32757 this._spatialEdgesChanged$.next(this._spatialEdges);
32758 this._disposed = true;
32759 if (this._imageRequest != null) {
32760 this._imageRequest.abort();
32762 if (this._meshRequest != null) {
32763 this._meshRequest.abort();
32767 * Reset the sequence edges.
32769 NodeCache.prototype.resetSequenceEdges = function () {
32770 this._sequenceEdges = { cached: false, edges: [] };
32771 this._sequenceEdgesChanged$.next(this._sequenceEdges);
32774 * Reset the spatial edges.
32776 NodeCache.prototype.resetSpatialEdges = function () {
32777 this._spatialEdges = { cached: false, edges: [] };
32778 this._spatialEdgesChanged$.next(this._spatialEdges);
32783 * @param {string} key - Key of the node to cache.
32784 * @param {boolean} pano - Value indicating whether node is a panorama.
32785 * @returns {Observable<ILoadStatusObject<HTMLImageElement>>} Observable
32786 * emitting a load status object every time the load status changes
32787 * and completes when the image is fully loaded.
32789 NodeCache.prototype._cacheImage$ = function (key, imageSize) {
32791 return Observable_1.Observable.create(function (subscriber) {
32792 var xmlHTTP = new XMLHttpRequest();
32793 xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize), true);
32794 xmlHTTP.responseType = "arraybuffer";
32795 xmlHTTP.timeout = 15000;
32796 xmlHTTP.onload = function (pe) {
32797 if (xmlHTTP.status !== 200) {
32798 _this._imageRequest = null;
32799 subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
32802 var image = new Image();
32803 image.crossOrigin = "Anonymous";
32804 image.onload = function (e) {
32805 _this._imageRequest = null;
32806 if (_this._disposed) {
32807 window.URL.revokeObjectURL(image.src);
32808 subscriber.error(new Error("Image load was aborted (" + key + ")"));
32811 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
32812 subscriber.complete();
32814 image.onerror = function (error) {
32815 _this._imageRequest = null;
32816 subscriber.error(new Error("Failed to load image (" + key + ")"));
32818 var blob = new Blob([xmlHTTP.response]);
32819 image.src = window.URL.createObjectURL(blob);
32821 xmlHTTP.onprogress = function (pe) {
32822 if (_this._disposed) {
32825 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
32827 xmlHTTP.onerror = function (error) {
32828 _this._imageRequest = null;
32829 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
32831 xmlHTTP.ontimeout = function (e) {
32832 _this._imageRequest = null;
32833 subscriber.error(new Error("Image request timed out (" + key + ")"));
32835 xmlHTTP.onabort = function (event) {
32836 _this._imageRequest = null;
32837 subscriber.error(new Error("Image request was aborted (" + key + ")"));
32839 _this._imageRequest = xmlHTTP;
32840 xmlHTTP.send(null);
32846 * @param {string} key - Key of the node to cache.
32847 * @param {boolean} merged - Value indicating whether node is merged.
32848 * @returns {Observable<ILoadStatusObject<IMesh>>} Observable emitting
32849 * a load status object every time the load status changes and completes
32850 * when the mesh is fully loaded.
32852 NodeCache.prototype._cacheMesh$ = function (key, merged) {
32854 return Observable_1.Observable.create(function (subscriber) {
32856 subscriber.next(_this._createEmptyMeshLoadStatus());
32857 subscriber.complete();
32860 var xmlHTTP = new XMLHttpRequest();
32861 xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true);
32862 xmlHTTP.responseType = "arraybuffer";
32863 xmlHTTP.timeout = 15000;
32864 xmlHTTP.onload = function (pe) {
32865 _this._meshRequest = null;
32866 if (_this._disposed) {
32869 var mesh = xmlHTTP.status === 200 ?
32870 Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) :
32871 { faces: [], vertices: [] };
32872 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: mesh });
32873 subscriber.complete();
32875 xmlHTTP.onprogress = function (pe) {
32876 if (_this._disposed) {
32879 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
32881 xmlHTTP.onerror = function (e) {
32882 _this._meshRequest = null;
32883 console.error("Failed to cache mesh (" + key + ")");
32884 subscriber.next(_this._createEmptyMeshLoadStatus());
32885 subscriber.complete();
32887 xmlHTTP.ontimeout = function (e) {
32888 _this._meshRequest = null;
32889 console.error("Mesh request timed out (" + key + ")");
32890 subscriber.next(_this._createEmptyMeshLoadStatus());
32891 subscriber.complete();
32893 xmlHTTP.onabort = function (e) {
32894 _this._meshRequest = null;
32895 subscriber.error(new Error("Mesh request was aborted (" + key + ")"));
32897 _this._meshRequest = xmlHTTP;
32898 xmlHTTP.send(null);
32902 * Create a load status object with an empty mesh.
32904 * @returns {ILoadStatusObject<IMesh>} Load status object
32907 NodeCache.prototype._createEmptyMeshLoadStatus = function () {
32909 loaded: { loaded: 0, total: 0 },
32910 object: { faces: [], vertices: [] },
32913 NodeCache.prototype._disposeImage = function () {
32914 if (this._image != null) {
32915 window.URL.revokeObjectURL(this._image.src);
32917 this._image = null;
32921 exports.NodeCache = NodeCache;
32922 Object.defineProperty(exports, "__esModule", { value: true });
32923 exports.default = NodeCache;
32925 }).call(this,require("buffer").Buffer)
32927 },{"../Graph":229,"../Utils":234,"buffer":5,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/publishReplay":71}],314:[function(require,module,exports){
32928 /// <reference path="../../typings/index.d.ts" />
32930 var _ = require("underscore");
32934 * @classdesc Represents a sequence of ordered nodes.
32936 var Sequence = (function () {
32938 * Create a new sequene instance.
32940 * @param {ISequence} sequence - Raw sequence data.
32942 function Sequence(sequence) {
32943 this._key = sequence.key;
32944 this._keys = sequence.keys;
32946 Object.defineProperty(Sequence.prototype, "key", {
32950 * @returns {string} Unique sequence key.
32958 Object.defineProperty(Sequence.prototype, "keys", {
32962 * @returns {Array<string>} Array of ordered node keys in the sequence.
32971 * Dispose the sequence.
32973 * @description Disposes all cached assets.
32975 Sequence.prototype.dispose = function () {
32980 * Find the next node key in the sequence with respect to
32981 * the provided node key.
32983 * @param {string} key - Reference node key.
32984 * @returns {string} Next key in sequence if it exists, null otherwise.
32986 Sequence.prototype.findNextKey = function (key) {
32987 var i = _.indexOf(this._keys, key);
32988 if ((i + 1) >= this._keys.length || i === -1) {
32992 return this._keys[i + 1];
32996 * Find the previous node key in the sequence with respect to
32997 * the provided node key.
32999 * @param {string} key - Reference node key.
33000 * @returns {string} Previous key in sequence if it exists, null otherwise.
33002 Sequence.prototype.findPrevKey = function (key) {
33003 var i = _.indexOf(this._keys, key);
33004 if (i === 0 || i === -1) {
33008 return this._keys[i - 1];
33013 exports.Sequence = Sequence;
33014 Object.defineProperty(exports, "__esModule", { value: true });
33015 exports.default = Sequence;
33017 },{"underscore":176}],315:[function(require,module,exports){
33018 /// <reference path="../../../typings/index.d.ts" />
33020 var THREE = require("three");
33021 var Edge_1 = require("../../Edge");
33022 var Error_1 = require("../../Error");
33023 var Geo_1 = require("../../Geo");
33025 * @class EdgeCalculator
33027 * @classdesc Represents a class for calculating node edges.
33029 var EdgeCalculator = (function () {
33031 * Create a new edge calculator instance.
33033 * @param {EdgeCalculatorSettings} settings - Settings struct.
33034 * @param {EdgeCalculatorDirections} directions - Directions struct.
33035 * @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
33037 function EdgeCalculator(settings, directions, coefficients) {
33038 this._spatial = new Geo_1.Spatial();
33039 this._geoCoords = new Geo_1.GeoCoords();
33040 this._settings = settings != null ? settings : new Edge_1.EdgeCalculatorSettings();
33041 this._directions = directions != null ? directions : new Edge_1.EdgeCalculatorDirections();
33042 this._coefficients = coefficients != null ? coefficients : new Edge_1.EdgeCalculatorCoefficients();
33045 * Returns the potential edges to destination nodes for a set
33046 * of nodes with respect to a source node.
33048 * @param {Node} node - Source node.
33049 * @param {Array<Node>} nodes - Potential destination nodes.
33050 * @param {Array<string>} fallbackKeys - Keys for destination nodes that should
33051 * be returned even if they do not meet the criteria for a potential edge.
33052 * @throws {ArgumentMapillaryError} If node is not full.
33054 EdgeCalculator.prototype.getPotentialEdges = function (node, potentialNodes, fallbackKeys) {
33056 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
33058 if (!node.merged) {
33061 var currentDirection = this._spatial.viewingDirection(node.rotation);
33062 var currentVerticalDirection = this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
33063 var potentialEdges = [];
33064 for (var _i = 0, potentialNodes_1 = potentialNodes; _i < potentialNodes_1.length; _i++) {
33065 var potential = potentialNodes_1[_i];
33066 if (!potential.merged ||
33067 potential.key === node.key) {
33070 var enu = this._geoCoords.geodeticToEnu(potential.latLon.lat, potential.latLon.lon, potential.alt, node.latLon.lat, node.latLon.lon, node.alt);
33071 var motion = new THREE.Vector3(enu[0], enu[1], enu[2]);
33072 var distance = motion.length();
33073 if (distance > this._settings.maxDistance &&
33074 fallbackKeys.indexOf(potential.key) < 0) {
33077 var motionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, motion.x, motion.y);
33078 var verticalMotion = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
33079 var direction = this._spatial.viewingDirection(potential.rotation);
33080 var directionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
33081 var verticalDirection = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
33082 var verticalDirectionChange = verticalDirection - currentVerticalDirection;
33083 var rotation = this._spatial.relativeRotationAngle(node.rotation, potential.rotation);
33084 var worldMotionAzimuth = this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
33085 var sameSequence = potential.sequenceKey != null &&
33086 node.sequenceKey != null &&
33087 potential.sequenceKey === node.sequenceKey;
33088 var sameMergeCC = (potential.mergeCC == null && node.mergeCC == null) ||
33089 potential.mergeCC === node.mergeCC;
33090 var sameUser = potential.userKey === node.userKey;
33091 var potentialEdge = {
33092 capturedAt: potential.capturedAt,
33093 directionChange: directionChange,
33094 distance: distance,
33095 fullPano: potential.fullPano,
33096 key: potential.key,
33097 motionChange: motionChange,
33098 rotation: rotation,
33099 sameMergeCC: sameMergeCC,
33100 sameSequence: sameSequence,
33101 sameUser: sameUser,
33102 sequenceKey: potential.sequenceKey,
33103 verticalDirectionChange: verticalDirectionChange,
33104 verticalMotion: verticalMotion,
33105 worldMotionAzimuth: worldMotionAzimuth,
33107 potentialEdges.push(potentialEdge);
33109 return potentialEdges;
33112 * Computes the sequence edges for a node.
33114 * @param {Node} node - Source node.
33115 * @throws {ArgumentMapillaryError} If node is not full.
33117 EdgeCalculator.prototype.computeSequenceEdges = function (node, sequence) {
33119 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
33121 if (node.sequenceKey !== sequence.key) {
33122 throw new Error_1.ArgumentMapillaryError("Node and sequence does not correspond.");
33125 var nextKey = sequence.findNextKey(node.key);
33126 if (nextKey != null) {
33129 direction: Edge_1.EdgeDirection.Next,
33130 worldMotionAzimuth: Number.NaN,
33136 var prevKey = sequence.findPrevKey(node.key);
33137 if (prevKey != null) {
33140 direction: Edge_1.EdgeDirection.Prev,
33141 worldMotionAzimuth: Number.NaN,
33150 * Computes the similar edges for a node.
33152 * @description Similar edges for perspective images and cropped panoramas
33153 * look roughly in the same direction and are positioned closed to the node.
33154 * Similar edges for full panoramas only target other full panoramas.
33156 * @param {Node} node - Source node.
33157 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
33158 * @throws {ArgumentMapillaryError} If node is not full.
33160 EdgeCalculator.prototype.computeSimilarEdges = function (node, potentialEdges) {
33163 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
33165 var nodeFullPano = node.fullPano;
33166 var sequenceGroups = {};
33167 for (var _i = 0, potentialEdges_1 = potentialEdges; _i < potentialEdges_1.length; _i++) {
33168 var potentialEdge = potentialEdges_1[_i];
33169 if (potentialEdge.sequenceKey == null) {
33172 if (potentialEdge.sameSequence ||
33173 !potentialEdge.sameMergeCC) {
33176 if (nodeFullPano) {
33177 if (!potentialEdge.fullPano) {
33182 if (!potentialEdge.fullPano &&
33183 Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
33187 if (potentialEdge.distance > this._settings.similarMaxDistance) {
33190 if (potentialEdge.sameUser &&
33191 Math.abs(potentialEdge.capturedAt - node.capturedAt) <
33192 this._settings.similarMinTimeDifference) {
33195 if (sequenceGroups[potentialEdge.sequenceKey] == null) {
33196 sequenceGroups[potentialEdge.sequenceKey] = [];
33198 sequenceGroups[potentialEdge.sequenceKey].push(potentialEdge);
33200 var similarEdges = [];
33201 var calculateScore = node.fullPano ?
33202 function (potentialEdge) {
33203 return potentialEdge.distance;
33205 function (potentialEdge) {
33206 return _this._coefficients.similarDistance * potentialEdge.distance +
33207 _this._coefficients.similarRotation * potentialEdge.rotation;
33209 for (var sequenceKey in sequenceGroups) {
33210 if (!sequenceGroups.hasOwnProperty(sequenceKey)) {
33213 var lowestScore = Number.MAX_VALUE;
33214 var similarEdge = null;
33215 for (var _a = 0, _b = sequenceGroups[sequenceKey]; _a < _b.length; _a++) {
33216 var potentialEdge = _b[_a];
33217 var score = calculateScore(potentialEdge);
33218 if (score < lowestScore) {
33219 lowestScore = score;
33220 similarEdge = potentialEdge;
33223 if (similarEdge == null) {
33226 similarEdges.push(similarEdge);
33228 return similarEdges
33229 .map(function (potentialEdge) {
33232 direction: Edge_1.EdgeDirection.Similar,
33233 worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
33236 to: potentialEdge.key,
33241 * Computes the step edges for a perspective node.
33243 * @param {Node} node - Source node.
33244 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
33245 * @param {string} prevKey - Key of previous node in sequence.
33246 * @param {string} prevKey - Key of next node in sequence.
33247 * @throws {ArgumentMapillaryError} If node is not full.
33249 EdgeCalculator.prototype.computeStepEdges = function (node, potentialEdges, prevKey, nextKey) {
33251 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
33254 if (node.fullPano) {
33257 for (var k in this._directions.steps) {
33258 if (!this._directions.steps.hasOwnProperty(k)) {
33261 var step = this._directions.steps[k];
33262 var lowestScore = Number.MAX_VALUE;
33264 var fallback = null;
33265 for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) {
33266 var potential = potentialEdges_2[_i];
33267 if (potential.fullPano) {
33270 if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
33273 var motionDifference = this._spatial.angleDifference(step.motionChange, potential.motionChange);
33274 var directionMotionDifference = this._spatial.angleDifference(potential.directionChange, motionDifference);
33275 var drift = Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
33276 if (Math.abs(drift) > this._settings.stepMaxDrift) {
33279 var potentialKey = potential.key;
33280 if (step.useFallback && (potentialKey === prevKey || potentialKey === nextKey)) {
33281 fallback = potential;
33283 if (potential.distance > this._settings.stepMaxDistance) {
33286 motionDifference = Math.sqrt(motionDifference * motionDifference +
33287 potential.verticalMotion * potential.verticalMotion);
33288 var score = this._coefficients.stepPreferredDistance *
33289 Math.abs(potential.distance - this._settings.stepPreferredDistance) /
33290 this._settings.stepMaxDistance +
33291 this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
33292 this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
33293 this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
33294 this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
33295 if (score < lowestScore) {
33296 lowestScore = score;
33300 edge = edge == null ? fallback : edge;
33301 if (edge != null) {
33304 direction: step.direction,
33305 worldMotionAzimuth: edge.worldMotionAzimuth,
33315 * Computes the turn edges for a perspective node.
33317 * @param {Node} node - Source node.
33318 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
33319 * @throws {ArgumentMapillaryError} If node is not full.
33321 EdgeCalculator.prototype.computeTurnEdges = function (node, potentialEdges) {
33323 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
33326 if (node.fullPano) {
33329 for (var k in this._directions.turns) {
33330 if (!this._directions.turns.hasOwnProperty(k)) {
33333 var turn = this._directions.turns[k];
33334 var lowestScore = Number.MAX_VALUE;
33336 for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) {
33337 var potential = potentialEdges_3[_i];
33338 if (potential.fullPano) {
33341 if (potential.distance > this._settings.turnMaxDistance) {
33344 var rig = turn.direction !== Edge_1.EdgeDirection.TurnU &&
33345 potential.distance < this._settings.turnMaxRigDistance &&
33346 Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
33347 var directionDifference = this._spatial.angleDifference(turn.directionChange, potential.directionChange);
33348 var score = void 0;
33350 potential.directionChange * turn.directionChange > 0 &&
33351 Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
33352 score = -Math.PI / 2 + Math.abs(potential.directionChange);
33355 if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
33358 var motionDifference = turn.motionChange ?
33359 this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
33360 motionDifference = Math.sqrt(motionDifference * motionDifference +
33361 potential.verticalMotion * potential.verticalMotion);
33363 this._coefficients.turnDistance * potential.distance /
33364 this._settings.turnMaxDistance +
33365 this._coefficients.turnMotion * motionDifference / Math.PI +
33366 this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
33367 this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
33369 if (score < lowestScore) {
33370 lowestScore = score;
33374 if (edge != null) {
33377 direction: turn.direction,
33378 worldMotionAzimuth: edge.worldMotionAzimuth,
33388 * Computes the pano edges for a perspective node.
33390 * @param {Node} node - Source node.
33391 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
33392 * @throws {ArgumentMapillaryError} If node is not full.
33394 EdgeCalculator.prototype.computePerspectiveToPanoEdges = function (node, potentialEdges) {
33396 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
33398 if (node.fullPano) {
33401 var lowestScore = Number.MAX_VALUE;
33403 for (var _i = 0, potentialEdges_4 = potentialEdges; _i < potentialEdges_4.length; _i++) {
33404 var potential = potentialEdges_4[_i];
33405 if (!potential.fullPano) {
33408 var score = this._coefficients.panoPreferredDistance *
33409 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
33410 this._settings.panoMaxDistance +
33411 this._coefficients.panoMotion * Math.abs(potential.motionChange) / Math.PI +
33412 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
33413 if (score < lowestScore) {
33414 lowestScore = score;
33418 if (edge == null) {
33424 direction: Edge_1.EdgeDirection.Pano,
33425 worldMotionAzimuth: edge.worldMotionAzimuth,
33433 * Computes the pano and step edges for a pano node.
33435 * @param {Node} node - Source node.
33436 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
33437 * @throws {ArgumentMapillaryError} If node is not full.
33439 EdgeCalculator.prototype.computePanoEdges = function (node, potentialEdges) {
33441 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
33443 if (!node.fullPano) {
33446 var panoEdges = [];
33447 var potentialPanos = [];
33448 var potentialSteps = [];
33449 for (var _i = 0, potentialEdges_5 = potentialEdges; _i < potentialEdges_5.length; _i++) {
33450 var potential = potentialEdges_5[_i];
33451 if (potential.distance > this._settings.panoMaxDistance) {
33454 if (potential.fullPano) {
33455 if (potential.distance < this._settings.panoMinDistance) {
33458 potentialPanos.push(potential);
33461 for (var k in this._directions.panos) {
33462 if (!this._directions.panos.hasOwnProperty(k)) {
33465 var pano = this._directions.panos[k];
33466 var turn = this._spatial.angleDifference(potential.directionChange, potential.motionChange);
33467 var turnChange = this._spatial.angleDifference(pano.directionChange, turn);
33468 if (Math.abs(turnChange) > this._settings.panoMaxStepTurnChange) {
33471 potentialSteps.push([pano.direction, potential]);
33472 // break if step direction found
33477 var maxRotationDifference = Math.PI / this._settings.panoMaxItems;
33478 var occupiedAngles = [];
33479 var stepAngles = [];
33480 for (var index = 0; index < this._settings.panoMaxItems; index++) {
33481 var rotation = index / this._settings.panoMaxItems * 2 * Math.PI;
33482 var lowestScore = Number.MAX_VALUE;
33484 for (var _a = 0, potentialPanos_1 = potentialPanos; _a < potentialPanos_1.length; _a++) {
33485 var potential = potentialPanos_1[_a];
33486 var motionDifference = this._spatial.angleDifference(rotation, potential.motionChange);
33487 if (Math.abs(motionDifference) > maxRotationDifference) {
33490 var occupiedDifference = Number.MAX_VALUE;
33491 for (var _b = 0, occupiedAngles_1 = occupiedAngles; _b < occupiedAngles_1.length; _b++) {
33492 var occupiedAngle = occupiedAngles_1[_b];
33493 var difference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
33494 if (difference < occupiedDifference) {
33495 occupiedDifference = difference;
33498 if (occupiedDifference <= maxRotationDifference) {
33501 var score = this._coefficients.panoPreferredDistance *
33502 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
33503 this._settings.panoMaxDistance +
33504 this._coefficients.panoMotion * Math.abs(motionDifference) / maxRotationDifference +
33505 this._coefficients.panoSequencePenalty * (potential.sameSequence ? 0 : 1) +
33506 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
33507 if (score < lowestScore) {
33508 lowestScore = score;
33512 if (edge != null) {
33513 occupiedAngles.push(edge.motionChange);
33516 direction: Edge_1.EdgeDirection.Pano,
33517 worldMotionAzimuth: edge.worldMotionAzimuth,
33524 stepAngles.push(rotation);
33527 var occupiedStepAngles = {};
33528 occupiedStepAngles[Edge_1.EdgeDirection.Pano] = occupiedAngles;
33529 occupiedStepAngles[Edge_1.EdgeDirection.StepForward] = [];
33530 occupiedStepAngles[Edge_1.EdgeDirection.StepLeft] = [];
33531 occupiedStepAngles[Edge_1.EdgeDirection.StepBackward] = [];
33532 occupiedStepAngles[Edge_1.EdgeDirection.StepRight] = [];
33533 for (var _c = 0, stepAngles_1 = stepAngles; _c < stepAngles_1.length; _c++) {
33534 var stepAngle = stepAngles_1[_c];
33535 var occupations = [];
33536 for (var k in this._directions.panos) {
33537 if (!this._directions.panos.hasOwnProperty(k)) {
33540 var pano = this._directions.panos[k];
33541 var allOccupiedAngles = occupiedStepAngles[Edge_1.EdgeDirection.Pano]
33542 .concat(occupiedStepAngles[pano.direction])
33543 .concat(occupiedStepAngles[pano.prev])
33544 .concat(occupiedStepAngles[pano.next]);
33545 var lowestScore = Number.MAX_VALUE;
33547 for (var _d = 0, potentialSteps_1 = potentialSteps; _d < potentialSteps_1.length; _d++) {
33548 var potential = potentialSteps_1[_d];
33549 if (potential[0] !== pano.direction) {
33552 var motionChange = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
33553 if (Math.abs(motionChange) > maxRotationDifference) {
33556 var minOccupiedDifference = Number.MAX_VALUE;
33557 for (var _e = 0, allOccupiedAngles_1 = allOccupiedAngles; _e < allOccupiedAngles_1.length; _e++) {
33558 var occupiedAngle = allOccupiedAngles_1[_e];
33559 var occupiedDifference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
33560 if (occupiedDifference < minOccupiedDifference) {
33561 minOccupiedDifference = occupiedDifference;
33564 if (minOccupiedDifference <= maxRotationDifference) {
33567 var score = this._coefficients.panoPreferredDistance *
33568 Math.abs(potential[1].distance - this._settings.panoPreferredDistance) /
33569 this._settings.panoMaxDistance +
33570 this._coefficients.panoMotion * Math.abs(motionChange) / maxRotationDifference +
33571 this._coefficients.panoMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
33572 if (score < lowestScore) {
33573 lowestScore = score;
33577 if (edge != null) {
33578 occupations.push(edge);
33581 direction: edge[0],
33582 worldMotionAzimuth: edge[1].worldMotionAzimuth,
33589 for (var _f = 0, occupations_1 = occupations; _f < occupations_1.length; _f++) {
33590 var occupation = occupations_1[_f];
33591 occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
33596 return EdgeCalculator;
33598 exports.EdgeCalculator = EdgeCalculator;
33599 Object.defineProperty(exports, "__esModule", { value: true });
33600 exports.default = EdgeCalculator;
33602 },{"../../Edge":226,"../../Error":227,"../../Geo":228,"three":175}],316:[function(require,module,exports){
33604 var EdgeCalculatorCoefficients = (function () {
33605 function EdgeCalculatorCoefficients() {
33606 this.panoPreferredDistance = 2;
33607 this.panoMotion = 2;
33608 this.panoSequencePenalty = 1;
33609 this.panoMergeCCPenalty = 4;
33610 this.stepPreferredDistance = 4;
33611 this.stepMotion = 3;
33612 this.stepRotation = 4;
33613 this.stepSequencePenalty = 2;
33614 this.stepMergeCCPenalty = 6;
33615 this.similarDistance = 2;
33616 this.similarRotation = 3;
33617 this.turnDistance = 4;
33618 this.turnMotion = 2;
33619 this.turnSequencePenalty = 1;
33620 this.turnMergeCCPenalty = 4;
33622 return EdgeCalculatorCoefficients;
33624 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients;
33625 Object.defineProperty(exports, "__esModule", { value: true });
33626 exports.default = EdgeCalculatorCoefficients;
33628 },{}],317:[function(require,module,exports){
33630 var Edge_1 = require("../../Edge");
33631 var EdgeCalculatorDirections = (function () {
33632 function EdgeCalculatorDirections() {
33636 this.steps[Edge_1.EdgeDirection.StepForward] = {
33637 direction: Edge_1.EdgeDirection.StepForward,
33641 this.steps[Edge_1.EdgeDirection.StepBackward] = {
33642 direction: Edge_1.EdgeDirection.StepBackward,
33643 motionChange: Math.PI,
33646 this.steps[Edge_1.EdgeDirection.StepLeft] = {
33647 direction: Edge_1.EdgeDirection.StepLeft,
33648 motionChange: Math.PI / 2,
33649 useFallback: false,
33651 this.steps[Edge_1.EdgeDirection.StepRight] = {
33652 direction: Edge_1.EdgeDirection.StepRight,
33653 motionChange: -Math.PI / 2,
33654 useFallback: false,
33656 this.turns[Edge_1.EdgeDirection.TurnLeft] = {
33657 direction: Edge_1.EdgeDirection.TurnLeft,
33658 directionChange: Math.PI / 2,
33659 motionChange: Math.PI / 4,
33661 this.turns[Edge_1.EdgeDirection.TurnRight] = {
33662 direction: Edge_1.EdgeDirection.TurnRight,
33663 directionChange: -Math.PI / 2,
33664 motionChange: -Math.PI / 4,
33666 this.turns[Edge_1.EdgeDirection.TurnU] = {
33667 direction: Edge_1.EdgeDirection.TurnU,
33668 directionChange: Math.PI,
33669 motionChange: null,
33671 this.panos[Edge_1.EdgeDirection.StepForward] = {
33672 direction: Edge_1.EdgeDirection.StepForward,
33673 directionChange: 0,
33674 next: Edge_1.EdgeDirection.StepLeft,
33675 prev: Edge_1.EdgeDirection.StepRight,
33677 this.panos[Edge_1.EdgeDirection.StepBackward] = {
33678 direction: Edge_1.EdgeDirection.StepBackward,
33679 directionChange: Math.PI,
33680 next: Edge_1.EdgeDirection.StepRight,
33681 prev: Edge_1.EdgeDirection.StepLeft,
33683 this.panos[Edge_1.EdgeDirection.StepLeft] = {
33684 direction: Edge_1.EdgeDirection.StepLeft,
33685 directionChange: Math.PI / 2,
33686 next: Edge_1.EdgeDirection.StepBackward,
33687 prev: Edge_1.EdgeDirection.StepForward,
33689 this.panos[Edge_1.EdgeDirection.StepRight] = {
33690 direction: Edge_1.EdgeDirection.StepRight,
33691 directionChange: -Math.PI / 2,
33692 next: Edge_1.EdgeDirection.StepForward,
33693 prev: Edge_1.EdgeDirection.StepBackward,
33696 return EdgeCalculatorDirections;
33698 exports.EdgeCalculatorDirections = EdgeCalculatorDirections;
33700 },{"../../Edge":226}],318:[function(require,module,exports){
33702 var EdgeCalculatorSettings = (function () {
33703 function EdgeCalculatorSettings() {
33704 this.panoMinDistance = 0.1;
33705 this.panoMaxDistance = 20;
33706 this.panoPreferredDistance = 5;
33707 this.panoMaxItems = 4;
33708 this.panoMaxStepTurnChange = Math.PI / 8;
33709 this.rotationMaxDistance = this.turnMaxRigDistance;
33710 this.rotationMaxDirectionChange = Math.PI / 6;
33711 this.rotationMaxVerticalDirectionChange = Math.PI / 8;
33712 this.similarMaxDirectionChange = Math.PI / 8;
33713 this.similarMaxDistance = 12;
33714 this.similarMinTimeDifference = 12 * 3600 * 1000;
33715 this.stepMaxDistance = 20;
33716 this.stepMaxDirectionChange = Math.PI / 6;
33717 this.stepMaxDrift = Math.PI / 6;
33718 this.stepPreferredDistance = 4;
33719 this.turnMaxDistance = 15;
33720 this.turnMaxDirectionChange = 2 * Math.PI / 9;
33721 this.turnMaxRigDistance = 0.65;
33722 this.turnMinRigDirectionChange = Math.PI / 6;
33724 Object.defineProperty(EdgeCalculatorSettings.prototype, "maxDistance", {
33726 return Math.max(this.panoMaxDistance, this.similarMaxDistance, this.stepMaxDistance, this.turnMaxDistance);
33731 return EdgeCalculatorSettings;
33733 exports.EdgeCalculatorSettings = EdgeCalculatorSettings;
33734 Object.defineProperty(exports, "__esModule", { value: true });
33735 exports.default = EdgeCalculatorSettings;
33737 },{}],319:[function(require,module,exports){
33740 * Enumeration for edge directions
33743 * @description Directions for edges in node graph describing
33744 * sequence, spatial and node type relations between nodes.
33747 (function (EdgeDirection) {
33749 * Next node in the sequence.
33751 EdgeDirection[EdgeDirection["Next"] = 0] = "Next";
33753 * Previous node in the sequence.
33755 EdgeDirection[EdgeDirection["Prev"] = 1] = "Prev";
33757 * Step to the left keeping viewing direction.
33759 EdgeDirection[EdgeDirection["StepLeft"] = 2] = "StepLeft";
33761 * Step to the right keeping viewing direction.
33763 EdgeDirection[EdgeDirection["StepRight"] = 3] = "StepRight";
33765 * Step forward keeping viewing direction.
33767 EdgeDirection[EdgeDirection["StepForward"] = 4] = "StepForward";
33769 * Step backward keeping viewing direction.
33771 EdgeDirection[EdgeDirection["StepBackward"] = 5] = "StepBackward";
33773 * Turn 90 degrees counter clockwise.
33775 EdgeDirection[EdgeDirection["TurnLeft"] = 6] = "TurnLeft";
33777 * Turn 90 degrees clockwise.
33779 EdgeDirection[EdgeDirection["TurnRight"] = 7] = "TurnRight";
33781 * Turn 180 degrees.
33783 EdgeDirection[EdgeDirection["TurnU"] = 8] = "TurnU";
33785 * Panorama in general direction.
33787 EdgeDirection[EdgeDirection["Pano"] = 9] = "Pano";
33789 * Looking in roughly the same direction at rougly the same position.
33791 EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar";
33792 })(EdgeDirection = exports.EdgeDirection || (exports.EdgeDirection = {}));
33795 },{}],320:[function(require,module,exports){
33796 /// <reference path="../../typings/index.d.ts" />
33798 var _ = require("underscore");
33799 var vd = require("virtual-dom");
33800 var Subject_1 = require("rxjs/Subject");
33801 require("rxjs/add/operator/combineLatest");
33802 require("rxjs/add/operator/distinctUntilChanged");
33803 require("rxjs/add/operator/filter");
33804 require("rxjs/add/operator/map");
33805 require("rxjs/add/operator/pluck");
33806 require("rxjs/add/operator/scan");
33807 var Render_1 = require("../Render");
33808 var DOMRenderer = (function () {
33809 function DOMRenderer(element, renderService, currentFrame$) {
33810 this._adaptiveOperation$ = new Subject_1.Subject();
33811 this._render$ = new Subject_1.Subject();
33812 this._renderAdaptive$ = new Subject_1.Subject();
33813 this._renderService = renderService;
33814 this._currentFrame$ = currentFrame$;
33815 var rootNode = vd.create(vd.h("div.domRenderer", []));
33816 element.appendChild(rootNode);
33817 this._offset$ = this._adaptiveOperation$
33818 .scan(function (adaptive, operation) {
33819 return operation(adaptive);
33821 elementHeight: element.offsetHeight,
33822 elementWidth: element.offsetWidth,
33824 renderMode: Render_1.RenderMode.Fill,
33826 .filter(function (adaptive) {
33827 return adaptive.imageAspect > 0 && adaptive.elementWidth > 0 && adaptive.elementHeight > 0;
33829 .map(function (adaptive) {
33830 var elementAspect = adaptive.elementWidth / adaptive.elementHeight;
33831 var ratio = adaptive.imageAspect / elementAspect;
33832 var verticalOffset = 0;
33833 var horizontalOffset = 0;
33834 if (adaptive.renderMode === Render_1.RenderMode.Letterbox) {
33835 if (adaptive.imageAspect > elementAspect) {
33836 verticalOffset = adaptive.elementHeight * (1 - 1 / ratio) / 2;
33839 horizontalOffset = adaptive.elementWidth * (1 - ratio) / 2;
33843 if (adaptive.imageAspect > elementAspect) {
33844 horizontalOffset = -adaptive.elementWidth * (ratio - 1) / 2;
33847 verticalOffset = -adaptive.elementHeight * (1 / ratio - 1) / 2;
33851 bottom: verticalOffset,
33852 left: horizontalOffset,
33853 right: horizontalOffset,
33854 top: verticalOffset,
33857 this._currentFrame$
33858 .filter(function (frame) {
33859 return frame.state.currentNode != null;
33861 .distinctUntilChanged(function (k1, k2) {
33863 }, function (frame) {
33864 return frame.state.currentNode.key;
33866 .map(function (frame) {
33867 return frame.state.currentTransform.basicAspect;
33869 .map(function (aspect) {
33870 return function (adaptive) {
33871 adaptive.imageAspect = aspect;
33875 .subscribe(this._adaptiveOperation$);
33876 this._renderAdaptive$
33877 .scan(function (vNodeHashes, vNodeHash) {
33878 if (vNodeHash.vnode == null) {
33879 delete vNodeHashes[vNodeHash.name];
33882 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
33884 return vNodeHashes;
33886 .combineLatest(this._offset$)
33887 .map(function (vo) {
33888 var vNodes = _.values(vo[0]);
33889 var offset = vo[1];
33892 bottom: offset.bottom + "px",
33893 left: offset.left + "px",
33894 "pointer-events": "none",
33895 position: "absolute",
33896 right: offset.right + "px",
33897 top: offset.top + "px",
33901 name: "adaptiveDomRenderer",
33902 vnode: vd.h("div.adaptiveDomRenderer", properties, vNodes),
33905 .subscribe(this._render$);
33906 this._vNode$ = this._render$
33907 .scan(function (vNodeHashes, vNodeHash) {
33908 if (vNodeHash.vnode == null) {
33909 delete vNodeHashes[vNodeHash.name];
33912 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
33914 return vNodeHashes;
33916 .map(function (vNodeHashes) {
33917 var vNodes = _.values(vNodeHashes);
33918 return vd.h("div.domRenderer", vNodes);
33920 this._vPatch$ = this._vNode$
33921 .scan(function (nodePatch, vNode) {
33922 nodePatch.vpatch = vd.diff(nodePatch.vnode, vNode);
33923 nodePatch.vnode = vNode;
33925 }, { vnode: vd.h("div.domRenderer", []), vpatch: null })
33927 this._element$ = this._vPatch$
33928 .scan(function (oldElement, vPatch) {
33929 return vd.patch(oldElement, vPatch);
33933 this._element$.subscribe(function () { });
33934 this._renderService.size$
33935 .map(function (size) {
33936 return function (adaptive) {
33937 adaptive.elementWidth = size.width;
33938 adaptive.elementHeight = size.height;
33942 .subscribe(this._adaptiveOperation$);
33943 this._renderService.renderMode$
33944 .map(function (renderMode) {
33945 return function (adaptive) {
33946 adaptive.renderMode = renderMode;
33950 .subscribe(this._adaptiveOperation$);
33952 Object.defineProperty(DOMRenderer.prototype, "element$", {
33954 return this._element$;
33959 Object.defineProperty(DOMRenderer.prototype, "render$", {
33961 return this._render$;
33966 Object.defineProperty(DOMRenderer.prototype, "renderAdaptive$", {
33968 return this._renderAdaptive$;
33973 DOMRenderer.prototype.clear = function (name) {
33974 this._renderAdaptive$.next({ name: name, vnode: null });
33975 this._render$.next({ name: name, vnode: null });
33977 return DOMRenderer;
33979 exports.DOMRenderer = DOMRenderer;
33980 Object.defineProperty(exports, "__esModule", { value: true });
33981 exports.default = DOMRenderer;
33983 },{"../Render":231,"rxjs/Subject":33,"rxjs/add/operator/combineLatest":52,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/pluck":69,"rxjs/add/operator/scan":72,"underscore":176,"virtual-dom":181}],321:[function(require,module,exports){
33986 (function (GLRenderStage) {
33987 GLRenderStage[GLRenderStage["Background"] = 0] = "Background";
33988 GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground";
33989 })(GLRenderStage = exports.GLRenderStage || (exports.GLRenderStage = {}));
33990 Object.defineProperty(exports, "__esModule", { value: true });
33991 exports.default = GLRenderStage;
33993 },{}],322:[function(require,module,exports){
33994 /// <reference path="../../typings/index.d.ts" />
33996 var THREE = require("three");
33997 var Observable_1 = require("rxjs/Observable");
33998 var Subject_1 = require("rxjs/Subject");
33999 require("rxjs/add/observable/combineLatest");
34000 require("rxjs/add/operator/distinctUntilChanged");
34001 require("rxjs/add/operator/filter");
34002 require("rxjs/add/operator/first");
34003 require("rxjs/add/operator/map");
34004 require("rxjs/add/operator/merge");
34005 require("rxjs/add/operator/mergeMap");
34006 require("rxjs/add/operator/scan");
34007 require("rxjs/add/operator/share");
34008 require("rxjs/add/operator/startWith");
34009 var Render_1 = require("../Render");
34010 var GLRenderer = (function () {
34011 function GLRenderer(canvasContainer, renderService) {
34013 this._renderFrame$ = new Subject_1.Subject();
34014 this._renderCameraOperation$ = new Subject_1.Subject();
34015 this._render$ = new Subject_1.Subject();
34016 this._clear$ = new Subject_1.Subject();
34017 this._renderOperation$ = new Subject_1.Subject();
34018 this._rendererOperation$ = new Subject_1.Subject();
34019 this._eraserOperation$ = new Subject_1.Subject();
34020 this._renderService = renderService;
34021 this._renderer$ = this._rendererOperation$
34022 .scan(function (renderer, operation) {
34023 return operation(renderer);
34024 }, { needsRender: false, renderer: null });
34025 this._renderCollection$ = this._renderOperation$
34026 .scan(function (hashes, operation) {
34027 return operation(hashes);
34030 this._renderCamera$ = this._renderCameraOperation$
34031 .scan(function (rc, operation) {
34032 return operation(rc);
34033 }, { frameId: -1, needsRender: false, perspective: null });
34034 this._eraser$ = this._eraserOperation$
34035 .startWith(function (eraser) {
34038 .scan(function (eraser, operation) {
34039 return operation(eraser);
34040 }, { needsRender: false });
34041 Observable_1.Observable
34042 .combineLatest([this._renderer$, this._renderCollection$, this._renderCamera$, this._eraser$], function (renderer, hashes, rc, eraser) {
34043 var renders = Object.keys(hashes)
34044 .map(function (key) {
34045 return hashes[key];
34047 return { camera: rc, eraser: eraser, renderer: renderer, renders: renders };
34049 .filter(function (co) {
34050 var needsRender = co.renderer.needsRender ||
34051 co.camera.needsRender ||
34052 co.eraser.needsRender;
34053 var frameId = co.camera.frameId;
34054 for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
34055 var render = _a[_i];
34056 if (render.frameId !== frameId) {
34059 needsRender = needsRender || render.needsRender;
34061 return needsRender;
34063 .distinctUntilChanged(function (n1, n2) {
34066 return co.eraser.needsRender ? -1 : co.camera.frameId;
34068 .subscribe(function (co) {
34069 co.renderer.needsRender = false;
34070 co.camera.needsRender = false;
34071 co.eraser.needsRender = false;
34072 var perspectiveCamera = co.camera.perspective;
34073 var backgroundRenders = [];
34074 var foregroundRenders = [];
34075 for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
34076 var render = _a[_i];
34077 if (render.stage === Render_1.GLRenderStage.Background) {
34078 backgroundRenders.push(render.render);
34080 else if (render.stage === Render_1.GLRenderStage.Foreground) {
34081 foregroundRenders.push(render.render);
34084 var renderer = co.renderer.renderer;
34086 for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) {
34087 var render = backgroundRenders_1[_b];
34088 render(perspectiveCamera, renderer);
34090 renderer.clearDepth();
34091 for (var _c = 0, foregroundRenders_1 = foregroundRenders; _c < foregroundRenders_1.length; _c++) {
34092 var render = foregroundRenders_1[_c];
34093 render(perspectiveCamera, renderer);
34097 .map(function (rc) {
34098 return function (irc) {
34099 irc.frameId = rc.frameId;
34100 irc.perspective = rc.perspective;
34101 if (rc.changed === true) {
34102 irc.needsRender = true;
34107 .subscribe(this._renderCameraOperation$);
34108 this._renderFrameSubscribe();
34109 var renderHash$ = this._render$
34110 .map(function (hash) {
34111 return function (hashes) {
34112 hashes[hash.name] = hash.render;
34116 var clearHash$ = this._clear$
34117 .map(function (name) {
34118 return function (hashes) {
34119 delete hashes[name];
34123 Observable_1.Observable
34124 .merge(renderHash$, clearHash$)
34125 .subscribe(this._renderOperation$);
34126 this._webGLRenderer$ = this._render$
34128 .map(function (hash) {
34129 var element = renderService.element;
34130 var webGLRenderer = new THREE.WebGLRenderer();
34131 webGLRenderer.setPixelRatio(window.devicePixelRatio);
34132 webGLRenderer.setSize(element.offsetWidth, element.offsetHeight);
34133 webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0);
34134 webGLRenderer.autoClear = false;
34135 webGLRenderer.domElement.style.position = "absolute";
34136 canvasContainer.appendChild(webGLRenderer.domElement);
34137 return webGLRenderer;
34141 this._webGLRenderer$.subscribe(function () { });
34142 var createRenderer$ = this._webGLRenderer$
34144 .map(function (webGLRenderer) {
34145 return function (renderer) {
34146 renderer.needsRender = true;
34147 renderer.renderer = webGLRenderer;
34151 var resizeRenderer$ = this._renderService.size$
34152 .map(function (size) {
34153 return function (renderer) {
34154 if (renderer.renderer == null) {
34157 renderer.renderer.setSize(size.width, size.height);
34158 renderer.needsRender = true;
34162 var clearRenderer$ = this._clear$
34163 .map(function (name) {
34164 return function (renderer) {
34165 if (renderer.renderer == null) {
34168 renderer.needsRender = true;
34172 Observable_1.Observable
34173 .merge(createRenderer$, resizeRenderer$, clearRenderer$)
34174 .subscribe(this._rendererOperation$);
34175 var renderCollectionEmpty$ = this._renderCollection$
34176 .filter(function (hashes) {
34177 return Object.keys(hashes).length === 0;
34180 renderCollectionEmpty$
34181 .subscribe(function (hashes) {
34182 if (_this._renderFrameSubscription == null) {
34185 _this._renderFrameSubscription.unsubscribe();
34186 _this._renderFrameSubscription = null;
34187 _this._renderFrameSubscribe();
34189 renderCollectionEmpty$
34190 .map(function (hashes) {
34191 return function (eraser) {
34192 eraser.needsRender = true;
34196 .subscribe(this._eraserOperation$);
34198 Object.defineProperty(GLRenderer.prototype, "render$", {
34200 return this._render$;
34205 Object.defineProperty(GLRenderer.prototype, "webGLRenderer$", {
34207 return this._webGLRenderer$;
34212 GLRenderer.prototype.clear = function (name) {
34213 this._clear$.next(name);
34215 GLRenderer.prototype._renderFrameSubscribe = function () {
34219 .map(function (renderHash) {
34220 return function (irc) {
34221 irc.needsRender = true;
34225 .subscribe(function (operation) {
34226 _this._renderCameraOperation$.next(operation);
34228 this._renderFrameSubscription = this._render$
34230 .mergeMap(function (hash) {
34231 return _this._renderService.renderCameraFrame$;
34233 .subscribe(this._renderFrame$);
34237 exports.GLRenderer = GLRenderer;
34238 Object.defineProperty(exports, "__esModule", { value: true });
34239 exports.default = GLRenderer;
34241 },{"../Render":231,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/filter":60,"rxjs/add/operator/first":62,"rxjs/add/operator/map":64,"rxjs/add/operator/merge":65,"rxjs/add/operator/mergeMap":67,"rxjs/add/operator/scan":72,"rxjs/add/operator/share":73,"rxjs/add/operator/startWith":77,"three":175}],323:[function(require,module,exports){
34242 /// <reference path="../../typings/index.d.ts" />
34244 var THREE = require("three");
34245 var Geo_1 = require("../Geo");
34246 var Render_1 = require("../Render");
34247 var RenderCamera = (function () {
34248 function RenderCamera(elementWidth, elementHeight, renderMode) {
34251 this._frameId = -1;
34252 this._changed = false;
34253 this._changedForFrame = -1;
34254 this.currentAspect = 1;
34255 this.currentPano = false;
34256 this.previousAspect = 1;
34257 this.previousPano = false;
34258 this.renderMode = renderMode;
34259 this._spatial = new Geo_1.Spatial();
34260 this._camera = new Geo_1.Camera();
34261 var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
34262 this._perspective = new THREE.PerspectiveCamera(50, perspectiveCameraAspect, 0.4, 10000);
34263 this._perspective.matrixAutoUpdate = false;
34264 this._rotation = { phi: 0, theta: 0 };
34266 Object.defineProperty(RenderCamera.prototype, "camera", {
34268 return this._camera;
34273 Object.defineProperty(RenderCamera.prototype, "changed", {
34275 return this.frameId === this._changedForFrame;
34280 Object.defineProperty(RenderCamera.prototype, "frameId", {
34282 return this._frameId;
34284 set: function (value) {
34285 this._frameId = value;
34286 if (this._changed) {
34287 this._changed = false;
34288 this._changedForFrame = value;
34294 Object.defineProperty(RenderCamera.prototype, "perspective", {
34296 return this._perspective;
34301 Object.defineProperty(RenderCamera.prototype, "rotation", {
34303 return this._rotation;
34308 RenderCamera.prototype.updateAspect = function (elementWidth, elementHeight) {
34309 var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
34310 this._perspective.aspect = perspectiveCameraAspect;
34311 this._changed = true;
34313 RenderCamera.prototype.updateProjection = function () {
34314 var currentAspect = this._getAspect(this.currentAspect, this.currentPano, this.perspective.aspect);
34315 var previousAspect = this._getAspect(this.previousAspect, this.previousPano, this.perspective.aspect);
34316 var aspect = (1 - this.alpha) * previousAspect + this.alpha * currentAspect;
34317 var verticalFov = this._getVerticalFov(aspect, this._camera.focal, this.zoom);
34318 this._perspective.fov = verticalFov;
34319 this._perspective.updateProjectionMatrix();
34320 this._changed = true;
34322 RenderCamera.prototype.updatePerspective = function (camera) {
34323 this._perspective.up.copy(camera.up);
34324 this._perspective.position.copy(camera.position);
34325 this._perspective.lookAt(camera.lookat);
34326 this._perspective.updateMatrix();
34327 this._perspective.updateMatrixWorld(false);
34328 this._changed = true;
34330 RenderCamera.prototype.updateRotation = function (camera) {
34331 this._rotation = this._getRotation(camera);
34333 RenderCamera.prototype._getVerticalFov = function (aspect, focal, zoom) {
34334 return 2 * Math.atan(0.5 / (Math.pow(2, zoom) * aspect * focal)) * 180 / Math.PI;
34336 RenderCamera.prototype._getAspect = function (nodeAspect, pano, perspectiveCameraAspect) {
34340 var coeff = Math.max(1, 1 / nodeAspect);
34341 var usePerspective = this.renderMode === Render_1.RenderMode.Letterbox ?
34342 nodeAspect > perspectiveCameraAspect :
34343 nodeAspect < perspectiveCameraAspect;
34344 var aspect = usePerspective ?
34345 coeff * perspectiveCameraAspect :
34346 coeff * nodeAspect;
34349 RenderCamera.prototype._getPerspectiveCameraAspect = function (elementWidth, elementHeight) {
34350 return elementWidth === 0 ? 0 : elementWidth / elementHeight;
34352 RenderCamera.prototype._getRotation = function (camera) {
34353 var direction = camera.lookat.clone().sub(camera.position);
34354 var up = camera.up.clone();
34355 var upProjection = direction.clone().dot(up);
34356 var planeProjection = direction.clone().sub(up.clone().multiplyScalar(upProjection));
34357 var phi = Math.atan2(planeProjection.y, planeProjection.x);
34358 var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
34359 return { phi: phi, theta: theta };
34361 return RenderCamera;
34363 exports.RenderCamera = RenderCamera;
34364 Object.defineProperty(exports, "__esModule", { value: true });
34365 exports.default = RenderCamera;
34367 },{"../Geo":228,"../Render":231,"three":175}],324:[function(require,module,exports){
34370 * Enumeration for render mode
34373 * @description Modes for specifying how rendering is done
34374 * in the viewer. All modes preserves the original aspect
34375 * ratio of the images.
34378 (function (RenderMode) {
34380 * Displays all content within the viewer.
34382 * @description Black bars shown on both
34383 * sides of the content. Bars are shown
34384 * either below and above or to the left
34385 * and right of the content depending on
34386 * the aspect ratio relation between the
34387 * image and the viewer.
34389 RenderMode[RenderMode["Letterbox"] = 0] = "Letterbox";
34391 * Fills the viewer by cropping content.
34393 * @description Cropping is done either
34394 * in horizontal or vertical direction
34395 * depending on the aspect ratio relation
34396 * between the image and the viewer.
34398 RenderMode[RenderMode["Fill"] = 1] = "Fill";
34399 })(RenderMode = exports.RenderMode || (exports.RenderMode = {}));
34400 Object.defineProperty(exports, "__esModule", { value: true });
34401 exports.default = RenderMode;
34403 },{}],325:[function(require,module,exports){
34404 /// <reference path="../../typings/index.d.ts" />
34406 var Subject_1 = require("rxjs/Subject");
34407 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
34408 require("rxjs/add/observable/combineLatest");
34409 require("rxjs/add/operator/do");
34410 require("rxjs/add/operator/filter");
34411 require("rxjs/add/operator/map");
34412 require("rxjs/add/operator/publishReplay");
34413 require("rxjs/add/operator/scan");
34414 require("rxjs/add/operator/skip");
34415 require("rxjs/add/operator/startWith");
34416 require("rxjs/add/operator/withLatestFrom");
34417 var Geo_1 = require("../Geo");
34418 var Render_1 = require("../Render");
34419 var RenderService = (function () {
34420 function RenderService(element, currentFrame$, renderMode) {
34422 this._element = element;
34423 this._currentFrame$ = currentFrame$;
34424 this._spatial = new Geo_1.Spatial();
34425 renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill;
34426 this._resize$ = new Subject_1.Subject();
34427 this._renderCameraOperation$ = new Subject_1.Subject();
34429 new BehaviorSubject_1.BehaviorSubject({
34430 height: this._element.offsetHeight,
34431 width: this._element.offsetWidth,
34435 return { height: _this._element.offsetHeight, width: _this._element.offsetWidth };
34437 .subscribe(this._size$);
34438 this._renderMode$ = new BehaviorSubject_1.BehaviorSubject(renderMode);
34439 this._renderCameraHolder$ = this._renderCameraOperation$
34440 .startWith(function (rc) {
34443 .scan(function (rc, operation) {
34444 return operation(rc);
34445 }, new Render_1.RenderCamera(this._element.offsetWidth, this._element.offsetHeight, renderMode))
34448 this._renderCameraFrame$ = this._currentFrame$
34449 .withLatestFrom(this._renderCameraHolder$, function (frame, renderCamera) {
34450 return [frame, renderCamera];
34452 .do(function (args) {
34453 var frame = args[0];
34455 var camera = frame.state.camera;
34456 if (rc.alpha !== frame.state.alpha ||
34457 rc.zoom !== frame.state.zoom ||
34458 rc.camera.diff(camera) > 1e-9) {
34459 var currentTransform = frame.state.currentTransform;
34460 var previousTransform = frame.state.previousTransform != null ?
34461 frame.state.previousTransform :
34462 frame.state.currentTransform;
34463 var previousNode = frame.state.previousNode != null ?
34464 frame.state.previousNode :
34465 frame.state.currentNode;
34466 rc.currentAspect = currentTransform.basicAspect;
34467 rc.currentPano = frame.state.currentNode.pano;
34468 rc.previousAspect = previousTransform.basicAspect;
34469 rc.previousPano = previousNode.pano;
34470 rc.alpha = frame.state.alpha;
34471 rc.zoom = frame.state.zoom;
34472 rc.camera.copy(camera);
34473 rc.updatePerspective(camera);
34474 rc.updateRotation(camera);
34475 rc.updateProjection();
34477 rc.frameId = frame.id;
34479 .map(function (args) {
34484 this._renderCamera$ = this._renderCameraFrame$
34485 .filter(function (rc) {
34490 this._bearing$ = this._renderCamera$
34491 .map(function (renderCamera) {
34492 var bearing = _this._spatial.radToDeg(_this._spatial.azimuthalToBearing(renderCamera.rotation.phi));
34493 return _this._spatial.wrap(bearing, 0, 360);
34499 .map(function (size) {
34500 return function (rc) {
34501 rc.updateAspect(size.width, size.height);
34502 rc.updateProjection();
34506 .subscribe(this._renderCameraOperation$);
34509 .map(function (rm) {
34510 return function (rc) {
34511 rc.renderMode = rm;
34512 rc.updateProjection();
34516 .subscribe(this._renderCameraOperation$);
34517 this._bearing$.subscribe(function () { });
34518 this._renderCameraHolder$.subscribe(function () { });
34519 this._size$.subscribe(function () { });
34520 this._renderMode$.subscribe(function () { });
34521 this._renderCamera$.subscribe(function () { });
34522 this._renderCameraFrame$.subscribe(function () { });
34524 Object.defineProperty(RenderService.prototype, "bearing$", {
34526 return this._bearing$;
34531 Object.defineProperty(RenderService.prototype, "element", {
34533 return this._element;
34538 Object.defineProperty(RenderService.prototype, "resize$", {
34540 return this._resize$;
34545 Object.defineProperty(RenderService.prototype, "size$", {
34547 return this._size$;
34552 Object.defineProperty(RenderService.prototype, "renderMode$", {
34554 return this._renderMode$;
34559 Object.defineProperty(RenderService.prototype, "renderCameraFrame$", {
34561 return this._renderCameraFrame$;
34566 Object.defineProperty(RenderService.prototype, "renderCamera$", {
34568 return this._renderCamera$;
34573 return RenderService;
34575 exports.RenderService = RenderService;
34576 Object.defineProperty(exports, "__esModule", { value: true });
34577 exports.default = RenderService;
34579 },{"../Geo":228,"../Render":231,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/do":58,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/skip":74,"rxjs/add/operator/startWith":77,"rxjs/add/operator/withLatestFrom":82}],326:[function(require,module,exports){
34582 (function (State) {
34583 State[State["Traversing"] = 0] = "Traversing";
34584 State[State["Waiting"] = 1] = "Waiting";
34585 })(State = exports.State || (exports.State = {}));
34586 Object.defineProperty(exports, "__esModule", { value: true });
34587 exports.default = State;
34589 },{}],327:[function(require,module,exports){
34591 var State_1 = require("../State");
34592 var Geo_1 = require("../Geo");
34593 var StateContext = (function () {
34594 function StateContext() {
34595 this._state = new State_1.TraversingState({
34597 camera: new Geo_1.Camera(),
34599 reference: { alt: 0, lat: 0, lon: 0 },
34604 StateContext.prototype.traverse = function () {
34605 this._state = this._state.traverse();
34607 StateContext.prototype.wait = function () {
34608 this._state = this._state.wait();
34610 Object.defineProperty(StateContext.prototype, "state", {
34612 if (this._state instanceof State_1.TraversingState) {
34613 return State_1.State.Traversing;
34615 else if (this._state instanceof State_1.WaitingState) {
34616 return State_1.State.Waiting;
34618 throw new Error("Invalid state");
34623 Object.defineProperty(StateContext.prototype, "reference", {
34625 return this._state.reference;
34630 Object.defineProperty(StateContext.prototype, "alpha", {
34632 return this._state.alpha;
34637 Object.defineProperty(StateContext.prototype, "camera", {
34639 return this._state.camera;
34644 Object.defineProperty(StateContext.prototype, "zoom", {
34646 return this._state.zoom;
34651 Object.defineProperty(StateContext.prototype, "currentNode", {
34653 return this._state.currentNode;
34658 Object.defineProperty(StateContext.prototype, "previousNode", {
34660 return this._state.previousNode;
34665 Object.defineProperty(StateContext.prototype, "currentCamera", {
34667 return this._state.currentCamera;
34672 Object.defineProperty(StateContext.prototype, "currentTransform", {
34674 return this._state.currentTransform;
34679 Object.defineProperty(StateContext.prototype, "previousTransform", {
34681 return this._state.previousTransform;
34686 Object.defineProperty(StateContext.prototype, "trajectory", {
34688 return this._state.trajectory;
34693 Object.defineProperty(StateContext.prototype, "currentIndex", {
34695 return this._state.currentIndex;
34700 Object.defineProperty(StateContext.prototype, "lastNode", {
34702 return this._state.trajectory[this._state.trajectory.length - 1];
34707 Object.defineProperty(StateContext.prototype, "nodesAhead", {
34709 return this._state.trajectory.length - 1 - this._state.currentIndex;
34714 Object.defineProperty(StateContext.prototype, "motionless", {
34716 return this._state.motionless;
34721 StateContext.prototype.getCenter = function () {
34722 return this._state.getCenter();
34724 StateContext.prototype.setCenter = function (center) {
34725 this._state.setCenter(center);
34727 StateContext.prototype.setZoom = function (zoom) {
34728 this._state.setZoom(zoom);
34730 StateContext.prototype.update = function (fps) {
34731 this._state.update(fps);
34733 StateContext.prototype.append = function (nodes) {
34734 this._state.append(nodes);
34736 StateContext.prototype.prepend = function (nodes) {
34737 this._state.prepend(nodes);
34739 StateContext.prototype.remove = function (n) {
34740 this._state.remove(n);
34742 StateContext.prototype.clear = function () {
34743 this._state.clear();
34745 StateContext.prototype.clearPrior = function () {
34746 this._state.clearPrior();
34748 StateContext.prototype.cut = function () {
34751 StateContext.prototype.set = function (nodes) {
34752 this._state.set(nodes);
34754 StateContext.prototype.rotate = function (delta) {
34755 this._state.rotate(delta);
34757 StateContext.prototype.rotateBasic = function (basicRotation) {
34758 this._state.rotateBasic(basicRotation);
34760 StateContext.prototype.rotateBasicUnbounded = function (basicRotation) {
34761 this._state.rotateBasicUnbounded(basicRotation);
34763 StateContext.prototype.rotateToBasic = function (basic) {
34764 this._state.rotateToBasic(basic);
34766 StateContext.prototype.move = function (delta) {
34767 this._state.move(delta);
34769 StateContext.prototype.moveTo = function (delta) {
34770 this._state.moveTo(delta);
34772 StateContext.prototype.zoomIn = function (delta, reference) {
34773 this._state.zoomIn(delta, reference);
34775 return StateContext;
34777 exports.StateContext = StateContext;
34779 },{"../Geo":228,"../State":232}],328:[function(require,module,exports){
34781 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
34782 var Subject_1 = require("rxjs/Subject");
34783 var AnimationFrame_1 = require("rxjs/util/AnimationFrame");
34784 require("rxjs/add/operator/bufferCount");
34785 require("rxjs/add/operator/distinctUntilChanged");
34786 require("rxjs/add/operator/do");
34787 require("rxjs/add/operator/filter");
34788 require("rxjs/add/operator/first");
34789 require("rxjs/add/operator/map");
34790 require("rxjs/add/operator/pairwise");
34791 require("rxjs/add/operator/publishReplay");
34792 require("rxjs/add/operator/scan");
34793 require("rxjs/add/operator/startWith");
34794 require("rxjs/add/operator/switchMap");
34795 require("rxjs/add/operator/withLatestFrom");
34796 var State_1 = require("../State");
34797 var StateService = (function () {
34798 function StateService() {
34800 this._appendNode$ = new Subject_1.Subject();
34801 this._start$ = new Subject_1.Subject();
34802 this._frame$ = new Subject_1.Subject();
34803 this._fpsSampleRate = 30;
34804 this._contextOperation$ = new BehaviorSubject_1.BehaviorSubject(function (context) {
34807 this._context$ = this._contextOperation$
34808 .scan(function (context, operation) {
34809 return operation(context);
34810 }, new State_1.StateContext())
34813 this._state$ = this._context$
34814 .map(function (context) {
34815 return context.state;
34817 .distinctUntilChanged()
34820 this._fps$ = this._start$
34821 .switchMap(function () {
34822 return _this._frame$
34823 .bufferCount(1, _this._fpsSampleRate)
34824 .map(function (frameIds) {
34825 return new Date().getTime();
34828 .map(function (times) {
34829 return Math.max(20, 1000 * _this._fpsSampleRate / (times[1] - times[0]));
34834 this._currentState$ = this._frame$
34835 .withLatestFrom(this._fps$, this._context$, function (frameId, fps, context) {
34836 return [frameId, fps, context];
34838 .filter(function (fc) {
34839 return fc[2].currentNode != null;
34841 .do(function (fc) {
34842 fc[2].update(fc[1]);
34844 .map(function (fc) {
34845 return { fps: fc[1], id: fc[0], state: fc[2] };
34848 this._lastState$ = this._currentState$
34851 var nodeChanged$ = this._currentState$
34852 .distinctUntilChanged(undefined, function (f) {
34853 return f.state.currentNode.key;
34857 var nodeChangedSubject$ = new Subject_1.Subject();
34859 .subscribe(nodeChangedSubject$);
34860 this._currentKey$ = new BehaviorSubject_1.BehaviorSubject(null);
34861 nodeChangedSubject$
34862 .map(function (f) {
34863 return f.state.currentNode.key;
34865 .subscribe(this._currentKey$);
34866 this._currentNode$ = nodeChangedSubject$
34867 .map(function (f) {
34868 return f.state.currentNode;
34872 this._currentCamera$ = nodeChangedSubject$
34873 .map(function (f) {
34874 return f.state.currentCamera;
34878 this._currentTransform$ = nodeChangedSubject$
34879 .map(function (f) {
34880 return f.state.currentTransform;
34884 this._reference$ = nodeChangedSubject$
34885 .map(function (f) {
34886 return f.state.reference;
34888 .distinctUntilChanged(function (r1, r2) {
34889 return r1.lat === r2.lat && r1.lon === r2.lon;
34890 }, function (reference) {
34891 return { lat: reference.lat, lon: reference.lon };
34895 this._currentNodeExternal$ = nodeChanged$
34896 .map(function (f) {
34897 return f.state.currentNode;
34902 .map(function (node) {
34903 return function (context) {
34904 context.append([node]);
34908 .subscribe(this._contextOperation$);
34909 this._inMotionOperation$ = new Subject_1.Subject();
34911 .map(function (frame) {
34914 .subscribe(this._inMotionOperation$);
34915 this._inMotionOperation$
34916 .distinctUntilChanged()
34917 .filter(function (moving) {
34920 .switchMap(function (moving) {
34921 return _this._currentState$
34922 .filter(function (frame) {
34923 return frame.state.nodesAhead === 0;
34925 .map(function (frame) {
34926 return [frame.state.camera.clone(), frame.state.zoom];
34929 .map(function (pair) {
34930 var c1 = pair[0][0];
34931 var c2 = pair[1][0];
34932 var z1 = pair[0][1];
34933 var z2 = pair[1][1];
34934 return c1.diff(c2) > 1e-5 || Math.abs(z1 - z2) > 1e-5;
34936 .first(function (changed) {
34940 .subscribe(this._inMotionOperation$);
34941 this._inMotion$ = this._inMotionOperation$
34942 .distinctUntilChanged()
34945 this._inTranslationOperation$ = new Subject_1.Subject();
34947 .map(function (frame) {
34950 .subscribe(this._inTranslationOperation$);
34951 this._inTranslationOperation$
34952 .distinctUntilChanged()
34953 .filter(function (inTranslation) {
34954 return inTranslation;
34956 .switchMap(function (inTranslation) {
34957 return _this._currentState$
34958 .filter(function (frame) {
34959 return frame.state.nodesAhead === 0;
34961 .map(function (frame) {
34962 return frame.state.camera.position.clone();
34965 .map(function (pair) {
34966 return pair[0].distanceToSquared(pair[1]) !== 0;
34968 .first(function (changed) {
34972 .subscribe(this._inTranslationOperation$);
34973 this._inTranslation$ = this._inTranslationOperation$
34974 .distinctUntilChanged()
34977 this._state$.subscribe(function () { });
34978 this._currentNode$.subscribe(function () { });
34979 this._currentCamera$.subscribe(function () { });
34980 this._currentTransform$.subscribe(function () { });
34981 this._reference$.subscribe(function () { });
34982 this._currentNodeExternal$.subscribe(function () { });
34983 this._lastState$.subscribe(function () { });
34984 this._inMotion$.subscribe(function () { });
34985 this._inTranslation$.subscribe(function () { });
34986 this._frameId = null;
34987 this._frameGenerator = new AnimationFrame_1.RequestAnimationFrameDefinition(window);
34989 Object.defineProperty(StateService.prototype, "currentState$", {
34991 return this._currentState$;
34996 Object.defineProperty(StateService.prototype, "currentNode$", {
34998 return this._currentNode$;
35003 Object.defineProperty(StateService.prototype, "currentKey$", {
35005 return this._currentKey$;
35010 Object.defineProperty(StateService.prototype, "currentNodeExternal$", {
35012 return this._currentNodeExternal$;
35017 Object.defineProperty(StateService.prototype, "currentCamera$", {
35019 return this._currentCamera$;
35024 Object.defineProperty(StateService.prototype, "currentTransform$", {
35026 return this._currentTransform$;
35031 Object.defineProperty(StateService.prototype, "state$", {
35033 return this._state$;
35038 Object.defineProperty(StateService.prototype, "reference$", {
35040 return this._reference$;
35045 Object.defineProperty(StateService.prototype, "inMotion$", {
35047 return this._inMotion$;
35052 Object.defineProperty(StateService.prototype, "inTranslation$", {
35054 return this._inTranslation$;
35059 Object.defineProperty(StateService.prototype, "appendNode$", {
35061 return this._appendNode$;
35066 StateService.prototype.traverse = function () {
35067 this._inMotionOperation$.next(true);
35068 this._invokeContextOperation(function (context) { context.traverse(); });
35070 StateService.prototype.wait = function () {
35071 this._invokeContextOperation(function (context) { context.wait(); });
35073 StateService.prototype.appendNodes = function (nodes) {
35074 this._invokeContextOperation(function (context) { context.append(nodes); });
35076 StateService.prototype.prependNodes = function (nodes) {
35077 this._invokeContextOperation(function (context) { context.prepend(nodes); });
35079 StateService.prototype.removeNodes = function (n) {
35080 this._invokeContextOperation(function (context) { context.remove(n); });
35082 StateService.prototype.clearNodes = function () {
35083 this._invokeContextOperation(function (context) { context.clear(); });
35085 StateService.prototype.clearPriorNodes = function () {
35086 this._invokeContextOperation(function (context) { context.clearPrior(); });
35088 StateService.prototype.cutNodes = function () {
35089 this._invokeContextOperation(function (context) { context.cut(); });
35091 StateService.prototype.setNodes = function (nodes) {
35092 this._invokeContextOperation(function (context) { context.set(nodes); });
35094 StateService.prototype.rotate = function (delta) {
35095 this._inMotionOperation$.next(true);
35096 this._invokeContextOperation(function (context) { context.rotate(delta); });
35098 StateService.prototype.rotateBasic = function (basicRotation) {
35099 this._inMotionOperation$.next(true);
35100 this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); });
35102 StateService.prototype.rotateBasicUnbounded = function (basicRotation) {
35103 this._inMotionOperation$.next(true);
35104 this._invokeContextOperation(function (context) { context.rotateBasicUnbounded(basicRotation); });
35106 StateService.prototype.rotateToBasic = function (basic) {
35107 this._inMotionOperation$.next(true);
35108 this._invokeContextOperation(function (context) { context.rotateToBasic(basic); });
35110 StateService.prototype.move = function (delta) {
35111 this._inMotionOperation$.next(true);
35112 this._invokeContextOperation(function (context) { context.move(delta); });
35114 StateService.prototype.moveTo = function (position) {
35115 this._inMotionOperation$.next(true);
35116 this._invokeContextOperation(function (context) { context.moveTo(position); });
35119 * Change zoom level while keeping the reference point position approximately static.
35121 * @parameter {number} delta - Change in zoom level.
35122 * @parameter {Array<number>} reference - Reference point in basic coordinates.
35124 StateService.prototype.zoomIn = function (delta, reference) {
35125 this._inMotionOperation$.next(true);
35126 this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); });
35128 StateService.prototype.getCenter = function () {
35129 return this._lastState$
35131 .map(function (frame) {
35132 return frame.state.getCenter();
35135 StateService.prototype.getZoom = function () {
35136 return this._lastState$
35138 .map(function (frame) {
35139 return frame.state.zoom;
35142 StateService.prototype.setCenter = function (center) {
35143 this._inMotionOperation$.next(true);
35144 this._invokeContextOperation(function (context) { context.setCenter(center); });
35146 StateService.prototype.setZoom = function (zoom) {
35147 this._inMotionOperation$.next(true);
35148 this._invokeContextOperation(function (context) { context.setZoom(zoom); });
35150 StateService.prototype.start = function () {
35151 if (this._frameId == null) {
35152 this._start$.next(null);
35153 this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
35154 this._frame$.next(this._frameId);
35157 StateService.prototype.stop = function () {
35158 if (this._frameId != null) {
35159 this._frameGenerator.cancelAnimationFrame(this._frameId);
35160 this._frameId = null;
35163 StateService.prototype._invokeContextOperation = function (action) {
35164 this._contextOperation$
35165 .next(function (context) {
35170 StateService.prototype._frame = function (time) {
35171 this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
35172 this._frame$.next(this._frameId);
35174 return StateService;
35176 exports.StateService = StateService;
35178 },{"../State":232,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/operator/bufferCount":49,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/do":58,"rxjs/add/operator/filter":60,"rxjs/add/operator/first":62,"rxjs/add/operator/map":64,"rxjs/add/operator/pairwise":68,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/startWith":77,"rxjs/add/operator/switchMap":78,"rxjs/add/operator/withLatestFrom":82,"rxjs/util/AnimationFrame":156}],329:[function(require,module,exports){
35179 /// <reference path="../../../typings/index.d.ts" />
35181 var Error_1 = require("../../Error");
35182 var Geo_1 = require("../../Geo");
35183 var StateBase = (function () {
35184 function StateBase(state) {
35185 this._spatial = new Geo_1.Spatial();
35186 this._geoCoords = new Geo_1.GeoCoords();
35187 this._referenceThreshold = 0.01;
35188 this._reference = state.reference;
35189 this._alpha = state.alpha;
35190 this._camera = state.camera.clone();
35191 this._zoom = state.zoom;
35192 this._currentIndex = state.currentIndex;
35193 this._trajectory = state.trajectory.slice();
35194 this._trajectoryTransforms = [];
35195 this._trajectoryCameras = [];
35196 for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) {
35198 var translation = this._nodeToTranslation(node);
35199 var transform = new Geo_1.Transform(node, node.image, translation);
35200 this._trajectoryTransforms.push(transform);
35201 this._trajectoryCameras.push(new Geo_1.Camera(transform));
35203 this._currentNode = this._trajectory.length > 0 ?
35204 this._trajectory[this._currentIndex] :
35206 this._previousNode = this._trajectory.length > 1 && this.currentIndex > 0 ?
35207 this._trajectory[this._currentIndex - 1] :
35209 this._currentCamera = this._trajectoryCameras.length > 0 ?
35210 this._trajectoryCameras[this._currentIndex].clone() :
35211 new Geo_1.Camera();
35212 this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
35213 this._trajectoryCameras[this._currentIndex - 1].clone() :
35214 this._currentCamera.clone();
35216 Object.defineProperty(StateBase.prototype, "reference", {
35218 return this._reference;
35223 Object.defineProperty(StateBase.prototype, "alpha", {
35225 return this._getAlpha();
35230 Object.defineProperty(StateBase.prototype, "camera", {
35232 return this._camera;
35237 Object.defineProperty(StateBase.prototype, "zoom", {
35244 Object.defineProperty(StateBase.prototype, "trajectory", {
35246 return this._trajectory;
35251 Object.defineProperty(StateBase.prototype, "currentIndex", {
35253 return this._currentIndex;
35258 Object.defineProperty(StateBase.prototype, "currentNode", {
35260 return this._currentNode;
35265 Object.defineProperty(StateBase.prototype, "previousNode", {
35267 return this._previousNode;
35272 Object.defineProperty(StateBase.prototype, "currentCamera", {
35274 return this._currentCamera;
35279 Object.defineProperty(StateBase.prototype, "currentTransform", {
35281 return this._trajectoryTransforms.length > 0 ?
35282 this._trajectoryTransforms[this.currentIndex] : null;
35287 Object.defineProperty(StateBase.prototype, "previousTransform", {
35289 return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
35290 this._trajectoryTransforms[this.currentIndex - 1] : null;
35295 Object.defineProperty(StateBase.prototype, "motionless", {
35297 return this._motionless;
35302 StateBase.prototype.append = function (nodes) {
35303 if (nodes.length < 1) {
35304 throw Error("Trajectory can not be empty");
35306 if (this._currentIndex < 0) {
35310 this._trajectory = this._trajectory.concat(nodes);
35311 this._appendToTrajectories(nodes);
35314 StateBase.prototype.prepend = function (nodes) {
35315 if (nodes.length < 1) {
35316 throw Error("Trajectory can not be empty");
35318 this._trajectory = nodes.slice().concat(this._trajectory);
35319 this._currentIndex += nodes.length;
35320 this._setCurrentNode();
35321 var referenceReset = this._setReference(this._currentNode);
35322 if (referenceReset) {
35323 this._setTrajectories();
35326 this._prependToTrajectories(nodes);
35328 this._setCurrentCamera();
35330 StateBase.prototype.remove = function (n) {
35332 throw Error("n must be a positive integer");
35334 if (this._currentIndex - 1 < n) {
35335 throw Error("Current and previous nodes can not be removed");
35337 for (var i = 0; i < n; i++) {
35338 this._trajectory.shift();
35339 this._trajectoryTransforms.shift();
35340 this._trajectoryCameras.shift();
35341 this._currentIndex--;
35343 this._setCurrentNode();
35345 StateBase.prototype.clearPrior = function () {
35346 if (this._currentIndex > 0) {
35347 this.remove(this._currentIndex - 1);
35350 StateBase.prototype.clear = function () {
35352 if (this._currentIndex > 0) {
35353 this.remove(this._currentIndex - 1);
35356 StateBase.prototype.cut = function () {
35357 while (this._trajectory.length - 1 > this._currentIndex) {
35358 this._trajectory.pop();
35359 this._trajectoryTransforms.pop();
35360 this._trajectoryCameras.pop();
35363 StateBase.prototype.set = function (nodes) {
35364 this._setTrajectory(nodes);
35365 this._setCurrentNode();
35366 this._setReference(this._currentNode);
35367 this._setTrajectories();
35368 this._setCurrentCamera();
35370 StateBase.prototype.getCenter = function () {
35371 return this._currentNode != null ?
35372 this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
35375 StateBase.prototype._setCurrent = function () {
35376 this._setCurrentNode();
35377 var referenceReset = this._setReference(this._currentNode);
35378 if (referenceReset) {
35379 this._setTrajectories();
35381 this._setCurrentCamera();
35383 StateBase.prototype._setCurrentCamera = function () {
35384 this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
35385 this._previousCamera = this._currentIndex > 0 ?
35386 this._trajectoryCameras[this._currentIndex - 1].clone() :
35387 this._currentCamera.clone();
35389 StateBase.prototype._motionlessTransition = function () {
35390 var nodesSet = this._currentNode != null && this._previousNode != null;
35391 return nodesSet && !(this._currentNode.merged &&
35392 this._previousNode.merged &&
35393 this._withinOriginalDistance() &&
35394 this._sameConnectedComponent());
35396 StateBase.prototype._setReference = function (node) {
35397 // do not reset reference if node is within threshold distance
35398 if (Math.abs(node.latLon.lat - this.reference.lat) < this._referenceThreshold &&
35399 Math.abs(node.latLon.lon - this.reference.lon) < this._referenceThreshold) {
35402 // do not reset reference if previous node exist and transition is with motion
35403 if (this._previousNode != null && !this._motionlessTransition()) {
35406 this._reference.lat = node.latLon.lat;
35407 this._reference.lon = node.latLon.lon;
35408 this._reference.alt = node.alt;
35411 StateBase.prototype._setCurrentNode = function () {
35412 this._currentNode = this._trajectory.length > 0 ?
35413 this._trajectory[this._currentIndex] :
35415 this._previousNode = this._currentIndex > 0 ?
35416 this._trajectory[this._currentIndex - 1] :
35419 StateBase.prototype._setTrajectory = function (nodes) {
35420 if (nodes.length < 1) {
35421 throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty");
35423 if (this._currentNode != null) {
35424 this._trajectory = [this._currentNode].concat(nodes);
35425 this._currentIndex = 1;
35428 this._trajectory = nodes.slice();
35429 this._currentIndex = 0;
35432 StateBase.prototype._setTrajectories = function () {
35433 this._trajectoryTransforms.length = 0;
35434 this._trajectoryCameras.length = 0;
35435 this._appendToTrajectories(this._trajectory);
35437 StateBase.prototype._appendToTrajectories = function (nodes) {
35438 for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
35439 var node = nodes_1[_i];
35440 if (!node.assetsCached) {
35441 throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory");
35443 var translation = this._nodeToTranslation(node);
35444 var transform = new Geo_1.Transform(node, node.image, translation);
35445 this._trajectoryTransforms.push(transform);
35446 this._trajectoryCameras.push(new Geo_1.Camera(transform));
35449 StateBase.prototype._prependToTrajectories = function (nodes) {
35450 for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) {
35452 if (!node.assetsCached) {
35453 throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory");
35455 var translation = this._nodeToTranslation(node);
35456 var transform = new Geo_1.Transform(node, node.image, translation);
35457 this._trajectoryTransforms.unshift(transform);
35458 this._trajectoryCameras.unshift(new Geo_1.Camera(transform));
35461 StateBase.prototype._nodeToTranslation = function (node) {
35462 var C = this._geoCoords.geodeticToEnu(node.latLon.lat, node.latLon.lon, node.alt, this._reference.lat, this._reference.lon, this._reference.alt);
35463 var RC = this._spatial.rotate(C, node.rotation);
35464 return [-RC.x, -RC.y, -RC.z];
35466 StateBase.prototype._sameConnectedComponent = function () {
35467 var current = this._currentNode;
35468 var previous = this._previousNode;
35470 !current.mergeCC ||
35472 !previous.mergeCC) {
35475 return current.mergeCC === previous.mergeCC;
35477 StateBase.prototype._withinOriginalDistance = function () {
35478 var current = this._currentNode;
35479 var previous = this._previousNode;
35480 if (!current || !previous) {
35483 // 50 km/h moves 28m in 2s
35484 var distance = this._spatial.distanceFromLatLon(current.originalLatLon.lat, current.originalLatLon.lon, previous.originalLatLon.lat, previous.originalLatLon.lon);
35485 return distance < 25;
35489 exports.StateBase = StateBase;
35491 },{"../../Error":227,"../../Geo":228}],330:[function(require,module,exports){
35492 /// <reference path="../../../typings/index.d.ts" />
35494 var __extends = (this && this.__extends) || function (d, b) {
35495 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
35496 function __() { this.constructor = d; }
35497 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35499 var THREE = require("three");
35500 var UnitBezier = require("unitbezier");
35501 var State_1 = require("../../State");
35502 var RotationDelta = (function () {
35503 function RotationDelta(phi, theta) {
35505 this._theta = theta;
35507 Object.defineProperty(RotationDelta.prototype, "phi", {
35511 set: function (value) {
35517 Object.defineProperty(RotationDelta.prototype, "theta", {
35519 return this._theta;
35521 set: function (value) {
35522 this._theta = value;
35527 Object.defineProperty(RotationDelta.prototype, "isZero", {
35529 return this._phi === 0 && this._theta === 0;
35534 RotationDelta.prototype.copy = function (delta) {
35535 this._phi = delta.phi;
35536 this._theta = delta.theta;
35538 RotationDelta.prototype.lerp = function (other, alpha) {
35539 this._phi = (1 - alpha) * this._phi + alpha * other.phi;
35540 this._theta = (1 - alpha) * this._theta + alpha * other.theta;
35542 RotationDelta.prototype.multiply = function (value) {
35543 this._phi *= value;
35544 this._theta *= value;
35546 RotationDelta.prototype.threshold = function (value) {
35547 this._phi = Math.abs(this._phi) > value ? this._phi : 0;
35548 this._theta = Math.abs(this._theta) > value ? this._theta : 0;
35550 RotationDelta.prototype.lengthSquared = function () {
35551 return this._phi * this._phi + this._theta * this._theta;
35553 RotationDelta.prototype.reset = function () {
35557 return RotationDelta;
35559 var TraversingState = (function (_super) {
35560 __extends(TraversingState, _super);
35561 function TraversingState(state) {
35562 var _this = _super.call(this, state) || this;
35563 _this._adjustCameras();
35564 _this._motionless = _this._motionlessTransition();
35565 _this._baseAlpha = _this._alpha;
35566 _this._animationSpeed = 0.025;
35567 _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
35568 _this._useBezier = false;
35569 _this._rotationDelta = new RotationDelta(0, 0);
35570 _this._requestedRotationDelta = null;
35571 _this._basicRotation = [0, 0];
35572 _this._requestedBasicRotation = null;
35573 _this._requestedBasicRotationUnbounded = null;
35574 _this._rotationAcceleration = 0.86;
35575 _this._rotationIncreaseAlpha = 0.97;
35576 _this._rotationDecreaseAlpha = 0.9;
35577 _this._rotationThreshold = 1e-3;
35578 _this._unboundedRotationAlpha = 0.8;
35579 _this._desiredZoom = state.zoom;
35580 _this._minZoom = 0;
35581 _this._maxZoom = 3;
35582 _this._lookatDepth = 10;
35583 _this._desiredLookat = null;
35584 _this._desiredCenter = null;
35587 TraversingState.prototype.traverse = function () {
35588 throw new Error("Not implemented");
35590 TraversingState.prototype.wait = function () {
35591 return new State_1.WaitingState(this);
35593 TraversingState.prototype.append = function (nodes) {
35594 var emptyTrajectory = this._trajectory.length === 0;
35595 if (emptyTrajectory) {
35596 this._resetTransition();
35598 _super.prototype.append.call(this, nodes);
35599 if (emptyTrajectory) {
35600 this._setDesiredCenter();
35601 this._setDesiredZoom();
35604 TraversingState.prototype.prepend = function (nodes) {
35605 var emptyTrajectory = this._trajectory.length === 0;
35606 if (emptyTrajectory) {
35607 this._resetTransition();
35609 _super.prototype.prepend.call(this, nodes);
35610 if (emptyTrajectory) {
35611 this._setDesiredCenter();
35612 this._setDesiredZoom();
35615 TraversingState.prototype.set = function (nodes) {
35616 _super.prototype.set.call(this, nodes);
35617 this._desiredLookat = null;
35618 this._resetTransition();
35619 this._clearRotation();
35620 this._setDesiredCenter();
35621 this._setDesiredZoom();
35622 if (this._trajectory.length < 3) {
35623 this._useBezier = true;
35626 TraversingState.prototype.move = function (delta) {
35627 throw new Error("Not implemented");
35629 TraversingState.prototype.moveTo = function (delta) {
35630 throw new Error("Not implemented");
35632 TraversingState.prototype.rotate = function (rotationDelta) {
35633 if (this._currentNode == null) {
35636 this._desiredZoom = this._zoom;
35637 this._desiredLookat = null;
35638 this._requestedBasicRotation = null;
35639 if (this._requestedRotationDelta != null) {
35640 this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi;
35641 this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta;
35644 this._requestedRotationDelta = new RotationDelta(rotationDelta.phi, rotationDelta.theta);
35647 TraversingState.prototype.rotateBasic = function (basicRotation) {
35648 if (this._currentNode == null) {
35651 this._desiredZoom = this._zoom;
35652 this._desiredLookat = null;
35653 this._requestedRotationDelta = null;
35654 if (this._requestedBasicRotation != null) {
35655 this._requestedBasicRotation[0] += basicRotation[0];
35656 this._requestedBasicRotation[1] += basicRotation[1];
35657 var threshold = 0.05 / Math.pow(2, this._zoom);
35658 this._requestedBasicRotation[0] =
35659 this._spatial.clamp(this._requestedBasicRotation[0], -threshold, threshold);
35660 this._requestedBasicRotation[1] =
35661 this._spatial.clamp(this._requestedBasicRotation[1], -threshold, threshold);
35664 this._requestedBasicRotation = basicRotation.slice();
35667 TraversingState.prototype.rotateBasicUnbounded = function (basicRotation) {
35668 if (this._currentNode == null) {
35671 if (this._requestedBasicRotationUnbounded != null) {
35672 this._requestedBasicRotationUnbounded[0] += basicRotation[0];
35673 this._requestedBasicRotationUnbounded[1] += basicRotation[1];
35676 this._requestedBasicRotationUnbounded = basicRotation.slice();
35679 TraversingState.prototype.rotateToBasic = function (basic) {
35680 if (this._currentNode == null) {
35683 this._desiredZoom = this._zoom;
35684 this._desiredLookat = null;
35685 basic[0] = this._spatial.clamp(basic[0], 0, 1);
35686 basic[1] = this._spatial.clamp(basic[1], 0, 1);
35687 var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth);
35688 this._currentCamera.lookat.fromArray(lookat);
35690 TraversingState.prototype.zoomIn = function (delta, reference) {
35691 if (this._currentNode == null) {
35694 this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta));
35695 var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray());
35696 var currentCenterX = currentCenter[0];
35697 var currentCenterY = currentCenter[1];
35698 var zoom0 = Math.pow(2, this._zoom);
35699 var zoom1 = Math.pow(2, this._desiredZoom);
35700 var refX = reference[0];
35701 var refY = reference[1];
35702 if (this.currentTransform.gpano != null &&
35703 this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
35704 if (refX - currentCenterX > 0.5) {
35707 else if (currentCenterX - refX > 0.5) {
35711 var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX);
35712 var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY);
35713 var gpano = this.currentTransform.gpano;
35714 if (this._currentNode.fullPano) {
35715 newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
35716 newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95);
35718 else if (gpano != null &&
35719 this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
35720 newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
35721 newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1);
35724 newCenterX = this._spatial.clamp(newCenterX, 0, 1);
35725 newCenterY = this._spatial.clamp(newCenterY, 0, 1);
35727 this._desiredLookat = new THREE.Vector3()
35728 .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth));
35730 TraversingState.prototype.setCenter = function (center) {
35731 this._desiredLookat = null;
35732 this._requestedRotationDelta = null;
35733 this._requestedBasicRotation = null;
35734 this._desiredZoom = this._zoom;
35736 this._spatial.clamp(center[0], 0, 1),
35737 this._spatial.clamp(center[1], 0, 1),
35739 if (this._currentNode == null) {
35740 this._desiredCenter = clamped;
35743 this._desiredCenter = null;
35744 var currentLookat = new THREE.Vector3()
35745 .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth));
35746 var previousTransform = this.previousTransform != null ?
35747 this.previousTransform :
35748 this.currentTransform;
35749 var previousLookat = new THREE.Vector3()
35750 .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth));
35751 this._currentCamera.lookat.copy(currentLookat);
35752 this._previousCamera.lookat.copy(previousLookat);
35754 TraversingState.prototype.setZoom = function (zoom) {
35755 this._desiredLookat = null;
35756 this._requestedRotationDelta = null;
35757 this._requestedBasicRotation = null;
35758 this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom);
35759 this._desiredZoom = this._zoom;
35761 TraversingState.prototype.update = function (fps) {
35762 if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) {
35763 this._currentIndex += 1;
35764 this._useBezier = this._trajectory.length < 3 &&
35765 this._currentIndex + 1 === this._trajectory.length;
35766 this._setCurrent();
35767 this._resetTransition();
35768 this._clearRotation();
35769 this._desiredZoom = this._currentNode.fullPano ? this._zoom : 0;
35770 this._desiredLookat = null;
35772 var animationSpeed = this._animationSpeed * (60 / fps);
35773 this._baseAlpha = Math.min(1, this._baseAlpha + animationSpeed);
35774 if (this._useBezier) {
35775 this._alpha = this._unitBezier.solve(this._baseAlpha);
35778 this._alpha = this._baseAlpha;
35780 this._updateRotation();
35781 if (!this._rotationDelta.isZero) {
35782 this._applyRotation(this._previousCamera);
35783 this._applyRotation(this._currentCamera);
35785 this._updateRotationBasic();
35786 if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
35787 this._applyRotationBasic();
35789 this._updateZoom(animationSpeed);
35790 this._updateLookat(animationSpeed);
35791 this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
35793 TraversingState.prototype._getAlpha = function () {
35794 return this._motionless ? Math.ceil(this._alpha) : this._alpha;
35796 TraversingState.prototype._setCurrentCamera = function () {
35797 _super.prototype._setCurrentCamera.call(this);
35798 this._adjustCameras();
35800 TraversingState.prototype._adjustCameras = function () {
35801 if (this._previousNode == null) {
35804 var lookat = this._camera.lookat.clone().sub(this._camera.position);
35805 this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
35806 if (this._currentNode.fullPano) {
35807 this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
35810 TraversingState.prototype._resetTransition = function () {
35812 this._baseAlpha = 0;
35813 this._motionless = this._motionlessTransition();
35815 TraversingState.prototype._applyRotation = function (camera) {
35816 if (camera == null) {
35819 var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
35820 var qInverse = q.clone().inverse();
35821 var offset = new THREE.Vector3();
35822 offset.copy(camera.lookat).sub(camera.position);
35823 offset.applyQuaternion(q);
35824 var length = offset.length();
35825 var phi = Math.atan2(offset.y, offset.x);
35826 phi += this._rotationDelta.phi;
35827 var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
35828 theta += this._rotationDelta.theta;
35829 theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
35830 offset.x = Math.sin(theta) * Math.cos(phi);
35831 offset.y = Math.sin(theta) * Math.sin(phi);
35832 offset.z = Math.cos(theta);
35833 offset.applyQuaternion(qInverse);
35834 camera.lookat.copy(camera.position).add(offset.multiplyScalar(length));
35836 TraversingState.prototype._applyRotationBasic = function () {
35837 var currentNode = this._currentNode;
35838 var previousNode = this._previousNode != null ?
35839 this.previousNode :
35841 var currentCamera = this._currentCamera;
35842 var previousCamera = this._previousCamera;
35843 var currentTransform = this.currentTransform;
35844 var previousTransform = this.previousTransform != null ?
35845 this.previousTransform :
35846 this.currentTransform;
35847 var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray());
35848 var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray());
35849 var currentGPano = currentTransform.gpano;
35850 var previousGPano = previousTransform.gpano;
35851 if (currentNode.fullPano) {
35852 currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1);
35853 currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0.05, 0.95);
35855 else if (currentGPano != null &&
35856 currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) {
35857 currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1);
35858 currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
35861 currentBasic[0] = this._spatial.clamp(currentBasic[0] + this._basicRotation[0], 0, 1);
35862 currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
35864 if (previousNode.fullPano) {
35865 previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1);
35866 previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0.05, 0.95);
35868 else if (previousGPano != null &&
35869 previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) {
35870 previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1);
35871 previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0, 1);
35874 previousBasic[0] = this._spatial.clamp(previousBasic[0] + this._basicRotation[0], 0, 1);
35875 previousBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
35877 var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth);
35878 currentCamera.lookat.fromArray(currentLookat);
35879 var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth);
35880 previousCamera.lookat.fromArray(previousLookat);
35882 TraversingState.prototype._updateZoom = function (animationSpeed) {
35883 var diff = this._desiredZoom - this._zoom;
35884 var sign = diff > 0 ? 1 : diff < 0 ? -1 : 0;
35888 else if (Math.abs(diff) < 2e-3) {
35889 this._zoom = this._desiredZoom;
35890 if (this._desiredLookat != null) {
35891 this._desiredLookat = null;
35895 this._zoom += sign * Math.max(Math.abs(5 * animationSpeed * diff), 2e-3);
35898 TraversingState.prototype._updateLookat = function (animationSpeed) {
35899 if (this._desiredLookat === null) {
35902 var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat);
35903 if (Math.abs(diff) < 1e-6) {
35904 this._currentCamera.lookat.copy(this._desiredLookat);
35905 this._desiredLookat = null;
35908 this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed);
35911 TraversingState.prototype._updateRotation = function () {
35912 if (this._requestedRotationDelta != null) {
35913 var length_1 = this._rotationDelta.lengthSquared();
35914 var requestedLength = this._requestedRotationDelta.lengthSquared();
35915 if (requestedLength > length_1) {
35916 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha);
35919 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha);
35921 this._requestedRotationDelta = null;
35924 if (this._rotationDelta.isZero) {
35927 this._rotationDelta.multiply(this._rotationAcceleration);
35928 this._rotationDelta.threshold(this._rotationThreshold);
35930 TraversingState.prototype._updateRotationBasic = function () {
35931 if (this._requestedBasicRotation != null) {
35932 var x = this._basicRotation[0];
35933 var y = this._basicRotation[1];
35934 var reqX = this._requestedBasicRotation[0];
35935 var reqY = this._requestedBasicRotation[1];
35936 if (Math.abs(reqX) > Math.abs(x)) {
35937 this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX;
35940 this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX;
35942 if (Math.abs(reqY) > Math.abs(y)) {
35943 this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY;
35946 this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY;
35948 this._requestedBasicRotation = null;
35951 if (this._requestedBasicRotationUnbounded != null) {
35952 var reqX = this._requestedBasicRotationUnbounded[0];
35953 var reqY = this._requestedBasicRotationUnbounded[1];
35954 if (Math.abs(reqX) > 0) {
35955 this._basicRotation[0] = (1 - this._unboundedRotationAlpha) * this._basicRotation[0] + this._unboundedRotationAlpha * reqX;
35957 if (Math.abs(reqY) > 0) {
35958 this._basicRotation[1] = (1 - this._unboundedRotationAlpha) * this._basicRotation[1] + this._unboundedRotationAlpha * reqY;
35960 if (this._desiredLookat != null) {
35961 var desiredBasicLookat = this.currentTransform.projectBasic(this._desiredLookat.toArray());
35962 desiredBasicLookat[0] += reqX;
35963 desiredBasicLookat[1] += reqY;
35964 this._desiredLookat = new THREE.Vector3()
35965 .fromArray(this.currentTransform.unprojectBasic(desiredBasicLookat, this._lookatDepth));
35967 this._requestedBasicRotationUnbounded = null;
35969 if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) {
35972 this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0];
35973 this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1];
35974 if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) &&
35975 Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) {
35976 this._basicRotation = [0, 0];
35979 TraversingState.prototype._clearRotation = function () {
35980 if (this._currentNode.fullPano) {
35983 if (this._requestedRotationDelta != null) {
35984 this._requestedRotationDelta = null;
35986 if (!this._rotationDelta.isZero) {
35987 this._rotationDelta.reset();
35989 if (this._requestedBasicRotation != null) {
35990 this._requestedBasicRotation = null;
35992 if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) {
35993 this._basicRotation = [0, 0];
35996 TraversingState.prototype._setDesiredCenter = function () {
35997 if (this._desiredCenter == null) {
36000 var lookatDirection = new THREE.Vector3()
36001 .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth))
36002 .sub(this._currentCamera.position);
36003 this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection));
36004 this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection));
36005 this._desiredCenter = null;
36007 TraversingState.prototype._setDesiredZoom = function () {
36008 this._desiredZoom =
36009 this._currentNode.fullPano || this._previousNode == null ?
36012 return TraversingState;
36013 }(State_1.StateBase));
36014 exports.TraversingState = TraversingState;
36016 },{"../../State":232,"three":175,"unitbezier":177}],331:[function(require,module,exports){
36018 var __extends = (this && this.__extends) || function (d, b) {
36019 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
36020 function __() { this.constructor = d; }
36021 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
36023 var State_1 = require("../../State");
36024 var WaitingState = (function (_super) {
36025 __extends(WaitingState, _super);
36026 function WaitingState(state) {
36027 var _this = _super.call(this, state) || this;
36028 _this._adjustCameras();
36029 _this._motionless = _this._motionlessTransition();
36032 WaitingState.prototype.traverse = function () {
36033 return new State_1.TraversingState(this);
36035 WaitingState.prototype.wait = function () {
36036 throw new Error("Not implemented");
36038 WaitingState.prototype.prepend = function (nodes) {
36039 _super.prototype.prepend.call(this, nodes);
36040 this._motionless = this._motionlessTransition();
36042 WaitingState.prototype.set = function (nodes) {
36043 _super.prototype.set.call(this, nodes);
36044 this._motionless = this._motionlessTransition();
36046 WaitingState.prototype.rotate = function (delta) { return; };
36047 WaitingState.prototype.rotateBasic = function (basicRotation) { return; };
36048 WaitingState.prototype.rotateBasicUnbounded = function (basicRotation) { return; };
36049 WaitingState.prototype.rotateToBasic = function (basic) { return; };
36050 WaitingState.prototype.zoomIn = function (delta, reference) { return; };
36051 WaitingState.prototype.move = function (delta) {
36052 this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
36054 WaitingState.prototype.moveTo = function (position) {
36055 this._alpha = Math.max(0, Math.min(1, position));
36057 WaitingState.prototype.update = function (fps) {
36058 this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
36060 WaitingState.prototype.setCenter = function (center) { return; };
36061 WaitingState.prototype.setZoom = function (zoom) { return; };
36062 WaitingState.prototype._getAlpha = function () {
36063 return this._motionless ? Math.round(this._alpha) : this._alpha;
36066 WaitingState.prototype._setCurrentCamera = function () {
36067 _super.prototype._setCurrentCamera.call(this);
36068 this._adjustCameras();
36070 WaitingState.prototype._adjustCameras = function () {
36071 if (this._previousNode == null) {
36074 if (this._currentNode.fullPano) {
36075 var lookat = this._camera.lookat.clone().sub(this._camera.position);
36076 this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
36078 if (this._previousNode.fullPano) {
36079 var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
36080 this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
36083 return WaitingState;
36084 }(State_1.StateBase));
36085 exports.WaitingState = WaitingState;
36087 },{"../../State":232}],332:[function(require,module,exports){
36089 var Observable_1 = require("rxjs/Observable");
36091 * @class ImageTileLoader
36093 * @classdesc Represents a loader of image tiles.
36095 var ImageTileLoader = (function () {
36097 * Create a new node image tile loader instance.
36099 * @param {string} scheme - The URI scheme.
36100 * @param {string} host - The URI host.
36101 * @param {string} [origin] - The origin query param.
36103 function ImageTileLoader(scheme, host, origin) {
36104 this._scheme = scheme;
36106 this._origin = origin != null ? "?origin=" + origin : "";
36109 * Retrieve an image tile.
36111 * @description Retrieve an image tile by specifying the area
36112 * as well as the scaled size.
36114 * @param {string} identifier - The identifier of the image.
36115 * @param {number} x - The top left x pixel coordinate for the tile
36116 * in the original image.
36117 * @param {number} y - The top left y pixel coordinate for the tile
36118 * in the original image.
36119 * @param {number} w - The pixel width of the tile in the original image.
36120 * @param {number} h - The pixel height of the tile in the original image.
36121 * @param {number} scaledW - The scaled width of the returned tile.
36122 * @param {number} scaledH - The scaled height of the returned tile.
36124 ImageTileLoader.prototype.getTile = function (identifier, x, y, w, h, scaledW, scaledH) {
36125 var characteristics = "/" + identifier + "/" + x + "," + y + "," + w + "," + h + "/" + scaledW + "," + scaledH + "/0/default.jpg";
36126 var url = this._scheme +
36131 var xmlHTTP = null;
36132 return [Observable_1.Observable.create(function (subscriber) {
36133 xmlHTTP = new XMLHttpRequest();
36134 xmlHTTP.open("GET", url, true);
36135 xmlHTTP.responseType = "arraybuffer";
36136 xmlHTTP.timeout = 15000;
36137 xmlHTTP.onload = function (event) {
36138 if (xmlHTTP.status !== 200) {
36139 subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + "). " +
36140 ("Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)));
36143 var image = new Image();
36144 image.crossOrigin = "Anonymous";
36145 image.onload = function (e) {
36146 subscriber.next(image);
36147 subscriber.complete();
36149 image.onerror = function (error) {
36150 subscriber.error(new Error("Failed to load tile image (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
36152 var blob = new Blob([xmlHTTP.response]);
36153 image.src = window.URL.createObjectURL(blob);
36155 xmlHTTP.onerror = function (error) {
36156 subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
36158 xmlHTTP.ontimeout = function (error) {
36159 subscriber.error(new Error("Tile request timed out (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
36161 xmlHTTP.onabort = function (event) {
36162 subscriber.error(new Error("Tile request was aborted (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
36164 xmlHTTP.send(null);
36167 if (xmlHTTP != null) {
36173 return ImageTileLoader;
36175 exports.ImageTileLoader = ImageTileLoader;
36176 Object.defineProperty(exports, "__esModule", { value: true });
36177 exports.default = ImageTileLoader;
36179 },{"rxjs/Observable":28}],333:[function(require,module,exports){
36182 * @class ImageTileStore
36184 * @classdesc Represents a store for image tiles.
36186 var ImageTileStore = (function () {
36188 * Create a new node image tile store instance.
36190 function ImageTileStore() {
36194 * Add an image tile to the store.
36196 * @param {HTMLImageElement} image - The image tile.
36197 * @param {string} key - The identifier for the tile.
36198 * @param {number} level - The level of the tile.
36200 ImageTileStore.prototype.addImage = function (image, key, level) {
36201 if (!(level in this._images)) {
36202 this._images[level] = {};
36204 this._images[level][key] = image;
36207 * Dispose the store.
36209 * @description Disposes all cached assets.
36211 ImageTileStore.prototype.dispose = function () {
36212 for (var _i = 0, _a = Object.keys(this._images); _i < _a.length; _i++) {
36213 var level = _a[_i];
36214 var levelImages = this._images[level];
36215 for (var _b = 0, _c = Object.keys(levelImages); _b < _c.length; _b++) {
36217 window.URL.revokeObjectURL(levelImages[key].src);
36218 delete levelImages[key];
36220 delete this._images[level];
36224 * Get an image tile from the store.
36226 * @param {string} key - The identifier for the tile.
36227 * @param {number} level - The level of the tile.
36229 ImageTileStore.prototype.getImage = function (key, level) {
36230 return this._images[level][key];
36233 * Check if an image tile exist in the store.
36235 * @param {string} key - The identifier for the tile.
36236 * @param {number} level - The level of the tile.
36238 ImageTileStore.prototype.hasImage = function (key, level) {
36239 return level in this._images && key in this._images[level];
36241 return ImageTileStore;
36243 exports.ImageTileStore = ImageTileStore;
36244 Object.defineProperty(exports, "__esModule", { value: true });
36245 exports.default = ImageTileStore;
36247 },{}],334:[function(require,module,exports){
36248 /// <reference path="../../typings/index.d.ts" />
36250 var Geo_1 = require("../Geo");
36252 * @class RegionOfInterestCalculator
36254 * @classdesc Represents a calculator for regions of interest.
36256 var RegionOfInterestCalculator = (function () {
36257 function RegionOfInterestCalculator() {
36258 this._viewportCoords = new Geo_1.ViewportCoords();
36261 * Compute a region of interest based on the current render camera
36262 * and the viewport size.
36264 * @param {RenderCamera} renderCamera - Render camera used for unprojections.
36265 * @param {ISize} size - Viewport size in pixels.
36266 * @param {Transform} transform - Transform used for projections.
36268 * @returns {IRegionOfInterest} A region of interest.
36270 RegionOfInterestCalculator.prototype.computeRegionOfInterest = function (renderCamera, size, transform) {
36271 var viewportBoundaryPoints = this._viewportBoundaryPoints(4);
36272 var bbox = this._viewportPointsBoundingBox(viewportBoundaryPoints, renderCamera, transform);
36273 this._clipBoundingBox(bbox);
36274 var viewportPixelWidth = 2 / size.width;
36275 var viewportPixelHeight = 2 / size.height;
36276 var centralViewportPixel = [
36277 [-0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
36278 [0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
36279 [0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
36280 [-0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
36282 var cpbox = this._viewportPointsBoundingBox(centralViewportPixel, renderCamera, transform);
36285 pixelHeight: cpbox.maxY - cpbox.minY,
36286 pixelWidth: cpbox.maxX - cpbox.minX + (cpbox.minX < cpbox.maxX ? 0 : 1),
36289 RegionOfInterestCalculator.prototype._viewportBoundaryPoints = function (pointsPerSide) {
36291 var os = [[-1, 1], [1, 1], [1, -1], [-1, -1]];
36292 var ds = [[2, 0], [0, -2], [-2, 0], [0, 2]];
36293 for (var side = 0; side < 4; ++side) {
36296 for (var i = 0; i < pointsPerSide; ++i) {
36297 points.push([o[0] + d[0] * i / pointsPerSide,
36298 o[1] + d[1] * i / pointsPerSide]);
36303 RegionOfInterestCalculator.prototype._viewportPointsBoundingBox = function (viewportPoints, renderCamera, transform) {
36305 var basicPoints = viewportPoints
36306 .map(function (point) {
36307 return _this._viewportCoords
36308 .viewportToBasic(point[0], point[1], transform, renderCamera.perspective);
36310 if (transform.gpano != null) {
36311 return this._boundingBoxPano(basicPoints);
36314 return this._boundingBox(basicPoints);
36317 RegionOfInterestCalculator.prototype._boundingBox = function (points) {
36319 maxX: Number.NEGATIVE_INFINITY,
36320 maxY: Number.NEGATIVE_INFINITY,
36321 minX: Number.POSITIVE_INFINITY,
36322 minY: Number.POSITIVE_INFINITY,
36324 for (var i = 0; i < points.length; ++i) {
36325 bbox.minX = Math.min(bbox.minX, points[i][0]);
36326 bbox.maxX = Math.max(bbox.maxX, points[i][0]);
36327 bbox.minY = Math.min(bbox.minY, points[i][1]);
36328 bbox.maxY = Math.max(bbox.maxY, points[i][1]);
36332 RegionOfInterestCalculator.prototype._boundingBoxPano = function (points) {
36336 for (var i = 0; i < points.length; ++i) {
36337 xs.push(points[i][0]);
36338 ys.push(points[i][1]);
36340 xs.sort(function (a, b) { return _this._sign(a - b); });
36341 ys.sort(function (a, b) { return _this._sign(a - b); });
36342 var intervalX = this._intervalPano(xs);
36344 maxX: intervalX[1],
36345 maxY: ys[ys.length - 1],
36346 minX: intervalX[0],
36351 * Find the max interval between consecutive numbers.
36352 * Assumes numbers are between 0 and 1, sorted and that
36353 * x is equivalent to x + 1.
36355 RegionOfInterestCalculator.prototype._intervalPano = function (xs) {
36358 for (var i = 0; i < xs.length - 1; ++i) {
36359 var dx = xs[i + 1] - xs[i];
36365 var loopdx = xs[0] + 1 - xs[xs.length - 1];
36366 if (loopdx > maxdx) {
36367 return [xs[0], xs[xs.length - 1]];
36370 return [xs[maxi + 1], xs[maxi]];
36373 RegionOfInterestCalculator.prototype._clipBoundingBox = function (bbox) {
36374 bbox.minX = Math.max(0, Math.min(1, bbox.minX));
36375 bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
36376 bbox.minY = Math.max(0, Math.min(1, bbox.minY));
36377 bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
36379 RegionOfInterestCalculator.prototype._sign = function (n) {
36380 return n > 0 ? 1 : n < 0 ? -1 : 0;
36382 return RegionOfInterestCalculator;
36384 exports.RegionOfInterestCalculator = RegionOfInterestCalculator;
36385 Object.defineProperty(exports, "__esModule", { value: true });
36386 exports.default = RegionOfInterestCalculator;
36388 },{"../Geo":228}],335:[function(require,module,exports){
36389 /// <reference path="../../typings/index.d.ts" />
36391 var THREE = require("three");
36392 var Subject_1 = require("rxjs/Subject");
36394 * @class TextureProvider
36396 * @classdesc Represents a provider of textures.
36398 var TextureProvider = (function () {
36400 * Create a new node texture provider instance.
36402 * @param {string} key - The identifier of the image for which to request tiles.
36403 * @param {number} width - The full width of the original image.
36404 * @param {number} height - The full height of the original image.
36405 * @param {number} tileSize - The size used when requesting tiles.
36406 * @param {HTMLImageElement} background - Image to use as background.
36407 * @param {ImageTileLoader} imageTileLoader - Loader for retrieving tiles.
36408 * @param {ImageTileStore} imageTileStore - Store for saving tiles.
36409 * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture.
36411 function TextureProvider(key, width, height, tileSize, background, imageTileLoader, imageTileStore, renderer) {
36412 this._disposed = false;
36414 if (width <= 0 || height <= 0) {
36415 console.warn("Original image size (" + width + ", " + height + ") is invalid (" + key + "). Tiles will not be loaded.");
36417 this._width = width;
36418 this._height = height;
36419 this._maxLevel = Math.ceil(Math.log(Math.max(height, width)) / Math.log(2));
36420 this._currentLevel = -1;
36421 this._tileSize = tileSize;
36422 this._updated$ = new Subject_1.Subject();
36423 this._createdSubject$ = new Subject_1.Subject();
36424 this._created$ = this._createdSubject$
36427 this._createdSubscription = this._created$.subscribe(function () { });
36428 this._hasSubject$ = new Subject_1.Subject();
36429 this._has$ = this._hasSubject$
36433 this._hasSubscription = this._has$.subscribe(function () { });
36434 this._abortFunctions = [];
36435 this._tileSubscriptions = {};
36436 this._renderedCurrentLevelTiles = {};
36437 this._renderedTiles = {};
36438 this._background = background;
36439 this._camera = null;
36440 this._imageTileLoader = imageTileLoader;
36441 this._imageTileStore = imageTileStore;
36442 this._renderer = renderer;
36443 this._renderTarget = null;
36446 Object.defineProperty(TextureProvider.prototype, "disposed", {
36450 * @returns {boolean} Value indicating whether provider has
36454 return this._disposed;
36459 Object.defineProperty(TextureProvider.prototype, "hasTexture$", {
36463 * @returns {Observable<boolean>} Observable emitting
36464 * values indicating when the existance of a texture
36473 Object.defineProperty(TextureProvider.prototype, "key", {
36477 * @returns {boolean} The identifier of the image for
36478 * which to render textures.
36486 Object.defineProperty(TextureProvider.prototype, "textureUpdated$", {
36488 * Get textureUpdated$.
36490 * @returns {Observable<boolean>} Observable emitting
36491 * values when an existing texture has been updated.
36494 return this._updated$;
36499 Object.defineProperty(TextureProvider.prototype, "textureCreated$", {
36501 * Get textureCreated$.
36503 * @returns {Observable<boolean>} Observable emitting
36504 * values when a new texture has been created.
36507 return this._created$;
36513 * Abort all outstanding image tile requests.
36515 TextureProvider.prototype.abort = function () {
36516 for (var key in this._tileSubscriptions) {
36517 if (!this._tileSubscriptions.hasOwnProperty(key)) {
36520 this._tileSubscriptions[key].unsubscribe();
36522 this._tileSubscriptions = {};
36523 for (var _i = 0, _a = this._abortFunctions; _i < _a.length; _i++) {
36524 var abort = _a[_i];
36527 this._abortFunctions = [];
36530 * Dispose the provider.
36532 * @description Disposes all cached assets and
36533 * aborts all outstanding image tile requests.
36535 TextureProvider.prototype.dispose = function () {
36536 if (this._disposed) {
36537 console.warn("Texture already disposed (" + this._key + ")");
36541 if (this._renderTarget != null) {
36542 this._renderTarget.dispose();
36543 this._renderTarget = null;
36545 this._imageTileStore.dispose();
36546 this._imageTileStore = null;
36547 this._background = null;
36548 this._camera = null;
36549 this._imageTileLoader = null;
36550 this._renderer = null;
36552 this._createdSubscription.unsubscribe();
36553 this._hasSubscription.unsubscribe();
36554 this._disposed = true;
36557 * Set the region of interest.
36559 * @description When the region of interest is set the
36560 * the tile level is determined and tiles for the region
36561 * are fetched from the store or the loader and renderedLevel
36564 * @param {IRegionOfInterest} roi - Spatial edges to cache.
36566 TextureProvider.prototype.setRegionOfInterest = function (roi) {
36567 if (this._width <= 0 || this._height <= 0) {
36571 var width = 1 / this._roi.pixelWidth;
36572 var height = 1 / this._roi.pixelHeight;
36573 var size = Math.max(height, width);
36574 var currentLevel = Math.max(0, Math.min(this._maxLevel, Math.round(Math.log(size) / Math.log(2))));
36575 if (currentLevel !== this._currentLevel) {
36577 this._currentLevel = currentLevel;
36578 if (!(this._currentLevel in this._renderedTiles)) {
36579 this._renderedTiles[this._currentLevel] = [];
36581 this._renderedCurrentLevelTiles = {};
36582 for (var _i = 0, _a = this._renderedTiles[this._currentLevel]; _i < _a.length; _i++) {
36584 this._renderedCurrentLevelTiles[this._tileKey(tile)] = true;
36587 var topLeft = this._getTileCoords([this._roi.bbox.minX, this._roi.bbox.minY]);
36588 var bottomRight = this._getTileCoords([this._roi.bbox.maxX, this._roi.bbox.maxY]);
36589 var tiles = this._getTiles(topLeft, bottomRight);
36590 if (this._camera == null) {
36591 this._camera = new THREE.OrthographicCamera(-this._width / 2, this._width / 2, this._height / 2, -this._height / 2, -1, 1);
36592 this._camera.position.z = 1;
36593 var gl = this._renderer.getContext();
36594 var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
36595 var backgroundSize = Math.max(this._width, this._height);
36596 var scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize;
36597 var targetWidth = Math.floor(scale * this._width);
36598 var targetHeight = Math.floor(scale * this._height);
36599 this._renderTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, {
36600 depthBuffer: false,
36601 format: THREE.RGBFormat,
36602 magFilter: THREE.LinearFilter,
36603 minFilter: THREE.LinearFilter,
36604 stencilBuffer: false,
36606 this._renderToTarget(0, 0, this._width, this._height, this._background);
36607 this._createdSubject$.next(this._renderTarget.texture);
36608 this._hasSubject$.next(true);
36610 this._fetchTiles(tiles);
36613 * Update the image used as background for the texture.
36615 * @param {HTMLImageElement} background - The background image.
36617 TextureProvider.prototype.updateBackground = function (background) {
36618 this._background = background;
36621 * Retrieve an image tile.
36623 * @description Retrieve an image tile and render it to the
36624 * texture. Add the tile to the store and emit to the updated
36627 * @param {Array<number>} tile - The tile coordinates.
36628 * @param {number} level - The tile level.
36629 * @param {number} x - The top left x pixel coordinate of the tile.
36630 * @param {number} y - The top left y pixel coordinate of the tile.
36631 * @param {number} w - The pixel width of the tile.
36632 * @param {number} h - The pixel height of the tile.
36633 * @param {number} scaledW - The scaled width of the returned tile.
36634 * @param {number} scaledH - The scaled height of the returned tile.
36636 TextureProvider.prototype._fetchTile = function (tile, level, x, y, w, h, scaledX, scaledY) {
36638 var getTile = this._imageTileLoader.getTile(this._key, x, y, w, h, scaledX, scaledY);
36639 var tile$ = getTile[0];
36640 var abort = getTile[1];
36641 this._abortFunctions.push(abort);
36642 var tileKey = this._tileKey(tile);
36643 var subscription = tile$
36644 .subscribe(function (image) {
36645 _this._renderToTarget(x, y, w, h, image);
36646 _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
36647 _this._removeFromArray(abort, _this._abortFunctions);
36648 _this._setTileRendered(tile, _this._currentLevel);
36649 _this._imageTileStore.addImage(image, tileKey, level);
36650 _this._updated$.next(true);
36651 }, function (error) {
36652 _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
36653 _this._removeFromArray(abort, _this._abortFunctions);
36654 console.error(error);
36656 if (!subscription.closed) {
36657 this._tileSubscriptions[tileKey] = subscription;
36661 * Retrieve image tiles.
36663 * @description Retrieve a image tiles and render them to the
36664 * texture. Retrieve from store if it exists, otherwise Retrieve
36667 * @param {Array<Array<number>>} tiles - Array of tile coordinates to
36670 TextureProvider.prototype._fetchTiles = function (tiles) {
36671 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
36672 for (var _i = 0, tiles_1 = tiles; _i < tiles_1.length; _i++) {
36673 var tile = tiles_1[_i];
36674 var tileKey = this._tileKey(tile);
36675 if (tileKey in this._renderedCurrentLevelTiles ||
36676 tileKey in this._tileSubscriptions) {
36679 var tileX = tileSize * tile[0];
36680 var tileY = tileSize * tile[1];
36681 var tileWidth = tileX + tileSize > this._width ? this._width - tileX : tileSize;
36682 var tileHeight = tileY + tileSize > this._height ? this._height - tileY : tileSize;
36683 if (this._imageTileStore.hasImage(tileKey, this._currentLevel)) {
36684 this._renderToTarget(tileX, tileY, tileWidth, tileHeight, this._imageTileStore.getImage(tileKey, this._currentLevel));
36685 this._setTileRendered(tile, this._currentLevel);
36686 this._updated$.next(true);
36689 var scaledX = Math.floor(tileWidth / tileSize * this._tileSize);
36690 var scaledY = Math.floor(tileHeight / tileSize * this._tileSize);
36691 this._fetchTile(tile, this._currentLevel, tileX, tileY, tileWidth, tileHeight, scaledX, scaledY);
36695 * Get tile coordinates for a point using the current level.
36697 * @param {Array<number>} point - Point in basic coordinates.
36699 * @returns {Array<number>} x and y tile coodinates.
36701 TextureProvider.prototype._getTileCoords = function (point) {
36702 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
36703 var maxX = Math.ceil(this._width / tileSize) - 1;
36704 var maxY = Math.ceil(this._height / tileSize) - 1;
36706 Math.min(Math.floor(this._width * point[0] / tileSize), maxX),
36707 Math.min(Math.floor(this._height * point[1] / tileSize), maxY),
36711 * Get tile coordinates for all tiles contained in a bounding
36714 * @param {Array<number>} topLeft - Top left tile coordinate of bounding box.
36715 * @param {Array<number>} bottomRight - Bottom right tile coordinate of bounding box.
36717 * @returns {Array<Array<number>>} Array of x, y tile coodinates.
36719 TextureProvider.prototype._getTiles = function (topLeft, bottomRight) {
36721 if (topLeft[0] > bottomRight[0]) {
36722 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
36723 var maxX = Math.ceil(this._width / tileSize) - 1;
36724 for (var x = topLeft[0]; x <= maxX; x++) {
36727 for (var x = 0; x <= bottomRight[0]; x++) {
36732 for (var x = topLeft[0]; x <= bottomRight[0]; x++) {
36737 for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
36739 for (var y = topLeft[1]; y <= bottomRight[1]; y++) {
36740 tiles.push([x, y]);
36746 * Remove an item from an array if it exists in array.
36748 * @param {T} item - Item to remove.
36749 * @param {Array<T>} array - Array from which item should be removed.
36751 TextureProvider.prototype._removeFromArray = function (item, array) {
36752 var index = array.indexOf(item);
36753 if (index !== -1) {
36754 array.splice(index, 1);
36758 * Remove an item from a dictionary.
36760 * @param {string} key - Key of the item to remove.
36761 * @param {Object} dict - Dictionary from which item should be removed.
36763 TextureProvider.prototype._removeFromDictionary = function (key, dict) {
36769 * Render an image tile to the target texture.
36771 * @param {number} x - The top left x pixel coordinate of the tile.
36772 * @param {number} y - The top left y pixel coordinate of the tile.
36773 * @param {number} w - The pixel width of the tile.
36774 * @param {number} h - The pixel height of the tile.
36775 * @param {HTMLImageElement} background - The image tile to render.
36777 TextureProvider.prototype._renderToTarget = function (x, y, w, h, image) {
36778 var texture = new THREE.Texture(image);
36779 texture.minFilter = THREE.LinearFilter;
36780 texture.needsUpdate = true;
36781 var geometry = new THREE.PlaneGeometry(w, h);
36782 var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide });
36783 var mesh = new THREE.Mesh(geometry, material);
36784 mesh.position.x = -this._width / 2 + x + w / 2;
36785 mesh.position.y = this._height / 2 - y - h / 2;
36786 var scene = new THREE.Scene();
36788 this._renderer.render(scene, this._camera, this._renderTarget);
36789 this._renderer.setRenderTarget(undefined);
36790 scene.remove(mesh);
36791 geometry.dispose();
36792 material.dispose();
36796 * Mark a tile as rendered.
36798 * @description Clears tiles marked as rendered in other
36799 * levels of the tile pyramid if they were rendered on
36800 * top of or below the tile.
36802 * @param {Arrary<number>} tile - The tile coordinates.
36803 * @param {number} level - Tile level of the tile coordinates.
36805 TextureProvider.prototype._setTileRendered = function (tile, level) {
36806 var otherLevels = Object.keys(this._renderedTiles)
36807 .map(function (key) {
36808 return parseInt(key, 10);
36810 .filter(function (renderedLevel) {
36811 return renderedLevel !== level;
36813 for (var _i = 0, otherLevels_1 = otherLevels; _i < otherLevels_1.length; _i++) {
36814 var otherLevel = otherLevels_1[_i];
36815 var scale = Math.pow(2, otherLevel - level);
36816 if (otherLevel < level) {
36817 var x = Math.floor(scale * tile[0]);
36818 var y = Math.floor(scale * tile[1]);
36819 for (var _a = 0, _b = this._renderedTiles[otherLevel].slice(); _a < _b.length; _a++) {
36820 var otherTile = _b[_a];
36821 if (otherTile[0] === x && otherTile[1] === y) {
36822 var index = this._renderedTiles[otherLevel].indexOf(otherTile);
36823 this._renderedTiles[otherLevel].splice(index, 1);
36828 var startX = scale * tile[0];
36829 var endX = startX + scale - 1;
36830 var startY = scale * tile[1];
36831 var endY = startY + scale - 1;
36832 for (var _c = 0, _d = this._renderedTiles[otherLevel].slice(); _c < _d.length; _c++) {
36833 var otherTile = _d[_c];
36834 if (otherTile[0] >= startX && otherTile[0] <= endX &&
36835 otherTile[1] >= startY && otherTile[1] <= endY) {
36836 var index = this._renderedTiles[otherLevel].indexOf(otherTile);
36837 this._renderedTiles[otherLevel].splice(index, 1);
36841 if (this._renderedTiles[otherLevel].length === 0) {
36842 delete this._renderedTiles[otherLevel];
36845 this._renderedTiles[level].push(tile);
36846 this._renderedCurrentLevelTiles[this._tileKey(tile)] = true;
36849 * Create a tile key from a tile coordinates.
36851 * @description Tile keys are used as a hash for
36852 * storing the tile in a dictionary.
36854 * @param {Arrary<number>} tile - The tile coordinates.
36856 TextureProvider.prototype._tileKey = function (tile) {
36857 return tile[0] + "-" + tile[1];
36859 return TextureProvider;
36861 exports.TextureProvider = TextureProvider;
36862 Object.defineProperty(exports, "__esModule", { value: true });
36863 exports.default = TextureProvider;
36865 },{"rxjs/Subject":33,"three":175}],336:[function(require,module,exports){
36867 var EventEmitter = (function () {
36868 function EventEmitter() {
36872 * Subscribe to an event by its name.
36873 * @param {string }eventType - The name of the event to subscribe to.
36874 * @param {any} fn - The handler called when the event occurs.
36876 EventEmitter.prototype.on = function (eventType, fn) {
36877 this._events[eventType] = this._events[eventType] || [];
36878 this._events[eventType].push(fn);
36882 * Unsubscribe from an event by its name.
36883 * @param {string} eventType - The name of the event to subscribe to.
36884 * @param {any} fn - The handler to remove.
36886 EventEmitter.prototype.off = function (eventType, fn) {
36891 if (!this._listens(eventType)) {
36892 var idx = this._events[eventType].indexOf(fn);
36894 this._events[eventType].splice(idx, 1);
36896 if (this._events[eventType].length) {
36897 delete this._events[eventType];
36901 delete this._events[eventType];
36905 EventEmitter.prototype.fire = function (eventType, data) {
36906 if (!this._listens(eventType)) {
36909 for (var _i = 0, _a = this._events[eventType]; _i < _a.length; _i++) {
36911 fn.call(this, data);
36915 EventEmitter.prototype._listens = function (eventType) {
36916 return !!(this._events && this._events[eventType]);
36918 return EventEmitter;
36920 exports.EventEmitter = EventEmitter;
36921 Object.defineProperty(exports, "__esModule", { value: true });
36922 exports.default = EventEmitter;
36924 },{}],337:[function(require,module,exports){
36926 var Viewer_1 = require("../Viewer");
36927 var Settings = (function () {
36928 function Settings() {
36930 Settings.setOptions = function (options) {
36931 Settings._baseImageSize = options.baseImageSize != null ?
36932 options.baseImageSize :
36933 Viewer_1.ImageSize.Size640;
36934 Settings._basePanoramaSize = options.basePanoramaSize != null ?
36935 options.basePanoramaSize :
36936 Viewer_1.ImageSize.Size2048;
36937 Settings._maxImageSize = options.maxImageSize != null ?
36938 options.maxImageSize :
36939 Viewer_1.ImageSize.Size2048;
36941 Object.defineProperty(Settings, "baseImageSize", {
36943 return Settings._baseImageSize;
36948 Object.defineProperty(Settings, "basePanoramaSize", {
36950 return Settings._basePanoramaSize;
36955 Object.defineProperty(Settings, "maxImageSize", {
36957 return Settings._maxImageSize;
36964 exports.Settings = Settings;
36965 Object.defineProperty(exports, "__esModule", { value: true });
36966 exports.default = Settings;
36968 },{"../Viewer":235}],338:[function(require,module,exports){
36970 var Urls = (function () {
36973 Object.defineProperty(Urls, "tileScheme", {
36980 Object.defineProperty(Urls, "tileDomain", {
36982 return "d2qb1440i7l50o.cloudfront.net";
36987 Object.defineProperty(Urls, "origin", {
36989 return "mapillary.webgl";
36994 Urls.thumbnail = function (key, size) {
36995 return "https://d1cuyjsrcm0gby.cloudfront.net/" + key + "/thumb-" + size + ".jpg?origin=" + this.origin;
36997 Urls.falcorModel = function (clientId) {
36998 return "https://a.mapillary.com/v3/model.json?client_id=" + clientId;
37000 Urls.protoMesh = function (key) {
37001 return "https://d1brzeo354iq2l.cloudfront.net/v2/mesh/" + key;
37005 exports.Urls = Urls;
37006 Object.defineProperty(exports, "__esModule", { value: true });
37007 exports.default = Urls;
37009 },{}],339:[function(require,module,exports){
37011 require("rxjs/add/operator/bufferCount");
37012 require("rxjs/add/operator/delay");
37013 require("rxjs/add/operator/distinctUntilChanged");
37014 require("rxjs/add/operator/map");
37015 require("rxjs/add/operator/switchMap");
37016 var CacheService = (function () {
37017 function CacheService(graphService, stateService) {
37018 this._graphService = graphService;
37019 this._stateService = stateService;
37020 this._started = false;
37022 Object.defineProperty(CacheService.prototype, "started", {
37024 return this._started;
37029 CacheService.prototype.start = function () {
37031 if (this._started) {
37034 this._uncacheSubscription = this._stateService.currentState$
37035 .distinctUntilChanged(undefined, function (frame) {
37036 return frame.state.currentNode.key;
37038 .map(function (frame) {
37039 return frame.state.trajectory
37040 .map(function (n) {
37045 .switchMap(function (keepKeysBuffer) {
37046 var keepKeys = keepKeysBuffer[0];
37047 return _this._graphService.uncache$(keepKeys);
37049 .subscribe(function () { });
37050 this._started = true;
37052 CacheService.prototype.stop = function () {
37053 if (!this._started) {
37056 this._uncacheSubscription.unsubscribe();
37057 this._uncacheSubscription = null;
37058 this._started = false;
37060 return CacheService;
37062 exports.CacheService = CacheService;
37063 Object.defineProperty(exports, "__esModule", { value: true });
37064 exports.default = CacheService;
37066 },{"rxjs/add/operator/bufferCount":49,"rxjs/add/operator/delay":55,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/map":64,"rxjs/add/operator/switchMap":78}],340:[function(require,module,exports){
37068 var Component_1 = require("../Component");
37069 var ComponentController = (function () {
37070 function ComponentController(container, navigator, observer, key, options) {
37072 this._container = container;
37073 this._observer = observer;
37074 this._navigator = navigator;
37075 this._options = options != null ? options : {};
37077 this._componentService = new Component_1.ComponentService(this._container, this._navigator);
37078 this._coverComponent = this._componentService.getCover();
37079 this._initializeComponents();
37081 this._initilizeCoverComponent();
37082 this._subscribeCoverComponent();
37085 this._navigator.movedToKey$
37086 .first(function (k) {
37089 .subscribe(function (k) {
37091 _this._componentService.deactivateCover();
37092 _this._coverComponent.configure({ key: _this._key, loading: false, visible: false });
37093 _this._subscribeCoverComponent();
37094 _this._navigator.stateService.start();
37095 _this._observer.startEmit();
37099 ComponentController.prototype.get = function (name) {
37100 return this._componentService.get(name);
37102 ComponentController.prototype.activate = function (name) {
37103 this._componentService.activate(name);
37105 ComponentController.prototype.activateCover = function () {
37106 this._coverComponent.configure({ loading: false, visible: true });
37108 ComponentController.prototype.deactivate = function (name) {
37109 this._componentService.deactivate(name);
37111 ComponentController.prototype.deactivateCover = function () {
37112 this._coverComponent.configure({ loading: true, visible: true });
37114 ComponentController.prototype.resize = function () {
37115 this._componentService.resize();
37117 ComponentController.prototype._initializeComponents = function () {
37118 var options = this._options;
37119 this._uFalse(options.background, "background");
37120 this._uFalse(options.debug, "debug");
37121 this._uFalse(options.image, "image");
37122 this._uFalse(options.marker, "marker");
37123 this._uFalse(options.navigation, "navigation");
37124 this._uFalse(options.route, "route");
37125 this._uFalse(options.slider, "slider");
37126 this._uFalse(options.tag, "tag");
37127 this._uTrue(options.attribution, "attribution");
37128 this._uTrue(options.bearing, "bearing");
37129 this._uTrue(options.cache, "cache");
37130 this._uTrue(options.direction, "direction");
37131 this._uTrue(options.imagePlane, "imagePlane");
37132 this._uTrue(options.keyboard, "keyboard");
37133 this._uTrue(options.loading, "loading");
37134 this._uTrue(options.mouse, "mouse");
37135 this._uTrue(options.sequence, "sequence");
37136 this._uTrue(options.stats, "stats");
37138 ComponentController.prototype._initilizeCoverComponent = function () {
37139 var options = this._options;
37140 this._coverComponent.configure({ key: this._key });
37141 if (options.cover === undefined || options.cover) {
37142 this.activateCover();
37145 this.deactivateCover();
37148 ComponentController.prototype._subscribeCoverComponent = function () {
37150 this._coverComponent.configuration$.subscribe(function (conf) {
37151 if (conf.loading) {
37152 _this._navigator.stateService.currentKey$
37154 .switchMap(function (key) {
37155 return key == null || key !== conf.key ?
37156 _this._navigator.moveToKey$(conf.key) :
37157 _this._navigator.stateService.currentNode$
37160 .subscribe(function (node) {
37161 _this._navigator.stateService.start();
37162 _this._observer.startEmit();
37163 _this._coverComponent.configure({ loading: false, visible: false });
37164 _this._componentService.deactivateCover();
37165 }, function (error) {
37166 console.error("Failed to deactivate cover.", error);
37167 _this._coverComponent.configure({ loading: false, visible: true });
37170 else if (conf.visible) {
37171 _this._observer.stopEmit();
37172 _this._navigator.stateService.stop();
37173 _this._componentService.activateCover();
37177 ComponentController.prototype._uFalse = function (option, name) {
37178 if (option === undefined) {
37179 this._componentService.deactivate(name);
37182 if (typeof option === "boolean") {
37184 this._componentService.activate(name);
37187 this._componentService.deactivate(name);
37191 this._componentService.configure(name, option);
37192 this._componentService.activate(name);
37194 ComponentController.prototype._uTrue = function (option, name) {
37195 if (option === undefined) {
37196 this._componentService.activate(name);
37199 if (typeof option === "boolean") {
37201 this._componentService.activate(name);
37204 this._componentService.deactivate(name);
37208 this._componentService.configure(name, option);
37209 this._componentService.activate(name);
37211 return ComponentController;
37213 exports.ComponentController = ComponentController;
37215 },{"../Component":225}],341:[function(require,module,exports){
37217 var Render_1 = require("../Render");
37218 var Viewer_1 = require("../Viewer");
37219 var Container = (function () {
37220 function Container(id, stateService, options) {
37222 this._container = document.getElementById(id);
37223 this._container.classList.add("mapillary-js");
37224 this._canvasContainer = document.createElement("div");
37225 this._canvasContainer.className = "mapillary-js-interactive";
37226 this._container.appendChild(this._canvasContainer);
37227 this.renderService = new Render_1.RenderService(this._container, stateService.currentState$, options.renderMode);
37228 this.glRenderer = new Render_1.GLRenderer(this._canvasContainer, this.renderService);
37229 this.domRenderer = new Render_1.DOMRenderer(this._container, this.renderService, stateService.currentState$);
37230 this.mouseService = new Viewer_1.MouseService(this._canvasContainer, this._container);
37231 this.touchService = new Viewer_1.TouchService(this._canvasContainer);
37232 this.spriteService = new Viewer_1.SpriteService(options.sprite);
37234 Object.defineProperty(Container.prototype, "element", {
37236 return this._container;
37241 Object.defineProperty(Container.prototype, "canvasContainer", {
37243 return this.canvasContainer;
37250 exports.Container = Container;
37251 Object.defineProperty(exports, "__esModule", { value: true });
37252 exports.default = Container;
37254 },{"../Render":231,"../Viewer":235}],342:[function(require,module,exports){
37257 * Enumeration for image sizes
37260 * @description Image sizes in pixels for the long side of the image.
37263 (function (ImageSize) {
37265 * 320 pixels image size
37267 ImageSize[ImageSize["Size320"] = 320] = "Size320";
37269 * 640 pixels image size
37271 ImageSize[ImageSize["Size640"] = 640] = "Size640";
37273 * 1024 pixels image size
37275 ImageSize[ImageSize["Size1024"] = 1024] = "Size1024";
37277 * 2048 pixels image size
37279 ImageSize[ImageSize["Size2048"] = 2048] = "Size2048";
37280 })(ImageSize = exports.ImageSize || (exports.ImageSize = {}));
37282 },{}],343:[function(require,module,exports){
37283 /// <reference path="../../typings/index.d.ts" />
37285 var _ = require("underscore");
37286 var Subject_1 = require("rxjs/Subject");
37287 require("rxjs/add/operator/debounceTime");
37288 require("rxjs/add/operator/distinctUntilChanged");
37289 require("rxjs/add/operator/map");
37290 require("rxjs/add/operator/publishReplay");
37291 require("rxjs/add/operator/scan");
37292 require("rxjs/add/operator/startWith");
37293 var LoadingService = (function () {
37294 function LoadingService() {
37295 this._loadersSubject$ = new Subject_1.Subject();
37296 this._loaders$ = this._loadersSubject$
37297 .scan(function (loaders, loader) {
37298 if (loader.task !== undefined) {
37299 loaders[loader.task] = loader.loading;
37307 Object.defineProperty(LoadingService.prototype, "loading$", {
37309 return this._loaders$
37310 .map(function (loaders) {
37311 return _.reduce(loaders, function (loader, acc) {
37312 return (loader || acc);
37316 .distinctUntilChanged();
37321 LoadingService.prototype.taskLoading$ = function (task) {
37322 return this._loaders$
37323 .map(function (loaders) {
37324 return !!loaders[task];
37327 .distinctUntilChanged();
37329 LoadingService.prototype.startLoading = function (task) {
37330 this._loadersSubject$.next({ loading: true, task: task });
37332 LoadingService.prototype.stopLoading = function (task) {
37333 this._loadersSubject$.next({ loading: false, task: task });
37335 return LoadingService;
37337 exports.LoadingService = LoadingService;
37338 Object.defineProperty(exports, "__esModule", { value: true });
37339 exports.default = LoadingService;
37341 },{"rxjs/Subject":33,"rxjs/add/operator/debounceTime":54,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/map":64,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/startWith":77,"underscore":176}],344:[function(require,module,exports){
37343 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
37344 var Observable_1 = require("rxjs/Observable");
37345 var Subject_1 = require("rxjs/Subject");
37346 require("rxjs/add/observable/fromEvent");
37347 require("rxjs/add/operator/distinctUntilChanged");
37348 require("rxjs/add/operator/filter");
37349 require("rxjs/add/operator/map");
37350 require("rxjs/add/operator/merge");
37351 require("rxjs/add/operator/mergeMap");
37352 require("rxjs/add/operator/publishReplay");
37353 require("rxjs/add/operator/scan");
37354 require("rxjs/add/operator/switchMap");
37355 require("rxjs/add/operator/withLatestFrom");
37356 var Geo_1 = require("../Geo");
37357 var MouseService = (function () {
37358 function MouseService(canvasContainer, container, viewportCoords) {
37360 this._canvasContainer = canvasContainer;
37361 this._container = container;
37362 this._viewportCoords = viewportCoords != null ? viewportCoords : new Geo_1.ViewportCoords();
37363 this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
37364 this._active$ = this._activeSubject$
37365 .distinctUntilChanged()
37368 this._claimMouse$ = new Subject_1.Subject();
37369 this._documentMouseDown$ = Observable_1.Observable.fromEvent(document, "mousedown")
37370 .filter(function (event) {
37371 return _this._viewportCoords.insideElement(event, _this._container);
37374 this._documentMouseMove$ = Observable_1.Observable.fromEvent(document, "mousemove");
37375 this._documentMouseUp$ = Observable_1.Observable.fromEvent(document, "mouseup");
37376 this._documentCanvasMouseMove$ = this._documentMouseMove$
37377 .filter(function (event) {
37378 return _this._viewportCoords.insideElement(event, _this._container);
37381 this._mouseDown$ = Observable_1.Observable.fromEvent(canvasContainer, "mousedown");
37382 this._mouseLeave$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseleave");
37383 this._mouseMove$ = Observable_1.Observable.fromEvent(canvasContainer, "mousemove");
37384 this._mouseUp$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseup");
37385 this._mouseOut$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseout");
37386 this._mouseOver$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseover");
37387 this._click$ = Observable_1.Observable.fromEvent(canvasContainer, "click");
37388 this._dblClick$ = Observable_1.Observable.fromEvent(canvasContainer, "dblclick");
37390 .subscribe(function (event) {
37391 event.preventDefault();
37393 this._contextMenu$ = Observable_1.Observable.fromEvent(canvasContainer, "contextmenu");
37395 .subscribe(function (event) {
37396 event.preventDefault();
37398 this._mouseWheel$ = Observable_1.Observable.fromEvent(document, "wheel")
37399 .filter(function (event) {
37400 return _this._viewportCoords.insideElement(event, _this._container);
37403 this._consistentContextMenu$ = Observable_1.Observable
37404 .merge(this._mouseDown$, this._mouseMove$, this._mouseOut$, this._mouseUp$, this._contextMenu$)
37406 .filter(function (events) {
37407 // fire context menu on mouse up both on mac and windows
37408 return events[0].type === "mousedown" &&
37409 events[1].type === "contextmenu" &&
37410 events[2].type === "mouseup";
37412 .map(function (events) {
37416 var dragStop$ = Observable_1.Observable
37417 .merge(this._documentMouseUp$.filter(function (e) {
37418 return e.button === 0;
37421 var leftButtonDown$ = this._mouseDown$
37422 .filter(function (e) {
37423 return e.button === 0;
37426 this._mouseDragStart$ = leftButtonDown$
37427 .mergeMap(function (e) {
37428 return _this._documentMouseMove$
37429 .takeUntil(dragStop$)
37432 this._mouseDrag$ = leftButtonDown$
37433 .mergeMap(function (e) {
37434 return _this._documentMouseMove$
37436 .takeUntil(dragStop$);
37438 this._mouseDragEnd$ = this._mouseDragStart$
37439 .mergeMap(function (e) {
37440 return dragStop$.first();
37442 this._documentCanvasMouseDown$ = this._documentMouseDown$
37443 .filter(function (e) {
37444 return _this._viewportCoords.insideElement(e, _this._container);
37447 var documentCanvasLeftButtonDown$ = this._documentCanvasMouseDown$
37448 .filter(function (e) {
37449 return e.button === 0;
37452 this._documentCanvasMouseDragStart$ = documentCanvasLeftButtonDown$
37453 .mergeMap(function (e) {
37454 return _this._documentCanvasMouseMove$
37455 .takeUntil(dragStop$)
37458 this._documentCanvasMouseDrag$ = documentCanvasLeftButtonDown$
37459 .mergeMap(function (e) {
37460 return _this._documentCanvasMouseMove$
37462 .takeUntil(dragStop$);
37464 this._documentCanvasMouseDragEnd$ = this._documentCanvasMouseDragStart$
37465 .mergeMap(function (e) {
37466 return dragStop$.first();
37468 this._staticClick$ = this._mouseDown$
37469 .switchMap(function (e) {
37470 return _this._click$
37471 .takeUntil(_this._mouseMove$)
37474 this._mouseOwner$ = this._claimMouse$
37475 .scan(function (claims, mouseClaim) {
37476 if (mouseClaim.zindex == null) {
37477 delete claims[mouseClaim.name];
37480 claims[mouseClaim.name] = mouseClaim.zindex;
37484 .map(function (claims) {
37487 for (var name_1 in claims) {
37488 if (claims.hasOwnProperty(name_1)) {
37489 if (claims[name_1] > curZ) {
37490 curZ = claims[name_1];
37499 this._mouseOwner$.subscribe(function () { });
37501 Object.defineProperty(MouseService.prototype, "active$", {
37503 return this._active$;
37508 Object.defineProperty(MouseService.prototype, "activate$", {
37510 return this._activeSubject$;
37515 Object.defineProperty(MouseService.prototype, "documentCanvasMouseDown$", {
37517 return this._documentCanvasMouseDown$;
37522 Object.defineProperty(MouseService.prototype, "documentCanvasMouseMove$", {
37524 return this._documentCanvasMouseMove$;
37529 Object.defineProperty(MouseService.prototype, "documentCanvasMouseDragStart$", {
37531 return this._documentCanvasMouseDragStart$;
37536 Object.defineProperty(MouseService.prototype, "documentCanvasMouseDrag$", {
37538 return this._documentCanvasMouseDrag$;
37543 Object.defineProperty(MouseService.prototype, "documentCanvasMouseDragEnd$", {
37545 return this._documentCanvasMouseDragEnd$;
37550 Object.defineProperty(MouseService.prototype, "documentMouseMove$", {
37552 return this._documentMouseMove$;
37557 Object.defineProperty(MouseService.prototype, "documentMouseUp$", {
37559 return this._documentMouseUp$;
37564 Object.defineProperty(MouseService.prototype, "mouseOwner$", {
37566 return this._mouseOwner$;
37571 Object.defineProperty(MouseService.prototype, "mouseDown$", {
37573 return this._mouseDown$;
37578 Object.defineProperty(MouseService.prototype, "mouseMove$", {
37580 return this._mouseMove$;
37585 Object.defineProperty(MouseService.prototype, "mouseLeave$", {
37587 return this._mouseLeave$;
37592 Object.defineProperty(MouseService.prototype, "mouseOut$", {
37594 return this._mouseOut$;
37599 Object.defineProperty(MouseService.prototype, "mouseOver$", {
37601 return this._mouseOver$;
37606 Object.defineProperty(MouseService.prototype, "mouseUp$", {
37608 return this._mouseUp$;
37613 Object.defineProperty(MouseService.prototype, "click$", {
37615 return this._click$;
37620 Object.defineProperty(MouseService.prototype, "dblClick$", {
37622 return this._dblClick$;
37627 Object.defineProperty(MouseService.prototype, "contextMenu$", {
37629 return this._consistentContextMenu$;
37634 Object.defineProperty(MouseService.prototype, "mouseWheel$", {
37636 return this._mouseWheel$;
37641 Object.defineProperty(MouseService.prototype, "mouseDragStart$", {
37643 return this._mouseDragStart$;
37648 Object.defineProperty(MouseService.prototype, "mouseDrag$", {
37650 return this._mouseDrag$;
37655 Object.defineProperty(MouseService.prototype, "mouseDragEnd$", {
37657 return this._mouseDragEnd$;
37662 Object.defineProperty(MouseService.prototype, "staticClick$", {
37664 return this._staticClick$;
37669 MouseService.prototype.claimMouse = function (name, zindex) {
37670 this._claimMouse$.next({ name: name, zindex: zindex });
37672 MouseService.prototype.unclaimMouse = function (name) {
37673 this._claimMouse$.next({ name: name, zindex: null });
37675 MouseService.prototype.filtered$ = function (name, observable$) {
37677 .withLatestFrom(this.mouseOwner$, function (event, owner) {
37678 return [event, owner];
37680 .filter(function (eo) {
37681 return eo[1] === name;
37683 .map(function (eo) {
37687 return MouseService;
37689 exports.MouseService = MouseService;
37690 Object.defineProperty(exports, "__esModule", { value: true });
37691 exports.default = MouseService;
37693 },{"../Geo":228,"rxjs/BehaviorSubject":25,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/fromEvent":41,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/merge":65,"rxjs/add/operator/mergeMap":67,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/switchMap":78,"rxjs/add/operator/withLatestFrom":82}],345:[function(require,module,exports){
37694 /// <reference path="../../typings/index.d.ts" />
37696 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
37697 var Observable_1 = require("rxjs/Observable");
37698 require("rxjs/add/observable/throw");
37699 require("rxjs/add/operator/do");
37700 require("rxjs/add/operator/finally");
37701 require("rxjs/add/operator/first");
37702 require("rxjs/add/operator/map");
37703 require("rxjs/add/operator/mergeMap");
37704 var API_1 = require("../API");
37705 var Graph_1 = require("../Graph");
37706 var Edge_1 = require("../Edge");
37707 var State_1 = require("../State");
37708 var Viewer_1 = require("../Viewer");
37709 var Navigator = (function () {
37710 function Navigator(clientId, token, apiV3, graphService, imageLoadingService, loadingService, stateService, cacheService) {
37711 this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token);
37712 this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService();
37713 this._graphService = graphService != null ?
37715 new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService);
37716 this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService();
37717 this._loadingName = "navigator";
37718 this._stateService = stateService != null ? stateService : new State_1.StateService();
37719 this._cacheService = cacheService != null ?
37721 new Viewer_1.CacheService(this._graphService, this._stateService);
37722 this._cacheService.start();
37723 this._keyRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
37724 this._movedToKey$ = new BehaviorSubject_1.BehaviorSubject(null);
37725 this._dirRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
37726 this._latLonRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
37728 Object.defineProperty(Navigator.prototype, "apiV3", {
37730 return this._apiV3;
37735 Object.defineProperty(Navigator.prototype, "graphService", {
37737 return this._graphService;
37742 Object.defineProperty(Navigator.prototype, "imageLoadingService", {
37744 return this._imageLoadingService;
37749 Object.defineProperty(Navigator.prototype, "keyRequested$", {
37751 return this._keyRequested$;
37756 Object.defineProperty(Navigator.prototype, "loadingService", {
37758 return this._loadingService;
37763 Object.defineProperty(Navigator.prototype, "movedToKey$", {
37765 return this._movedToKey$;
37770 Object.defineProperty(Navigator.prototype, "stateService", {
37772 return this._stateService;
37777 Navigator.prototype.moveToKey$ = function (key) {
37779 this.loadingService.startLoading(this._loadingName);
37780 this._keyRequested$.next(key);
37781 return this._graphService.cacheNode$(key)
37782 .do(function (node) {
37783 _this.stateService.setNodes([node]);
37784 _this._movedToKey$.next(node.key);
37786 .finally(function () {
37787 _this.loadingService.stopLoading(_this._loadingName);
37790 Navigator.prototype.moveDir$ = function (direction) {
37792 this.loadingService.startLoading(this._loadingName);
37793 this._dirRequested$.next(direction);
37794 return this.stateService.currentNode$
37796 .mergeMap(function (node) {
37797 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
37798 node.sequenceEdges$ :
37799 node.spatialEdges$)
37801 .map(function (status) {
37802 for (var _i = 0, _a = status.edges; _i < _a.length; _i++) {
37804 if (edge.data.direction === direction) {
37811 .mergeMap(function (directionKey) {
37812 if (directionKey == null) {
37813 _this.loadingService.stopLoading(_this._loadingName);
37814 return Observable_1.Observable
37815 .throw(new Error("Direction (" + direction + ") does not exist for current node."));
37817 return _this.moveToKey$(directionKey);
37820 Navigator.prototype.moveCloseTo$ = function (lat, lon) {
37822 this.loadingService.startLoading(this._loadingName);
37823 this._latLonRequested$.next({ lat: lat, lon: lon });
37824 return this.apiV3.imageCloseTo$(lat, lon)
37825 .mergeMap(function (fullNode) {
37826 if (fullNode == null) {
37827 _this.loadingService.stopLoading(_this._loadingName);
37828 return Observable_1.Observable
37829 .throw(new Error("No image found close to lat " + lat + ", lon " + lon + "."));
37831 return _this.moveToKey$(fullNode.key);
37834 Navigator.prototype.setFilter$ = function (filter) {
37836 this._stateService.clearNodes();
37837 return this._movedToKey$
37839 .mergeMap(function (key) {
37841 return _this._trajectoryKeys$()
37842 .mergeMap(function (keys) {
37843 return _this._graphService.setFilter$(filter)
37844 .mergeMap(function (graph) {
37845 return _this._cacheKeys$(keys);
37850 return _this._keyRequested$
37851 .mergeMap(function (requestedKey) {
37852 if (requestedKey != null) {
37853 return _this._graphService.setFilter$(filter)
37854 .mergeMap(function (graph) {
37855 return _this._graphService.cacheNode$(requestedKey);
37858 return _this._graphService.setFilter$(filter)
37859 .map(function (graph) {
37864 .map(function (node) {
37868 Navigator.prototype.setToken$ = function (token) {
37870 this._stateService.clearNodes();
37871 return this._movedToKey$
37873 .do(function (key) {
37874 _this._apiV3.setToken(token);
37876 .mergeMap(function (key) {
37877 return key == null ?
37878 _this._graphService.reset$([])
37879 .map(function (graph) {
37882 _this._trajectoryKeys$()
37883 .mergeMap(function (keys) {
37884 return _this._graphService.reset$(keys)
37885 .mergeMap(function (graph) {
37886 return _this._cacheKeys$(keys);
37890 .map(function (node) {
37895 Navigator.prototype._cacheKeys$ = function (keys) {
37897 var cacheNodes$ = keys
37898 .map(function (key) {
37899 return _this._graphService.cacheNode$(key);
37901 return Observable_1.Observable
37905 Navigator.prototype._trajectoryKeys$ = function () {
37906 return this._stateService.currentState$
37908 .map(function (frame) {
37909 return frame.state.trajectory
37910 .map(function (node) {
37917 exports.Navigator = Navigator;
37918 Object.defineProperty(exports, "__esModule", { value: true });
37919 exports.default = Navigator;
37921 },{"../API":224,"../Edge":226,"../Graph":229,"../State":232,"../Viewer":235,"rxjs/BehaviorSubject":25,"rxjs/Observable":28,"rxjs/add/observable/throw":45,"rxjs/add/operator/do":58,"rxjs/add/operator/finally":61,"rxjs/add/operator/first":62,"rxjs/add/operator/map":64,"rxjs/add/operator/mergeMap":67}],346:[function(require,module,exports){
37923 var Observable_1 = require("rxjs/Observable");
37924 require("rxjs/add/observable/combineLatest");
37925 require("rxjs/add/operator/distinctUntilChanged");
37926 require("rxjs/add/operator/map");
37927 require("rxjs/add/operator/throttleTime");
37928 var Viewer_1 = require("../Viewer");
37929 var Observer = (function () {
37930 function Observer(eventEmitter, navigator, container) {
37932 this._container = container;
37933 this._eventEmitter = eventEmitter;
37934 this._navigator = navigator;
37935 this._projection = new Viewer_1.Projection();
37936 this._started = false;
37937 // loading should always emit, also when cover is activated
37938 this._navigator.loadingService.loading$
37939 .subscribe(function (loading) {
37940 _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading);
37943 Object.defineProperty(Observer.prototype, "started", {
37945 return this._started;
37950 Observer.prototype.startEmit = function () {
37952 if (this._started) {
37955 this._started = true;
37956 this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$
37957 .subscribe(function (node) {
37958 _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node);
37960 this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$
37961 .switchMap(function (node) {
37962 return node.sequenceEdges$;
37964 .subscribe(function (status) {
37965 _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status);
37967 this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$
37968 .switchMap(function (node) {
37969 return node.spatialEdges$;
37971 .subscribe(function (status) {
37972 _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status);
37974 this._moveSubscription = Observable_1.Observable
37975 .combineLatest(this._navigator.stateService.inMotion$, this._container.mouseService.active$, this._container.touchService.active$)
37976 .map(function (values) {
37977 return values[0] || values[1] || values[2];
37979 .distinctUntilChanged()
37980 .subscribe(function (started) {
37982 _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null);
37985 _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null);
37988 this._bearingSubscription = this._container.renderService.bearing$
37990 .distinctUntilChanged(function (b1, b2) {
37991 return Math.abs(b2 - b1) < 1;
37993 .subscribe(function (bearing) {
37994 _this._eventEmitter.fire(Viewer_1.Viewer.bearingchanged, bearing);
37996 var mouseMove$ = this._container.mouseService.active$
37997 .switchMap(function (active) {
37999 Observable_1.Observable.empty() :
38000 _this._container.mouseService.mouseMove$;
38002 this._viewerMouseEventSubscription = Observable_1.Observable
38003 .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$))
38004 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
38005 .map(function (_a) {
38006 var _b = _a[0], type = _b[0], event = _b[1], render = _a[1], reference = _a[2], transform = _a[3];
38007 var unprojection = _this._projection.unprojectFromEvent(event, _this._container.element, render, reference, transform);
38009 basicPoint: unprojection.basicPoint,
38010 latLon: unprojection.latLon,
38011 originalEvent: event,
38012 pixelPoint: unprojection.pixelPoint,
38013 target: _this._eventEmitter,
38017 .subscribe(function (event) {
38018 _this._eventEmitter.fire(event.type, event);
38021 Observer.prototype.stopEmit = function () {
38022 if (!this.started) {
38025 this._started = false;
38026 this._bearingSubscription.unsubscribe();
38027 this._currentNodeSubscription.unsubscribe();
38028 this._moveSubscription.unsubscribe();
38029 this._sequenceEdgesSubscription.unsubscribe();
38030 this._spatialEdgesSubscription.unsubscribe();
38031 this._viewerMouseEventSubscription.unsubscribe();
38032 this._bearingSubscription = null;
38033 this._currentNodeSubscription = null;
38034 this._moveSubscription = null;
38035 this._sequenceEdgesSubscription = null;
38036 this._spatialEdgesSubscription = null;
38037 this._viewerMouseEventSubscription = null;
38039 Observer.prototype.unproject$ = function (pixelPoint) {
38041 return Observable_1.Observable
38042 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
38044 .map(function (_a) {
38045 var render = _a[0], reference = _a[1], transform = _a[2];
38046 var unprojection = _this._projection.unprojectFromCanvas(pixelPoint, _this._container.element, render, reference, transform);
38047 return unprojection.latLon;
38050 Observer.prototype._mapMouseEvent$ = function (type, mouseEvent$) {
38051 return mouseEvent$.map(function (event) {
38052 return [type, event];
38057 exports.Observer = Observer;
38058 Object.defineProperty(exports, "__esModule", { value: true });
38059 exports.default = Observer;
38061 },{"../Viewer":235,"rxjs/Observable":28,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":57,"rxjs/add/operator/map":64,"rxjs/add/operator/throttleTime":81}],347:[function(require,module,exports){
38062 /// <reference path="../../typings/index.d.ts" />
38064 var THREE = require("three");
38065 var Geo_1 = require("../Geo");
38066 var Projection = (function () {
38067 function Projection(geoCoords, viewportCoords) {
38068 this._geoCoords = !!geoCoords ? geoCoords : new Geo_1.GeoCoords();
38069 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
38071 Projection.prototype.unprojectFromEvent = function (event, container, renderCamera, reference, transform) {
38072 var pixelPoint = this._viewportCoords.canvasPosition(event, container);
38073 return this.unprojectFromCanvas(pixelPoint, container, renderCamera, reference, transform);
38075 Projection.prototype.unprojectFromCanvas = function (pixelPoint, container, render, reference, transform) {
38076 var canvasX = pixelPoint[0];
38077 var canvasY = pixelPoint[1];
38078 var _a = this._viewportCoords.canvasToViewport(canvasX, canvasY, container), viewportX = _a[0], viewportY = _a[1];
38079 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
38080 .unproject(render.perspective);
38081 var basicPoint = transform.projectBasic(point3d.toArray());
38082 if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
38085 var direction3d = point3d.clone().sub(render.camera.position).normalize();
38086 var dist = -2 / direction3d.z;
38088 if (dist > 0 && dist < 100 && !!basicPoint) {
38089 var point = direction3d.clone().multiplyScalar(dist).add(render.camera.position);
38090 var latLonArray = this._geoCoords
38091 .enuToGeodetic(point.x, point.y, point.z, reference.lat, reference.lon, reference.alt)
38093 latLon = { lat: latLonArray[0], lon: latLonArray[1] };
38095 var unprojection = {
38096 basicPoint: basicPoint,
38098 pixelPoint: [canvasX, canvasY],
38100 return unprojection;
38104 exports.Projection = Projection;
38105 Object.defineProperty(exports, "__esModule", { value: true });
38106 exports.default = Projection;
38108 },{"../Geo":228,"three":175}],348:[function(require,module,exports){
38110 var SpriteAlignment;
38111 (function (SpriteAlignment) {
38112 SpriteAlignment[SpriteAlignment["Center"] = 0] = "Center";
38113 SpriteAlignment[SpriteAlignment["Start"] = 1] = "Start";
38114 SpriteAlignment[SpriteAlignment["End"] = 2] = "End";
38115 })(SpriteAlignment = exports.SpriteAlignment || (exports.SpriteAlignment = {}));
38116 Object.defineProperty(exports, "__esModule", { value: true });
38117 exports.default = SpriteAlignment;
38119 },{}],349:[function(require,module,exports){
38120 /// <reference path="../../typings/index.d.ts" />
38122 var THREE = require("three");
38123 var vd = require("virtual-dom");
38124 var Subject_1 = require("rxjs/Subject");
38125 require("rxjs/add/operator/publishReplay");
38126 require("rxjs/add/operator/scan");
38127 require("rxjs/add/operator/startWith");
38128 var Viewer_1 = require("../Viewer");
38129 var SpriteAtlas = (function () {
38130 function SpriteAtlas() {
38132 Object.defineProperty(SpriteAtlas.prototype, "json", {
38133 set: function (value) {
38134 this._json = value;
38139 Object.defineProperty(SpriteAtlas.prototype, "image", {
38140 set: function (value) {
38141 this._image = value;
38142 this._texture = new THREE.Texture(this._image);
38143 this._texture.minFilter = THREE.NearestFilter;
38148 Object.defineProperty(SpriteAtlas.prototype, "loaded", {
38150 return !!(this._image && this._json);
38155 SpriteAtlas.prototype.getGLSprite = function (name) {
38156 if (!this.loaded) {
38157 throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
38159 var definition = this._json[name];
38161 console.warn("Sprite with key" + name + "does not exist in sprite definition.");
38162 return new THREE.Object3D();
38164 var texture = this._texture.clone();
38165 texture.needsUpdate = true;
38166 var width = this._image.width;
38167 var height = this._image.height;
38168 texture.offset.x = definition.x / width;
38169 texture.offset.y = (height - definition.y - definition.height) / height;
38170 texture.repeat.x = definition.width / width;
38171 texture.repeat.y = definition.height / height;
38172 var material = new THREE.SpriteMaterial({ map: texture });
38173 return new THREE.Sprite(material);
38175 SpriteAtlas.prototype.getDOMSprite = function (name, horizontalAlign, verticalAlign) {
38176 if (!this.loaded) {
38177 throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
38179 if (horizontalAlign == null) {
38180 horizontalAlign = Viewer_1.SpriteAlignment.Start;
38182 if (verticalAlign == null) {
38183 verticalAlign = Viewer_1.SpriteAlignment.Start;
38185 var definition = this._json[name];
38187 console.warn("Sprite with key" + name + "does not exist in sprite definition.");
38188 return vd.h("div", {}, []);
38190 var clipTop = definition.y;
38191 var clipRigth = definition.x + definition.width;
38192 var clipBottom = definition.y + definition.height;
38193 var clipLeft = definition.x;
38194 var left = -definition.x;
38195 var top = -definition.y;
38196 var height = this._image.height;
38197 var width = this._image.width;
38198 switch (horizontalAlign) {
38199 case Viewer_1.SpriteAlignment.Center:
38200 left -= definition.width / 2;
38202 case Viewer_1.SpriteAlignment.End:
38203 left -= definition.width;
38205 case Viewer_1.SpriteAlignment.Start:
38210 switch (verticalAlign) {
38211 case Viewer_1.SpriteAlignment.Center:
38212 top -= definition.height / 2;
38214 case Viewer_1.SpriteAlignment.End:
38215 top -= definition.height;
38217 case Viewer_1.SpriteAlignment.Start:
38222 var pixelRatioInverse = 1 / definition.pixelRatio;
38223 clipTop *= pixelRatioInverse;
38224 clipRigth *= pixelRatioInverse;
38225 clipBottom *= pixelRatioInverse;
38226 clipLeft *= pixelRatioInverse;
38227 left *= pixelRatioInverse;
38228 top *= pixelRatioInverse;
38229 height *= pixelRatioInverse;
38230 width *= pixelRatioInverse;
38232 src: this._image.src,
38234 clip: "rect(" + clipTop + "px, " + clipRigth + "px, " + clipBottom + "px, " + clipLeft + "px)",
38235 height: height + "px",
38237 position: "absolute",
38239 width: width + "px",
38242 return vd.h("img", properties, []);
38244 return SpriteAtlas;
38246 var SpriteService = (function () {
38247 function SpriteService(sprite) {
38249 this._retina = window.devicePixelRatio > 1;
38250 this._spriteAtlasOperation$ = new Subject_1.Subject();
38251 this._spriteAtlas$ = this._spriteAtlasOperation$
38252 .startWith(function (atlas) {
38255 .scan(function (atlas, operation) {
38256 return operation(atlas);
38257 }, new SpriteAtlas())
38260 this._spriteAtlas$.subscribe(function () { });
38261 if (sprite == null) {
38264 var format = this._retina ? "@2x" : "";
38265 var imageXmlHTTP = new XMLHttpRequest();
38266 imageXmlHTTP.open("GET", sprite + format + ".png", true);
38267 imageXmlHTTP.responseType = "arraybuffer";
38268 imageXmlHTTP.onload = function () {
38269 var image = new Image();
38270 image.onload = function () {
38271 _this._spriteAtlasOperation$.next(function (atlas) {
38272 atlas.image = image;
38276 var blob = new Blob([imageXmlHTTP.response]);
38277 image.src = window.URL.createObjectURL(blob);
38279 imageXmlHTTP.onerror = function (error) {
38280 console.error(new Error("Failed to fetch sprite sheet (" + sprite + format + ".png)"));
38282 imageXmlHTTP.send();
38283 var jsonXmlHTTP = new XMLHttpRequest();
38284 jsonXmlHTTP.open("GET", sprite + format + ".json", true);
38285 jsonXmlHTTP.responseType = "text";
38286 jsonXmlHTTP.onload = function () {
38287 var json = JSON.parse(jsonXmlHTTP.response);
38288 _this._spriteAtlasOperation$.next(function (atlas) {
38293 jsonXmlHTTP.onerror = function (error) {
38294 console.error(new Error("Failed to fetch sheet (" + sprite + format + ".json)"));
38296 jsonXmlHTTP.send();
38298 Object.defineProperty(SpriteService.prototype, "spriteAtlas$", {
38300 return this._spriteAtlas$;
38305 return SpriteService;
38307 exports.SpriteService = SpriteService;
38308 Object.defineProperty(exports, "__esModule", { value: true });
38309 exports.default = SpriteService;
38311 },{"../Viewer":235,"rxjs/Subject":33,"rxjs/add/operator/publishReplay":71,"rxjs/add/operator/scan":72,"rxjs/add/operator/startWith":77,"three":175,"virtual-dom":181}],350:[function(require,module,exports){
38313 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
38314 var Observable_1 = require("rxjs/Observable");
38315 var Subject_1 = require("rxjs/Subject");
38316 require("rxjs/add/observable/timer");
38317 require("rxjs/add/operator/bufferWhen");
38318 require("rxjs/add/operator/filter");
38319 require("rxjs/add/operator/map");
38320 require("rxjs/add/operator/merge");
38321 require("rxjs/add/operator/scan");
38322 require("rxjs/add/operator/switchMap");
38323 var TouchService = (function () {
38324 function TouchService(element) {
38326 this._element = element;
38327 this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
38328 this._active$ = this._activeSubject$
38329 .distinctUntilChanged()
38332 this._touchStart$ = Observable_1.Observable.fromEvent(element, "touchstart");
38333 this._touchMove$ = Observable_1.Observable.fromEvent(element, "touchmove");
38334 this._touchEnd$ = Observable_1.Observable.fromEvent(element, "touchend");
38335 this._touchCancel$ = Observable_1.Observable.fromEvent(element, "touchcancel");
38336 var tapStart$ = this._touchStart$
38337 .filter(function (te) {
38338 return te.touches.length === 1 && te.targetTouches.length === 1;
38341 this._doubleTap$ = tapStart$
38342 .bufferWhen(function () {
38345 .switchMap(function (event) {
38346 return Observable_1.Observable
38352 .filter(function (events) {
38353 return events.length === 2;
38355 .map(function (events) {
38356 return events[events.length - 1];
38360 .subscribe(function (event) {
38361 event.preventDefault();
38363 this._singleTouchMove$ = this._touchMove$
38364 .filter(function (te) {
38365 return te.touches.length === 1 && te.targetTouches.length === 1;
38368 var singleTouchStart$ = Observable_1.Observable
38369 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
38370 .filter(function (te) {
38371 return te.touches.length === 1 && te.targetTouches.length === 1;
38373 var multipleTouchStart$ = Observable_1.Observable
38374 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
38375 .filter(function (te) {
38376 return te.touches.length >= 1;
38378 var touchStop$ = Observable_1.Observable
38379 .merge(this._touchEnd$, this._touchCancel$)
38380 .filter(function (te) {
38381 return te.touches.length === 0;
38383 this._singleTouchDragStart$ = singleTouchStart$
38384 .mergeMap(function (e) {
38385 return _this._singleTouchMove$
38386 .takeUntil(Observable_1.Observable.merge(touchStop$, multipleTouchStart$))
38389 this._singleTouchDragEnd$ = singleTouchStart$
38390 .mergeMap(function (e) {
38391 return Observable_1.Observable
38392 .merge(touchStop$, multipleTouchStart$)
38395 this._singleTouchDrag$ = singleTouchStart$
38396 .switchMap(function (te) {
38397 return _this._singleTouchMove$
38399 .takeUntil(Observable_1.Observable
38400 .merge(multipleTouchStart$, touchStop$));
38402 var touchesChanged$ = Observable_1.Observable
38403 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$);
38404 this._pinchStart$ = touchesChanged$
38405 .filter(function (te) {
38406 return te.touches.length === 2 && te.targetTouches.length === 2;
38408 this._pinchEnd$ = touchesChanged$
38409 .filter(function (te) {
38410 return te.touches.length !== 2 || te.targetTouches.length !== 2;
38412 this._pinchOperation$ = new Subject_1.Subject();
38413 this._pinch$ = this._pinchOperation$
38414 .scan(function (pinch, operation) {
38415 return operation(pinch);
38425 originalEvent: null,
38434 .filter(function (te) {
38435 return te.touches.length === 2 && te.targetTouches.length === 2;
38437 .map(function (te) {
38438 return function (previous) {
38439 var touch1 = te.touches[0];
38440 var touch2 = te.touches[1];
38441 var minX = Math.min(touch1.clientX, touch2.clientX);
38442 var maxX = Math.max(touch1.clientX, touch2.clientX);
38443 var minY = Math.min(touch1.clientY, touch2.clientY);
38444 var maxY = Math.max(touch1.clientY, touch2.clientY);
38445 var centerClientX = minX + (maxX - minX) / 2;
38446 var centerClientY = minY + (maxY - minY) / 2;
38447 var centerPageX = centerClientX + touch1.pageX - touch1.clientX;
38448 var centerPageY = centerClientY + touch1.pageY - touch1.clientY;
38449 var centerScreenX = centerClientX + touch1.screenX - touch1.clientX;
38450 var centerScreenY = centerClientY + touch1.screenY - touch1.clientY;
38451 var distanceX = Math.abs(touch1.clientX - touch2.clientX);
38452 var distanceY = Math.abs(touch1.clientY - touch2.clientY);
38453 var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
38454 var distanceChange = distance - previous.distance;
38455 var changeX = distanceX - previous.distanceX;
38456 var changeY = distanceY - previous.distanceY;
38460 clientX: centerClientX,
38461 clientY: centerClientY,
38462 distance: distance,
38463 distanceChange: distanceChange,
38464 distanceX: distanceX,
38465 distanceY: distanceY,
38467 pageX: centerPageX,
38468 pageY: centerPageY,
38469 screenX: centerScreenX,
38470 screenY: centerScreenY,
38477 .subscribe(this._pinchOperation$);
38478 this._pinchChange$ = this._pinchStart$
38479 .switchMap(function (te) {
38480 return _this._pinch$
38482 .takeUntil(_this._pinchEnd$);
38485 Object.defineProperty(TouchService.prototype, "active$", {
38487 return this._active$;
38492 Object.defineProperty(TouchService.prototype, "activate$", {
38494 return this._activeSubject$;
38499 Object.defineProperty(TouchService.prototype, "doubleTap$", {
38501 return this._doubleTap$;
38506 Object.defineProperty(TouchService.prototype, "touchStart$", {
38508 return this._touchStart$;
38513 Object.defineProperty(TouchService.prototype, "touchMove$", {
38515 return this._touchMove$;
38520 Object.defineProperty(TouchService.prototype, "touchEnd$", {
38522 return this._touchEnd$;
38527 Object.defineProperty(TouchService.prototype, "touchCancel$", {
38529 return this._touchCancel$;
38534 Object.defineProperty(TouchService.prototype, "singleTouchDragStart$", {
38536 return this._singleTouchDragStart$;
38541 Object.defineProperty(TouchService.prototype, "singleTouchDrag$", {
38543 return this._singleTouchDrag$;
38548 Object.defineProperty(TouchService.prototype, "singleTouchDragEnd$", {
38550 return this._singleTouchDragEnd$;
38555 Object.defineProperty(TouchService.prototype, "pinch$", {
38557 return this._pinchChange$;
38562 Object.defineProperty(TouchService.prototype, "pinchStart$", {
38564 return this._pinchStart$;
38569 Object.defineProperty(TouchService.prototype, "pinchEnd$", {
38571 return this._pinchEnd$;
38576 return TouchService;
38578 exports.TouchService = TouchService;
38580 },{"rxjs/BehaviorSubject":25,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/timer":46,"rxjs/add/operator/bufferWhen":50,"rxjs/add/operator/filter":60,"rxjs/add/operator/map":64,"rxjs/add/operator/merge":65,"rxjs/add/operator/scan":72,"rxjs/add/operator/switchMap":78}],351:[function(require,module,exports){
38581 /// <reference path="../../typings/index.d.ts" />
38583 var __extends = (this && this.__extends) || function (d, b) {
38584 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
38585 function __() { this.constructor = d; }
38586 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
38588 var when = require("when");
38589 var Viewer_1 = require("../Viewer");
38590 var Utils_1 = require("../Utils");
38594 * @classdesc The Viewer object represents the navigable photo viewer.
38595 * Create a Viewer by specifying a container, client ID, photo key and
38596 * other options. The viewer exposes methods and events for programmatic
38599 var Viewer = (function (_super) {
38600 __extends(Viewer, _super);
38602 * Create a new viewer instance.
38604 * @param {string} id - Required `id` of a DOM element which will
38605 * be transformed into the viewer.
38606 * @param {string} clientId - Required `Mapillary API ClientID`. Can
38607 * be obtained from https://www.mapillary.com/app/settings/developers.
38608 * @param {string} [key] - Optional `photoId` to start from, can be any
38609 * Mapillary photo, if null no image is loaded.
38610 * @param {IViewerOptions} [options] - Optional configuration object
38611 * specifing Viewer's initial setup.
38612 * @param {string} [token] - Optional bearer token for API requests of
38613 * protected resources.
38617 * var viewer = new Viewer("<element-id>", "<client-id>", "<my key>");
38620 function Viewer(id, clientId, key, options, token) {
38621 var _this = _super.call(this) || this;
38622 options = options != null ? options : {};
38623 Utils_1.Settings.setOptions(options);
38624 _this._navigator = new Viewer_1.Navigator(clientId, token);
38625 _this._container = new Viewer_1.Container(id, _this._navigator.stateService, options);
38626 _this._observer = new Viewer_1.Observer(_this, _this._navigator, _this._container);
38627 _this._componentController = new Viewer_1.ComponentController(_this._container, _this._navigator, _this._observer, key, options.component);
38631 * Activate a component.
38633 * @param {string} name - Name of the component which will become active.
38637 * viewer.activateComponent("mouse");
38640 Viewer.prototype.activateComponent = function (name) {
38641 this._componentController.activate(name);
38644 * Activate the cover (deactivates all other components).
38646 Viewer.prototype.activateCover = function () {
38647 this._componentController.activateCover();
38650 * Deactivate a component.
38652 * @param {string} name - Name of component which become inactive.
38656 * viewer.deactivateComponent("mouse");
38659 Viewer.prototype.deactivateComponent = function (name) {
38660 this._componentController.deactivate(name);
38663 * Deactivate the cover (activates all components marked as active).
38665 Viewer.prototype.deactivateCover = function () {
38666 this._componentController.deactivateCover();
38669 * Get the bearing of the current viewer camera.
38671 * @description The bearing depends on how the camera
38672 * is currently rotated and does not correspond
38673 * to the compass angle of the current node if the view
38676 * Bearing is measured in degrees clockwise with respect to
38679 * @returns {Promise<number>} Promise to the bearing
38680 * of the current viewer camera.
38684 * viewer.getBearing().then((b) => { console.log(b); });
38687 Viewer.prototype.getBearing = function () {
38689 return when.promise(function (resolve, reject) {
38690 _this._container.renderService.bearing$
38692 .subscribe(function (bearing) {
38694 }, function (error) {
38700 * Get the basic coordinates of the current photo that is
38701 * at the center of the viewport.
38703 * @description Basic coordinates are 2D coordinates on the [0, 1] interval
38704 * and have the origin point, (0, 0), at the top left corner and the
38705 * maximum value, (1, 1), at the bottom right corner of the original
38708 * @returns {Promise<number[]>} Promise to the basic coordinates
38709 * of the current photo at the center for the viewport.
38713 * viewer.getCenter().then((c) => { console.log(c); });
38716 Viewer.prototype.getCenter = function () {
38718 return when.promise(function (resolve, reject) {
38719 _this._navigator.stateService.getCenter()
38720 .subscribe(function (center) {
38722 }, function (error) {
38730 * @param {string} name - Name of component.
38731 * @returns {Component} The requested component.
38735 * var mouseComponent = viewer.getComponent("mouse");
38738 Viewer.prototype.getComponent = function (name) {
38739 return this._componentController.get(name);
38742 * Get the photo's current zoom level.
38744 * @returns {Promise<number>} Promise to the viewers's current
38749 * viewer.getZoom().then((z) => { console.log(z); });
38752 Viewer.prototype.getZoom = function () {
38754 return when.promise(function (resolve, reject) {
38755 _this._navigator.stateService.getZoom()
38756 .subscribe(function (zoom) {
38758 }, function (error) {
38764 * Move close to given latitude and longitude.
38766 * @description Because the method propagates IO errors, these potential errors
38767 * need to be handled by the method caller (see example).
38769 * @param {Number} lat - Latitude, in degrees.
38770 * @param {Number} lon - Longitude, in degrees.
38771 * @returns {Promise<Node>} Promise to the node that was navigated to.
38772 * @throws {Error} If no nodes exist close to provided latitude
38774 * @throws {Error} Propagates any IO errors to the caller.
38778 * viewer.moveCloseTo(0, 0).then(
38779 * (n) => { console.log(n); },
38780 * (e) => { console.error(e); });
38783 Viewer.prototype.moveCloseTo = function (lat, lon) {
38785 return when.promise(function (resolve, reject) {
38786 _this._navigator.moveCloseTo$(lat, lon).subscribe(function (node) {
38788 }, function (error) {
38794 * Navigate in a given direction.
38796 * @description This method has to be called through EdgeDirection enumeration as in the example.
38798 * @param {EdgeDirection} dir - Direction in which which to move.
38799 * @returns {Promise<Node>} Promise to the node that was navigated to.
38800 * @throws {Error} If the current node does not have the edge direction
38801 * or the edges has not yet been cached.
38802 * @throws {Error} Propagates any IO errors to the caller.
38806 * viewer.moveDir(Mapillary.EdgeDirection.Next).then(
38807 * (n) => { console.log(n); },
38808 * (e) => { console.error(e); });
38811 Viewer.prototype.moveDir = function (dir) {
38813 return when.promise(function (resolve, reject) {
38814 _this._navigator.moveDir$(dir).subscribe(function (node) {
38816 }, function (error) {
38822 * Navigate to a given photo key.
38824 * @param {string} key - A valid Mapillary photo key.
38825 * @returns {Promise<Node>} Promise to the node that was navigated to.
38826 * @throws {Error} Propagates any IO errors to the caller.
38830 * viewer.moveToKey("<my key>").then(
38831 * (n) => { console.log(n); },
38832 * (e) => { console.error(e); });
38835 Viewer.prototype.moveToKey = function (key) {
38837 return when.promise(function (resolve, reject) {
38838 _this._navigator.moveToKey$(key).subscribe(function (node) {
38840 }, function (error) {
38846 * Detect the viewer's new width and height and resize it.
38848 * @description The components will also detect the viewer's
38849 * new size and resize their rendered elements if needed.
38856 Viewer.prototype.resize = function () {
38857 this._container.renderService.resize$.next(null);
38858 this._componentController.resize();
38861 * Set a bearer token for authenticated API requests of
38862 * protected resources.
38864 * @description When the supplied token is null or undefined,
38865 * any previously set bearer token will be cleared and the
38866 * viewer will make unauthenticated requests.
38868 * Calling setAuthToken aborts all outstanding move requests.
38869 * The promises of those move requests will be rejected and
38870 * the rejections need to be caught.
38872 * @param {string} [token] token - Bearer token.
38873 * @returns {Promise<void>} Promise that resolves after token
38878 * viewer.setAuthToken("<my token>")
38879 * .then(() => { console.log("token set"); });
38882 Viewer.prototype.setAuthToken = function (token) {
38884 return when.promise(function (resolve, reject) {
38885 _this._navigator.setToken$(token)
38886 .subscribe(function () {
38887 resolve(undefined);
38888 }, function (error) {
38894 * Set the basic coordinates of the current photo to be in the
38895 * center of the viewport.
38897 * @description Basic coordinates are 2D coordinates on the [0, 1] interval
38898 * and has the origin point, (0, 0), at the top left corner and the
38899 * maximum value, (1, 1), at the bottom right corner of the original
38902 * @param {number[]} The basic coordinates of the current
38903 * photo to be at the center for the viewport.
38907 * viewer.setCenter([0.5, 0.5]);
38910 Viewer.prototype.setCenter = function (center) {
38911 this._navigator.stateService.setCenter(center);
38914 * Set the filter selecting nodes to use when calculating
38915 * the spatial edges.
38917 * @description The following filter types are supported:
38921 * `["==", key, value]` equality: `node[key] = value`
38923 * `["!=", key, value]` inequality: `node[key] ≠ value`
38925 * `["<", key, value]` less than: `node[key] < value`
38927 * `["<=", key, value]` less than or equal: `node[key] ≤ value`
38929 * `[">", key, value]` greater than: `node[key] > value`
38931 * `[">=", key, value]` greater than or equal: `node[key] ≥ value`
38935 * `["in", key, v0, ..., vn]` set inclusion: `node[key] ∈ {v0, ..., vn}`
38937 * `["!in", key, v0, ..., vn]` set exclusion: `node[key] ∉ {v0, ..., vn}`
38941 * `["all", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`
38943 * A key must be a string that identifies a node property name. A value must be
38944 * a string, number, or boolean. Strictly-typed comparisons are used. The values
38945 * `f0, ..., fn` of the combining filter must be filter expressions.
38947 * Clear the filter by setting it to null or empty array.
38949 * @param {FilterExpression} filter - The filter expression.
38950 * @returns {Promise<void>} Promise that resolves after filter is applied.
38954 * viewer.setFilter(["==", "sequenceKey", "<my sequence key>"]);
38957 Viewer.prototype.setFilter = function (filter) {
38959 return when.promise(function (resolve, reject) {
38960 _this._navigator.setFilter$(filter)
38961 .subscribe(function () {
38962 resolve(undefined);
38963 }, function (error) {
38969 * Set the viewer's render mode.
38971 * @param {RenderMode} renderMode - Render mode.
38975 * viewer.setRenderMode(Mapillary.RenderMode.Letterbox);
38978 Viewer.prototype.setRenderMode = function (renderMode) {
38979 this._container.renderService.renderMode$.next(renderMode);
38982 * Set the photo's current zoom level.
38984 * @description Possible zoom level values are on the [0, 3] interval.
38985 * Zero means zooming out to fit the photo to the view whereas three
38986 * shows the highest level of detail.
38988 * @param {number} The photo's current zoom level.
38992 * viewer.setZoom(2);
38995 Viewer.prototype.setZoom = function (zoom) {
38996 this._navigator.stateService.setZoom(zoom);
39000 * Returns an ILatLon representing geographical coordinates that correspond
39001 * to the specified pixel coordinates.
39003 * @description The pixel point may not always correspond to geographical
39004 * coordinates. In the case of no correspondence the returned value will
39007 * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
39008 * @returns {Promise<ILatLon>} Promise to the latLon corresponding to the pixel point.
39012 * viewer.unproject([100, 100])
39013 * .then((latLon) => { console.log(latLon); });
39016 Viewer.prototype.unproject = function (pixelPoint) {
39018 return when.promise(function (resolve, reject) {
39019 _this._observer.unproject$(pixelPoint)
39020 .subscribe(function (latLon) {
39022 }, function (error) {
39028 }(Utils_1.EventEmitter));
39030 * Fired when the viewing direction of the camera changes.
39032 * @type {number} bearing - Value indicating the current bearing
39033 * measured in degrees clockwise with respect to north.
39035 Viewer.bearingchanged = "bearingchanged";
39037 * Fired when a pointing device (usually a mouse) is pressed and released at
39038 * the same point in the viewer.
39040 * @type {IViewerMouseEvent} event - Viewer mouse event data.
39042 Viewer.click = "click";
39044 * Fired when the right button of the mouse is clicked within the viewer.
39046 * @type {IViewerMouseEvent} event - Viewer mouse event data.
39048 Viewer.contextmenu = "contextmenu";
39050 * Fired when a pointing device (usually a mouse) is clicked twice at
39051 * the same point in the viewer.
39053 * @type {IViewerMouseEvent} event - Viewer mouse event data.
39055 Viewer.dblclick = "dblclick";
39057 * Fired when the viewer is loading more data.
39059 * @type {boolean} loading - Value indicating whether the viewer is loading.
39061 Viewer.loadingchanged = "loadingchanged";
39063 * Fired when a pointing device (usually a mouse) is pressed within the viewer.
39065 * @type {IViewerMouseEvent} event - Viewer mouse event data.
39067 Viewer.mousedown = "mousedown";
39069 * Fired when a pointing device (usually a mouse) is moved within the viewer.
39070 * @description Will not fire when the mouse is actively used, e.g. for drag pan.
39072 * @type {IViewerMouseEvent} event - Viewer mouse event data.
39074 Viewer.mousemove = "mousemove";
39076 * Fired when a pointing device (usually a mouse) leaves the viewer's canvas.
39078 * @type {IViewerMouseEvent} event - Viewer mouse event data.
39080 Viewer.mouseout = "mouseout";
39082 * Fired when a pointing device (usually a mouse) is moved onto the viewer's canvas.
39084 * @type {IViewerMouseEvent} event - Viewer mouse event data.
39086 Viewer.mouseover = "mouseover";
39088 * Fired when a pointing device (usually a mouse) is released within the viewer.
39090 * @type {IViewerMouseEvent} event - Viewer mouse event data.
39092 Viewer.mouseup = "mouseup";
39094 * Fired when the viewer motion stops and it is in a fixed
39095 * position with a fixed point of view.
39098 Viewer.moveend = "moveend";
39100 * Fired when the motion from one view to another start,
39101 * either by changing the position (e.g. when changing node) or
39102 * when changing point of view (e.g. by interaction such as pan and zoom).
39105 Viewer.movestart = "movestart";
39107 * Fired every time the viewer navigates to a new node.
39109 * @type {Node} node - Current node.
39111 Viewer.nodechanged = "nodechanged";
39113 * Fired every time the sequence edges of the current node changes.
39115 * @type {IEdgeStatus} status - The edge status object.
39117 Viewer.sequenceedgeschanged = "sequenceedgeschanged";
39119 * Fired every time the spatial edges of the current node changes.
39121 * @type {IEdgeStatus} status - The edge status object.
39123 Viewer.spatialedgeschanged = "spatialedgeschanged";
39124 exports.Viewer = Viewer;
39126 },{"../Utils":234,"../Viewer":235,"when":222}]},{},[230])(230)
39128 //# sourceMappingURL=mapillary.js.map