]> git.openstreetmap.org Git - rails.git/blob - vendor/assets/iD/iD/mapillary-js/mapillary.js
92d68058809bfde9b0463b4825e68c39ae02cd47
[rails.git] / vendor / assets / iD / iD / mapillary-js / mapillary.js
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){
2 'use strict'
3
4 exports.byteLength = byteLength
5 exports.toByteArray = toByteArray
6 exports.fromByteArray = fromByteArray
7
8 var lookup = []
9 var revLookup = []
10 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
11
12 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
13 for (var i = 0, len = code.length; i < len; ++i) {
14   lookup[i] = code[i]
15   revLookup[code.charCodeAt(i)] = i
16 }
17
18 revLookup['-'.charCodeAt(0)] = 62
19 revLookup['_'.charCodeAt(0)] = 63
20
21 function placeHoldersCount (b64) {
22   var len = b64.length
23   if (len % 4 > 0) {
24     throw new Error('Invalid string. Length must be a multiple of 4')
25   }
26
27   // the number of equal signs (place holders)
28   // if there are two placeholders, than the two characters before it
29   // represent one byte
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
33 }
34
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)
38 }
39
40 function toByteArray (b64) {
41   var i, j, l, tmp, placeHolders, arr
42   var len = b64.length
43   placeHolders = placeHoldersCount(b64)
44
45   arr = new Arr(len * 3 / 4 - placeHolders)
46
47   // if there are placeholders, only get up to the last complete 4 chars
48   l = placeHolders > 0 ? len - 4 : len
49
50   var L = 0
51
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
56     arr[L++] = tmp & 0xFF
57   }
58
59   if (placeHolders === 2) {
60     tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
61     arr[L++] = tmp & 0xFF
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
65     arr[L++] = tmp & 0xFF
66   }
67
68   return arr
69 }
70
71 function tripletToBase64 (num) {
72   return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
73 }
74
75 function encodeChunk (uint8, start, end) {
76   var tmp
77   var output = []
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))
81   }
82   return output.join('')
83 }
84
85 function fromByteArray (uint8) {
86   var tmp
87   var len = uint8.length
88   var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
89   var output = ''
90   var parts = []
91   var maxChunkLength = 16383 // must be multiple of 3
92
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)))
96   }
97
98   // pad the end with zeros, but make sure to not forget the extra bytes
99   if (extraBytes === 1) {
100     tmp = uint8[len - 1]
101     output += lookup[tmp >> 2]
102     output += lookup[(tmp << 4) & 0x3F]
103     output += '=='
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]
109     output += '='
110   }
111
112   parts.push(output)
113
114   return parts.join('')
115 }
116
117 },{}],2:[function(require,module,exports){
118
119 },{}],3:[function(require,module,exports){
120 /*!
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
125  */
126
127 /**
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
132  * cross-browser.
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.
137  * @example
138  *
139  * // Basic use
140  * split('a b c d', ' ');
141  * // -> ['a', 'b', 'c', 'd']
142  *
143  * // With limit
144  * split('a b c d', ' ', 2);
145  * // -> ['a', 'b']
146  *
147  * // Backreferences in result array
148  * split('..word1 word2..', /([a-z]+)(\d+)/i);
149  * // -> ['..', 'word', '1', ' ', 'word', '2', '..']
150  */
151 module.exports = (function split(undef) {
152
153   var nativeSplit = String.prototype.split,
154     compliantExecNpcg = /()??/.exec("")[1] === undef,
155     // NPCG: nonparticipating capturing group
156     self;
157
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);
162     }
163     var output = [],
164       flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6
165       (separator.sticky ? "y" : ""),
166       // Firefox 3+
167       lastLastIndex = 0,
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);
175     }
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
182      */
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) {
196                 match[i] = undef;
197               }
198             }
199           });
200         }
201         if (match.length > 1 && match.index < str.length) {
202           Array.prototype.push.apply(output, match.slice(1));
203         }
204         lastLength = match[0].length;
205         lastLastIndex = lastIndex;
206         if (output.length >= limit) {
207           break;
208         }
209       }
210       if (separator.lastIndex === match.index) {
211         separator.lastIndex++; // Avoid an infinite loop
212       }
213     }
214     if (lastLastIndex === str.length) {
215       if (lastLength || !separator.test("")) {
216         output.push("");
217       }
218     } else {
219       output.push(str.slice(lastLastIndex));
220     }
221     return output.length > limit ? output.slice(0, limit) : output;
222   };
223
224   return self;
225 })();
226
227 },{}],4:[function(require,module,exports){
228 // shim for using process in browser
229 var process = module.exports = {};
230
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.
235
236 var cachedSetTimeout;
237 var cachedClearTimeout;
238
239 function defaultSetTimout() {
240     throw new Error('setTimeout has not been defined');
241 }
242 function defaultClearTimeout () {
243     throw new Error('clearTimeout has not been defined');
244 }
245 (function () {
246     try {
247         if (typeof setTimeout === 'function') {
248             cachedSetTimeout = setTimeout;
249         } else {
250             cachedSetTimeout = defaultSetTimout;
251         }
252     } catch (e) {
253         cachedSetTimeout = defaultSetTimout;
254     }
255     try {
256         if (typeof clearTimeout === 'function') {
257             cachedClearTimeout = clearTimeout;
258         } else {
259             cachedClearTimeout = defaultClearTimeout;
260         }
261     } catch (e) {
262         cachedClearTimeout = defaultClearTimeout;
263     }
264 } ())
265 function runTimeout(fun) {
266     if (cachedSetTimeout === setTimeout) {
267         //normal enviroments in sane situations
268         return setTimeout(fun, 0);
269     }
270     // if setTimeout wasn't available but was latter defined
271     if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
272         cachedSetTimeout = setTimeout;
273         return setTimeout(fun, 0);
274     }
275     try {
276         // when when somebody has screwed with setTimeout but no I.E. maddness
277         return cachedSetTimeout(fun, 0);
278     } catch(e){
279         try {
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);
282         } catch(e){
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);
285         }
286     }
287
288
289 }
290 function runClearTimeout(marker) {
291     if (cachedClearTimeout === clearTimeout) {
292         //normal enviroments in sane situations
293         return clearTimeout(marker);
294     }
295     // if clearTimeout wasn't available but was latter defined
296     if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
297         cachedClearTimeout = clearTimeout;
298         return clearTimeout(marker);
299     }
300     try {
301         // when when somebody has screwed with setTimeout but no I.E. maddness
302         return cachedClearTimeout(marker);
303     } catch (e){
304         try {
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);
307         } catch (e){
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);
311         }
312     }
313
314
315
316 }
317 var queue = [];
318 var draining = false;
319 var currentQueue;
320 var queueIndex = -1;
321
322 function cleanUpNextTick() {
323     if (!draining || !currentQueue) {
324         return;
325     }
326     draining = false;
327     if (currentQueue.length) {
328         queue = currentQueue.concat(queue);
329     } else {
330         queueIndex = -1;
331     }
332     if (queue.length) {
333         drainQueue();
334     }
335 }
336
337 function drainQueue() {
338     if (draining) {
339         return;
340     }
341     var timeout = runTimeout(cleanUpNextTick);
342     draining = true;
343
344     var len = queue.length;
345     while(len) {
346         currentQueue = queue;
347         queue = [];
348         while (++queueIndex < len) {
349             if (currentQueue) {
350                 currentQueue[queueIndex].run();
351             }
352         }
353         queueIndex = -1;
354         len = queue.length;
355     }
356     currentQueue = null;
357     draining = false;
358     runClearTimeout(timeout);
359 }
360
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];
366         }
367     }
368     queue.push(new Item(fun, args));
369     if (queue.length === 1 && !draining) {
370         runTimeout(drainQueue);
371     }
372 };
373
374 // v8 likes predictible objects
375 function Item(fun, array) {
376     this.fun = fun;
377     this.array = array;
378 }
379 Item.prototype.run = function () {
380     this.fun.apply(null, this.array);
381 };
382 process.title = 'browser';
383 process.browser = true;
384 process.env = {};
385 process.argv = [];
386 process.version = ''; // empty string to avoid regexp issues
387 process.versions = {};
388
389 function noop() {}
390
391 process.on = noop;
392 process.addListener = noop;
393 process.once = noop;
394 process.off = noop;
395 process.removeListener = noop;
396 process.removeAllListeners = noop;
397 process.emit = noop;
398
399 process.binding = function (name) {
400     throw new Error('process.binding is not supported');
401 };
402
403 process.cwd = function () { return '/' };
404 process.chdir = function (dir) {
405     throw new Error('process.chdir is not supported');
406 };
407 process.umask = function() { return 0; };
408
409 },{}],5:[function(require,module,exports){
410 (function (global){
411 /*!
412  * The buffer module from node.js, for the browser.
413  *
414  * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
415  * @license  MIT
416  */
417 /* eslint-disable no-proto */
418
419 'use strict'
420
421 var base64 = require('base64-js')
422 var ieee754 = require('ieee754')
423 var isArray = require('isarray')
424
425 exports.Buffer = Buffer
426 exports.SlowBuffer = SlowBuffer
427 exports.INSPECT_MAX_BYTES = 50
428
429 /**
430  * If `Buffer.TYPED_ARRAY_SUPPORT`:
431  *   === true    Use Uint8Array implementation (fastest)
432  *   === false   Use Object implementation (most compatible, even IE6)
433  *
434  * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
435  * Opera 11.6+, iOS 4.2+.
436  *
437  * Due to various browser bugs, sometimes the Object implementation will be used even
438  * when the browser supports typed arrays.
439  *
440  * Note:
441  *
442  *   - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
443  *     See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
444  *
445  *   - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
446  *
447  *   - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
448  *     incorrect length in some situations.
449
450  * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
451  * get the Object implementation, which is slower but behaves correctly.
452  */
453 Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
454   ? global.TYPED_ARRAY_SUPPORT
455   : typedArraySupport()
456
457 /*
458  * Export kMaxLength after typed array support is determined.
459  */
460 exports.kMaxLength = kMaxLength()
461
462 function typedArraySupport () {
463   try {
464     var arr = new Uint8Array(1)
465     arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
466     return arr.foo() === 42 && // typed array instances can be augmented
467         typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
468         arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
469   } catch (e) {
470     return false
471   }
472 }
473
474 function kMaxLength () {
475   return Buffer.TYPED_ARRAY_SUPPORT
476     ? 0x7fffffff
477     : 0x3fffffff
478 }
479
480 function createBuffer (that, length) {
481   if (kMaxLength() < length) {
482     throw new RangeError('Invalid typed array length')
483   }
484   if (Buffer.TYPED_ARRAY_SUPPORT) {
485     // Return an augmented `Uint8Array` instance, for best performance
486     that = new Uint8Array(length)
487     that.__proto__ = Buffer.prototype
488   } else {
489     // Fallback: Return an object instance of the Buffer class
490     if (that === null) {
491       that = new Buffer(length)
492     }
493     that.length = length
494   }
495
496   return that
497 }
498
499 /**
500  * The Buffer constructor returns instances of `Uint8Array` that have their
501  * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
502  * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
503  * and the `Uint8Array` methods. Square bracket notation works as expected -- it
504  * returns a single octet.
505  *
506  * The `Uint8Array` prototype remains unmodified.
507  */
508
509 function Buffer (arg, encodingOrOffset, length) {
510   if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
511     return new Buffer(arg, encodingOrOffset, length)
512   }
513
514   // Common case.
515   if (typeof arg === 'number') {
516     if (typeof encodingOrOffset === 'string') {
517       throw new Error(
518         'If encoding is specified then the first argument must be a string'
519       )
520     }
521     return allocUnsafe(this, arg)
522   }
523   return from(this, arg, encodingOrOffset, length)
524 }
525
526 Buffer.poolSize = 8192 // not used by this implementation
527
528 // TODO: Legacy, not needed anymore. Remove in next major version.
529 Buffer._augment = function (arr) {
530   arr.__proto__ = Buffer.prototype
531   return arr
532 }
533
534 function from (that, value, encodingOrOffset, length) {
535   if (typeof value === 'number') {
536     throw new TypeError('"value" argument must not be a number')
537   }
538
539   if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
540     return fromArrayBuffer(that, value, encodingOrOffset, length)
541   }
542
543   if (typeof value === 'string') {
544     return fromString(that, value, encodingOrOffset)
545   }
546
547   return fromObject(that, value)
548 }
549
550 /**
551  * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
552  * if value is a number.
553  * Buffer.from(str[, encoding])
554  * Buffer.from(array)
555  * Buffer.from(buffer)
556  * Buffer.from(arrayBuffer[, byteOffset[, length]])
557  **/
558 Buffer.from = function (value, encodingOrOffset, length) {
559   return from(null, value, encodingOrOffset, length)
560 }
561
562 if (Buffer.TYPED_ARRAY_SUPPORT) {
563   Buffer.prototype.__proto__ = Uint8Array.prototype
564   Buffer.__proto__ = Uint8Array
565   if (typeof Symbol !== 'undefined' && Symbol.species &&
566       Buffer[Symbol.species] === Buffer) {
567     // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
568     Object.defineProperty(Buffer, Symbol.species, {
569       value: null,
570       configurable: true
571     })
572   }
573 }
574
575 function assertSize (size) {
576   if (typeof size !== 'number') {
577     throw new TypeError('"size" argument must be a number')
578   } else if (size < 0) {
579     throw new RangeError('"size" argument must not be negative')
580   }
581 }
582
583 function alloc (that, size, fill, encoding) {
584   assertSize(size)
585   if (size <= 0) {
586     return createBuffer(that, size)
587   }
588   if (fill !== undefined) {
589     // Only pay attention to encoding if it's a string. This
590     // prevents accidentally sending in a number that would
591     // be interpretted as a start offset.
592     return typeof encoding === 'string'
593       ? createBuffer(that, size).fill(fill, encoding)
594       : createBuffer(that, size).fill(fill)
595   }
596   return createBuffer(that, size)
597 }
598
599 /**
600  * Creates a new filled Buffer instance.
601  * alloc(size[, fill[, encoding]])
602  **/
603 Buffer.alloc = function (size, fill, encoding) {
604   return alloc(null, size, fill, encoding)
605 }
606
607 function allocUnsafe (that, size) {
608   assertSize(size)
609   that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
610   if (!Buffer.TYPED_ARRAY_SUPPORT) {
611     for (var i = 0; i < size; ++i) {
612       that[i] = 0
613     }
614   }
615   return that
616 }
617
618 /**
619  * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
620  * */
621 Buffer.allocUnsafe = function (size) {
622   return allocUnsafe(null, size)
623 }
624 /**
625  * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
626  */
627 Buffer.allocUnsafeSlow = function (size) {
628   return allocUnsafe(null, size)
629 }
630
631 function fromString (that, string, encoding) {
632   if (typeof encoding !== 'string' || encoding === '') {
633     encoding = 'utf8'
634   }
635
636   if (!Buffer.isEncoding(encoding)) {
637     throw new TypeError('"encoding" must be a valid string encoding')
638   }
639
640   var length = byteLength(string, encoding) | 0
641   that = createBuffer(that, length)
642
643   var actual = that.write(string, encoding)
644
645   if (actual !== length) {
646     // Writing a hex string, for example, that contains invalid characters will
647     // cause everything after the first invalid character to be ignored. (e.g.
648     // 'abxxcd' will be treated as 'ab')
649     that = that.slice(0, actual)
650   }
651
652   return that
653 }
654
655 function fromArrayLike (that, array) {
656   var length = array.length < 0 ? 0 : checked(array.length) | 0
657   that = createBuffer(that, length)
658   for (var i = 0; i < length; i += 1) {
659     that[i] = array[i] & 255
660   }
661   return that
662 }
663
664 function fromArrayBuffer (that, array, byteOffset, length) {
665   array.byteLength // this throws if `array` is not a valid ArrayBuffer
666
667   if (byteOffset < 0 || array.byteLength < byteOffset) {
668     throw new RangeError('\'offset\' is out of bounds')
669   }
670
671   if (array.byteLength < byteOffset + (length || 0)) {
672     throw new RangeError('\'length\' is out of bounds')
673   }
674
675   if (byteOffset === undefined && length === undefined) {
676     array = new Uint8Array(array)
677   } else if (length === undefined) {
678     array = new Uint8Array(array, byteOffset)
679   } else {
680     array = new Uint8Array(array, byteOffset, length)
681   }
682
683   if (Buffer.TYPED_ARRAY_SUPPORT) {
684     // Return an augmented `Uint8Array` instance, for best performance
685     that = array
686     that.__proto__ = Buffer.prototype
687   } else {
688     // Fallback: Return an object instance of the Buffer class
689     that = fromArrayLike(that, array)
690   }
691   return that
692 }
693
694 function fromObject (that, obj) {
695   if (Buffer.isBuffer(obj)) {
696     var len = checked(obj.length) | 0
697     that = createBuffer(that, len)
698
699     if (that.length === 0) {
700       return that
701     }
702
703     obj.copy(that, 0, 0, len)
704     return that
705   }
706
707   if (obj) {
708     if ((typeof ArrayBuffer !== 'undefined' &&
709         obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
710       if (typeof obj.length !== 'number' || isnan(obj.length)) {
711         return createBuffer(that, 0)
712       }
713       return fromArrayLike(that, obj)
714     }
715
716     if (obj.type === 'Buffer' && isArray(obj.data)) {
717       return fromArrayLike(that, obj.data)
718     }
719   }
720
721   throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
722 }
723
724 function checked (length) {
725   // Note: cannot use `length < kMaxLength()` here because that fails when
726   // length is NaN (which is otherwise coerced to zero.)
727   if (length >= kMaxLength()) {
728     throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
729                          'size: 0x' + kMaxLength().toString(16) + ' bytes')
730   }
731   return length | 0
732 }
733
734 function SlowBuffer (length) {
735   if (+length != length) { // eslint-disable-line eqeqeq
736     length = 0
737   }
738   return Buffer.alloc(+length)
739 }
740
741 Buffer.isBuffer = function isBuffer (b) {
742   return !!(b != null && b._isBuffer)
743 }
744
745 Buffer.compare = function compare (a, b) {
746   if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
747     throw new TypeError('Arguments must be Buffers')
748   }
749
750   if (a === b) return 0
751
752   var x = a.length
753   var y = b.length
754
755   for (var i = 0, len = Math.min(x, y); i < len; ++i) {
756     if (a[i] !== b[i]) {
757       x = a[i]
758       y = b[i]
759       break
760     }
761   }
762
763   if (x < y) return -1
764   if (y < x) return 1
765   return 0
766 }
767
768 Buffer.isEncoding = function isEncoding (encoding) {
769   switch (String(encoding).toLowerCase()) {
770     case 'hex':
771     case 'utf8':
772     case 'utf-8':
773     case 'ascii':
774     case 'latin1':
775     case 'binary':
776     case 'base64':
777     case 'ucs2':
778     case 'ucs-2':
779     case 'utf16le':
780     case 'utf-16le':
781       return true
782     default:
783       return false
784   }
785 }
786
787 Buffer.concat = function concat (list, length) {
788   if (!isArray(list)) {
789     throw new TypeError('"list" argument must be an Array of Buffers')
790   }
791
792   if (list.length === 0) {
793     return Buffer.alloc(0)
794   }
795
796   var i
797   if (length === undefined) {
798     length = 0
799     for (i = 0; i < list.length; ++i) {
800       length += list[i].length
801     }
802   }
803
804   var buffer = Buffer.allocUnsafe(length)
805   var pos = 0
806   for (i = 0; i < list.length; ++i) {
807     var buf = list[i]
808     if (!Buffer.isBuffer(buf)) {
809       throw new TypeError('"list" argument must be an Array of Buffers')
810     }
811     buf.copy(buffer, pos)
812     pos += buf.length
813   }
814   return buffer
815 }
816
817 function byteLength (string, encoding) {
818   if (Buffer.isBuffer(string)) {
819     return string.length
820   }
821   if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
822       (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
823     return string.byteLength
824   }
825   if (typeof string !== 'string') {
826     string = '' + string
827   }
828
829   var len = string.length
830   if (len === 0) return 0
831
832   // Use a for loop to avoid recursion
833   var loweredCase = false
834   for (;;) {
835     switch (encoding) {
836       case 'ascii':
837       case 'latin1':
838       case 'binary':
839         return len
840       case 'utf8':
841       case 'utf-8':
842       case undefined:
843         return utf8ToBytes(string).length
844       case 'ucs2':
845       case 'ucs-2':
846       case 'utf16le':
847       case 'utf-16le':
848         return len * 2
849       case 'hex':
850         return len >>> 1
851       case 'base64':
852         return base64ToBytes(string).length
853       default:
854         if (loweredCase) return utf8ToBytes(string).length // assume utf8
855         encoding = ('' + encoding).toLowerCase()
856         loweredCase = true
857     }
858   }
859 }
860 Buffer.byteLength = byteLength
861
862 function slowToString (encoding, start, end) {
863   var loweredCase = false
864
865   // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
866   // property of a typed array.
867
868   // This behaves neither like String nor Uint8Array in that we set start/end
869   // to their upper/lower bounds if the value passed is out of range.
870   // undefined is handled specially as per ECMA-262 6th Edition,
871   // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
872   if (start === undefined || start < 0) {
873     start = 0
874   }
875   // Return early if start > this.length. Done here to prevent potential uint32
876   // coercion fail below.
877   if (start > this.length) {
878     return ''
879   }
880
881   if (end === undefined || end > this.length) {
882     end = this.length
883   }
884
885   if (end <= 0) {
886     return ''
887   }
888
889   // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
890   end >>>= 0
891   start >>>= 0
892
893   if (end <= start) {
894     return ''
895   }
896
897   if (!encoding) encoding = 'utf8'
898
899   while (true) {
900     switch (encoding) {
901       case 'hex':
902         return hexSlice(this, start, end)
903
904       case 'utf8':
905       case 'utf-8':
906         return utf8Slice(this, start, end)
907
908       case 'ascii':
909         return asciiSlice(this, start, end)
910
911       case 'latin1':
912       case 'binary':
913         return latin1Slice(this, start, end)
914
915       case 'base64':
916         return base64Slice(this, start, end)
917
918       case 'ucs2':
919       case 'ucs-2':
920       case 'utf16le':
921       case 'utf-16le':
922         return utf16leSlice(this, start, end)
923
924       default:
925         if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
926         encoding = (encoding + '').toLowerCase()
927         loweredCase = true
928     }
929   }
930 }
931
932 // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
933 // Buffer instances.
934 Buffer.prototype._isBuffer = true
935
936 function swap (b, n, m) {
937   var i = b[n]
938   b[n] = b[m]
939   b[m] = i
940 }
941
942 Buffer.prototype.swap16 = function swap16 () {
943   var len = this.length
944   if (len % 2 !== 0) {
945     throw new RangeError('Buffer size must be a multiple of 16-bits')
946   }
947   for (var i = 0; i < len; i += 2) {
948     swap(this, i, i + 1)
949   }
950   return this
951 }
952
953 Buffer.prototype.swap32 = function swap32 () {
954   var len = this.length
955   if (len % 4 !== 0) {
956     throw new RangeError('Buffer size must be a multiple of 32-bits')
957   }
958   for (var i = 0; i < len; i += 4) {
959     swap(this, i, i + 3)
960     swap(this, i + 1, i + 2)
961   }
962   return this
963 }
964
965 Buffer.prototype.swap64 = function swap64 () {
966   var len = this.length
967   if (len % 8 !== 0) {
968     throw new RangeError('Buffer size must be a multiple of 64-bits')
969   }
970   for (var i = 0; i < len; i += 8) {
971     swap(this, i, i + 7)
972     swap(this, i + 1, i + 6)
973     swap(this, i + 2, i + 5)
974     swap(this, i + 3, i + 4)
975   }
976   return this
977 }
978
979 Buffer.prototype.toString = function toString () {
980   var length = this.length | 0
981   if (length === 0) return ''
982   if (arguments.length === 0) return utf8Slice(this, 0, length)
983   return slowToString.apply(this, arguments)
984 }
985
986 Buffer.prototype.equals = function equals (b) {
987   if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
988   if (this === b) return true
989   return Buffer.compare(this, b) === 0
990 }
991
992 Buffer.prototype.inspect = function inspect () {
993   var str = ''
994   var max = exports.INSPECT_MAX_BYTES
995   if (this.length > 0) {
996     str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
997     if (this.length > max) str += ' ... '
998   }
999   return '<Buffer ' + str + '>'
1000 }
1001
1002 Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
1003   if (!Buffer.isBuffer(target)) {
1004     throw new TypeError('Argument must be a Buffer')
1005   }
1006
1007   if (start === undefined) {
1008     start = 0
1009   }
1010   if (end === undefined) {
1011     end = target ? target.length : 0
1012   }
1013   if (thisStart === undefined) {
1014     thisStart = 0
1015   }
1016   if (thisEnd === undefined) {
1017     thisEnd = this.length
1018   }
1019
1020   if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1021     throw new RangeError('out of range index')
1022   }
1023
1024   if (thisStart >= thisEnd && start >= end) {
1025     return 0
1026   }
1027   if (thisStart >= thisEnd) {
1028     return -1
1029   }
1030   if (start >= end) {
1031     return 1
1032   }
1033
1034   start >>>= 0
1035   end >>>= 0
1036   thisStart >>>= 0
1037   thisEnd >>>= 0
1038
1039   if (this === target) return 0
1040
1041   var x = thisEnd - thisStart
1042   var y = end - start
1043   var len = Math.min(x, y)
1044
1045   var thisCopy = this.slice(thisStart, thisEnd)
1046   var targetCopy = target.slice(start, end)
1047
1048   for (var i = 0; i < len; ++i) {
1049     if (thisCopy[i] !== targetCopy[i]) {
1050       x = thisCopy[i]
1051       y = targetCopy[i]
1052       break
1053     }
1054   }
1055
1056   if (x < y) return -1
1057   if (y < x) return 1
1058   return 0
1059 }
1060
1061 // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
1062 // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
1063 //
1064 // Arguments:
1065 // - buffer - a Buffer to search
1066 // - val - a string, Buffer, or number
1067 // - byteOffset - an index into `buffer`; will be clamped to an int32
1068 // - encoding - an optional encoding, relevant is val is a string
1069 // - dir - true for indexOf, false for lastIndexOf
1070 function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
1071   // Empty buffer means no match
1072   if (buffer.length === 0) return -1
1073
1074   // Normalize byteOffset
1075   if (typeof byteOffset === 'string') {
1076     encoding = byteOffset
1077     byteOffset = 0
1078   } else if (byteOffset > 0x7fffffff) {
1079     byteOffset = 0x7fffffff
1080   } else if (byteOffset < -0x80000000) {
1081     byteOffset = -0x80000000
1082   }
1083   byteOffset = +byteOffset  // Coerce to Number.
1084   if (isNaN(byteOffset)) {
1085     // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
1086     byteOffset = dir ? 0 : (buffer.length - 1)
1087   }
1088
1089   // Normalize byteOffset: negative offsets start from the end of the buffer
1090   if (byteOffset < 0) byteOffset = buffer.length + byteOffset
1091   if (byteOffset >= buffer.length) {
1092     if (dir) return -1
1093     else byteOffset = buffer.length - 1
1094   } else if (byteOffset < 0) {
1095     if (dir) byteOffset = 0
1096     else return -1
1097   }
1098
1099   // Normalize val
1100   if (typeof val === 'string') {
1101     val = Buffer.from(val, encoding)
1102   }
1103
1104   // Finally, search either indexOf (if dir is true) or lastIndexOf
1105   if (Buffer.isBuffer(val)) {
1106     // Special case: looking for empty string/buffer always fails
1107     if (val.length === 0) {
1108       return -1
1109     }
1110     return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
1111   } else if (typeof val === 'number') {
1112     val = val & 0xFF // Search for a byte value [0-255]
1113     if (Buffer.TYPED_ARRAY_SUPPORT &&
1114         typeof Uint8Array.prototype.indexOf === 'function') {
1115       if (dir) {
1116         return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1117       } else {
1118         return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1119       }
1120     }
1121     return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
1122   }
1123
1124   throw new TypeError('val must be string, number or Buffer')
1125 }
1126
1127 function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1128   var indexSize = 1
1129   var arrLength = arr.length
1130   var valLength = val.length
1131
1132   if (encoding !== undefined) {
1133     encoding = String(encoding).toLowerCase()
1134     if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1135         encoding === 'utf16le' || encoding === 'utf-16le') {
1136       if (arr.length < 2 || val.length < 2) {
1137         return -1
1138       }
1139       indexSize = 2
1140       arrLength /= 2
1141       valLength /= 2
1142       byteOffset /= 2
1143     }
1144   }
1145
1146   function read (buf, i) {
1147     if (indexSize === 1) {
1148       return buf[i]
1149     } else {
1150       return buf.readUInt16BE(i * indexSize)
1151     }
1152   }
1153
1154   var i
1155   if (dir) {
1156     var foundIndex = -1
1157     for (i = byteOffset; i < arrLength; i++) {
1158       if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1159         if (foundIndex === -1) foundIndex = i
1160         if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
1161       } else {
1162         if (foundIndex !== -1) i -= i - foundIndex
1163         foundIndex = -1
1164       }
1165     }
1166   } else {
1167     if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1168     for (i = byteOffset; i >= 0; i--) {
1169       var found = true
1170       for (var j = 0; j < valLength; j++) {
1171         if (read(arr, i + j) !== read(val, j)) {
1172           found = false
1173           break
1174         }
1175       }
1176       if (found) return i
1177     }
1178   }
1179
1180   return -1
1181 }
1182
1183 Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1184   return this.indexOf(val, byteOffset, encoding) !== -1
1185 }
1186
1187 Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1188   return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1189 }
1190
1191 Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1192   return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1193 }
1194
1195 function hexWrite (buf, string, offset, length) {
1196   offset = Number(offset) || 0
1197   var remaining = buf.length - offset
1198   if (!length) {
1199     length = remaining
1200   } else {
1201     length = Number(length)
1202     if (length > remaining) {
1203       length = remaining
1204     }
1205   }
1206
1207   // must be an even number of digits
1208   var strLen = string.length
1209   if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
1210
1211   if (length > strLen / 2) {
1212     length = strLen / 2
1213   }
1214   for (var i = 0; i < length; ++i) {
1215     var parsed = parseInt(string.substr(i * 2, 2), 16)
1216     if (isNaN(parsed)) return i
1217     buf[offset + i] = parsed
1218   }
1219   return i
1220 }
1221
1222 function utf8Write (buf, string, offset, length) {
1223   return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1224 }
1225
1226 function asciiWrite (buf, string, offset, length) {
1227   return blitBuffer(asciiToBytes(string), buf, offset, length)
1228 }
1229
1230 function latin1Write (buf, string, offset, length) {
1231   return asciiWrite(buf, string, offset, length)
1232 }
1233
1234 function base64Write (buf, string, offset, length) {
1235   return blitBuffer(base64ToBytes(string), buf, offset, length)
1236 }
1237
1238 function ucs2Write (buf, string, offset, length) {
1239   return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1240 }
1241
1242 Buffer.prototype.write = function write (string, offset, length, encoding) {
1243   // Buffer#write(string)
1244   if (offset === undefined) {
1245     encoding = 'utf8'
1246     length = this.length
1247     offset = 0
1248   // Buffer#write(string, encoding)
1249   } else if (length === undefined && typeof offset === 'string') {
1250     encoding = offset
1251     length = this.length
1252     offset = 0
1253   // Buffer#write(string, offset[, length][, encoding])
1254   } else if (isFinite(offset)) {
1255     offset = offset | 0
1256     if (isFinite(length)) {
1257       length = length | 0
1258       if (encoding === undefined) encoding = 'utf8'
1259     } else {
1260       encoding = length
1261       length = undefined
1262     }
1263   // legacy write(string, encoding, offset, length) - remove in v0.13
1264   } else {
1265     throw new Error(
1266       'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1267     )
1268   }
1269
1270   var remaining = this.length - offset
1271   if (length === undefined || length > remaining) length = remaining
1272
1273   if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1274     throw new RangeError('Attempt to write outside buffer bounds')
1275   }
1276
1277   if (!encoding) encoding = 'utf8'
1278
1279   var loweredCase = false
1280   for (;;) {
1281     switch (encoding) {
1282       case 'hex':
1283         return hexWrite(this, string, offset, length)
1284
1285       case 'utf8':
1286       case 'utf-8':
1287         return utf8Write(this, string, offset, length)
1288
1289       case 'ascii':
1290         return asciiWrite(this, string, offset, length)
1291
1292       case 'latin1':
1293       case 'binary':
1294         return latin1Write(this, string, offset, length)
1295
1296       case 'base64':
1297         // Warning: maxLength not taken into account in base64Write
1298         return base64Write(this, string, offset, length)
1299
1300       case 'ucs2':
1301       case 'ucs-2':
1302       case 'utf16le':
1303       case 'utf-16le':
1304         return ucs2Write(this, string, offset, length)
1305
1306       default:
1307         if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1308         encoding = ('' + encoding).toLowerCase()
1309         loweredCase = true
1310     }
1311   }
1312 }
1313
1314 Buffer.prototype.toJSON = function toJSON () {
1315   return {
1316     type: 'Buffer',
1317     data: Array.prototype.slice.call(this._arr || this, 0)
1318   }
1319 }
1320
1321 function base64Slice (buf, start, end) {
1322   if (start === 0 && end === buf.length) {
1323     return base64.fromByteArray(buf)
1324   } else {
1325     return base64.fromByteArray(buf.slice(start, end))
1326   }
1327 }
1328
1329 function utf8Slice (buf, start, end) {
1330   end = Math.min(buf.length, end)
1331   var res = []
1332
1333   var i = start
1334   while (i < end) {
1335     var firstByte = buf[i]
1336     var codePoint = null
1337     var bytesPerSequence = (firstByte > 0xEF) ? 4
1338       : (firstByte > 0xDF) ? 3
1339       : (firstByte > 0xBF) ? 2
1340       : 1
1341
1342     if (i + bytesPerSequence <= end) {
1343       var secondByte, thirdByte, fourthByte, tempCodePoint
1344
1345       switch (bytesPerSequence) {
1346         case 1:
1347           if (firstByte < 0x80) {
1348             codePoint = firstByte
1349           }
1350           break
1351         case 2:
1352           secondByte = buf[i + 1]
1353           if ((secondByte & 0xC0) === 0x80) {
1354             tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
1355             if (tempCodePoint > 0x7F) {
1356               codePoint = tempCodePoint
1357             }
1358           }
1359           break
1360         case 3:
1361           secondByte = buf[i + 1]
1362           thirdByte = buf[i + 2]
1363           if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1364             tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
1365             if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1366               codePoint = tempCodePoint
1367             }
1368           }
1369           break
1370         case 4:
1371           secondByte = buf[i + 1]
1372           thirdByte = buf[i + 2]
1373           fourthByte = buf[i + 3]
1374           if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1375             tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
1376             if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1377               codePoint = tempCodePoint
1378             }
1379           }
1380       }
1381     }
1382
1383     if (codePoint === null) {
1384       // we did not generate a valid codePoint so insert a
1385       // replacement char (U+FFFD) and advance only 1 byte
1386       codePoint = 0xFFFD
1387       bytesPerSequence = 1
1388     } else if (codePoint > 0xFFFF) {
1389       // encode to utf16 (surrogate pair dance)
1390       codePoint -= 0x10000
1391       res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1392       codePoint = 0xDC00 | codePoint & 0x3FF
1393     }
1394
1395     res.push(codePoint)
1396     i += bytesPerSequence
1397   }
1398
1399   return decodeCodePointsArray(res)
1400 }
1401
1402 // Based on http://stackoverflow.com/a/22747272/680742, the browser with
1403 // the lowest limit is Chrome, with 0x10000 args.
1404 // We go 1 magnitude less, for safety
1405 var MAX_ARGUMENTS_LENGTH = 0x1000
1406
1407 function decodeCodePointsArray (codePoints) {
1408   var len = codePoints.length
1409   if (len <= MAX_ARGUMENTS_LENGTH) {
1410     return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1411   }
1412
1413   // Decode in chunks to avoid "call stack size exceeded".
1414   var res = ''
1415   var i = 0
1416   while (i < len) {
1417     res += String.fromCharCode.apply(
1418       String,
1419       codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1420     )
1421   }
1422   return res
1423 }
1424
1425 function asciiSlice (buf, start, end) {
1426   var ret = ''
1427   end = Math.min(buf.length, end)
1428
1429   for (var i = start; i < end; ++i) {
1430     ret += String.fromCharCode(buf[i] & 0x7F)
1431   }
1432   return ret
1433 }
1434
1435 function latin1Slice (buf, start, end) {
1436   var ret = ''
1437   end = Math.min(buf.length, end)
1438
1439   for (var i = start; i < end; ++i) {
1440     ret += String.fromCharCode(buf[i])
1441   }
1442   return ret
1443 }
1444
1445 function hexSlice (buf, start, end) {
1446   var len = buf.length
1447
1448   if (!start || start < 0) start = 0
1449   if (!end || end < 0 || end > len) end = len
1450
1451   var out = ''
1452   for (var i = start; i < end; ++i) {
1453     out += toHex(buf[i])
1454   }
1455   return out
1456 }
1457
1458 function utf16leSlice (buf, start, end) {
1459   var bytes = buf.slice(start, end)
1460   var res = ''
1461   for (var i = 0; i < bytes.length; i += 2) {
1462     res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
1463   }
1464   return res
1465 }
1466
1467 Buffer.prototype.slice = function slice (start, end) {
1468   var len = this.length
1469   start = ~~start
1470   end = end === undefined ? len : ~~end
1471
1472   if (start < 0) {
1473     start += len
1474     if (start < 0) start = 0
1475   } else if (start > len) {
1476     start = len
1477   }
1478
1479   if (end < 0) {
1480     end += len
1481     if (end < 0) end = 0
1482   } else if (end > len) {
1483     end = len
1484   }
1485
1486   if (end < start) end = start
1487
1488   var newBuf
1489   if (Buffer.TYPED_ARRAY_SUPPORT) {
1490     newBuf = this.subarray(start, end)
1491     newBuf.__proto__ = Buffer.prototype
1492   } else {
1493     var sliceLen = end - start
1494     newBuf = new Buffer(sliceLen, undefined)
1495     for (var i = 0; i < sliceLen; ++i) {
1496       newBuf[i] = this[i + start]
1497     }
1498   }
1499
1500   return newBuf
1501 }
1502
1503 /*
1504  * Need to make sure that buffer isn't trying to write out of bounds.
1505  */
1506 function checkOffset (offset, ext, length) {
1507   if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1508   if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1509 }
1510
1511 Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1512   offset = offset | 0
1513   byteLength = byteLength | 0
1514   if (!noAssert) checkOffset(offset, byteLength, this.length)
1515
1516   var val = this[offset]
1517   var mul = 1
1518   var i = 0
1519   while (++i < byteLength && (mul *= 0x100)) {
1520     val += this[offset + i] * mul
1521   }
1522
1523   return val
1524 }
1525
1526 Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1527   offset = offset | 0
1528   byteLength = byteLength | 0
1529   if (!noAssert) {
1530     checkOffset(offset, byteLength, this.length)
1531   }
1532
1533   var val = this[offset + --byteLength]
1534   var mul = 1
1535   while (byteLength > 0 && (mul *= 0x100)) {
1536     val += this[offset + --byteLength] * mul
1537   }
1538
1539   return val
1540 }
1541
1542 Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1543   if (!noAssert) checkOffset(offset, 1, this.length)
1544   return this[offset]
1545 }
1546
1547 Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1548   if (!noAssert) checkOffset(offset, 2, this.length)
1549   return this[offset] | (this[offset + 1] << 8)
1550 }
1551
1552 Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1553   if (!noAssert) checkOffset(offset, 2, this.length)
1554   return (this[offset] << 8) | this[offset + 1]
1555 }
1556
1557 Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1558   if (!noAssert) checkOffset(offset, 4, this.length)
1559
1560   return ((this[offset]) |
1561       (this[offset + 1] << 8) |
1562       (this[offset + 2] << 16)) +
1563       (this[offset + 3] * 0x1000000)
1564 }
1565
1566 Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1567   if (!noAssert) checkOffset(offset, 4, this.length)
1568
1569   return (this[offset] * 0x1000000) +
1570     ((this[offset + 1] << 16) |
1571     (this[offset + 2] << 8) |
1572     this[offset + 3])
1573 }
1574
1575 Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1576   offset = offset | 0
1577   byteLength = byteLength | 0
1578   if (!noAssert) checkOffset(offset, byteLength, this.length)
1579
1580   var val = this[offset]
1581   var mul = 1
1582   var i = 0
1583   while (++i < byteLength && (mul *= 0x100)) {
1584     val += this[offset + i] * mul
1585   }
1586   mul *= 0x80
1587
1588   if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1589
1590   return val
1591 }
1592
1593 Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1594   offset = offset | 0
1595   byteLength = byteLength | 0
1596   if (!noAssert) checkOffset(offset, byteLength, this.length)
1597
1598   var i = byteLength
1599   var mul = 1
1600   var val = this[offset + --i]
1601   while (i > 0 && (mul *= 0x100)) {
1602     val += this[offset + --i] * mul
1603   }
1604   mul *= 0x80
1605
1606   if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1607
1608   return val
1609 }
1610
1611 Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1612   if (!noAssert) checkOffset(offset, 1, this.length)
1613   if (!(this[offset] & 0x80)) return (this[offset])
1614   return ((0xff - this[offset] + 1) * -1)
1615 }
1616
1617 Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1618   if (!noAssert) checkOffset(offset, 2, this.length)
1619   var val = this[offset] | (this[offset + 1] << 8)
1620   return (val & 0x8000) ? val | 0xFFFF0000 : val
1621 }
1622
1623 Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1624   if (!noAssert) checkOffset(offset, 2, this.length)
1625   var val = this[offset + 1] | (this[offset] << 8)
1626   return (val & 0x8000) ? val | 0xFFFF0000 : val
1627 }
1628
1629 Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1630   if (!noAssert) checkOffset(offset, 4, this.length)
1631
1632   return (this[offset]) |
1633     (this[offset + 1] << 8) |
1634     (this[offset + 2] << 16) |
1635     (this[offset + 3] << 24)
1636 }
1637
1638 Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1639   if (!noAssert) checkOffset(offset, 4, this.length)
1640
1641   return (this[offset] << 24) |
1642     (this[offset + 1] << 16) |
1643     (this[offset + 2] << 8) |
1644     (this[offset + 3])
1645 }
1646
1647 Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1648   if (!noAssert) checkOffset(offset, 4, this.length)
1649   return ieee754.read(this, offset, true, 23, 4)
1650 }
1651
1652 Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1653   if (!noAssert) checkOffset(offset, 4, this.length)
1654   return ieee754.read(this, offset, false, 23, 4)
1655 }
1656
1657 Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1658   if (!noAssert) checkOffset(offset, 8, this.length)
1659   return ieee754.read(this, offset, true, 52, 8)
1660 }
1661
1662 Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1663   if (!noAssert) checkOffset(offset, 8, this.length)
1664   return ieee754.read(this, offset, false, 52, 8)
1665 }
1666
1667 function checkInt (buf, value, offset, ext, max, min) {
1668   if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1669   if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1670   if (offset + ext > buf.length) throw new RangeError('Index out of range')
1671 }
1672
1673 Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1674   value = +value
1675   offset = offset | 0
1676   byteLength = byteLength | 0
1677   if (!noAssert) {
1678     var maxBytes = Math.pow(2, 8 * byteLength) - 1
1679     checkInt(this, value, offset, byteLength, maxBytes, 0)
1680   }
1681
1682   var mul = 1
1683   var i = 0
1684   this[offset] = value & 0xFF
1685   while (++i < byteLength && (mul *= 0x100)) {
1686     this[offset + i] = (value / mul) & 0xFF
1687   }
1688
1689   return offset + byteLength
1690 }
1691
1692 Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1693   value = +value
1694   offset = offset | 0
1695   byteLength = byteLength | 0
1696   if (!noAssert) {
1697     var maxBytes = Math.pow(2, 8 * byteLength) - 1
1698     checkInt(this, value, offset, byteLength, maxBytes, 0)
1699   }
1700
1701   var i = byteLength - 1
1702   var mul = 1
1703   this[offset + i] = value & 0xFF
1704   while (--i >= 0 && (mul *= 0x100)) {
1705     this[offset + i] = (value / mul) & 0xFF
1706   }
1707
1708   return offset + byteLength
1709 }
1710
1711 Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1712   value = +value
1713   offset = offset | 0
1714   if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1715   if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
1716   this[offset] = (value & 0xff)
1717   return offset + 1
1718 }
1719
1720 function objectWriteUInt16 (buf, value, offset, littleEndian) {
1721   if (value < 0) value = 0xffff + value + 1
1722   for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
1723     buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
1724       (littleEndian ? i : 1 - i) * 8
1725   }
1726 }
1727
1728 Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1729   value = +value
1730   offset = offset | 0
1731   if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1732   if (Buffer.TYPED_ARRAY_SUPPORT) {
1733     this[offset] = (value & 0xff)
1734     this[offset + 1] = (value >>> 8)
1735   } else {
1736     objectWriteUInt16(this, value, offset, true)
1737   }
1738   return offset + 2
1739 }
1740
1741 Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1742   value = +value
1743   offset = offset | 0
1744   if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1745   if (Buffer.TYPED_ARRAY_SUPPORT) {
1746     this[offset] = (value >>> 8)
1747     this[offset + 1] = (value & 0xff)
1748   } else {
1749     objectWriteUInt16(this, value, offset, false)
1750   }
1751   return offset + 2
1752 }
1753
1754 function objectWriteUInt32 (buf, value, offset, littleEndian) {
1755   if (value < 0) value = 0xffffffff + value + 1
1756   for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
1757     buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
1758   }
1759 }
1760
1761 Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1762   value = +value
1763   offset = offset | 0
1764   if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1765   if (Buffer.TYPED_ARRAY_SUPPORT) {
1766     this[offset + 3] = (value >>> 24)
1767     this[offset + 2] = (value >>> 16)
1768     this[offset + 1] = (value >>> 8)
1769     this[offset] = (value & 0xff)
1770   } else {
1771     objectWriteUInt32(this, value, offset, true)
1772   }
1773   return offset + 4
1774 }
1775
1776 Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1777   value = +value
1778   offset = offset | 0
1779   if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1780   if (Buffer.TYPED_ARRAY_SUPPORT) {
1781     this[offset] = (value >>> 24)
1782     this[offset + 1] = (value >>> 16)
1783     this[offset + 2] = (value >>> 8)
1784     this[offset + 3] = (value & 0xff)
1785   } else {
1786     objectWriteUInt32(this, value, offset, false)
1787   }
1788   return offset + 4
1789 }
1790
1791 Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1792   value = +value
1793   offset = offset | 0
1794   if (!noAssert) {
1795     var limit = Math.pow(2, 8 * byteLength - 1)
1796
1797     checkInt(this, value, offset, byteLength, limit - 1, -limit)
1798   }
1799
1800   var i = 0
1801   var mul = 1
1802   var sub = 0
1803   this[offset] = value & 0xFF
1804   while (++i < byteLength && (mul *= 0x100)) {
1805     if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1806       sub = 1
1807     }
1808     this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1809   }
1810
1811   return offset + byteLength
1812 }
1813
1814 Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1815   value = +value
1816   offset = offset | 0
1817   if (!noAssert) {
1818     var limit = Math.pow(2, 8 * byteLength - 1)
1819
1820     checkInt(this, value, offset, byteLength, limit - 1, -limit)
1821   }
1822
1823   var i = byteLength - 1
1824   var mul = 1
1825   var sub = 0
1826   this[offset + i] = value & 0xFF
1827   while (--i >= 0 && (mul *= 0x100)) {
1828     if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1829       sub = 1
1830     }
1831     this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1832   }
1833
1834   return offset + byteLength
1835 }
1836
1837 Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1838   value = +value
1839   offset = offset | 0
1840   if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
1841   if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
1842   if (value < 0) value = 0xff + value + 1
1843   this[offset] = (value & 0xff)
1844   return offset + 1
1845 }
1846
1847 Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1848   value = +value
1849   offset = offset | 0
1850   if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1851   if (Buffer.TYPED_ARRAY_SUPPORT) {
1852     this[offset] = (value & 0xff)
1853     this[offset + 1] = (value >>> 8)
1854   } else {
1855     objectWriteUInt16(this, value, offset, true)
1856   }
1857   return offset + 2
1858 }
1859
1860 Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1861   value = +value
1862   offset = offset | 0
1863   if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1864   if (Buffer.TYPED_ARRAY_SUPPORT) {
1865     this[offset] = (value >>> 8)
1866     this[offset + 1] = (value & 0xff)
1867   } else {
1868     objectWriteUInt16(this, value, offset, false)
1869   }
1870   return offset + 2
1871 }
1872
1873 Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1874   value = +value
1875   offset = offset | 0
1876   if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1877   if (Buffer.TYPED_ARRAY_SUPPORT) {
1878     this[offset] = (value & 0xff)
1879     this[offset + 1] = (value >>> 8)
1880     this[offset + 2] = (value >>> 16)
1881     this[offset + 3] = (value >>> 24)
1882   } else {
1883     objectWriteUInt32(this, value, offset, true)
1884   }
1885   return offset + 4
1886 }
1887
1888 Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
1889   value = +value
1890   offset = offset | 0
1891   if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1892   if (value < 0) value = 0xffffffff + value + 1
1893   if (Buffer.TYPED_ARRAY_SUPPORT) {
1894     this[offset] = (value >>> 24)
1895     this[offset + 1] = (value >>> 16)
1896     this[offset + 2] = (value >>> 8)
1897     this[offset + 3] = (value & 0xff)
1898   } else {
1899     objectWriteUInt32(this, value, offset, false)
1900   }
1901   return offset + 4
1902 }
1903
1904 function checkIEEE754 (buf, value, offset, ext, max, min) {
1905   if (offset + ext > buf.length) throw new RangeError('Index out of range')
1906   if (offset < 0) throw new RangeError('Index out of range')
1907 }
1908
1909 function writeFloat (buf, value, offset, littleEndian, noAssert) {
1910   if (!noAssert) {
1911     checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
1912   }
1913   ieee754.write(buf, value, offset, littleEndian, 23, 4)
1914   return offset + 4
1915 }
1916
1917 Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
1918   return writeFloat(this, value, offset, true, noAssert)
1919 }
1920
1921 Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
1922   return writeFloat(this, value, offset, false, noAssert)
1923 }
1924
1925 function writeDouble (buf, value, offset, littleEndian, noAssert) {
1926   if (!noAssert) {
1927     checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
1928   }
1929   ieee754.write(buf, value, offset, littleEndian, 52, 8)
1930   return offset + 8
1931 }
1932
1933 Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
1934   return writeDouble(this, value, offset, true, noAssert)
1935 }
1936
1937 Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
1938   return writeDouble(this, value, offset, false, noAssert)
1939 }
1940
1941 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1942 Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1943   if (!start) start = 0
1944   if (!end && end !== 0) end = this.length
1945   if (targetStart >= target.length) targetStart = target.length
1946   if (!targetStart) targetStart = 0
1947   if (end > 0 && end < start) end = start
1948
1949   // Copy 0 bytes; we're done
1950   if (end === start) return 0
1951   if (target.length === 0 || this.length === 0) return 0
1952
1953   // Fatal error conditions
1954   if (targetStart < 0) {
1955     throw new RangeError('targetStart out of bounds')
1956   }
1957   if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
1958   if (end < 0) throw new RangeError('sourceEnd out of bounds')
1959
1960   // Are we oob?
1961   if (end > this.length) end = this.length
1962   if (target.length - targetStart < end - start) {
1963     end = target.length - targetStart + start
1964   }
1965
1966   var len = end - start
1967   var i
1968
1969   if (this === target && start < targetStart && targetStart < end) {
1970     // descending copy from end
1971     for (i = len - 1; i >= 0; --i) {
1972       target[i + targetStart] = this[i + start]
1973     }
1974   } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
1975     // ascending copy from start
1976     for (i = 0; i < len; ++i) {
1977       target[i + targetStart] = this[i + start]
1978     }
1979   } else {
1980     Uint8Array.prototype.set.call(
1981       target,
1982       this.subarray(start, start + len),
1983       targetStart
1984     )
1985   }
1986
1987   return len
1988 }
1989
1990 // Usage:
1991 //    buffer.fill(number[, offset[, end]])
1992 //    buffer.fill(buffer[, offset[, end]])
1993 //    buffer.fill(string[, offset[, end]][, encoding])
1994 Buffer.prototype.fill = function fill (val, start, end, encoding) {
1995   // Handle string cases:
1996   if (typeof val === 'string') {
1997     if (typeof start === 'string') {
1998       encoding = start
1999       start = 0
2000       end = this.length
2001     } else if (typeof end === 'string') {
2002       encoding = end
2003       end = this.length
2004     }
2005     if (val.length === 1) {
2006       var code = val.charCodeAt(0)
2007       if (code < 256) {
2008         val = code
2009       }
2010     }
2011     if (encoding !== undefined && typeof encoding !== 'string') {
2012       throw new TypeError('encoding must be a string')
2013     }
2014     if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2015       throw new TypeError('Unknown encoding: ' + encoding)
2016     }
2017   } else if (typeof val === 'number') {
2018     val = val & 255
2019   }
2020
2021   // Invalid ranges are not set to a default, so can range check early.
2022   if (start < 0 || this.length < start || this.length < end) {
2023     throw new RangeError('Out of range index')
2024   }
2025
2026   if (end <= start) {
2027     return this
2028   }
2029
2030   start = start >>> 0
2031   end = end === undefined ? this.length : end >>> 0
2032
2033   if (!val) val = 0
2034
2035   var i
2036   if (typeof val === 'number') {
2037     for (i = start; i < end; ++i) {
2038       this[i] = val
2039     }
2040   } else {
2041     var bytes = Buffer.isBuffer(val)
2042       ? val
2043       : utf8ToBytes(new Buffer(val, encoding).toString())
2044     var len = bytes.length
2045     for (i = 0; i < end - start; ++i) {
2046       this[i + start] = bytes[i % len]
2047     }
2048   }
2049
2050   return this
2051 }
2052
2053 // HELPER FUNCTIONS
2054 // ================
2055
2056 var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
2057
2058 function base64clean (str) {
2059   // Node strips out invalid characters like \n and \t from the string, base64-js does not
2060   str = stringtrim(str).replace(INVALID_BASE64_RE, '')
2061   // Node converts strings with length < 2 to ''
2062   if (str.length < 2) return ''
2063   // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2064   while (str.length % 4 !== 0) {
2065     str = str + '='
2066   }
2067   return str
2068 }
2069
2070 function stringtrim (str) {
2071   if (str.trim) return str.trim()
2072   return str.replace(/^\s+|\s+$/g, '')
2073 }
2074
2075 function toHex (n) {
2076   if (n < 16) return '0' + n.toString(16)
2077   return n.toString(16)
2078 }
2079
2080 function utf8ToBytes (string, units) {
2081   units = units || Infinity
2082   var codePoint
2083   var length = string.length
2084   var leadSurrogate = null
2085   var bytes = []
2086
2087   for (var i = 0; i < length; ++i) {
2088     codePoint = string.charCodeAt(i)
2089
2090     // is surrogate component
2091     if (codePoint > 0xD7FF && codePoint < 0xE000) {
2092       // last char was a lead
2093       if (!leadSurrogate) {
2094         // no lead yet
2095         if (codePoint > 0xDBFF) {
2096           // unexpected trail
2097           if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2098           continue
2099         } else if (i + 1 === length) {
2100           // unpaired lead
2101           if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2102           continue
2103         }
2104
2105         // valid lead
2106         leadSurrogate = codePoint
2107
2108         continue
2109       }
2110
2111       // 2 leads in a row
2112       if (codePoint < 0xDC00) {
2113         if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2114         leadSurrogate = codePoint
2115         continue
2116       }
2117
2118       // valid surrogate pair
2119       codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
2120     } else if (leadSurrogate) {
2121       // valid bmp char, but last char was a lead
2122       if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2123     }
2124
2125     leadSurrogate = null
2126
2127     // encode utf8
2128     if (codePoint < 0x80) {
2129       if ((units -= 1) < 0) break
2130       bytes.push(codePoint)
2131     } else if (codePoint < 0x800) {
2132       if ((units -= 2) < 0) break
2133       bytes.push(
2134         codePoint >> 0x6 | 0xC0,
2135         codePoint & 0x3F | 0x80
2136       )
2137     } else if (codePoint < 0x10000) {
2138       if ((units -= 3) < 0) break
2139       bytes.push(
2140         codePoint >> 0xC | 0xE0,
2141         codePoint >> 0x6 & 0x3F | 0x80,
2142         codePoint & 0x3F | 0x80
2143       )
2144     } else if (codePoint < 0x110000) {
2145       if ((units -= 4) < 0) break
2146       bytes.push(
2147         codePoint >> 0x12 | 0xF0,
2148         codePoint >> 0xC & 0x3F | 0x80,
2149         codePoint >> 0x6 & 0x3F | 0x80,
2150         codePoint & 0x3F | 0x80
2151       )
2152     } else {
2153       throw new Error('Invalid code point')
2154     }
2155   }
2156
2157   return bytes
2158 }
2159
2160 function asciiToBytes (str) {
2161   var byteArray = []
2162   for (var i = 0; i < str.length; ++i) {
2163     // Node's code seems to be doing this and not & 0x7F..
2164     byteArray.push(str.charCodeAt(i) & 0xFF)
2165   }
2166   return byteArray
2167 }
2168
2169 function utf16leToBytes (str, units) {
2170   var c, hi, lo
2171   var byteArray = []
2172   for (var i = 0; i < str.length; ++i) {
2173     if ((units -= 2) < 0) break
2174
2175     c = str.charCodeAt(i)
2176     hi = c >> 8
2177     lo = c % 256
2178     byteArray.push(lo)
2179     byteArray.push(hi)
2180   }
2181
2182   return byteArray
2183 }
2184
2185 function base64ToBytes (str) {
2186   return base64.toByteArray(base64clean(str))
2187 }
2188
2189 function blitBuffer (src, dst, offset, length) {
2190   for (var i = 0; i < length; ++i) {
2191     if ((i + offset >= dst.length) || (i >= src.length)) break
2192     dst[i + offset] = src[i]
2193   }
2194   return i
2195 }
2196
2197 function isnan (val) {
2198   return val !== val // eslint-disable-line no-self-compare
2199 }
2200
2201 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
2202
2203 },{"base64-js":1,"ieee754":15,"isarray":19}],6:[function(require,module,exports){
2204 'use strict';
2205
2206 module.exports = earcut;
2207
2208 function earcut(data, holeIndices, dim) {
2209
2210     dim = dim || 2;
2211
2212     var hasHoles = holeIndices && holeIndices.length,
2213         outerLen = hasHoles ? holeIndices[0] * dim : data.length,
2214         outerNode = linkedList(data, 0, outerLen, dim, true),
2215         triangles = [];
2216
2217     if (!outerNode) return triangles;
2218
2219     var minX, minY, maxX, maxY, x, y, size;
2220
2221     if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
2222
2223     // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
2224     if (data.length > 80 * dim) {
2225         minX = maxX = data[0];
2226         minY = maxY = data[1];
2227
2228         for (var i = dim; i < outerLen; i += dim) {
2229             x = data[i];
2230             y = data[i + 1];
2231             if (x < minX) minX = x;
2232             if (y < minY) minY = y;
2233             if (x > maxX) maxX = x;
2234             if (y > maxY) maxY = y;
2235         }
2236
2237         // minX, minY and size are later used to transform coords into integers for z-order calculation
2238         size = Math.max(maxX - minX, maxY - minY);
2239     }
2240
2241     earcutLinked(outerNode, triangles, dim, minX, minY, size);
2242
2243     return triangles;
2244 }
2245
2246 // create a circular doubly linked list from polygon points in the specified winding order
2247 function linkedList(data, start, end, dim, clockwise) {
2248     var i, last;
2249
2250     if (clockwise === (signedArea(data, start, end, dim) > 0)) {
2251         for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
2252     } else {
2253         for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
2254     }
2255
2256     if (last && equals(last, last.next)) {
2257         removeNode(last);
2258         last = last.next;
2259     }
2260
2261     return last;
2262 }
2263
2264 // eliminate colinear or duplicate points
2265 function filterPoints(start, end) {
2266     if (!start) return start;
2267     if (!end) end = start;
2268
2269     var p = start,
2270         again;
2271     do {
2272         again = false;
2273
2274         if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
2275             removeNode(p);
2276             p = end = p.prev;
2277             if (p === p.next) return null;
2278             again = true;
2279
2280         } else {
2281             p = p.next;
2282         }
2283     } while (again || p !== end);
2284
2285     return end;
2286 }
2287
2288 // main ear slicing loop which triangulates a polygon (given as a linked list)
2289 function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
2290     if (!ear) return;
2291
2292     // interlink polygon nodes in z-order
2293     if (!pass && size) indexCurve(ear, minX, minY, size);
2294
2295     var stop = ear,
2296         prev, next;
2297
2298     // iterate through ears, slicing them one by one
2299     while (ear.prev !== ear.next) {
2300         prev = ear.prev;
2301         next = ear.next;
2302
2303         if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
2304             // cut off the triangle
2305             triangles.push(prev.i / dim);
2306             triangles.push(ear.i / dim);
2307             triangles.push(next.i / dim);
2308
2309             removeNode(ear);
2310
2311             // skipping the next vertice leads to less sliver triangles
2312             ear = next.next;
2313             stop = next.next;
2314
2315             continue;
2316         }
2317
2318         ear = next;
2319
2320         // if we looped through the whole remaining polygon and can't find any more ears
2321         if (ear === stop) {
2322             // try filtering points and slicing again
2323             if (!pass) {
2324                 earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
2325
2326             // if this didn't work, try curing all small self-intersections locally
2327             } else if (pass === 1) {
2328                 ear = cureLocalIntersections(ear, triangles, dim);
2329                 earcutLinked(ear, triangles, dim, minX, minY, size, 2);
2330
2331             // as a last resort, try splitting the remaining polygon into two
2332             } else if (pass === 2) {
2333                 splitEarcut(ear, triangles, dim, minX, minY, size);
2334             }
2335
2336             break;
2337         }
2338     }
2339 }
2340
2341 // check whether a polygon node forms a valid ear with adjacent nodes
2342 function isEar(ear) {
2343     var a = ear.prev,
2344         b = ear,
2345         c = ear.next;
2346
2347     if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2348
2349     // now make sure we don't have other points inside the potential ear
2350     var p = ear.next.next;
2351
2352     while (p !== ear.prev) {
2353         if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2354             area(p.prev, p, p.next) >= 0) return false;
2355         p = p.next;
2356     }
2357
2358     return true;
2359 }
2360
2361 function isEarHashed(ear, minX, minY, size) {
2362     var a = ear.prev,
2363         b = ear,
2364         c = ear.next;
2365
2366     if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2367
2368     // triangle bbox; min & max are calculated like this for speed
2369     var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
2370         minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
2371         maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
2372         maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
2373
2374     // z-order range for the current triangle bbox;
2375     var minZ = zOrder(minTX, minTY, minX, minY, size),
2376         maxZ = zOrder(maxTX, maxTY, minX, minY, size);
2377
2378     // first look for points inside the triangle in increasing z-order
2379     var p = ear.nextZ;
2380
2381     while (p && p.z <= maxZ) {
2382         if (p !== ear.prev && p !== ear.next &&
2383             pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2384             area(p.prev, p, p.next) >= 0) return false;
2385         p = p.nextZ;
2386     }
2387
2388     // then look for points in decreasing z-order
2389     p = ear.prevZ;
2390
2391     while (p && p.z >= minZ) {
2392         if (p !== ear.prev && p !== ear.next &&
2393             pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2394             area(p.prev, p, p.next) >= 0) return false;
2395         p = p.prevZ;
2396     }
2397
2398     return true;
2399 }
2400
2401 // go through all polygon nodes and cure small local self-intersections
2402 function cureLocalIntersections(start, triangles, dim) {
2403     var p = start;
2404     do {
2405         var a = p.prev,
2406             b = p.next.next;
2407
2408         if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
2409
2410             triangles.push(a.i / dim);
2411             triangles.push(p.i / dim);
2412             triangles.push(b.i / dim);
2413
2414             // remove two nodes involved
2415             removeNode(p);
2416             removeNode(p.next);
2417
2418             p = start = b;
2419         }
2420         p = p.next;
2421     } while (p !== start);
2422
2423     return p;
2424 }
2425
2426 // try splitting polygon into two and triangulate them independently
2427 function splitEarcut(start, triangles, dim, minX, minY, size) {
2428     // look for a valid diagonal that divides the polygon into two
2429     var a = start;
2430     do {
2431         var b = a.next.next;
2432         while (b !== a.prev) {
2433             if (a.i !== b.i && isValidDiagonal(a, b)) {
2434                 // split the polygon in two by the diagonal
2435                 var c = splitPolygon(a, b);
2436
2437                 // filter colinear points around the cuts
2438                 a = filterPoints(a, a.next);
2439                 c = filterPoints(c, c.next);
2440
2441                 // run earcut on each half
2442                 earcutLinked(a, triangles, dim, minX, minY, size);
2443                 earcutLinked(c, triangles, dim, minX, minY, size);
2444                 return;
2445             }
2446             b = b.next;
2447         }
2448         a = a.next;
2449     } while (a !== start);
2450 }
2451
2452 // link every hole into the outer loop, producing a single-ring polygon without holes
2453 function eliminateHoles(data, holeIndices, outerNode, dim) {
2454     var queue = [],
2455         i, len, start, end, list;
2456
2457     for (i = 0, len = holeIndices.length; i < len; i++) {
2458         start = holeIndices[i] * dim;
2459         end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2460         list = linkedList(data, start, end, dim, false);
2461         if (list === list.next) list.steiner = true;
2462         queue.push(getLeftmost(list));
2463     }
2464
2465     queue.sort(compareX);
2466
2467     // process holes from left to right
2468     for (i = 0; i < queue.length; i++) {
2469         eliminateHole(queue[i], outerNode);
2470         outerNode = filterPoints(outerNode, outerNode.next);
2471     }
2472
2473     return outerNode;
2474 }
2475
2476 function compareX(a, b) {
2477     return a.x - b.x;
2478 }
2479
2480 // find a bridge between vertices that connects hole with an outer ring and and link it
2481 function eliminateHole(hole, outerNode) {
2482     outerNode = findHoleBridge(hole, outerNode);
2483     if (outerNode) {
2484         var b = splitPolygon(outerNode, hole);
2485         filterPoints(b, b.next);
2486     }
2487 }
2488
2489 // David Eberly's algorithm for finding a bridge between hole and outer polygon
2490 function findHoleBridge(hole, outerNode) {
2491     var p = outerNode,
2492         hx = hole.x,
2493         hy = hole.y,
2494         qx = -Infinity,
2495         m;
2496
2497     // find a segment intersected by a ray from the hole's leftmost point to the left;
2498     // segment's endpoint with lesser x will be potential connection point
2499     do {
2500         if (hy <= p.y && hy >= p.next.y) {
2501             var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
2502             if (x <= hx && x > qx) {
2503                 qx = x;
2504                 if (x === hx) {
2505                     if (hy === p.y) return p;
2506                     if (hy === p.next.y) return p.next;
2507                 }
2508                 m = p.x < p.next.x ? p : p.next;
2509             }
2510         }
2511         p = p.next;
2512     } while (p !== outerNode);
2513
2514     if (!m) return null;
2515
2516     if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
2517
2518     // look for points inside the triangle of hole point, segment intersection and endpoint;
2519     // if there are no points found, we have a valid connection;
2520     // otherwise choose the point of the minimum angle with the ray as connection point
2521
2522     var stop = m,
2523         mx = m.x,
2524         my = m.y,
2525         tanMin = Infinity,
2526         tan;
2527
2528     p = m.next;
2529
2530     while (p !== stop) {
2531         if (hx >= p.x && p.x >= mx &&
2532                 pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
2533
2534             tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
2535
2536             if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
2537                 m = p;
2538                 tanMin = tan;
2539             }
2540         }
2541
2542         p = p.next;
2543     }
2544
2545     return m;
2546 }
2547
2548 // interlink polygon nodes in z-order
2549 function indexCurve(start, minX, minY, size) {
2550     var p = start;
2551     do {
2552         if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size);
2553         p.prevZ = p.prev;
2554         p.nextZ = p.next;
2555         p = p.next;
2556     } while (p !== start);
2557
2558     p.prevZ.nextZ = null;
2559     p.prevZ = null;
2560
2561     sortLinked(p);
2562 }
2563
2564 // Simon Tatham's linked list merge sort algorithm
2565 // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
2566 function sortLinked(list) {
2567     var i, p, q, e, tail, numMerges, pSize, qSize,
2568         inSize = 1;
2569
2570     do {
2571         p = list;
2572         list = null;
2573         tail = null;
2574         numMerges = 0;
2575
2576         while (p) {
2577             numMerges++;
2578             q = p;
2579             pSize = 0;
2580             for (i = 0; i < inSize; i++) {
2581                 pSize++;
2582                 q = q.nextZ;
2583                 if (!q) break;
2584             }
2585
2586             qSize = inSize;
2587
2588             while (pSize > 0 || (qSize > 0 && q)) {
2589
2590                 if (pSize === 0) {
2591                     e = q;
2592                     q = q.nextZ;
2593                     qSize--;
2594                 } else if (qSize === 0 || !q) {
2595                     e = p;
2596                     p = p.nextZ;
2597                     pSize--;
2598                 } else if (p.z <= q.z) {
2599                     e = p;
2600                     p = p.nextZ;
2601                     pSize--;
2602                 } else {
2603                     e = q;
2604                     q = q.nextZ;
2605                     qSize--;
2606                 }
2607
2608                 if (tail) tail.nextZ = e;
2609                 else list = e;
2610
2611                 e.prevZ = tail;
2612                 tail = e;
2613             }
2614
2615             p = q;
2616         }
2617
2618         tail.nextZ = null;
2619         inSize *= 2;
2620
2621     } while (numMerges > 1);
2622
2623     return list;
2624 }
2625
2626 // z-order of a point given coords and size of the data bounding box
2627 function zOrder(x, y, minX, minY, size) {
2628     // coords are transformed into non-negative 15-bit integer range
2629     x = 32767 * (x - minX) / size;
2630     y = 32767 * (y - minY) / size;
2631
2632     x = (x | (x << 8)) & 0x00FF00FF;
2633     x = (x | (x << 4)) & 0x0F0F0F0F;
2634     x = (x | (x << 2)) & 0x33333333;
2635     x = (x | (x << 1)) & 0x55555555;
2636
2637     y = (y | (y << 8)) & 0x00FF00FF;
2638     y = (y | (y << 4)) & 0x0F0F0F0F;
2639     y = (y | (y << 2)) & 0x33333333;
2640     y = (y | (y << 1)) & 0x55555555;
2641
2642     return x | (y << 1);
2643 }
2644
2645 // find the leftmost node of a polygon ring
2646 function getLeftmost(start) {
2647     var p = start,
2648         leftmost = start;
2649     do {
2650         if (p.x < leftmost.x) leftmost = p;
2651         p = p.next;
2652     } while (p !== start);
2653
2654     return leftmost;
2655 }
2656
2657 // check if a point lies within a convex triangle
2658 function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
2659     return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
2660            (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
2661            (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
2662 }
2663
2664 // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
2665 function isValidDiagonal(a, b) {
2666     return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
2667            locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
2668 }
2669
2670 // signed area of a triangle
2671 function area(p, q, r) {
2672     return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
2673 }
2674
2675 // check if two points are equal
2676 function equals(p1, p2) {
2677     return p1.x === p2.x && p1.y === p2.y;
2678 }
2679
2680 // check if two segments intersect
2681 function intersects(p1, q1, p2, q2) {
2682     if ((equals(p1, q1) && equals(p2, q2)) ||
2683         (equals(p1, q2) && equals(p2, q1))) return true;
2684     return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
2685            area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
2686 }
2687
2688 // check if a polygon diagonal intersects any polygon segments
2689 function intersectsPolygon(a, b) {
2690     var p = a;
2691     do {
2692         if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
2693                 intersects(p, p.next, a, b)) return true;
2694         p = p.next;
2695     } while (p !== a);
2696
2697     return false;
2698 }
2699
2700 // check if a polygon diagonal is locally inside the polygon
2701 function locallyInside(a, b) {
2702     return area(a.prev, a, a.next) < 0 ?
2703         area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
2704         area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
2705 }
2706
2707 // check if the middle point of a polygon diagonal is inside the polygon
2708 function middleInside(a, b) {
2709     var p = a,
2710         inside = false,
2711         px = (a.x + b.x) / 2,
2712         py = (a.y + b.y) / 2;
2713     do {
2714         if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
2715             inside = !inside;
2716         p = p.next;
2717     } while (p !== a);
2718
2719     return inside;
2720 }
2721
2722 // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
2723 // if one belongs to the outer ring and another to a hole, it merges it into a single ring
2724 function splitPolygon(a, b) {
2725     var a2 = new Node(a.i, a.x, a.y),
2726         b2 = new Node(b.i, b.x, b.y),
2727         an = a.next,
2728         bp = b.prev;
2729
2730     a.next = b;
2731     b.prev = a;
2732
2733     a2.next = an;
2734     an.prev = a2;
2735
2736     b2.next = a2;
2737     a2.prev = b2;
2738
2739     bp.next = b2;
2740     b2.prev = bp;
2741
2742     return b2;
2743 }
2744
2745 // create a node and optionally link it with previous one (in a circular doubly linked list)
2746 function insertNode(i, x, y, last) {
2747     var p = new Node(i, x, y);
2748
2749     if (!last) {
2750         p.prev = p;
2751         p.next = p;
2752
2753     } else {
2754         p.next = last.next;
2755         p.prev = last;
2756         last.next.prev = p;
2757         last.next = p;
2758     }
2759     return p;
2760 }
2761
2762 function removeNode(p) {
2763     p.next.prev = p.prev;
2764     p.prev.next = p.next;
2765
2766     if (p.prevZ) p.prevZ.nextZ = p.nextZ;
2767     if (p.nextZ) p.nextZ.prevZ = p.prevZ;
2768 }
2769
2770 function Node(i, x, y) {
2771     // vertice index in coordinates array
2772     this.i = i;
2773
2774     // vertex coordinates
2775     this.x = x;
2776     this.y = y;
2777
2778     // previous and next vertice nodes in a polygon ring
2779     this.prev = null;
2780     this.next = null;
2781
2782     // z-order curve value
2783     this.z = null;
2784
2785     // previous and next nodes in z-order
2786     this.prevZ = null;
2787     this.nextZ = null;
2788
2789     // indicates whether this is a steiner point
2790     this.steiner = false;
2791 }
2792
2793 // return a percentage difference between the polygon area and its triangulation area;
2794 // used to verify correctness of triangulation
2795 earcut.deviation = function (data, holeIndices, dim, triangles) {
2796     var hasHoles = holeIndices && holeIndices.length;
2797     var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
2798
2799     var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
2800     if (hasHoles) {
2801         for (var i = 0, len = holeIndices.length; i < len; i++) {
2802             var start = holeIndices[i] * dim;
2803             var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2804             polygonArea -= Math.abs(signedArea(data, start, end, dim));
2805         }
2806     }
2807
2808     var trianglesArea = 0;
2809     for (i = 0; i < triangles.length; i += 3) {
2810         var a = triangles[i] * dim;
2811         var b = triangles[i + 1] * dim;
2812         var c = triangles[i + 2] * dim;
2813         trianglesArea += Math.abs(
2814             (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
2815             (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
2816     }
2817
2818     return polygonArea === 0 && trianglesArea === 0 ? 0 :
2819         Math.abs((trianglesArea - polygonArea) / polygonArea);
2820 };
2821
2822 function signedArea(data, start, end, dim) {
2823     var sum = 0;
2824     for (var i = start, j = end - dim; i < end; i += dim) {
2825         sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
2826         j = i;
2827     }
2828     return sum;
2829 }
2830
2831 // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
2832 earcut.flatten = function (data) {
2833     var dim = data[0][0].length,
2834         result = {vertices: [], holes: [], dimensions: dim},
2835         holeIndex = 0;
2836
2837     for (var i = 0; i < data.length; i++) {
2838         for (var j = 0; j < data[i].length; j++) {
2839             for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
2840         }
2841         if (i > 0) {
2842             holeIndex += data[i - 1].length;
2843             result.holes.push(holeIndex);
2844         }
2845     }
2846     return result;
2847 };
2848
2849 },{}],7:[function(require,module,exports){
2850 'use strict';
2851
2852 var OneVersionConstraint = require('individual/one-version');
2853
2854 var MY_VERSION = '7';
2855 OneVersionConstraint('ev-store', MY_VERSION);
2856
2857 var hashKey = '__EV_STORE_KEY@' + MY_VERSION;
2858
2859 module.exports = EvStore;
2860
2861 function EvStore(elem) {
2862     var hash = elem[hashKey];
2863
2864     if (!hash) {
2865         hash = elem[hashKey] = {};
2866     }
2867
2868     return hash;
2869 }
2870
2871 },{"individual/one-version":17}],8:[function(require,module,exports){
2872 'use strict';
2873 var request = require('./request');
2874 var buildQueryObject = require('./buildQueryObject');
2875 var isArray = Array.isArray;
2876
2877 function simpleExtend(obj, obj2) {
2878   var prop;
2879   for (prop in obj2) {
2880     obj[prop] = obj2[prop];
2881   }
2882   return obj;
2883 }
2884
2885 function XMLHttpSource(jsongUrl, config) {
2886   this._jsongUrl = jsongUrl;
2887   if (typeof config === 'number') {
2888     var newConfig = {
2889       timeout: config
2890     };
2891     config = newConfig;
2892   }
2893   this._config = simpleExtend({
2894     timeout: 15000,
2895     headers: {}
2896   }, config || {});
2897 }
2898
2899 XMLHttpSource.prototype = {
2900   // because javascript
2901   constructor: XMLHttpSource,
2902   /**
2903    * buildQueryObject helper
2904    */
2905   buildQueryObject: buildQueryObject,
2906
2907   /**
2908    * @inheritDoc DataSource#get
2909    */
2910   get: function httpSourceGet(pathSet) {
2911     var method = 'GET';
2912     var queryObject = this.buildQueryObject(this._jsongUrl, method, {
2913       paths: pathSet,
2914       method: 'get'
2915     });
2916     var config = simpleExtend(queryObject, this._config);
2917     // pass context for onBeforeRequest callback
2918     var context = this;
2919     return request(method, config, context);
2920   },
2921
2922   /**
2923    * @inheritDoc DataSource#set
2924    */
2925   set: function httpSourceSet(jsongEnv) {
2926     var method = 'POST';
2927     var queryObject = this.buildQueryObject(this._jsongUrl, method, {
2928       jsonGraph: jsongEnv,
2929       method: 'set'
2930     });
2931     var config = simpleExtend(queryObject, this._config);
2932     config.headers["Content-Type"] = "application/x-www-form-urlencoded";
2933     
2934     // pass context for onBeforeRequest callback
2935     var context = this;
2936     return request(method, config, context);
2937
2938   },
2939
2940   /**
2941    * @inheritDoc DataSource#call
2942    */
2943   call: function httpSourceCall(callPath, args, pathSuffix, paths) {
2944     // arguments defaults
2945     args = args || [];
2946     pathSuffix = pathSuffix || [];
2947     paths = paths || [];
2948
2949     var method = 'POST';
2950     var queryData = [];
2951     queryData.push('method=call');
2952     queryData.push('callPath=' + encodeURIComponent(JSON.stringify(callPath)));
2953     queryData.push('arguments=' + encodeURIComponent(JSON.stringify(args)));
2954     queryData.push('pathSuffixes=' + encodeURIComponent(JSON.stringify(pathSuffix)));
2955     queryData.push('paths=' + encodeURIComponent(JSON.stringify(paths)));
2956
2957     var queryObject = this.buildQueryObject(this._jsongUrl, method, queryData.join('&'));
2958     var config = simpleExtend(queryObject, this._config);
2959     config.headers["Content-Type"] = "application/x-www-form-urlencoded";
2960     
2961     // pass context for onBeforeRequest callback
2962     var context = this;
2963     return request(method, config, context);
2964   }
2965 };
2966 // ES6 modules
2967 XMLHttpSource.XMLHttpSource = XMLHttpSource;
2968 XMLHttpSource['default'] = XMLHttpSource;
2969 // commonjs
2970 module.exports = XMLHttpSource;
2971
2972 },{"./buildQueryObject":9,"./request":12}],9:[function(require,module,exports){
2973 'use strict';
2974 module.exports = function buildQueryObject(url, method, queryData) {
2975   var qData = [];
2976   var keys;
2977   var data = {url: url};
2978   var isQueryParamUrl = url.indexOf('?') !== -1;
2979   var startUrl = (isQueryParamUrl) ? '&' : '?';
2980
2981   if (typeof queryData === 'string') {
2982     qData.push(queryData);
2983   } else {
2984
2985     keys = Object.keys(queryData);
2986     keys.forEach(function (k) {
2987       var value = (typeof queryData[k] === 'object') ? JSON.stringify(queryData[k]) : queryData[k];
2988       qData.push(k + '=' + encodeURIComponent(value));
2989     });
2990   }
2991
2992   if (method === 'GET') {
2993     data.url += startUrl + qData.join('&');
2994   } else {
2995     data.data = qData.join('&');
2996   }
2997
2998   return data;
2999 };
3000
3001 },{}],10:[function(require,module,exports){
3002 (function (global){
3003 'use strict';
3004 // Get CORS support even for older IE
3005 module.exports = function getCORSRequest() {
3006     var xhr = new global.XMLHttpRequest();
3007     if ('withCredentials' in xhr) {
3008         return xhr;
3009     } else if (!!global.XDomainRequest) {
3010         return new XDomainRequest();
3011     } else {
3012         throw new Error('CORS is not supported by your browser');
3013     }
3014 };
3015
3016 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3017
3018 },{}],11:[function(require,module,exports){
3019 (function (global){
3020 'use strict';
3021 module.exports = function getXMLHttpRequest() {
3022   var progId,
3023     progIds,
3024     i;
3025   if (global.XMLHttpRequest) {
3026     return new global.XMLHttpRequest();
3027   } else {
3028     try {
3029     progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
3030     for (i = 0; i < 3; i++) {
3031       try {
3032         progId = progIds[i];
3033         if (new global.ActiveXObject(progId)) {
3034           break;
3035         }
3036       } catch(e) { }
3037     }
3038     return new global.ActiveXObject(progId);
3039     } catch (e) {
3040     throw new Error('XMLHttpRequest is not supported by your browser');
3041     }
3042   }
3043 };
3044
3045 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3046
3047 },{}],12:[function(require,module,exports){
3048 'use strict';
3049 var getXMLHttpRequest = require('./getXMLHttpRequest');
3050 var getCORSRequest = require('./getCORSRequest');
3051 var hasOwnProp = Object.prototype.hasOwnProperty;
3052
3053 var noop = function() {};
3054
3055 function Observable() {}
3056
3057 Observable.create = function(subscribe) {
3058   var o = new Observable();
3059
3060   o.subscribe = function(onNext, onError, onCompleted) {
3061
3062     var observer;
3063     var disposable;
3064
3065     if (typeof onNext === 'function') {
3066         observer = {
3067             onNext: onNext,
3068             onError: (onError || noop),
3069             onCompleted: (onCompleted || noop)
3070         };
3071     } else {
3072         observer = onNext;
3073     }
3074
3075     disposable = subscribe(observer);
3076
3077     if (typeof disposable === 'function') {
3078       return {
3079         dispose: disposable
3080       };
3081     } else {
3082       return disposable;
3083     }
3084   };
3085
3086   return o;
3087 };
3088
3089 function request(method, options, context) {
3090   return Observable.create(function requestObserver(observer) {
3091
3092     var config = {
3093       method: method || 'GET',
3094       crossDomain: false,
3095       async: true,
3096       headers: {},
3097       responseType: 'json'
3098     };
3099
3100     var xhr,
3101       isDone,
3102       headers,
3103       header,
3104       prop;
3105
3106     for (prop in options) {
3107       if (hasOwnProp.call(options, prop)) {
3108         config[prop] = options[prop];
3109       }
3110     }
3111
3112     // Add request with Headers
3113     if (!config.crossDomain && !config.headers['X-Requested-With']) {
3114       config.headers['X-Requested-With'] = 'XMLHttpRequest';
3115     }
3116
3117     // allow the user to mutate the config open
3118     if (context.onBeforeRequest != null) {
3119       context.onBeforeRequest(config);
3120     }
3121
3122     // create xhr
3123     try {
3124       xhr = config.crossDomain ? getCORSRequest() : getXMLHttpRequest();
3125     } catch (err) {
3126       observer.onError(err);
3127     }
3128     try {
3129       // Takes the url and opens the connection
3130       if (config.user) {
3131         xhr.open(config.method, config.url, config.async, config.user, config.password);
3132       } else {
3133         xhr.open(config.method, config.url, config.async);
3134       }
3135
3136       // Sets timeout information
3137       xhr.timeout = config.timeout;
3138
3139       // Anything but explicit false results in true.
3140       xhr.withCredentials = config.withCredentials !== false;
3141
3142       // Fills the request headers
3143       headers = config.headers;
3144       for (header in headers) {
3145         if (hasOwnProp.call(headers, header)) {
3146           xhr.setRequestHeader(header, headers[header]);
3147         }
3148       }
3149
3150       if (config.responseType) {
3151         try {
3152           xhr.responseType = config.responseType;
3153         } catch (e) {
3154           // WebKit added support for the json responseType value on 09/03/2013
3155           // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
3156           // known to throw when setting the value "json" as the response type. Other older
3157           // browsers implementing the responseType
3158           //
3159           // The json response type can be ignored if not supported, because JSON payloads are
3160           // parsed on the client-side regardless.
3161           if (config.responseType !== 'json') {
3162             throw e;
3163           }
3164         }
3165       }
3166
3167       xhr.onreadystatechange = function onreadystatechange(e) {
3168         // Complete
3169         if (xhr.readyState === 4) {
3170           if (!isDone) {
3171             isDone = true;
3172             onXhrLoad(observer, xhr, e);
3173           }
3174         }
3175       };
3176
3177       // Timeout
3178       xhr.ontimeout = function ontimeout(e) {
3179         if (!isDone) {
3180           isDone = true;
3181           onXhrError(observer, xhr, 'timeout error', e);
3182         }
3183       };
3184
3185       // Send Request
3186       xhr.send(config.data);
3187
3188     } catch (e) {
3189       observer.onError(e);
3190     }
3191     // Dispose
3192     return function dispose() {
3193       // Doesn't work in IE9
3194       if (!isDone && xhr.readyState !== 4) {
3195         isDone = true;
3196         xhr.abort();
3197       }
3198     };//Dispose
3199   });
3200 }
3201
3202 /*
3203  * General handling of ultimate failure (after appropriate retries)
3204  */
3205 function _handleXhrError(observer, textStatus, errorThrown) {
3206   // IE9: cross-domain request may be considered errors
3207   if (!errorThrown) {
3208     errorThrown = new Error(textStatus);
3209   }
3210
3211   observer.onError(errorThrown);
3212 }
3213
3214 function onXhrLoad(observer, xhr, e) {
3215   var responseData,
3216     responseObject,
3217     responseType;
3218
3219   // If there's no observer, the request has been (or is being) cancelled.
3220   if (xhr && observer) {
3221     responseType = xhr.responseType;
3222     // responseText is the old-school way of retrieving response (supported by IE8 & 9)
3223     // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
3224     responseData = ('response' in xhr) ? xhr.response : xhr.responseText;
3225
3226     // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
3227     var status = (xhr.status === 1223) ? 204 : xhr.status;
3228
3229     if (status >= 200 && status <= 399) {
3230       try {
3231         if (responseType !== 'json') {
3232           responseData = JSON.parse(responseData || '');
3233         }
3234         if (typeof responseData === 'string') {
3235           responseData = JSON.parse(responseData || '');
3236         }
3237       } catch (e) {
3238         _handleXhrError(observer, 'invalid json', e);
3239       }
3240       observer.onNext(responseData);
3241       observer.onCompleted();
3242       return;
3243
3244     } else if (status === 401 || status === 403 || status === 407) {
3245
3246       return _handleXhrError(observer, responseData);
3247
3248     } else if (status === 410) {
3249       // TODO: Retry ?
3250       return _handleXhrError(observer, responseData);
3251
3252     } else if (status === 408 || status === 504) {
3253       // TODO: Retry ?
3254       return _handleXhrError(observer, responseData);
3255
3256     } else {
3257
3258       return _handleXhrError(observer, responseData || ('Response code ' + status));
3259
3260     }//if
3261   }//if
3262 }//onXhrLoad
3263
3264 function onXhrError(observer, xhr, status, e) {
3265   _handleXhrError(observer, status || xhr.statusText || 'request error', e);
3266 }
3267
3268 module.exports = request;
3269
3270 },{"./getCORSRequest":10,"./getXMLHttpRequest":11}],13:[function(require,module,exports){
3271 (function (global){
3272 !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(){
3273 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);
3274 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(){
3275 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(){
3276 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)});
3277 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3278
3279 },{}],14:[function(require,module,exports){
3280 (function (global){
3281 var topLevel = typeof global !== 'undefined' ? global :
3282     typeof window !== 'undefined' ? window : {}
3283 var minDoc = require('min-document');
3284
3285 if (typeof document !== 'undefined') {
3286     module.exports = document;
3287 } else {
3288     var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
3289
3290     if (!doccy) {
3291         doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
3292     }
3293
3294     module.exports = doccy;
3295 }
3296
3297 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3298
3299 },{"min-document":2}],15:[function(require,module,exports){
3300 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
3301   var e, m
3302   var eLen = nBytes * 8 - mLen - 1
3303   var eMax = (1 << eLen) - 1
3304   var eBias = eMax >> 1
3305   var nBits = -7
3306   var i = isLE ? (nBytes - 1) : 0
3307   var d = isLE ? -1 : 1
3308   var s = buffer[offset + i]
3309
3310   i += d
3311
3312   e = s & ((1 << (-nBits)) - 1)
3313   s >>= (-nBits)
3314   nBits += eLen
3315   for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3316
3317   m = e & ((1 << (-nBits)) - 1)
3318   e >>= (-nBits)
3319   nBits += mLen
3320   for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3321
3322   if (e === 0) {
3323     e = 1 - eBias
3324   } else if (e === eMax) {
3325     return m ? NaN : ((s ? -1 : 1) * Infinity)
3326   } else {
3327     m = m + Math.pow(2, mLen)
3328     e = e - eBias
3329   }
3330   return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
3331 }
3332
3333 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
3334   var e, m, c
3335   var eLen = nBytes * 8 - mLen - 1
3336   var eMax = (1 << eLen) - 1
3337   var eBias = eMax >> 1
3338   var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
3339   var i = isLE ? 0 : (nBytes - 1)
3340   var d = isLE ? 1 : -1
3341   var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
3342
3343   value = Math.abs(value)
3344
3345   if (isNaN(value) || value === Infinity) {
3346     m = isNaN(value) ? 1 : 0
3347     e = eMax
3348   } else {
3349     e = Math.floor(Math.log(value) / Math.LN2)
3350     if (value * (c = Math.pow(2, -e)) < 1) {
3351       e--
3352       c *= 2
3353     }
3354     if (e + eBias >= 1) {
3355       value += rt / c
3356     } else {
3357       value += rt * Math.pow(2, 1 - eBias)
3358     }
3359     if (value * c >= 2) {
3360       e++
3361       c /= 2
3362     }
3363
3364     if (e + eBias >= eMax) {
3365       m = 0
3366       e = eMax
3367     } else if (e + eBias >= 1) {
3368       m = (value * c - 1) * Math.pow(2, mLen)
3369       e = e + eBias
3370     } else {
3371       m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
3372       e = 0
3373     }
3374   }
3375
3376   for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
3377
3378   e = (e << mLen) | m
3379   eLen += mLen
3380   for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
3381
3382   buffer[offset + i - d] |= s * 128
3383 }
3384
3385 },{}],16:[function(require,module,exports){
3386 (function (global){
3387 'use strict';
3388
3389 /*global window, global*/
3390
3391 var root = typeof window !== 'undefined' ?
3392     window : typeof global !== 'undefined' ?
3393     global : {};
3394
3395 module.exports = Individual;
3396
3397 function Individual(key, value) {
3398     if (key in root) {
3399         return root[key];
3400     }
3401
3402     root[key] = value;
3403
3404     return value;
3405 }
3406
3407 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3408
3409 },{}],17:[function(require,module,exports){
3410 'use strict';
3411
3412 var Individual = require('./index.js');
3413
3414 module.exports = OneVersion;
3415
3416 function OneVersion(moduleName, version, defaultValue) {
3417     var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName;
3418     var enforceKey = key + '_ENFORCE_SINGLETON';
3419
3420     var versionValue = Individual(enforceKey, version);
3421
3422     if (versionValue !== version) {
3423         throw new Error('Can only have one copy of ' +
3424             moduleName + '.\n' +
3425             'You already have version ' + versionValue +
3426             ' installed.\n' +
3427             'This means you cannot install version ' + version);
3428     }
3429
3430     return Individual(key, defaultValue);
3431 }
3432
3433 },{"./index.js":16}],18:[function(require,module,exports){
3434 "use strict";
3435
3436 module.exports = function isObject(x) {
3437         return typeof x === "object" && x !== null;
3438 };
3439
3440 },{}],19:[function(require,module,exports){
3441 var toString = {}.toString;
3442
3443 module.exports = Array.isArray || function (arr) {
3444   return toString.call(arr) == '[object Array]';
3445 };
3446
3447 },{}],20:[function(require,module,exports){
3448 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3449 /* Geohash encoding/decoding and associated functions   (c) Chris Veness 2014-2016 / MIT Licence  */
3450 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3451
3452 'use strict';
3453
3454
3455 /**
3456  * Geohash encode, decode, bounds, neighbours.
3457  *
3458  * @namespace
3459  */
3460 var Geohash = {};
3461
3462 /* (Geohash-specific) Base32 map */
3463 Geohash.base32 = '0123456789bcdefghjkmnpqrstuvwxyz';
3464
3465 /**
3466  * Encodes latitude/longitude to geohash, either to specified precision or to automatically
3467  * evaluated precision.
3468  *
3469  * @param   {number} lat - Latitude in degrees.
3470  * @param   {number} lon - Longitude in degrees.
3471  * @param   {number} [precision] - Number of characters in resulting geohash.
3472  * @returns {string} Geohash of supplied latitude/longitude.
3473  * @throws  Invalid geohash.
3474  *
3475  * @example
3476  *     var geohash = Geohash.encode(52.205, 0.119, 7); // geohash: 'u120fxw'
3477  */
3478 Geohash.encode = function(lat, lon, precision) {
3479     // infer precision?
3480     if (typeof precision == 'undefined') {
3481         // refine geohash until it matches precision of supplied lat/lon
3482         for (var p=1; p<=12; p++) {
3483             var hash = Geohash.encode(lat, lon, p);
3484             var posn = Geohash.decode(hash);
3485             if (posn.lat==lat && posn.lon==lon) return hash;
3486         }
3487         precision = 12; // set to maximum
3488     }
3489
3490     lat = Number(lat);
3491     lon = Number(lon);
3492     precision = Number(precision);
3493
3494     if (isNaN(lat) || isNaN(lon) || isNaN(precision)) throw new Error('Invalid geohash');
3495
3496     var idx = 0; // index into base32 map
3497     var bit = 0; // each char holds 5 bits
3498     var evenBit = true;
3499     var geohash = '';
3500
3501     var latMin =  -90, latMax =  90;
3502     var lonMin = -180, lonMax = 180;
3503
3504     while (geohash.length < precision) {
3505         if (evenBit) {
3506             // bisect E-W longitude
3507             var lonMid = (lonMin + lonMax) / 2;
3508             if (lon >= lonMid) {
3509                 idx = idx*2 + 1;
3510                 lonMin = lonMid;
3511             } else {
3512                 idx = idx*2;
3513                 lonMax = lonMid;
3514             }
3515         } else {
3516             // bisect N-S latitude
3517             var latMid = (latMin + latMax) / 2;
3518             if (lat >= latMid) {
3519                 idx = idx*2 + 1;
3520                 latMin = latMid;
3521             } else {
3522                 idx = idx*2;
3523                 latMax = latMid;
3524             }
3525         }
3526         evenBit = !evenBit;
3527
3528         if (++bit == 5) {
3529             // 5 bits gives us a character: append it and start over
3530             geohash += Geohash.base32.charAt(idx);
3531             bit = 0;
3532             idx = 0;
3533         }
3534     }
3535
3536     return geohash;
3537 };
3538
3539
3540 /**
3541  * Decode geohash to latitude/longitude (location is approximate centre of geohash cell,
3542  *     to reasonable precision).
3543  *
3544  * @param   {string} geohash - Geohash string to be converted to latitude/longitude.
3545  * @returns {{lat:number, lon:number}} (Center of) geohashed location.
3546  * @throws  Invalid geohash.
3547  *
3548  * @example
3549  *     var latlon = Geohash.decode('u120fxw'); // latlon: { lat: 52.205, lon: 0.1188 }
3550  */
3551 Geohash.decode = function(geohash) {
3552
3553     var bounds = Geohash.bounds(geohash); // <-- the hard work
3554     // now just determine the centre of the cell...
3555
3556     var latMin = bounds.sw.lat, lonMin = bounds.sw.lon;
3557     var latMax = bounds.ne.lat, lonMax = bounds.ne.lon;
3558
3559     // cell centre
3560     var lat = (latMin + latMax)/2;
3561     var lon = (lonMin + lonMax)/2;
3562
3563     // round to close to centre without excessive precision: ⌊2-log10(Δ°)⌋ decimal places
3564     lat = lat.toFixed(Math.floor(2-Math.log(latMax-latMin)/Math.LN10));
3565     lon = lon.toFixed(Math.floor(2-Math.log(lonMax-lonMin)/Math.LN10));
3566
3567     return { lat: Number(lat), lon: Number(lon) };
3568 };
3569
3570
3571 /**
3572  * Returns SW/NE latitude/longitude bounds of specified geohash.
3573  *
3574  * @param   {string} geohash - Cell that bounds are required of.
3575  * @returns {{sw: {lat: number, lon: number}, ne: {lat: number, lon: number}}}
3576  * @throws  Invalid geohash.
3577  */
3578 Geohash.bounds = function(geohash) {
3579     if (geohash.length === 0) throw new Error('Invalid geohash');
3580
3581     geohash = geohash.toLowerCase();
3582
3583     var evenBit = true;
3584     var latMin =  -90, latMax =  90;
3585     var lonMin = -180, lonMax = 180;
3586
3587     for (var i=0; i<geohash.length; i++) {
3588         var chr = geohash.charAt(i);
3589         var idx = Geohash.base32.indexOf(chr);
3590         if (idx == -1) throw new Error('Invalid geohash');
3591
3592         for (var n=4; n>=0; n--) {
3593             var bitN = idx >> n & 1;
3594             if (evenBit) {
3595                 // longitude
3596                 var lonMid = (lonMin+lonMax) / 2;
3597                 if (bitN == 1) {
3598                     lonMin = lonMid;
3599                 } else {
3600                     lonMax = lonMid;
3601                 }
3602             } else {
3603                 // latitude
3604                 var latMid = (latMin+latMax) / 2;
3605                 if (bitN == 1) {
3606                     latMin = latMid;
3607                 } else {
3608                     latMax = latMid;
3609                 }
3610             }
3611             evenBit = !evenBit;
3612         }
3613     }
3614
3615     var bounds = {
3616         sw: { lat: latMin, lon: lonMin },
3617         ne: { lat: latMax, lon: lonMax },
3618     };
3619
3620     return bounds;
3621 };
3622
3623
3624 /**
3625  * Determines adjacent cell in given direction.
3626  *
3627  * @param   geohash - Cell to which adjacent cell is required.
3628  * @param   direction - Direction from geohash (N/S/E/W).
3629  * @returns {string} Geocode of adjacent cell.
3630  * @throws  Invalid geohash.
3631  */
3632 Geohash.adjacent = function(geohash, direction) {
3633     // based on github.com/davetroy/geohash-js
3634
3635     geohash = geohash.toLowerCase();
3636     direction = direction.toLowerCase();
3637
3638     if (geohash.length === 0) throw new Error('Invalid geohash');
3639     if ('nsew'.indexOf(direction) == -1) throw new Error('Invalid direction');
3640
3641     var neighbour = {
3642         n: [ 'p0r21436x8zb9dcf5h7kjnmqesgutwvy', 'bc01fg45238967deuvhjyznpkmstqrwx' ],
3643         s: [ '14365h7k9dcfesgujnmqp0r2twvyx8zb', '238967debc01fg45kmstqrwxuvhjyznp' ],
3644         e: [ 'bc01fg45238967deuvhjyznpkmstqrwx', 'p0r21436x8zb9dcf5h7kjnmqesgutwvy' ],
3645         w: [ '238967debc01fg45kmstqrwxuvhjyznp', '14365h7k9dcfesgujnmqp0r2twvyx8zb' ],
3646     };
3647     var border = {
3648         n: [ 'prxz',     'bcfguvyz' ],
3649         s: [ '028b',     '0145hjnp' ],
3650         e: [ 'bcfguvyz', 'prxz'     ],
3651         w: [ '0145hjnp', '028b'     ],
3652     };
3653
3654     var lastCh = geohash.slice(-1);    // last character of hash
3655     var parent = geohash.slice(0, -1); // hash without last character
3656
3657     var type = geohash.length % 2;
3658
3659     // check for edge-cases which don't share common prefix
3660     if (border[direction][type].indexOf(lastCh) != -1 && parent !== '') {
3661         parent = Geohash.adjacent(parent, direction);
3662     }
3663
3664     // append letter for direction to parent
3665     return parent + Geohash.base32.charAt(neighbour[direction][type].indexOf(lastCh));
3666 };
3667
3668
3669 /**
3670  * Returns all 8 adjacent cells to specified geohash.
3671  *
3672  * @param   {string} geohash - Geohash neighbours are required of.
3673  * @returns {{n,ne,e,se,s,sw,w,nw: string}}
3674  * @throws  Invalid geohash.
3675  */
3676 Geohash.neighbours = function(geohash) {
3677     return {
3678         'n':  Geohash.adjacent(geohash, 'n'),
3679         'ne': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'e'),
3680         'e':  Geohash.adjacent(geohash, 'e'),
3681         'se': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'e'),
3682         's':  Geohash.adjacent(geohash, 's'),
3683         'sw': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'w'),
3684         'w':  Geohash.adjacent(geohash, 'w'),
3685         'nw': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'w'),
3686     };
3687 };
3688
3689
3690 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3691 if (typeof module != 'undefined' && module.exports) module.exports = Geohash; // CommonJS, node.js
3692
3693 },{}],21:[function(require,module,exports){
3694 (function (process){
3695 // Copyright Joyent, Inc. and other Node contributors.
3696 //
3697 // Permission is hereby granted, free of charge, to any person obtaining a
3698 // copy of this software and associated documentation files (the
3699 // "Software"), to deal in the Software without restriction, including
3700 // without limitation the rights to use, copy, modify, merge, publish,
3701 // distribute, sublicense, and/or sell copies of the Software, and to permit
3702 // persons to whom the Software is furnished to do so, subject to the
3703 // following conditions:
3704 //
3705 // The above copyright notice and this permission notice shall be included
3706 // in all copies or substantial portions of the Software.
3707 //
3708 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3709 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3710 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3711 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3712 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3713 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3714 // USE OR OTHER DEALINGS IN THE SOFTWARE.
3715
3716 // resolves . and .. elements in a path array with directory names there
3717 // must be no slashes, empty elements, or device names (c:\) in the array
3718 // (so also no leading and trailing slashes - it does not distinguish
3719 // relative and absolute paths)
3720 function normalizeArray(parts, allowAboveRoot) {
3721   // if the path tries to go above the root, `up` ends up > 0
3722   var up = 0;
3723   for (var i = parts.length - 1; i >= 0; i--) {
3724     var last = parts[i];
3725     if (last === '.') {
3726       parts.splice(i, 1);
3727     } else if (last === '..') {
3728       parts.splice(i, 1);
3729       up++;
3730     } else if (up) {
3731       parts.splice(i, 1);
3732       up--;
3733     }
3734   }
3735
3736   // if the path is allowed to go above the root, restore leading ..s
3737   if (allowAboveRoot) {
3738     for (; up--; up) {
3739       parts.unshift('..');
3740     }
3741   }
3742
3743   return parts;
3744 }
3745
3746 // Split a filename into [root, dir, basename, ext], unix version
3747 // 'root' is just a slash, or nothing.
3748 var splitPathRe =
3749     /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
3750 var splitPath = function(filename) {
3751   return splitPathRe.exec(filename).slice(1);
3752 };
3753
3754 // path.resolve([from ...], to)
3755 // posix version
3756 exports.resolve = function() {
3757   var resolvedPath = '',
3758       resolvedAbsolute = false;
3759
3760   for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
3761     var path = (i >= 0) ? arguments[i] : process.cwd();
3762
3763     // Skip empty and invalid entries
3764     if (typeof path !== 'string') {
3765       throw new TypeError('Arguments to path.resolve must be strings');
3766     } else if (!path) {
3767       continue;
3768     }
3769
3770     resolvedPath = path + '/' + resolvedPath;
3771     resolvedAbsolute = path.charAt(0) === '/';
3772   }
3773
3774   // At this point the path should be resolved to a full absolute path, but
3775   // handle relative paths to be safe (might happen when process.cwd() fails)
3776
3777   // Normalize the path
3778   resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
3779     return !!p;
3780   }), !resolvedAbsolute).join('/');
3781
3782   return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
3783 };
3784
3785 // path.normalize(path)
3786 // posix version
3787 exports.normalize = function(path) {
3788   var isAbsolute = exports.isAbsolute(path),
3789       trailingSlash = substr(path, -1) === '/';
3790
3791   // Normalize the path
3792   path = normalizeArray(filter(path.split('/'), function(p) {
3793     return !!p;
3794   }), !isAbsolute).join('/');
3795
3796   if (!path && !isAbsolute) {
3797     path = '.';
3798   }
3799   if (path && trailingSlash) {
3800     path += '/';
3801   }
3802
3803   return (isAbsolute ? '/' : '') + path;
3804 };
3805
3806 // posix version
3807 exports.isAbsolute = function(path) {
3808   return path.charAt(0) === '/';
3809 };
3810
3811 // posix version
3812 exports.join = function() {
3813   var paths = Array.prototype.slice.call(arguments, 0);
3814   return exports.normalize(filter(paths, function(p, index) {
3815     if (typeof p !== 'string') {
3816       throw new TypeError('Arguments to path.join must be strings');
3817     }
3818     return p;
3819   }).join('/'));
3820 };
3821
3822
3823 // path.relative(from, to)
3824 // posix version
3825 exports.relative = function(from, to) {
3826   from = exports.resolve(from).substr(1);
3827   to = exports.resolve(to).substr(1);
3828
3829   function trim(arr) {
3830     var start = 0;
3831     for (; start < arr.length; start++) {
3832       if (arr[start] !== '') break;
3833     }
3834
3835     var end = arr.length - 1;
3836     for (; end >= 0; end--) {
3837       if (arr[end] !== '') break;
3838     }
3839
3840     if (start > end) return [];
3841     return arr.slice(start, end - start + 1);
3842   }
3843
3844   var fromParts = trim(from.split('/'));
3845   var toParts = trim(to.split('/'));
3846
3847   var length = Math.min(fromParts.length, toParts.length);
3848   var samePartsLength = length;
3849   for (var i = 0; i < length; i++) {
3850     if (fromParts[i] !== toParts[i]) {
3851       samePartsLength = i;
3852       break;
3853     }
3854   }
3855
3856   var outputParts = [];
3857   for (var i = samePartsLength; i < fromParts.length; i++) {
3858     outputParts.push('..');
3859   }
3860
3861   outputParts = outputParts.concat(toParts.slice(samePartsLength));
3862
3863   return outputParts.join('/');
3864 };
3865
3866 exports.sep = '/';
3867 exports.delimiter = ':';
3868
3869 exports.dirname = function(path) {
3870   var result = splitPath(path),
3871       root = result[0],
3872       dir = result[1];
3873
3874   if (!root && !dir) {
3875     // No dirname whatsoever
3876     return '.';
3877   }
3878
3879   if (dir) {
3880     // It has a dirname, strip trailing slash
3881     dir = dir.substr(0, dir.length - 1);
3882   }
3883
3884   return root + dir;
3885 };
3886
3887
3888 exports.basename = function(path, ext) {
3889   var f = splitPath(path)[2];
3890   // TODO: make this comparison case-insensitive on windows?
3891   if (ext && f.substr(-1 * ext.length) === ext) {
3892     f = f.substr(0, f.length - ext.length);
3893   }
3894   return f;
3895 };
3896
3897
3898 exports.extname = function(path) {
3899   return splitPath(path)[3];
3900 };
3901
3902 function filter (xs, f) {
3903     if (xs.filter) return xs.filter(f);
3904     var res = [];
3905     for (var i = 0; i < xs.length; i++) {
3906         if (f(xs[i], i, xs)) res.push(xs[i]);
3907     }
3908     return res;
3909 }
3910
3911 // String.prototype.substr - negative index don't work in IE8
3912 var substr = 'ab'.substr(-1) === 'b'
3913     ? function (str, start, len) { return str.substr(start, len) }
3914     : function (str, start, len) {
3915         if (start < 0) start = str.length + start;
3916         return str.substr(start, len);
3917     }
3918 ;
3919
3920 }).call(this,require('_process'))
3921
3922 },{"_process":4}],22:[function(require,module,exports){
3923 'use strict';
3924
3925 module.exports = Pbf;
3926
3927 var ieee754 = require('ieee754');
3928
3929 function Pbf(buf) {
3930     this.buf = ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);
3931     this.pos = 0;
3932     this.type = 0;
3933     this.length = this.buf.length;
3934 }
3935
3936 Pbf.Varint  = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum
3937 Pbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64
3938 Pbf.Bytes   = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields
3939 Pbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32
3940
3941 var SHIFT_LEFT_32 = (1 << 16) * (1 << 16),
3942     SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
3943
3944 Pbf.prototype = {
3945
3946     destroy: function() {
3947         this.buf = null;
3948     },
3949
3950     // === READING =================================================================
3951
3952     readFields: function(readField, result, end) {
3953         end = end || this.length;
3954
3955         while (this.pos < end) {
3956             var val = this.readVarint(),
3957                 tag = val >> 3,
3958                 startPos = this.pos;
3959
3960             this.type = val & 0x7;
3961             readField(tag, result, this);
3962
3963             if (this.pos === startPos) this.skip(val);
3964         }
3965         return result;
3966     },
3967
3968     readMessage: function(readField, result) {
3969         return this.readFields(readField, result, this.readVarint() + this.pos);
3970     },
3971
3972     readFixed32: function() {
3973         var val = readUInt32(this.buf, this.pos);
3974         this.pos += 4;
3975         return val;
3976     },
3977
3978     readSFixed32: function() {
3979         var val = readInt32(this.buf, this.pos);
3980         this.pos += 4;
3981         return val;
3982     },
3983
3984     // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)
3985
3986     readFixed64: function() {
3987         var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
3988         this.pos += 8;
3989         return val;
3990     },
3991
3992     readSFixed64: function() {
3993         var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
3994         this.pos += 8;
3995         return val;
3996     },
3997
3998     readFloat: function() {
3999         var val = ieee754.read(this.buf, this.pos, true, 23, 4);
4000         this.pos += 4;
4001         return val;
4002     },
4003
4004     readDouble: function() {
4005         var val = ieee754.read(this.buf, this.pos, true, 52, 8);
4006         this.pos += 8;
4007         return val;
4008     },
4009
4010     readVarint: function(isSigned) {
4011         var buf = this.buf,
4012             val, b;
4013
4014         b = buf[this.pos++]; val  =  b & 0x7f;        if (b < 0x80) return val;
4015         b = buf[this.pos++]; val |= (b & 0x7f) << 7;  if (b < 0x80) return val;
4016         b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;
4017         b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;
4018         b = buf[this.pos];   val |= (b & 0x0f) << 28;
4019
4020         return readVarintRemainder(val, isSigned, this);
4021     },
4022
4023     readVarint64: function() { // for compatibility with v2.0.1
4024         return this.readVarint(true);
4025     },
4026
4027     readSVarint: function() {
4028         var num = this.readVarint();
4029         return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding
4030     },
4031
4032     readBoolean: function() {
4033         return Boolean(this.readVarint());
4034     },
4035
4036     readString: function() {
4037         var end = this.readVarint() + this.pos,
4038             str = readUtf8(this.buf, this.pos, end);
4039         this.pos = end;
4040         return str;
4041     },
4042
4043     readBytes: function() {
4044         var end = this.readVarint() + this.pos,
4045             buffer = this.buf.subarray(this.pos, end);
4046         this.pos = end;
4047         return buffer;
4048     },
4049
4050     // verbose for performance reasons; doesn't affect gzipped size
4051
4052     readPackedVarint: function(arr, isSigned) {
4053         var end = readPackedEnd(this);
4054         arr = arr || [];
4055         while (this.pos < end) arr.push(this.readVarint(isSigned));
4056         return arr;
4057     },
4058     readPackedSVarint: function(arr) {
4059         var end = readPackedEnd(this);
4060         arr = arr || [];
4061         while (this.pos < end) arr.push(this.readSVarint());
4062         return arr;
4063     },
4064     readPackedBoolean: function(arr) {
4065         var end = readPackedEnd(this);
4066         arr = arr || [];
4067         while (this.pos < end) arr.push(this.readBoolean());
4068         return arr;
4069     },
4070     readPackedFloat: function(arr) {
4071         var end = readPackedEnd(this);
4072         arr = arr || [];
4073         while (this.pos < end) arr.push(this.readFloat());
4074         return arr;
4075     },
4076     readPackedDouble: function(arr) {
4077         var end = readPackedEnd(this);
4078         arr = arr || [];
4079         while (this.pos < end) arr.push(this.readDouble());
4080         return arr;
4081     },
4082     readPackedFixed32: function(arr) {
4083         var end = readPackedEnd(this);
4084         arr = arr || [];
4085         while (this.pos < end) arr.push(this.readFixed32());
4086         return arr;
4087     },
4088     readPackedSFixed32: function(arr) {
4089         var end = readPackedEnd(this);
4090         arr = arr || [];
4091         while (this.pos < end) arr.push(this.readSFixed32());
4092         return arr;
4093     },
4094     readPackedFixed64: function(arr) {
4095         var end = readPackedEnd(this);
4096         arr = arr || [];
4097         while (this.pos < end) arr.push(this.readFixed64());
4098         return arr;
4099     },
4100     readPackedSFixed64: function(arr) {
4101         var end = readPackedEnd(this);
4102         arr = arr || [];
4103         while (this.pos < end) arr.push(this.readSFixed64());
4104         return arr;
4105     },
4106
4107     skip: function(val) {
4108         var type = val & 0x7;
4109         if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}
4110         else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos;
4111         else if (type === Pbf.Fixed32) this.pos += 4;
4112         else if (type === Pbf.Fixed64) this.pos += 8;
4113         else throw new Error('Unimplemented type: ' + type);
4114     },
4115
4116     // === WRITING =================================================================
4117
4118     writeTag: function(tag, type) {
4119         this.writeVarint((tag << 3) | type);
4120     },
4121
4122     realloc: function(min) {
4123         var length = this.length || 16;
4124
4125         while (length < this.pos + min) length *= 2;
4126
4127         if (length !== this.length) {
4128             var buf = new Uint8Array(length);
4129             buf.set(this.buf);
4130             this.buf = buf;
4131             this.length = length;
4132         }
4133     },
4134
4135     finish: function() {
4136         this.length = this.pos;
4137         this.pos = 0;
4138         return this.buf.subarray(0, this.length);
4139     },
4140
4141     writeFixed32: function(val) {
4142         this.realloc(4);
4143         writeInt32(this.buf, val, this.pos);
4144         this.pos += 4;
4145     },
4146
4147     writeSFixed32: function(val) {
4148         this.realloc(4);
4149         writeInt32(this.buf, val, this.pos);
4150         this.pos += 4;
4151     },
4152
4153     writeFixed64: function(val) {
4154         this.realloc(8);
4155         writeInt32(this.buf, val & -1, this.pos);
4156         writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4157         this.pos += 8;
4158     },
4159
4160     writeSFixed64: function(val) {
4161         this.realloc(8);
4162         writeInt32(this.buf, val & -1, this.pos);
4163         writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4164         this.pos += 8;
4165     },
4166
4167     writeVarint: function(val) {
4168         val = +val || 0;
4169
4170         if (val > 0xfffffff || val < 0) {
4171             writeBigVarint(val, this);
4172             return;
4173         }
4174
4175         this.realloc(4);
4176
4177         this.buf[this.pos++] =           val & 0x7f  | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4178         this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4179         this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4180         this.buf[this.pos++] =   (val >>> 7) & 0x7f;
4181     },
4182
4183     writeSVarint: function(val) {
4184         this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
4185     },
4186
4187     writeBoolean: function(val) {
4188         this.writeVarint(Boolean(val));
4189     },
4190
4191     writeString: function(str) {
4192         str = String(str);
4193         this.realloc(str.length * 4);
4194
4195         this.pos++; // reserve 1 byte for short string length
4196
4197         var startPos = this.pos;
4198         // write the string directly to the buffer and see how much was written
4199         this.pos = writeUtf8(this.buf, str, this.pos);
4200         var len = this.pos - startPos;
4201
4202         if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4203
4204         // finally, write the message length in the reserved place and restore the position
4205         this.pos = startPos - 1;
4206         this.writeVarint(len);
4207         this.pos += len;
4208     },
4209
4210     writeFloat: function(val) {
4211         this.realloc(4);
4212         ieee754.write(this.buf, val, this.pos, true, 23, 4);
4213         this.pos += 4;
4214     },
4215
4216     writeDouble: function(val) {
4217         this.realloc(8);
4218         ieee754.write(this.buf, val, this.pos, true, 52, 8);
4219         this.pos += 8;
4220     },
4221
4222     writeBytes: function(buffer) {
4223         var len = buffer.length;
4224         this.writeVarint(len);
4225         this.realloc(len);
4226         for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];
4227     },
4228
4229     writeRawMessage: function(fn, obj) {
4230         this.pos++; // reserve 1 byte for short message length
4231
4232         // write the message directly to the buffer and see how much was written
4233         var startPos = this.pos;
4234         fn(obj, this);
4235         var len = this.pos - startPos;
4236
4237         if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4238
4239         // finally, write the message length in the reserved place and restore the position
4240         this.pos = startPos - 1;
4241         this.writeVarint(len);
4242         this.pos += len;
4243     },
4244
4245     writeMessage: function(tag, fn, obj) {
4246         this.writeTag(tag, Pbf.Bytes);
4247         this.writeRawMessage(fn, obj);
4248     },
4249
4250     writePackedVarint:   function(tag, arr) { this.writeMessage(tag, writePackedVarint, arr);   },
4251     writePackedSVarint:  function(tag, arr) { this.writeMessage(tag, writePackedSVarint, arr);  },
4252     writePackedBoolean:  function(tag, arr) { this.writeMessage(tag, writePackedBoolean, arr);  },
4253     writePackedFloat:    function(tag, arr) { this.writeMessage(tag, writePackedFloat, arr);    },
4254     writePackedDouble:   function(tag, arr) { this.writeMessage(tag, writePackedDouble, arr);   },
4255     writePackedFixed32:  function(tag, arr) { this.writeMessage(tag, writePackedFixed32, arr);  },
4256     writePackedSFixed32: function(tag, arr) { this.writeMessage(tag, writePackedSFixed32, arr); },
4257     writePackedFixed64:  function(tag, arr) { this.writeMessage(tag, writePackedFixed64, arr);  },
4258     writePackedSFixed64: function(tag, arr) { this.writeMessage(tag, writePackedSFixed64, arr); },
4259
4260     writeBytesField: function(tag, buffer) {
4261         this.writeTag(tag, Pbf.Bytes);
4262         this.writeBytes(buffer);
4263     },
4264     writeFixed32Field: function(tag, val) {
4265         this.writeTag(tag, Pbf.Fixed32);
4266         this.writeFixed32(val);
4267     },
4268     writeSFixed32Field: function(tag, val) {
4269         this.writeTag(tag, Pbf.Fixed32);
4270         this.writeSFixed32(val);
4271     },
4272     writeFixed64Field: function(tag, val) {
4273         this.writeTag(tag, Pbf.Fixed64);
4274         this.writeFixed64(val);
4275     },
4276     writeSFixed64Field: function(tag, val) {
4277         this.writeTag(tag, Pbf.Fixed64);
4278         this.writeSFixed64(val);
4279     },
4280     writeVarintField: function(tag, val) {
4281         this.writeTag(tag, Pbf.Varint);
4282         this.writeVarint(val);
4283     },
4284     writeSVarintField: function(tag, val) {
4285         this.writeTag(tag, Pbf.Varint);
4286         this.writeSVarint(val);
4287     },
4288     writeStringField: function(tag, str) {
4289         this.writeTag(tag, Pbf.Bytes);
4290         this.writeString(str);
4291     },
4292     writeFloatField: function(tag, val) {
4293         this.writeTag(tag, Pbf.Fixed32);
4294         this.writeFloat(val);
4295     },
4296     writeDoubleField: function(tag, val) {
4297         this.writeTag(tag, Pbf.Fixed64);
4298         this.writeDouble(val);
4299     },
4300     writeBooleanField: function(tag, val) {
4301         this.writeVarintField(tag, Boolean(val));
4302     }
4303 };
4304
4305 function readVarintRemainder(l, s, p) {
4306     var buf = p.buf,
4307         h, b;
4308
4309     b = buf[p.pos++]; h  = (b & 0x70) >> 4;  if (b < 0x80) return toNum(l, h, s);
4310     b = buf[p.pos++]; h |= (b & 0x7f) << 3;  if (b < 0x80) return toNum(l, h, s);
4311     b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);
4312     b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);
4313     b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);
4314     b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);
4315
4316     throw new Error('Expected varint not more than 10 bytes');
4317 }
4318
4319 function readPackedEnd(pbf) {
4320     return pbf.type === Pbf.Bytes ?
4321         pbf.readVarint() + pbf.pos : pbf.pos + 1;
4322 }
4323
4324 function toNum(low, high, isSigned) {
4325     if (isSigned) {
4326         return high * 0x100000000 + (low >>> 0);
4327     }
4328
4329     return ((high >>> 0) * 0x100000000) + (low >>> 0);
4330 }
4331
4332 function writeBigVarint(val, pbf) {
4333     var low, high;
4334
4335     if (val >= 0) {
4336         low  = (val % 0x100000000) | 0;
4337         high = (val / 0x100000000) | 0;
4338     } else {
4339         low  = ~(-val % 0x100000000);
4340         high = ~(-val / 0x100000000);
4341
4342         if (low ^ 0xffffffff) {
4343             low = (low + 1) | 0;
4344         } else {
4345             low = 0;
4346             high = (high + 1) | 0;
4347         }
4348     }
4349
4350     if (val >= 0x10000000000000000 || val < -0x10000000000000000) {
4351         throw new Error('Given varint doesn\'t fit into 10 bytes');
4352     }
4353
4354     pbf.realloc(10);
4355
4356     writeBigVarintLow(low, high, pbf);
4357     writeBigVarintHigh(high, pbf);
4358 }
4359
4360 function writeBigVarintLow(low, high, pbf) {
4361     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4362     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4363     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4364     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4365     pbf.buf[pbf.pos]   = low & 0x7f;
4366 }
4367
4368 function writeBigVarintHigh(high, pbf) {
4369     var lsb = (high & 0x07) << 4;
4370
4371     pbf.buf[pbf.pos++] |= lsb         | ((high >>>= 3) ? 0x80 : 0); if (!high) return;
4372     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4373     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4374     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4375     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4376     pbf.buf[pbf.pos++]  = high & 0x7f;
4377 }
4378
4379 function makeRoomForExtraLength(startPos, len, pbf) {
4380     var extraLen =
4381         len <= 0x3fff ? 1 :
4382         len <= 0x1fffff ? 2 :
4383         len <= 0xfffffff ? 3 : Math.ceil(Math.log(len) / (Math.LN2 * 7));
4384
4385     // if 1 byte isn't enough for encoding message length, shift the data to the right
4386     pbf.realloc(extraLen);
4387     for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];
4388 }
4389
4390 function writePackedVarint(arr, pbf)   { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]);   }
4391 function writePackedSVarint(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]);  }
4392 function writePackedFloat(arr, pbf)    { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]);    }
4393 function writePackedDouble(arr, pbf)   { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]);   }
4394 function writePackedBoolean(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]);  }
4395 function writePackedFixed32(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]);  }
4396 function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); }
4397 function writePackedFixed64(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]);  }
4398 function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); }
4399
4400 // Buffer code below from https://github.com/feross/buffer, MIT-licensed
4401
4402 function readUInt32(buf, pos) {
4403     return ((buf[pos]) |
4404         (buf[pos + 1] << 8) |
4405         (buf[pos + 2] << 16)) +
4406         (buf[pos + 3] * 0x1000000);
4407 }
4408
4409 function writeInt32(buf, val, pos) {
4410     buf[pos] = val;
4411     buf[pos + 1] = (val >>> 8);
4412     buf[pos + 2] = (val >>> 16);
4413     buf[pos + 3] = (val >>> 24);
4414 }
4415
4416 function readInt32(buf, pos) {
4417     return ((buf[pos]) |
4418         (buf[pos + 1] << 8) |
4419         (buf[pos + 2] << 16)) +
4420         (buf[pos + 3] << 24);
4421 }
4422
4423 function readUtf8(buf, pos, end) {
4424     var str = '';
4425     var i = pos;
4426
4427     while (i < end) {
4428         var b0 = buf[i];
4429         var c = null; // codepoint
4430         var bytesPerSequence =
4431             b0 > 0xEF ? 4 :
4432             b0 > 0xDF ? 3 :
4433             b0 > 0xBF ? 2 : 1;
4434
4435         if (i + bytesPerSequence > end) break;
4436
4437         var b1, b2, b3;
4438
4439         if (bytesPerSequence === 1) {
4440             if (b0 < 0x80) {
4441                 c = b0;
4442             }
4443         } else if (bytesPerSequence === 2) {
4444             b1 = buf[i + 1];
4445             if ((b1 & 0xC0) === 0x80) {
4446                 c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);
4447                 if (c <= 0x7F) {
4448                     c = null;
4449                 }
4450             }
4451         } else if (bytesPerSequence === 3) {
4452             b1 = buf[i + 1];
4453             b2 = buf[i + 2];
4454             if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {
4455                 c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);
4456                 if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {
4457                     c = null;
4458                 }
4459             }
4460         } else if (bytesPerSequence === 4) {
4461             b1 = buf[i + 1];
4462             b2 = buf[i + 2];
4463             b3 = buf[i + 3];
4464             if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
4465                 c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);
4466                 if (c <= 0xFFFF || c >= 0x110000) {
4467                     c = null;
4468                 }
4469             }
4470         }
4471
4472         if (c === null) {
4473             c = 0xFFFD;
4474             bytesPerSequence = 1;
4475
4476         } else if (c > 0xFFFF) {
4477             c -= 0x10000;
4478             str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);
4479             c = 0xDC00 | c & 0x3FF;
4480         }
4481
4482         str += String.fromCharCode(c);
4483         i += bytesPerSequence;
4484     }
4485
4486     return str;
4487 }
4488
4489 function writeUtf8(buf, str, pos) {
4490     for (var i = 0, c, lead; i < str.length; i++) {
4491         c = str.charCodeAt(i); // code point
4492
4493         if (c > 0xD7FF && c < 0xE000) {
4494             if (lead) {
4495                 if (c < 0xDC00) {
4496                     buf[pos++] = 0xEF;
4497                     buf[pos++] = 0xBF;
4498                     buf[pos++] = 0xBD;
4499                     lead = c;
4500                     continue;
4501                 } else {
4502                     c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;
4503                     lead = null;
4504                 }
4505             } else {
4506                 if (c > 0xDBFF || (i + 1 === str.length)) {
4507                     buf[pos++] = 0xEF;
4508                     buf[pos++] = 0xBF;
4509                     buf[pos++] = 0xBD;
4510                 } else {
4511                     lead = c;
4512                 }
4513                 continue;
4514             }
4515         } else if (lead) {
4516             buf[pos++] = 0xEF;
4517             buf[pos++] = 0xBF;
4518             buf[pos++] = 0xBD;
4519             lead = null;
4520         }
4521
4522         if (c < 0x80) {
4523             buf[pos++] = c;
4524         } else {
4525             if (c < 0x800) {
4526                 buf[pos++] = c >> 0x6 | 0xC0;
4527             } else {
4528                 if (c < 0x10000) {
4529                     buf[pos++] = c >> 0xC | 0xE0;
4530                 } else {
4531                     buf[pos++] = c >> 0x12 | 0xF0;
4532                     buf[pos++] = c >> 0xC & 0x3F | 0x80;
4533                 }
4534                 buf[pos++] = c >> 0x6 & 0x3F | 0x80;
4535             }
4536             buf[pos++] = c & 0x3F | 0x80;
4537         }
4538     }
4539     return pos;
4540 }
4541
4542 },{"ieee754":15}],23:[function(require,module,exports){
4543 'use strict';
4544
4545 module.exports = partialSort;
4546
4547 // Floyd-Rivest selection algorithm:
4548 // Rearrange items so that all items in the [left, k] range are smaller than all items in (k, right];
4549 // The k-th element will have the (k - left + 1)th smallest value in [left, right]
4550
4551 function partialSort(arr, k, left, right, compare) {
4552     left = left || 0;
4553     right = right || (arr.length - 1);
4554     compare = compare || defaultCompare;
4555
4556     while (right > left) {
4557         if (right - left > 600) {
4558             var n = right - left + 1;
4559             var m = k - left + 1;
4560             var z = Math.log(n);
4561             var s = 0.5 * Math.exp(2 * z / 3);
4562             var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
4563             var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
4564             var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
4565             partialSort(arr, k, newLeft, newRight, compare);
4566         }
4567
4568         var t = arr[k];
4569         var i = left;
4570         var j = right;
4571
4572         swap(arr, left, k);
4573         if (compare(arr[right], t) > 0) swap(arr, left, right);
4574
4575         while (i < j) {
4576             swap(arr, i, j);
4577             i++;
4578             j--;
4579             while (compare(arr[i], t) < 0) i++;
4580             while (compare(arr[j], t) > 0) j--;
4581         }
4582
4583         if (compare(arr[left], t) === 0) swap(arr, left, j);
4584         else {
4585             j++;
4586             swap(arr, j, right);
4587         }
4588
4589         if (j <= k) left = j + 1;
4590         if (k <= j) right = j - 1;
4591     }
4592 }
4593
4594 function swap(arr, i, j) {
4595     var tmp = arr[i];
4596     arr[i] = arr[j];
4597     arr[j] = tmp;
4598 }
4599
4600 function defaultCompare(a, b) {
4601     return a < b ? -1 : a > b ? 1 : 0;
4602 }
4603
4604 },{}],24:[function(require,module,exports){
4605 'use strict';
4606
4607 module.exports = rbush;
4608
4609 var quickselect = require('quickselect');
4610
4611 function rbush(maxEntries, format) {
4612     if (!(this instanceof rbush)) return new rbush(maxEntries, format);
4613
4614     // max entries in a node is 9 by default; min node fill is 40% for best performance
4615     this._maxEntries = Math.max(4, maxEntries || 9);
4616     this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
4617
4618     if (format) {
4619         this._initFormat(format);
4620     }
4621
4622     this.clear();
4623 }
4624
4625 rbush.prototype = {
4626
4627     all: function () {
4628         return this._all(this.data, []);
4629     },
4630
4631     search: function (bbox) {
4632
4633         var node = this.data,
4634             result = [],
4635             toBBox = this.toBBox;
4636
4637         if (!intersects(bbox, node)) return result;
4638
4639         var nodesToSearch = [],
4640             i, len, child, childBBox;
4641
4642         while (node) {
4643             for (i = 0, len = node.children.length; i < len; i++) {
4644
4645                 child = node.children[i];
4646                 childBBox = node.leaf ? toBBox(child) : child;
4647
4648                 if (intersects(bbox, childBBox)) {
4649                     if (node.leaf) result.push(child);
4650                     else if (contains(bbox, childBBox)) this._all(child, result);
4651                     else nodesToSearch.push(child);
4652                 }
4653             }
4654             node = nodesToSearch.pop();
4655         }
4656
4657         return result;
4658     },
4659
4660     collides: function (bbox) {
4661
4662         var node = this.data,
4663             toBBox = this.toBBox;
4664
4665         if (!intersects(bbox, node)) return false;
4666
4667         var nodesToSearch = [],
4668             i, len, child, childBBox;
4669
4670         while (node) {
4671             for (i = 0, len = node.children.length; i < len; i++) {
4672
4673                 child = node.children[i];
4674                 childBBox = node.leaf ? toBBox(child) : child;
4675
4676                 if (intersects(bbox, childBBox)) {
4677                     if (node.leaf || contains(bbox, childBBox)) return true;
4678                     nodesToSearch.push(child);
4679                 }
4680             }
4681             node = nodesToSearch.pop();
4682         }
4683
4684         return false;
4685     },
4686
4687     load: function (data) {
4688         if (!(data && data.length)) return this;
4689
4690         if (data.length < this._minEntries) {
4691             for (var i = 0, len = data.length; i < len; i++) {
4692                 this.insert(data[i]);
4693             }
4694             return this;
4695         }
4696
4697         // recursively build the tree with the given data from stratch using OMT algorithm
4698         var node = this._build(data.slice(), 0, data.length - 1, 0);
4699
4700         if (!this.data.children.length) {
4701             // save as is if tree is empty
4702             this.data = node;
4703
4704         } else if (this.data.height === node.height) {
4705             // split root if trees have the same height
4706             this._splitRoot(this.data, node);
4707
4708         } else {
4709             if (this.data.height < node.height) {
4710                 // swap trees if inserted one is bigger
4711                 var tmpNode = this.data;
4712                 this.data = node;
4713                 node = tmpNode;
4714             }
4715
4716             // insert the small tree into the large tree at appropriate level
4717             this._insert(node, this.data.height - node.height - 1, true);
4718         }
4719
4720         return this;
4721     },
4722
4723     insert: function (item) {
4724         if (item) this._insert(item, this.data.height - 1);
4725         return this;
4726     },
4727
4728     clear: function () {
4729         this.data = createNode([]);
4730         return this;
4731     },
4732
4733     remove: function (item, equalsFn) {
4734         if (!item) return this;
4735
4736         var node = this.data,
4737             bbox = this.toBBox(item),
4738             path = [],
4739             indexes = [],
4740             i, parent, index, goingUp;
4741
4742         // depth-first iterative tree traversal
4743         while (node || path.length) {
4744
4745             if (!node) { // go up
4746                 node = path.pop();
4747                 parent = path[path.length - 1];
4748                 i = indexes.pop();
4749                 goingUp = true;
4750             }
4751
4752             if (node.leaf) { // check current node
4753                 index = findItem(item, node.children, equalsFn);
4754
4755                 if (index !== -1) {
4756                     // item found, remove the item and condense tree upwards
4757                     node.children.splice(index, 1);
4758                     path.push(node);
4759                     this._condense(path);
4760                     return this;
4761                 }
4762             }
4763
4764             if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
4765                 path.push(node);
4766                 indexes.push(i);
4767                 i = 0;
4768                 parent = node;
4769                 node = node.children[0];
4770
4771             } else if (parent) { // go right
4772                 i++;
4773                 node = parent.children[i];
4774                 goingUp = false;
4775
4776             } else node = null; // nothing found
4777         }
4778
4779         return this;
4780     },
4781
4782     toBBox: function (item) { return item; },
4783
4784     compareMinX: compareNodeMinX,
4785     compareMinY: compareNodeMinY,
4786
4787     toJSON: function () { return this.data; },
4788
4789     fromJSON: function (data) {
4790         this.data = data;
4791         return this;
4792     },
4793
4794     _all: function (node, result) {
4795         var nodesToSearch = [];
4796         while (node) {
4797             if (node.leaf) result.push.apply(result, node.children);
4798             else nodesToSearch.push.apply(nodesToSearch, node.children);
4799
4800             node = nodesToSearch.pop();
4801         }
4802         return result;
4803     },
4804
4805     _build: function (items, left, right, height) {
4806
4807         var N = right - left + 1,
4808             M = this._maxEntries,
4809             node;
4810
4811         if (N <= M) {
4812             // reached leaf level; return leaf
4813             node = createNode(items.slice(left, right + 1));
4814             calcBBox(node, this.toBBox);
4815             return node;
4816         }
4817
4818         if (!height) {
4819             // target height of the bulk-loaded tree
4820             height = Math.ceil(Math.log(N) / Math.log(M));
4821
4822             // target number of root entries to maximize storage utilization
4823             M = Math.ceil(N / Math.pow(M, height - 1));
4824         }
4825
4826         node = createNode([]);
4827         node.leaf = false;
4828         node.height = height;
4829
4830         // split the items into M mostly square tiles
4831
4832         var N2 = Math.ceil(N / M),
4833             N1 = N2 * Math.ceil(Math.sqrt(M)),
4834             i, j, right2, right3;
4835
4836         multiSelect(items, left, right, N1, this.compareMinX);
4837
4838         for (i = left; i <= right; i += N1) {
4839
4840             right2 = Math.min(i + N1 - 1, right);
4841
4842             multiSelect(items, i, right2, N2, this.compareMinY);
4843
4844             for (j = i; j <= right2; j += N2) {
4845
4846                 right3 = Math.min(j + N2 - 1, right2);
4847
4848                 // pack each entry recursively
4849                 node.children.push(this._build(items, j, right3, height - 1));
4850             }
4851         }
4852
4853         calcBBox(node, this.toBBox);
4854
4855         return node;
4856     },
4857
4858     _chooseSubtree: function (bbox, node, level, path) {
4859
4860         var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
4861
4862         while (true) {
4863             path.push(node);
4864
4865             if (node.leaf || path.length - 1 === level) break;
4866
4867             minArea = minEnlargement = Infinity;
4868
4869             for (i = 0, len = node.children.length; i < len; i++) {
4870                 child = node.children[i];
4871                 area = bboxArea(child);
4872                 enlargement = enlargedArea(bbox, child) - area;
4873
4874                 // choose entry with the least area enlargement
4875                 if (enlargement < minEnlargement) {
4876                     minEnlargement = enlargement;
4877                     minArea = area < minArea ? area : minArea;
4878                     targetNode = child;
4879
4880                 } else if (enlargement === minEnlargement) {
4881                     // otherwise choose one with the smallest area
4882                     if (area < minArea) {
4883                         minArea = area;
4884                         targetNode = child;
4885                     }
4886                 }
4887             }
4888
4889             node = targetNode || node.children[0];
4890         }
4891
4892         return node;
4893     },
4894
4895     _insert: function (item, level, isNode) {
4896
4897         var toBBox = this.toBBox,
4898             bbox = isNode ? item : toBBox(item),
4899             insertPath = [];
4900
4901         // find the best node for accommodating the item, saving all nodes along the path too
4902         var node = this._chooseSubtree(bbox, this.data, level, insertPath);
4903
4904         // put the item into the node
4905         node.children.push(item);
4906         extend(node, bbox);
4907
4908         // split on node overflow; propagate upwards if necessary
4909         while (level >= 0) {
4910             if (insertPath[level].children.length > this._maxEntries) {
4911                 this._split(insertPath, level);
4912                 level--;
4913             } else break;
4914         }
4915
4916         // adjust bboxes along the insertion path
4917         this._adjustParentBBoxes(bbox, insertPath, level);
4918     },
4919
4920     // split overflowed node into two
4921     _split: function (insertPath, level) {
4922
4923         var node = insertPath[level],
4924             M = node.children.length,
4925             m = this._minEntries;
4926
4927         this._chooseSplitAxis(node, m, M);
4928
4929         var splitIndex = this._chooseSplitIndex(node, m, M);
4930
4931         var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
4932         newNode.height = node.height;
4933         newNode.leaf = node.leaf;
4934
4935         calcBBox(node, this.toBBox);
4936         calcBBox(newNode, this.toBBox);
4937
4938         if (level) insertPath[level - 1].children.push(newNode);
4939         else this._splitRoot(node, newNode);
4940     },
4941
4942     _splitRoot: function (node, newNode) {
4943         // split root node
4944         this.data = createNode([node, newNode]);
4945         this.data.height = node.height + 1;
4946         this.data.leaf = false;
4947         calcBBox(this.data, this.toBBox);
4948     },
4949
4950     _chooseSplitIndex: function (node, m, M) {
4951
4952         var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
4953
4954         minOverlap = minArea = Infinity;
4955
4956         for (i = m; i <= M - m; i++) {
4957             bbox1 = distBBox(node, 0, i, this.toBBox);
4958             bbox2 = distBBox(node, i, M, this.toBBox);
4959
4960             overlap = intersectionArea(bbox1, bbox2);
4961             area = bboxArea(bbox1) + bboxArea(bbox2);
4962
4963             // choose distribution with minimum overlap
4964             if (overlap < minOverlap) {
4965                 minOverlap = overlap;
4966                 index = i;
4967
4968                 minArea = area < minArea ? area : minArea;
4969
4970             } else if (overlap === minOverlap) {
4971                 // otherwise choose distribution with minimum area
4972                 if (area < minArea) {
4973                     minArea = area;
4974                     index = i;
4975                 }
4976             }
4977         }
4978
4979         return index;
4980     },
4981
4982     // sorts node children by the best axis for split
4983     _chooseSplitAxis: function (node, m, M) {
4984
4985         var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
4986             compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
4987             xMargin = this._allDistMargin(node, m, M, compareMinX),
4988             yMargin = this._allDistMargin(node, m, M, compareMinY);
4989
4990         // if total distributions margin value is minimal for x, sort by minX,
4991         // otherwise it's already sorted by minY
4992         if (xMargin < yMargin) node.children.sort(compareMinX);
4993     },
4994
4995     // total margin of all possible split distributions where each node is at least m full
4996     _allDistMargin: function (node, m, M, compare) {
4997
4998         node.children.sort(compare);
4999
5000         var toBBox = this.toBBox,
5001             leftBBox = distBBox(node, 0, m, toBBox),
5002             rightBBox = distBBox(node, M - m, M, toBBox),
5003             margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
5004             i, child;
5005
5006         for (i = m; i < M - m; i++) {
5007             child = node.children[i];
5008             extend(leftBBox, node.leaf ? toBBox(child) : child);
5009             margin += bboxMargin(leftBBox);
5010         }
5011
5012         for (i = M - m - 1; i >= m; i--) {
5013             child = node.children[i];
5014             extend(rightBBox, node.leaf ? toBBox(child) : child);
5015             margin += bboxMargin(rightBBox);
5016         }
5017
5018         return margin;
5019     },
5020
5021     _adjustParentBBoxes: function (bbox, path, level) {
5022         // adjust bboxes along the given tree path
5023         for (var i = level; i >= 0; i--) {
5024             extend(path[i], bbox);
5025         }
5026     },
5027
5028     _condense: function (path) {
5029         // go through the path, removing empty nodes and updating bboxes
5030         for (var i = path.length - 1, siblings; i >= 0; i--) {
5031             if (path[i].children.length === 0) {
5032                 if (i > 0) {
5033                     siblings = path[i - 1].children;
5034                     siblings.splice(siblings.indexOf(path[i]), 1);
5035
5036                 } else this.clear();
5037
5038             } else calcBBox(path[i], this.toBBox);
5039         }
5040     },
5041
5042     _initFormat: function (format) {
5043         // data format (minX, minY, maxX, maxY accessors)
5044
5045         // uses eval-type function compilation instead of just accepting a toBBox function
5046         // because the algorithms are very sensitive to sorting functions performance,
5047         // so they should be dead simple and without inner calls
5048
5049         var compareArr = ['return a', ' - b', ';'];
5050
5051         this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
5052         this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
5053
5054         this.toBBox = new Function('a',
5055             'return {minX: a' + format[0] +
5056             ', minY: a' + format[1] +
5057             ', maxX: a' + format[2] +
5058             ', maxY: a' + format[3] + '};');
5059     }
5060 };
5061
5062 function findItem(item, items, equalsFn) {
5063     if (!equalsFn) return items.indexOf(item);
5064
5065     for (var i = 0; i < items.length; i++) {
5066         if (equalsFn(item, items[i])) return i;
5067     }
5068     return -1;
5069 }
5070
5071 // calculate node's bbox from bboxes of its children
5072 function calcBBox(node, toBBox) {
5073     distBBox(node, 0, node.children.length, toBBox, node);
5074 }
5075
5076 // min bounding rectangle of node children from k to p-1
5077 function distBBox(node, k, p, toBBox, destNode) {
5078     if (!destNode) destNode = createNode(null);
5079     destNode.minX = Infinity;
5080     destNode.minY = Infinity;
5081     destNode.maxX = -Infinity;
5082     destNode.maxY = -Infinity;
5083
5084     for (var i = k, child; i < p; i++) {
5085         child = node.children[i];
5086         extend(destNode, node.leaf ? toBBox(child) : child);
5087     }
5088
5089     return destNode;
5090 }
5091
5092 function extend(a, b) {
5093     a.minX = Math.min(a.minX, b.minX);
5094     a.minY = Math.min(a.minY, b.minY);
5095     a.maxX = Math.max(a.maxX, b.maxX);
5096     a.maxY = Math.max(a.maxY, b.maxY);
5097     return a;
5098 }
5099
5100 function compareNodeMinX(a, b) { return a.minX - b.minX; }
5101 function compareNodeMinY(a, b) { return a.minY - b.minY; }
5102
5103 function bboxArea(a)   { return (a.maxX - a.minX) * (a.maxY - a.minY); }
5104 function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
5105
5106 function enlargedArea(a, b) {
5107     return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
5108            (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
5109 }
5110
5111 function intersectionArea(a, b) {
5112     var minX = Math.max(a.minX, b.minX),
5113         minY = Math.max(a.minY, b.minY),
5114         maxX = Math.min(a.maxX, b.maxX),
5115         maxY = Math.min(a.maxY, b.maxY);
5116
5117     return Math.max(0, maxX - minX) *
5118            Math.max(0, maxY - minY);
5119 }
5120
5121 function contains(a, b) {
5122     return a.minX <= b.minX &&
5123            a.minY <= b.minY &&
5124            b.maxX <= a.maxX &&
5125            b.maxY <= a.maxY;
5126 }
5127
5128 function intersects(a, b) {
5129     return b.minX <= a.maxX &&
5130            b.minY <= a.maxY &&
5131            b.maxX >= a.minX &&
5132            b.maxY >= a.minY;
5133 }
5134
5135 function createNode(children) {
5136     return {
5137         children: children,
5138         height: 1,
5139         leaf: true,
5140         minX: Infinity,
5141         minY: Infinity,
5142         maxX: -Infinity,
5143         maxY: -Infinity
5144     };
5145 }
5146
5147 // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
5148 // combines selection algorithm with binary divide & conquer approach
5149
5150 function multiSelect(arr, left, right, n, compare) {
5151     var stack = [left, right],
5152         mid;
5153
5154     while (stack.length) {
5155         right = stack.pop();
5156         left = stack.pop();
5157
5158         if (right - left <= n) continue;
5159
5160         mid = left + Math.ceil((right - left) / n / 2) * n;
5161         quickselect(arr, mid, left, right, compare);
5162
5163         stack.push(left, mid, mid, right);
5164     }
5165 }
5166
5167 },{"quickselect":23}],25:[function(require,module,exports){
5168 "use strict";
5169 var __extends = (this && this.__extends) || function (d, b) {
5170     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5171     function __() { this.constructor = d; }
5172     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5173 };
5174 var Subject_1 = require('./Subject');
5175 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5176 /**
5177  * @class BehaviorSubject<T>
5178  */
5179 var BehaviorSubject = (function (_super) {
5180     __extends(BehaviorSubject, _super);
5181     function BehaviorSubject(_value) {
5182         _super.call(this);
5183         this._value = _value;
5184     }
5185     Object.defineProperty(BehaviorSubject.prototype, "value", {
5186         get: function () {
5187             return this.getValue();
5188         },
5189         enumerable: true,
5190         configurable: true
5191     });
5192     BehaviorSubject.prototype._subscribe = function (subscriber) {
5193         var subscription = _super.prototype._subscribe.call(this, subscriber);
5194         if (subscription && !subscription.closed) {
5195             subscriber.next(this._value);
5196         }
5197         return subscription;
5198     };
5199     BehaviorSubject.prototype.getValue = function () {
5200         if (this.hasError) {
5201             throw this.thrownError;
5202         }
5203         else if (this.closed) {
5204             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5205         }
5206         else {
5207             return this._value;
5208         }
5209     };
5210     BehaviorSubject.prototype.next = function (value) {
5211         _super.prototype.next.call(this, this._value = value);
5212     };
5213     return BehaviorSubject;
5214 }(Subject_1.Subject));
5215 exports.BehaviorSubject = BehaviorSubject;
5216
5217 },{"./Subject":33,"./util/ObjectUnsubscribedError":148}],26:[function(require,module,exports){
5218 "use strict";
5219 var __extends = (this && this.__extends) || function (d, b) {
5220     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5221     function __() { this.constructor = d; }
5222     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5223 };
5224 var Subscriber_1 = require('./Subscriber');
5225 /**
5226  * We need this JSDoc comment for affecting ESDoc.
5227  * @ignore
5228  * @extends {Ignored}
5229  */
5230 var InnerSubscriber = (function (_super) {
5231     __extends(InnerSubscriber, _super);
5232     function InnerSubscriber(parent, outerValue, outerIndex) {
5233         _super.call(this);
5234         this.parent = parent;
5235         this.outerValue = outerValue;
5236         this.outerIndex = outerIndex;
5237         this.index = 0;
5238     }
5239     InnerSubscriber.prototype._next = function (value) {
5240         this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
5241     };
5242     InnerSubscriber.prototype._error = function (error) {
5243         this.parent.notifyError(error, this);
5244         this.unsubscribe();
5245     };
5246     InnerSubscriber.prototype._complete = function () {
5247         this.parent.notifyComplete(this);
5248         this.unsubscribe();
5249     };
5250     return InnerSubscriber;
5251 }(Subscriber_1.Subscriber));
5252 exports.InnerSubscriber = InnerSubscriber;
5253
5254 },{"./Subscriber":35}],27:[function(require,module,exports){
5255 "use strict";
5256 var Observable_1 = require('./Observable');
5257 /**
5258  * Represents a push-based event or value that an {@link Observable} can emit.
5259  * This class is particularly useful for operators that manage notifications,
5260  * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and
5261  * others. Besides wrapping the actual delivered value, it also annotates it
5262  * with metadata of, for instance, what type of push message it is (`next`,
5263  * `error`, or `complete`).
5264  *
5265  * @see {@link materialize}
5266  * @see {@link dematerialize}
5267  * @see {@link observeOn}
5268  *
5269  * @class Notification<T>
5270  */
5271 var Notification = (function () {
5272     function Notification(kind, value, exception) {
5273         this.kind = kind;
5274         this.value = value;
5275         this.exception = exception;
5276         this.hasValue = kind === 'N';
5277     }
5278     /**
5279      * Delivers to the given `observer` the value wrapped by this Notification.
5280      * @param {Observer} observer
5281      * @return
5282      */
5283     Notification.prototype.observe = function (observer) {
5284         switch (this.kind) {
5285             case 'N':
5286                 return observer.next && observer.next(this.value);
5287             case 'E':
5288                 return observer.error && observer.error(this.exception);
5289             case 'C':
5290                 return observer.complete && observer.complete();
5291         }
5292     };
5293     /**
5294      * Given some {@link Observer} callbacks, deliver the value represented by the
5295      * current Notification to the correctly corresponding callback.
5296      * @param {function(value: T): void} next An Observer `next` callback.
5297      * @param {function(err: any): void} [error] An Observer `error` callback.
5298      * @param {function(): void} [complete] An Observer `complete` callback.
5299      * @return {any}
5300      */
5301     Notification.prototype.do = function (next, error, complete) {
5302         var kind = this.kind;
5303         switch (kind) {
5304             case 'N':
5305                 return next && next(this.value);
5306             case 'E':
5307                 return error && error(this.exception);
5308             case 'C':
5309                 return complete && complete();
5310         }
5311     };
5312     /**
5313      * Takes an Observer or its individual callback functions, and calls `observe`
5314      * or `do` methods accordingly.
5315      * @param {Observer|function(value: T): void} nextOrObserver An Observer or
5316      * the `next` callback.
5317      * @param {function(err: any): void} [error] An Observer `error` callback.
5318      * @param {function(): void} [complete] An Observer `complete` callback.
5319      * @return {any}
5320      */
5321     Notification.prototype.accept = function (nextOrObserver, error, complete) {
5322         if (nextOrObserver && typeof nextOrObserver.next === 'function') {
5323             return this.observe(nextOrObserver);
5324         }
5325         else {
5326             return this.do(nextOrObserver, error, complete);
5327         }
5328     };
5329     /**
5330      * Returns a simple Observable that just delivers the notification represented
5331      * by this Notification instance.
5332      * @return {any}
5333      */
5334     Notification.prototype.toObservable = function () {
5335         var kind = this.kind;
5336         switch (kind) {
5337             case 'N':
5338                 return Observable_1.Observable.of(this.value);
5339             case 'E':
5340                 return Observable_1.Observable.throw(this.exception);
5341             case 'C':
5342                 return Observable_1.Observable.empty();
5343         }
5344         throw new Error('unexpected notification kind value');
5345     };
5346     /**
5347      * A shortcut to create a Notification instance of the type `next` from a
5348      * given value.
5349      * @param {T} value The `next` value.
5350      * @return {Notification<T>} The "next" Notification representing the
5351      * argument.
5352      */
5353     Notification.createNext = function (value) {
5354         if (typeof value !== 'undefined') {
5355             return new Notification('N', value);
5356         }
5357         return this.undefinedValueNotification;
5358     };
5359     /**
5360      * A shortcut to create a Notification instance of the type `error` from a
5361      * given error.
5362      * @param {any} [err] The `error` exception.
5363      * @return {Notification<T>} The "error" Notification representing the
5364      * argument.
5365      */
5366     Notification.createError = function (err) {
5367         return new Notification('E', undefined, err);
5368     };
5369     /**
5370      * A shortcut to create a Notification instance of the type `complete`.
5371      * @return {Notification<any>} The valueless "complete" Notification.
5372      */
5373     Notification.createComplete = function () {
5374         return this.completeNotification;
5375     };
5376     Notification.completeNotification = new Notification('C');
5377     Notification.undefinedValueNotification = new Notification('N', undefined);
5378     return Notification;
5379 }());
5380 exports.Notification = Notification;
5381
5382 },{"./Observable":28}],28:[function(require,module,exports){
5383 "use strict";
5384 var root_1 = require('./util/root');
5385 var toSubscriber_1 = require('./util/toSubscriber');
5386 var observable_1 = require('./symbol/observable');
5387 /**
5388  * A representation of any set of values over any amount of time. This the most basic building block
5389  * of RxJS.
5390  *
5391  * @class Observable<T>
5392  */
5393 var Observable = (function () {
5394     /**
5395      * @constructor
5396      * @param {Function} subscribe the function that is  called when the Observable is
5397      * initially subscribed to. This function is given a Subscriber, to which new values
5398      * can be `next`ed, or an `error` method can be called to raise an error, or
5399      * `complete` can be called to notify of a successful completion.
5400      */
5401     function Observable(subscribe) {
5402         this._isScalar = false;
5403         if (subscribe) {
5404             this._subscribe = subscribe;
5405         }
5406     }
5407     /**
5408      * Creates a new Observable, with this Observable as the source, and the passed
5409      * operator defined as the new observable's operator.
5410      * @method lift
5411      * @param {Operator} operator the operator defining the operation to take on the observable
5412      * @return {Observable} a new observable with the Operator applied
5413      */
5414     Observable.prototype.lift = function (operator) {
5415         var observable = new Observable();
5416         observable.source = this;
5417         observable.operator = operator;
5418         return observable;
5419     };
5420     /**
5421      * Registers handlers for handling emitted values, error and completions from the observable, and
5422      *  executes the observable's subscriber function, which will take action to set up the underlying data stream
5423      * @method subscribe
5424      * @param {PartialObserver|Function} observerOrNext (optional) either an observer defining all functions to be called,
5425      *  or the first of three possible handlers, which is the handler for each value emitted from the observable.
5426      * @param {Function} error (optional) a handler for a terminal event resulting from an error. If no error handler is provided,
5427      *  the error will be thrown as unhandled
5428      * @param {Function} complete (optional) a handler for a terminal event resulting from successful completion.
5429      * @return {ISubscription} a subscription reference to the registered handlers
5430      */
5431     Observable.prototype.subscribe = function (observerOrNext, error, complete) {
5432         var operator = this.operator;
5433         var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
5434         if (operator) {
5435             operator.call(sink, this);
5436         }
5437         else {
5438             sink.add(this._subscribe(sink));
5439         }
5440         if (sink.syncErrorThrowable) {
5441             sink.syncErrorThrowable = false;
5442             if (sink.syncErrorThrown) {
5443                 throw sink.syncErrorValue;
5444             }
5445         }
5446         return sink;
5447     };
5448     /**
5449      * @method forEach
5450      * @param {Function} next a handler for each value emitted by the observable
5451      * @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
5452      * @return {Promise} a promise that either resolves on observable completion or
5453      *  rejects with the handled error
5454      */
5455     Observable.prototype.forEach = function (next, PromiseCtor) {
5456         var _this = this;
5457         if (!PromiseCtor) {
5458             if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
5459                 PromiseCtor = root_1.root.Rx.config.Promise;
5460             }
5461             else if (root_1.root.Promise) {
5462                 PromiseCtor = root_1.root.Promise;
5463             }
5464         }
5465         if (!PromiseCtor) {
5466             throw new Error('no Promise impl found');
5467         }
5468         return new PromiseCtor(function (resolve, reject) {
5469             var subscription = _this.subscribe(function (value) {
5470                 if (subscription) {
5471                     // if there is a subscription, then we can surmise
5472                     // the next handling is asynchronous. Any errors thrown
5473                     // need to be rejected explicitly and unsubscribe must be
5474                     // called manually
5475                     try {
5476                         next(value);
5477                     }
5478                     catch (err) {
5479                         reject(err);
5480                         subscription.unsubscribe();
5481                     }
5482                 }
5483                 else {
5484                     // if there is NO subscription, then we're getting a nexted
5485                     // value synchronously during subscription. We can just call it.
5486                     // If it errors, Observable's `subscribe` will ensure the
5487                     // unsubscription logic is called, then synchronously rethrow the error.
5488                     // After that, Promise will trap the error and send it
5489                     // down the rejection path.
5490                     next(value);
5491                 }
5492             }, reject, resolve);
5493         });
5494     };
5495     Observable.prototype._subscribe = function (subscriber) {
5496         return this.source.subscribe(subscriber);
5497     };
5498     /**
5499      * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
5500      * @method Symbol.observable
5501      * @return {Observable} this instance of the observable
5502      */
5503     Observable.prototype[observable_1.$$observable] = function () {
5504         return this;
5505     };
5506     // HACK: Since TypeScript inherits static properties too, we have to
5507     // fight against TypeScript here so Subject can have a different static create signature
5508     /**
5509      * Creates a new cold Observable by calling the Observable constructor
5510      * @static true
5511      * @owner Observable
5512      * @method create
5513      * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
5514      * @return {Observable} a new cold observable
5515      */
5516     Observable.create = function (subscribe) {
5517         return new Observable(subscribe);
5518     };
5519     return Observable;
5520 }());
5521 exports.Observable = Observable;
5522
5523 },{"./symbol/observable":143,"./util/root":156,"./util/toSubscriber":158}],29:[function(require,module,exports){
5524 "use strict";
5525 exports.empty = {
5526     closed: true,
5527     next: function (value) { },
5528     error: function (err) { throw err; },
5529     complete: function () { }
5530 };
5531
5532 },{}],30:[function(require,module,exports){
5533 "use strict";
5534 var __extends = (this && this.__extends) || function (d, b) {
5535     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5536     function __() { this.constructor = d; }
5537     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5538 };
5539 var Subscriber_1 = require('./Subscriber');
5540 /**
5541  * We need this JSDoc comment for affecting ESDoc.
5542  * @ignore
5543  * @extends {Ignored}
5544  */
5545 var OuterSubscriber = (function (_super) {
5546     __extends(OuterSubscriber, _super);
5547     function OuterSubscriber() {
5548         _super.apply(this, arguments);
5549     }
5550     OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
5551         this.destination.next(innerValue);
5552     };
5553     OuterSubscriber.prototype.notifyError = function (error, innerSub) {
5554         this.destination.error(error);
5555     };
5556     OuterSubscriber.prototype.notifyComplete = function (innerSub) {
5557         this.destination.complete();
5558     };
5559     return OuterSubscriber;
5560 }(Subscriber_1.Subscriber));
5561 exports.OuterSubscriber = OuterSubscriber;
5562
5563 },{"./Subscriber":35}],31:[function(require,module,exports){
5564 "use strict";
5565 var __extends = (this && this.__extends) || function (d, b) {
5566     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5567     function __() { this.constructor = d; }
5568     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5569 };
5570 var Subject_1 = require('./Subject');
5571 var queue_1 = require('./scheduler/queue');
5572 var observeOn_1 = require('./operator/observeOn');
5573 /**
5574  * @class ReplaySubject<T>
5575  */
5576 var ReplaySubject = (function (_super) {
5577     __extends(ReplaySubject, _super);
5578     function ReplaySubject(bufferSize, windowTime, scheduler) {
5579         if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
5580         if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
5581         _super.call(this);
5582         this.scheduler = scheduler;
5583         this._events = [];
5584         this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
5585         this._windowTime = windowTime < 1 ? 1 : windowTime;
5586     }
5587     ReplaySubject.prototype.next = function (value) {
5588         var now = this._getNow();
5589         this._events.push(new ReplayEvent(now, value));
5590         this._trimBufferThenGetEvents();
5591         _super.prototype.next.call(this, value);
5592     };
5593     ReplaySubject.prototype._subscribe = function (subscriber) {
5594         var _events = this._trimBufferThenGetEvents();
5595         var scheduler = this.scheduler;
5596         if (scheduler) {
5597             subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler));
5598         }
5599         var len = _events.length;
5600         for (var i = 0; i < len && !subscriber.closed; i++) {
5601             subscriber.next(_events[i].value);
5602         }
5603         return _super.prototype._subscribe.call(this, subscriber);
5604     };
5605     ReplaySubject.prototype._getNow = function () {
5606         return (this.scheduler || queue_1.queue).now();
5607     };
5608     ReplaySubject.prototype._trimBufferThenGetEvents = function () {
5609         var now = this._getNow();
5610         var _bufferSize = this._bufferSize;
5611         var _windowTime = this._windowTime;
5612         var _events = this._events;
5613         var eventsCount = _events.length;
5614         var spliceCount = 0;
5615         // Trim events that fall out of the time window.
5616         // Start at the front of the list. Break early once
5617         // we encounter an event that falls within the window.
5618         while (spliceCount < eventsCount) {
5619             if ((now - _events[spliceCount].time) < _windowTime) {
5620                 break;
5621             }
5622             spliceCount++;
5623         }
5624         if (eventsCount > _bufferSize) {
5625             spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
5626         }
5627         if (spliceCount > 0) {
5628             _events.splice(0, spliceCount);
5629         }
5630         return _events;
5631     };
5632     return ReplaySubject;
5633 }(Subject_1.Subject));
5634 exports.ReplaySubject = ReplaySubject;
5635 var ReplayEvent = (function () {
5636     function ReplayEvent(time, value) {
5637         this.time = time;
5638         this.value = value;
5639     }
5640     return ReplayEvent;
5641 }());
5642
5643 },{"./Subject":33,"./operator/observeOn":120,"./scheduler/queue":141}],32:[function(require,module,exports){
5644 "use strict";
5645 /**
5646  * An execution context and a data structure to order tasks and schedule their
5647  * execution. Provides a notion of (potentially virtual) time, through the
5648  * `now()` getter method.
5649  *
5650  * Each unit of work in a Scheduler is called an {@link Action}.
5651  *
5652  * ```ts
5653  * class Scheduler {
5654  *   now(): number;
5655  *   schedule(work, delay?, state?): Subscription;
5656  * }
5657  * ```
5658  *
5659  * @class Scheduler
5660  */
5661 var Scheduler = (function () {
5662     function Scheduler(SchedulerAction, now) {
5663         if (now === void 0) { now = Scheduler.now; }
5664         this.SchedulerAction = SchedulerAction;
5665         this.now = now;
5666     }
5667     /**
5668      * Schedules a function, `work`, for execution. May happen at some point in
5669      * the future, according to the `delay` parameter, if specified. May be passed
5670      * some context object, `state`, which will be passed to the `work` function.
5671      *
5672      * The given arguments will be processed an stored as an Action object in a
5673      * queue of actions.
5674      *
5675      * @param {function(state: ?T): ?Subscription} work A function representing a
5676      * task, or some unit of work to be executed by the Scheduler.
5677      * @param {number} [delay] Time to wait before executing the work, where the
5678      * time unit is implicit and defined by the Scheduler itself.
5679      * @param {T} [state] Some contextual data that the `work` function uses when
5680      * called by the Scheduler.
5681      * @return {Subscription} A subscription in order to be able to unsubscribe
5682      * the scheduled work.
5683      */
5684     Scheduler.prototype.schedule = function (work, delay, state) {
5685         if (delay === void 0) { delay = 0; }
5686         return new this.SchedulerAction(this, work).schedule(state, delay);
5687     };
5688     Scheduler.now = Date.now ? Date.now : function () { return +new Date(); };
5689     return Scheduler;
5690 }());
5691 exports.Scheduler = Scheduler;
5692
5693 },{}],33:[function(require,module,exports){
5694 "use strict";
5695 var __extends = (this && this.__extends) || function (d, b) {
5696     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5697     function __() { this.constructor = d; }
5698     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5699 };
5700 var Observable_1 = require('./Observable');
5701 var Subscriber_1 = require('./Subscriber');
5702 var Subscription_1 = require('./Subscription');
5703 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5704 var SubjectSubscription_1 = require('./SubjectSubscription');
5705 var rxSubscriber_1 = require('./symbol/rxSubscriber');
5706 /**
5707  * @class SubjectSubscriber<T>
5708  */
5709 var SubjectSubscriber = (function (_super) {
5710     __extends(SubjectSubscriber, _super);
5711     function SubjectSubscriber(destination) {
5712         _super.call(this, destination);
5713         this.destination = destination;
5714     }
5715     return SubjectSubscriber;
5716 }(Subscriber_1.Subscriber));
5717 exports.SubjectSubscriber = SubjectSubscriber;
5718 /**
5719  * @class Subject<T>
5720  */
5721 var Subject = (function (_super) {
5722     __extends(Subject, _super);
5723     function Subject() {
5724         _super.call(this);
5725         this.observers = [];
5726         this.closed = false;
5727         this.isStopped = false;
5728         this.hasError = false;
5729         this.thrownError = null;
5730     }
5731     Subject.prototype[rxSubscriber_1.$$rxSubscriber] = function () {
5732         return new SubjectSubscriber(this);
5733     };
5734     Subject.prototype.lift = function (operator) {
5735         var subject = new AnonymousSubject(this, this);
5736         subject.operator = operator;
5737         return subject;
5738     };
5739     Subject.prototype.next = function (value) {
5740         if (this.closed) {
5741             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5742         }
5743         if (!this.isStopped) {
5744             var observers = this.observers;
5745             var len = observers.length;
5746             var copy = observers.slice();
5747             for (var i = 0; i < len; i++) {
5748                 copy[i].next(value);
5749             }
5750         }
5751     };
5752     Subject.prototype.error = function (err) {
5753         if (this.closed) {
5754             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5755         }
5756         this.hasError = true;
5757         this.thrownError = err;
5758         this.isStopped = true;
5759         var observers = this.observers;
5760         var len = observers.length;
5761         var copy = observers.slice();
5762         for (var i = 0; i < len; i++) {
5763             copy[i].error(err);
5764         }
5765         this.observers.length = 0;
5766     };
5767     Subject.prototype.complete = function () {
5768         if (this.closed) {
5769             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5770         }
5771         this.isStopped = true;
5772         var observers = this.observers;
5773         var len = observers.length;
5774         var copy = observers.slice();
5775         for (var i = 0; i < len; i++) {
5776             copy[i].complete();
5777         }
5778         this.observers.length = 0;
5779     };
5780     Subject.prototype.unsubscribe = function () {
5781         this.isStopped = true;
5782         this.closed = true;
5783         this.observers = null;
5784     };
5785     Subject.prototype._subscribe = function (subscriber) {
5786         if (this.closed) {
5787             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5788         }
5789         else if (this.hasError) {
5790             subscriber.error(this.thrownError);
5791             return Subscription_1.Subscription.EMPTY;
5792         }
5793         else if (this.isStopped) {
5794             subscriber.complete();
5795             return Subscription_1.Subscription.EMPTY;
5796         }
5797         else {
5798             this.observers.push(subscriber);
5799             return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
5800         }
5801     };
5802     Subject.prototype.asObservable = function () {
5803         var observable = new Observable_1.Observable();
5804         observable.source = this;
5805         return observable;
5806     };
5807     Subject.create = function (destination, source) {
5808         return new AnonymousSubject(destination, source);
5809     };
5810     return Subject;
5811 }(Observable_1.Observable));
5812 exports.Subject = Subject;
5813 /**
5814  * @class AnonymousSubject<T>
5815  */
5816 var AnonymousSubject = (function (_super) {
5817     __extends(AnonymousSubject, _super);
5818     function AnonymousSubject(destination, source) {
5819         _super.call(this);
5820         this.destination = destination;
5821         this.source = source;
5822     }
5823     AnonymousSubject.prototype.next = function (value) {
5824         var destination = this.destination;
5825         if (destination && destination.next) {
5826             destination.next(value);
5827         }
5828     };
5829     AnonymousSubject.prototype.error = function (err) {
5830         var destination = this.destination;
5831         if (destination && destination.error) {
5832             this.destination.error(err);
5833         }
5834     };
5835     AnonymousSubject.prototype.complete = function () {
5836         var destination = this.destination;
5837         if (destination && destination.complete) {
5838             this.destination.complete();
5839         }
5840     };
5841     AnonymousSubject.prototype._subscribe = function (subscriber) {
5842         var source = this.source;
5843         if (source) {
5844             return this.source.subscribe(subscriber);
5845         }
5846         else {
5847             return Subscription_1.Subscription.EMPTY;
5848         }
5849     };
5850     return AnonymousSubject;
5851 }(Subject));
5852 exports.AnonymousSubject = AnonymousSubject;
5853
5854 },{"./Observable":28,"./SubjectSubscription":34,"./Subscriber":35,"./Subscription":36,"./symbol/rxSubscriber":144,"./util/ObjectUnsubscribedError":148}],34:[function(require,module,exports){
5855 "use strict";
5856 var __extends = (this && this.__extends) || function (d, b) {
5857     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5858     function __() { this.constructor = d; }
5859     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5860 };
5861 var Subscription_1 = require('./Subscription');
5862 /**
5863  * We need this JSDoc comment for affecting ESDoc.
5864  * @ignore
5865  * @extends {Ignored}
5866  */
5867 var SubjectSubscription = (function (_super) {
5868     __extends(SubjectSubscription, _super);
5869     function SubjectSubscription(subject, subscriber) {
5870         _super.call(this);
5871         this.subject = subject;
5872         this.subscriber = subscriber;
5873         this.closed = false;
5874     }
5875     SubjectSubscription.prototype.unsubscribe = function () {
5876         if (this.closed) {
5877             return;
5878         }
5879         this.closed = true;
5880         var subject = this.subject;
5881         var observers = subject.observers;
5882         this.subject = null;
5883         if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
5884             return;
5885         }
5886         var subscriberIndex = observers.indexOf(this.subscriber);
5887         if (subscriberIndex !== -1) {
5888             observers.splice(subscriberIndex, 1);
5889         }
5890     };
5891     return SubjectSubscription;
5892 }(Subscription_1.Subscription));
5893 exports.SubjectSubscription = SubjectSubscription;
5894
5895 },{"./Subscription":36}],35:[function(require,module,exports){
5896 "use strict";
5897 var __extends = (this && this.__extends) || function (d, b) {
5898     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5899     function __() { this.constructor = d; }
5900     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5901 };
5902 var isFunction_1 = require('./util/isFunction');
5903 var Subscription_1 = require('./Subscription');
5904 var Observer_1 = require('./Observer');
5905 var rxSubscriber_1 = require('./symbol/rxSubscriber');
5906 /**
5907  * Implements the {@link Observer} interface and extends the
5908  * {@link Subscription} class. While the {@link Observer} is the public API for
5909  * consuming the values of an {@link Observable}, all Observers get converted to
5910  * a Subscriber, in order to provide Subscription-like capabilities such as
5911  * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
5912  * implementing operators, but it is rarely used as a public API.
5913  *
5914  * @class Subscriber<T>
5915  */
5916 var Subscriber = (function (_super) {
5917     __extends(Subscriber, _super);
5918     /**
5919      * @param {Observer|function(value: T): void} [destinationOrNext] A partially
5920      * defined Observer or a `next` callback function.
5921      * @param {function(e: ?any): void} [error] The `error` callback of an
5922      * Observer.
5923      * @param {function(): void} [complete] The `complete` callback of an
5924      * Observer.
5925      */
5926     function Subscriber(destinationOrNext, error, complete) {
5927         _super.call(this);
5928         this.syncErrorValue = null;
5929         this.syncErrorThrown = false;
5930         this.syncErrorThrowable = false;
5931         this.isStopped = false;
5932         switch (arguments.length) {
5933             case 0:
5934                 this.destination = Observer_1.empty;
5935                 break;
5936             case 1:
5937                 if (!destinationOrNext) {
5938                     this.destination = Observer_1.empty;
5939                     break;
5940                 }
5941                 if (typeof destinationOrNext === 'object') {
5942                     if (destinationOrNext instanceof Subscriber) {
5943                         this.destination = destinationOrNext;
5944                         this.destination.add(this);
5945                     }
5946                     else {
5947                         this.syncErrorThrowable = true;
5948                         this.destination = new SafeSubscriber(this, destinationOrNext);
5949                     }
5950                     break;
5951                 }
5952             default:
5953                 this.syncErrorThrowable = true;
5954                 this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
5955                 break;
5956         }
5957     }
5958     Subscriber.prototype[rxSubscriber_1.$$rxSubscriber] = function () { return this; };
5959     /**
5960      * A static factory for a Subscriber, given a (potentially partial) definition
5961      * of an Observer.
5962      * @param {function(x: ?T): void} [next] The `next` callback of an Observer.
5963      * @param {function(e: ?any): void} [error] The `error` callback of an
5964      * Observer.
5965      * @param {function(): void} [complete] The `complete` callback of an
5966      * Observer.
5967      * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
5968      * Observer represented by the given arguments.
5969      */
5970     Subscriber.create = function (next, error, complete) {
5971         var subscriber = new Subscriber(next, error, complete);
5972         subscriber.syncErrorThrowable = false;
5973         return subscriber;
5974     };
5975     /**
5976      * The {@link Observer} callback to receive notifications of type `next` from
5977      * the Observable, with a value. The Observable may call this method 0 or more
5978      * times.
5979      * @param {T} [value] The `next` value.
5980      * @return {void}
5981      */
5982     Subscriber.prototype.next = function (value) {
5983         if (!this.isStopped) {
5984             this._next(value);
5985         }
5986     };
5987     /**
5988      * The {@link Observer} callback to receive notifications of type `error` from
5989      * the Observable, with an attached {@link Error}. Notifies the Observer that
5990      * the Observable has experienced an error condition.
5991      * @param {any} [err] The `error` exception.
5992      * @return {void}
5993      */
5994     Subscriber.prototype.error = function (err) {
5995         if (!this.isStopped) {
5996             this.isStopped = true;
5997             this._error(err);
5998         }
5999     };
6000     /**
6001      * The {@link Observer} callback to receive a valueless notification of type
6002      * `complete` from the Observable. Notifies the Observer that the Observable
6003      * has finished sending push-based notifications.
6004      * @return {void}
6005      */
6006     Subscriber.prototype.complete = function () {
6007         if (!this.isStopped) {
6008             this.isStopped = true;
6009             this._complete();
6010         }
6011     };
6012     Subscriber.prototype.unsubscribe = function () {
6013         if (this.closed) {
6014             return;
6015         }
6016         this.isStopped = true;
6017         _super.prototype.unsubscribe.call(this);
6018     };
6019     Subscriber.prototype._next = function (value) {
6020         this.destination.next(value);
6021     };
6022     Subscriber.prototype._error = function (err) {
6023         this.destination.error(err);
6024         this.unsubscribe();
6025     };
6026     Subscriber.prototype._complete = function () {
6027         this.destination.complete();
6028         this.unsubscribe();
6029     };
6030     return Subscriber;
6031 }(Subscription_1.Subscription));
6032 exports.Subscriber = Subscriber;
6033 /**
6034  * We need this JSDoc comment for affecting ESDoc.
6035  * @ignore
6036  * @extends {Ignored}
6037  */
6038 var SafeSubscriber = (function (_super) {
6039     __extends(SafeSubscriber, _super);
6040     function SafeSubscriber(_parent, observerOrNext, error, complete) {
6041         _super.call(this);
6042         this._parent = _parent;
6043         var next;
6044         var context = this;
6045         if (isFunction_1.isFunction(observerOrNext)) {
6046             next = observerOrNext;
6047         }
6048         else if (observerOrNext) {
6049             context = observerOrNext;
6050             next = observerOrNext.next;
6051             error = observerOrNext.error;
6052             complete = observerOrNext.complete;
6053             if (isFunction_1.isFunction(context.unsubscribe)) {
6054                 this.add(context.unsubscribe.bind(context));
6055             }
6056             context.unsubscribe = this.unsubscribe.bind(this);
6057         }
6058         this._context = context;
6059         this._next = next;
6060         this._error = error;
6061         this._complete = complete;
6062     }
6063     SafeSubscriber.prototype.next = function (value) {
6064         if (!this.isStopped && this._next) {
6065             var _parent = this._parent;
6066             if (!_parent.syncErrorThrowable) {
6067                 this.__tryOrUnsub(this._next, value);
6068             }
6069             else if (this.__tryOrSetError(_parent, this._next, value)) {
6070                 this.unsubscribe();
6071             }
6072         }
6073     };
6074     SafeSubscriber.prototype.error = function (err) {
6075         if (!this.isStopped) {
6076             var _parent = this._parent;
6077             if (this._error) {
6078                 if (!_parent.syncErrorThrowable) {
6079                     this.__tryOrUnsub(this._error, err);
6080                     this.unsubscribe();
6081                 }
6082                 else {
6083                     this.__tryOrSetError(_parent, this._error, err);
6084                     this.unsubscribe();
6085                 }
6086             }
6087             else if (!_parent.syncErrorThrowable) {
6088                 this.unsubscribe();
6089                 throw err;
6090             }
6091             else {
6092                 _parent.syncErrorValue = err;
6093                 _parent.syncErrorThrown = true;
6094                 this.unsubscribe();
6095             }
6096         }
6097     };
6098     SafeSubscriber.prototype.complete = function () {
6099         if (!this.isStopped) {
6100             var _parent = this._parent;
6101             if (this._complete) {
6102                 if (!_parent.syncErrorThrowable) {
6103                     this.__tryOrUnsub(this._complete);
6104                     this.unsubscribe();
6105                 }
6106                 else {
6107                     this.__tryOrSetError(_parent, this._complete);
6108                     this.unsubscribe();
6109                 }
6110             }
6111             else {
6112                 this.unsubscribe();
6113             }
6114         }
6115     };
6116     SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
6117         try {
6118             fn.call(this._context, value);
6119         }
6120         catch (err) {
6121             this.unsubscribe();
6122             throw err;
6123         }
6124     };
6125     SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
6126         try {
6127             fn.call(this._context, value);
6128         }
6129         catch (err) {
6130             parent.syncErrorValue = err;
6131             parent.syncErrorThrown = true;
6132             return true;
6133         }
6134         return false;
6135     };
6136     SafeSubscriber.prototype._unsubscribe = function () {
6137         var _parent = this._parent;
6138         this._context = null;
6139         this._parent = null;
6140         _parent.unsubscribe();
6141     };
6142     return SafeSubscriber;
6143 }(Subscriber));
6144
6145 },{"./Observer":29,"./Subscription":36,"./symbol/rxSubscriber":144,"./util/isFunction":152}],36:[function(require,module,exports){
6146 "use strict";
6147 var isArray_1 = require('./util/isArray');
6148 var isObject_1 = require('./util/isObject');
6149 var isFunction_1 = require('./util/isFunction');
6150 var tryCatch_1 = require('./util/tryCatch');
6151 var errorObject_1 = require('./util/errorObject');
6152 var UnsubscriptionError_1 = require('./util/UnsubscriptionError');
6153 /**
6154  * Represents a disposable resource, such as the execution of an Observable. A
6155  * Subscription has one important method, `unsubscribe`, that takes no argument
6156  * and just disposes the resource held by the subscription.
6157  *
6158  * Additionally, subscriptions may be grouped together through the `add()`
6159  * method, which will attach a child Subscription to the current Subscription.
6160  * When a Subscription is unsubscribed, all its children (and its grandchildren)
6161  * will be unsubscribed as well.
6162  *
6163  * @class Subscription
6164  */
6165 var Subscription = (function () {
6166     /**
6167      * @param {function(): void} [unsubscribe] A function describing how to
6168      * perform the disposal of resources when the `unsubscribe` method is called.
6169      */
6170     function Subscription(unsubscribe) {
6171         /**
6172          * A flag to indicate whether this Subscription has already been unsubscribed.
6173          * @type {boolean}
6174          */
6175         this.closed = false;
6176         if (unsubscribe) {
6177             this._unsubscribe = unsubscribe;
6178         }
6179     }
6180     /**
6181      * Disposes the resources held by the subscription. May, for instance, cancel
6182      * an ongoing Observable execution or cancel any other type of work that
6183      * started when the Subscription was created.
6184      * @return {void}
6185      */
6186     Subscription.prototype.unsubscribe = function () {
6187         var hasErrors = false;
6188         var errors;
6189         if (this.closed) {
6190             return;
6191         }
6192         this.closed = true;
6193         var _a = this, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
6194         this._subscriptions = null;
6195         if (isFunction_1.isFunction(_unsubscribe)) {
6196             var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
6197             if (trial === errorObject_1.errorObject) {
6198                 hasErrors = true;
6199                 (errors = errors || []).push(errorObject_1.errorObject.e);
6200             }
6201         }
6202         if (isArray_1.isArray(_subscriptions)) {
6203             var index = -1;
6204             var len = _subscriptions.length;
6205             while (++index < len) {
6206                 var sub = _subscriptions[index];
6207                 if (isObject_1.isObject(sub)) {
6208                     var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
6209                     if (trial === errorObject_1.errorObject) {
6210                         hasErrors = true;
6211                         errors = errors || [];
6212                         var err = errorObject_1.errorObject.e;
6213                         if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
6214                             errors = errors.concat(err.errors);
6215                         }
6216                         else {
6217                             errors.push(err);
6218                         }
6219                     }
6220                 }
6221             }
6222         }
6223         if (hasErrors) {
6224             throw new UnsubscriptionError_1.UnsubscriptionError(errors);
6225         }
6226     };
6227     /**
6228      * Adds a tear down to be called during the unsubscribe() of this
6229      * Subscription.
6230      *
6231      * If the tear down being added is a subscription that is already
6232      * unsubscribed, is the same reference `add` is being called on, or is
6233      * `Subscription.EMPTY`, it will not be added.
6234      *
6235      * If this subscription is already in an `closed` state, the passed
6236      * tear down logic will be executed immediately.
6237      *
6238      * @param {TeardownLogic} teardown The additional logic to execute on
6239      * teardown.
6240      * @return {Subscription} Returns the Subscription used or created to be
6241      * added to the inner subscriptions list. This Subscription can be used with
6242      * `remove()` to remove the passed teardown logic from the inner subscriptions
6243      * list.
6244      */
6245     Subscription.prototype.add = function (teardown) {
6246         if (!teardown || (teardown === Subscription.EMPTY)) {
6247             return Subscription.EMPTY;
6248         }
6249         if (teardown === this) {
6250             return this;
6251         }
6252         var sub = teardown;
6253         switch (typeof teardown) {
6254             case 'function':
6255                 sub = new Subscription(teardown);
6256             case 'object':
6257                 if (sub.closed || typeof sub.unsubscribe !== 'function') {
6258                     break;
6259                 }
6260                 else if (this.closed) {
6261                     sub.unsubscribe();
6262                 }
6263                 else {
6264                     (this._subscriptions || (this._subscriptions = [])).push(sub);
6265                 }
6266                 break;
6267             default:
6268                 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
6269         }
6270         return sub;
6271     };
6272     /**
6273      * Removes a Subscription from the internal list of subscriptions that will
6274      * unsubscribe during the unsubscribe process of this Subscription.
6275      * @param {Subscription} subscription The subscription to remove.
6276      * @return {void}
6277      */
6278     Subscription.prototype.remove = function (subscription) {
6279         // HACK: This might be redundant because of the logic in `add()`
6280         if (subscription == null || (subscription === this) || (subscription === Subscription.EMPTY)) {
6281             return;
6282         }
6283         var subscriptions = this._subscriptions;
6284         if (subscriptions) {
6285             var subscriptionIndex = subscriptions.indexOf(subscription);
6286             if (subscriptionIndex !== -1) {
6287                 subscriptions.splice(subscriptionIndex, 1);
6288             }
6289         }
6290     };
6291     Subscription.EMPTY = (function (empty) {
6292         empty.closed = true;
6293         return empty;
6294     }(new Subscription()));
6295     return Subscription;
6296 }());
6297 exports.Subscription = Subscription;
6298
6299 },{"./util/UnsubscriptionError":149,"./util/errorObject":150,"./util/isArray":151,"./util/isFunction":152,"./util/isObject":153,"./util/tryCatch":159}],37:[function(require,module,exports){
6300 "use strict";
6301 var Observable_1 = require('../../Observable');
6302 var combineLatest_1 = require('../../observable/combineLatest');
6303 Observable_1.Observable.combineLatest = combineLatest_1.combineLatest;
6304
6305 },{"../../Observable":28,"../../observable/combineLatest":91}],38:[function(require,module,exports){
6306 "use strict";
6307 var Observable_1 = require('../../Observable');
6308 var defer_1 = require('../../observable/defer');
6309 Observable_1.Observable.defer = defer_1.defer;
6310
6311 },{"../../Observable":28,"../../observable/defer":92}],39:[function(require,module,exports){
6312 "use strict";
6313 var Observable_1 = require('../../Observable');
6314 var empty_1 = require('../../observable/empty');
6315 Observable_1.Observable.empty = empty_1.empty;
6316
6317 },{"../../Observable":28,"../../observable/empty":93}],40:[function(require,module,exports){
6318 "use strict";
6319 var Observable_1 = require('../../Observable');
6320 var from_1 = require('../../observable/from');
6321 Observable_1.Observable.from = from_1.from;
6322
6323 },{"../../Observable":28,"../../observable/from":94}],41:[function(require,module,exports){
6324 "use strict";
6325 var Observable_1 = require('../../Observable');
6326 var fromEvent_1 = require('../../observable/fromEvent');
6327 Observable_1.Observable.fromEvent = fromEvent_1.fromEvent;
6328
6329 },{"../../Observable":28,"../../observable/fromEvent":95}],42:[function(require,module,exports){
6330 "use strict";
6331 var Observable_1 = require('../../Observable');
6332 var fromPromise_1 = require('../../observable/fromPromise');
6333 Observable_1.Observable.fromPromise = fromPromise_1.fromPromise;
6334
6335 },{"../../Observable":28,"../../observable/fromPromise":96}],43:[function(require,module,exports){
6336 "use strict";
6337 var Observable_1 = require('../../Observable');
6338 var merge_1 = require('../../observable/merge');
6339 Observable_1.Observable.merge = merge_1.merge;
6340
6341 },{"../../Observable":28,"../../observable/merge":97}],44:[function(require,module,exports){
6342 "use strict";
6343 var Observable_1 = require('../../Observable');
6344 var of_1 = require('../../observable/of');
6345 Observable_1.Observable.of = of_1.of;
6346
6347 },{"../../Observable":28,"../../observable/of":98}],45:[function(require,module,exports){
6348 "use strict";
6349 var Observable_1 = require('../../Observable');
6350 var throw_1 = require('../../observable/throw');
6351 Observable_1.Observable.throw = throw_1._throw;
6352
6353 },{"../../Observable":28,"../../observable/throw":99}],46:[function(require,module,exports){
6354 "use strict";
6355 var Observable_1 = require('../../Observable');
6356 var zip_1 = require('../../observable/zip');
6357 Observable_1.Observable.zip = zip_1.zip;
6358
6359 },{"../../Observable":28,"../../observable/zip":100}],47:[function(require,module,exports){
6360 "use strict";
6361 var Observable_1 = require('../../Observable');
6362 var buffer_1 = require('../../operator/buffer');
6363 Observable_1.Observable.prototype.buffer = buffer_1.buffer;
6364
6365 },{"../../Observable":28,"../../operator/buffer":101}],48:[function(require,module,exports){
6366 "use strict";
6367 var Observable_1 = require('../../Observable');
6368 var bufferCount_1 = require('../../operator/bufferCount');
6369 Observable_1.Observable.prototype.bufferCount = bufferCount_1.bufferCount;
6370
6371 },{"../../Observable":28,"../../operator/bufferCount":102}],49:[function(require,module,exports){
6372 "use strict";
6373 var Observable_1 = require('../../Observable');
6374 var catch_1 = require('../../operator/catch');
6375 Observable_1.Observable.prototype.catch = catch_1._catch;
6376 Observable_1.Observable.prototype._catch = catch_1._catch;
6377
6378 },{"../../Observable":28,"../../operator/catch":103}],50:[function(require,module,exports){
6379 "use strict";
6380 var Observable_1 = require('../../Observable');
6381 var combineLatest_1 = require('../../operator/combineLatest');
6382 Observable_1.Observable.prototype.combineLatest = combineLatest_1.combineLatest;
6383
6384 },{"../../Observable":28,"../../operator/combineLatest":104}],51:[function(require,module,exports){
6385 "use strict";
6386 var Observable_1 = require('../../Observable');
6387 var concat_1 = require('../../operator/concat');
6388 Observable_1.Observable.prototype.concat = concat_1.concat;
6389
6390 },{"../../Observable":28,"../../operator/concat":105}],52:[function(require,module,exports){
6391 "use strict";
6392 var Observable_1 = require('../../Observable');
6393 var debounceTime_1 = require('../../operator/debounceTime');
6394 Observable_1.Observable.prototype.debounceTime = debounceTime_1.debounceTime;
6395
6396 },{"../../Observable":28,"../../operator/debounceTime":106}],53:[function(require,module,exports){
6397 "use strict";
6398 var Observable_1 = require('../../Observable');
6399 var distinct_1 = require('../../operator/distinct');
6400 Observable_1.Observable.prototype.distinct = distinct_1.distinct;
6401
6402 },{"../../Observable":28,"../../operator/distinct":107}],54:[function(require,module,exports){
6403 "use strict";
6404 var Observable_1 = require('../../Observable');
6405 var distinctUntilChanged_1 = require('../../operator/distinctUntilChanged');
6406 Observable_1.Observable.prototype.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged;
6407
6408 },{"../../Observable":28,"../../operator/distinctUntilChanged":108}],55:[function(require,module,exports){
6409 "use strict";
6410 var Observable_1 = require('../../Observable');
6411 var do_1 = require('../../operator/do');
6412 Observable_1.Observable.prototype.do = do_1._do;
6413 Observable_1.Observable.prototype._do = do_1._do;
6414
6415 },{"../../Observable":28,"../../operator/do":109}],56:[function(require,module,exports){
6416 "use strict";
6417 var Observable_1 = require('../../Observable');
6418 var expand_1 = require('../../operator/expand');
6419 Observable_1.Observable.prototype.expand = expand_1.expand;
6420
6421 },{"../../Observable":28,"../../operator/expand":110}],57:[function(require,module,exports){
6422 "use strict";
6423 var Observable_1 = require('../../Observable');
6424 var filter_1 = require('../../operator/filter');
6425 Observable_1.Observable.prototype.filter = filter_1.filter;
6426
6427 },{"../../Observable":28,"../../operator/filter":111}],58:[function(require,module,exports){
6428 "use strict";
6429 var Observable_1 = require('../../Observable');
6430 var finally_1 = require('../../operator/finally');
6431 Observable_1.Observable.prototype.finally = finally_1._finally;
6432 Observable_1.Observable.prototype._finally = finally_1._finally;
6433
6434 },{"../../Observable":28,"../../operator/finally":112}],59:[function(require,module,exports){
6435 "use strict";
6436 var Observable_1 = require('../../Observable');
6437 var first_1 = require('../../operator/first');
6438 Observable_1.Observable.prototype.first = first_1.first;
6439
6440 },{"../../Observable":28,"../../operator/first":113}],60:[function(require,module,exports){
6441 "use strict";
6442 var Observable_1 = require('../../Observable');
6443 var last_1 = require('../../operator/last');
6444 Observable_1.Observable.prototype.last = last_1.last;
6445
6446 },{"../../Observable":28,"../../operator/last":114}],61:[function(require,module,exports){
6447 "use strict";
6448 var Observable_1 = require('../../Observable');
6449 var map_1 = require('../../operator/map');
6450 Observable_1.Observable.prototype.map = map_1.map;
6451
6452 },{"../../Observable":28,"../../operator/map":115}],62:[function(require,module,exports){
6453 "use strict";
6454 var Observable_1 = require('../../Observable');
6455 var merge_1 = require('../../operator/merge');
6456 Observable_1.Observable.prototype.merge = merge_1.merge;
6457
6458 },{"../../Observable":28,"../../operator/merge":116}],63:[function(require,module,exports){
6459 "use strict";
6460 var Observable_1 = require('../../Observable');
6461 var mergeAll_1 = require('../../operator/mergeAll');
6462 Observable_1.Observable.prototype.mergeAll = mergeAll_1.mergeAll;
6463
6464 },{"../../Observable":28,"../../operator/mergeAll":117}],64:[function(require,module,exports){
6465 "use strict";
6466 var Observable_1 = require('../../Observable');
6467 var mergeMap_1 = require('../../operator/mergeMap');
6468 Observable_1.Observable.prototype.mergeMap = mergeMap_1.mergeMap;
6469 Observable_1.Observable.prototype.flatMap = mergeMap_1.mergeMap;
6470
6471 },{"../../Observable":28,"../../operator/mergeMap":118}],65:[function(require,module,exports){
6472 "use strict";
6473 var Observable_1 = require('../../Observable');
6474 var pairwise_1 = require('../../operator/pairwise');
6475 Observable_1.Observable.prototype.pairwise = pairwise_1.pairwise;
6476
6477 },{"../../Observable":28,"../../operator/pairwise":121}],66:[function(require,module,exports){
6478 "use strict";
6479 var Observable_1 = require('../../Observable');
6480 var pluck_1 = require('../../operator/pluck');
6481 Observable_1.Observable.prototype.pluck = pluck_1.pluck;
6482
6483 },{"../../Observable":28,"../../operator/pluck":122}],67:[function(require,module,exports){
6484 "use strict";
6485 var Observable_1 = require('../../Observable');
6486 var publish_1 = require('../../operator/publish');
6487 Observable_1.Observable.prototype.publish = publish_1.publish;
6488
6489 },{"../../Observable":28,"../../operator/publish":123}],68:[function(require,module,exports){
6490 "use strict";
6491 var Observable_1 = require('../../Observable');
6492 var publishReplay_1 = require('../../operator/publishReplay');
6493 Observable_1.Observable.prototype.publishReplay = publishReplay_1.publishReplay;
6494
6495 },{"../../Observable":28,"../../operator/publishReplay":124}],69:[function(require,module,exports){
6496 "use strict";
6497 var Observable_1 = require('../../Observable');
6498 var scan_1 = require('../../operator/scan');
6499 Observable_1.Observable.prototype.scan = scan_1.scan;
6500
6501 },{"../../Observable":28,"../../operator/scan":125}],70:[function(require,module,exports){
6502 "use strict";
6503 var Observable_1 = require('../../Observable');
6504 var share_1 = require('../../operator/share');
6505 Observable_1.Observable.prototype.share = share_1.share;
6506
6507 },{"../../Observable":28,"../../operator/share":126}],71:[function(require,module,exports){
6508 "use strict";
6509 var Observable_1 = require('../../Observable');
6510 var skip_1 = require('../../operator/skip');
6511 Observable_1.Observable.prototype.skip = skip_1.skip;
6512
6513 },{"../../Observable":28,"../../operator/skip":127}],72:[function(require,module,exports){
6514 "use strict";
6515 var Observable_1 = require('../../Observable');
6516 var skipUntil_1 = require('../../operator/skipUntil');
6517 Observable_1.Observable.prototype.skipUntil = skipUntil_1.skipUntil;
6518
6519 },{"../../Observable":28,"../../operator/skipUntil":128}],73:[function(require,module,exports){
6520 "use strict";
6521 var Observable_1 = require('../../Observable');
6522 var startWith_1 = require('../../operator/startWith');
6523 Observable_1.Observable.prototype.startWith = startWith_1.startWith;
6524
6525 },{"../../Observable":28,"../../operator/startWith":129}],74:[function(require,module,exports){
6526 "use strict";
6527 var Observable_1 = require('../../Observable');
6528 var switchMap_1 = require('../../operator/switchMap');
6529 Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap;
6530
6531 },{"../../Observable":28,"../../operator/switchMap":130}],75:[function(require,module,exports){
6532 "use strict";
6533 var Observable_1 = require('../../Observable');
6534 var take_1 = require('../../operator/take');
6535 Observable_1.Observable.prototype.take = take_1.take;
6536
6537 },{"../../Observable":28,"../../operator/take":131}],76:[function(require,module,exports){
6538 "use strict";
6539 var Observable_1 = require('../../Observable');
6540 var takeUntil_1 = require('../../operator/takeUntil');
6541 Observable_1.Observable.prototype.takeUntil = takeUntil_1.takeUntil;
6542
6543 },{"../../Observable":28,"../../operator/takeUntil":132}],77:[function(require,module,exports){
6544 "use strict";
6545 var Observable_1 = require('../../Observable');
6546 var withLatestFrom_1 = require('../../operator/withLatestFrom');
6547 Observable_1.Observable.prototype.withLatestFrom = withLatestFrom_1.withLatestFrom;
6548
6549 },{"../../Observable":28,"../../operator/withLatestFrom":133}],78:[function(require,module,exports){
6550 "use strict";
6551 var Observable_1 = require('../../Observable');
6552 var zip_1 = require('../../operator/zip');
6553 Observable_1.Observable.prototype.zip = zip_1.zipProto;
6554
6555 },{"../../Observable":28,"../../operator/zip":134}],79:[function(require,module,exports){
6556 "use strict";
6557 var __extends = (this && this.__extends) || function (d, b) {
6558     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6559     function __() { this.constructor = d; }
6560     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6561 };
6562 var Observable_1 = require('../Observable');
6563 var ScalarObservable_1 = require('./ScalarObservable');
6564 var EmptyObservable_1 = require('./EmptyObservable');
6565 /**
6566  * We need this JSDoc comment for affecting ESDoc.
6567  * @extends {Ignored}
6568  * @hide true
6569  */
6570 var ArrayLikeObservable = (function (_super) {
6571     __extends(ArrayLikeObservable, _super);
6572     function ArrayLikeObservable(arrayLike, scheduler) {
6573         _super.call(this);
6574         this.arrayLike = arrayLike;
6575         this.scheduler = scheduler;
6576         if (!scheduler && arrayLike.length === 1) {
6577             this._isScalar = true;
6578             this.value = arrayLike[0];
6579         }
6580     }
6581     ArrayLikeObservable.create = function (arrayLike, scheduler) {
6582         var length = arrayLike.length;
6583         if (length === 0) {
6584             return new EmptyObservable_1.EmptyObservable();
6585         }
6586         else if (length === 1) {
6587             return new ScalarObservable_1.ScalarObservable(arrayLike[0], scheduler);
6588         }
6589         else {
6590             return new ArrayLikeObservable(arrayLike, scheduler);
6591         }
6592     };
6593     ArrayLikeObservable.dispatch = function (state) {
6594         var arrayLike = state.arrayLike, index = state.index, length = state.length, subscriber = state.subscriber;
6595         if (subscriber.closed) {
6596             return;
6597         }
6598         if (index >= length) {
6599             subscriber.complete();
6600             return;
6601         }
6602         subscriber.next(arrayLike[index]);
6603         state.index = index + 1;
6604         this.schedule(state);
6605     };
6606     ArrayLikeObservable.prototype._subscribe = function (subscriber) {
6607         var index = 0;
6608         var _a = this, arrayLike = _a.arrayLike, scheduler = _a.scheduler;
6609         var length = arrayLike.length;
6610         if (scheduler) {
6611             return scheduler.schedule(ArrayLikeObservable.dispatch, 0, {
6612                 arrayLike: arrayLike, index: index, length: length, subscriber: subscriber
6613             });
6614         }
6615         else {
6616             for (var i = 0; i < length && !subscriber.closed; i++) {
6617                 subscriber.next(arrayLike[i]);
6618             }
6619             subscriber.complete();
6620         }
6621     };
6622     return ArrayLikeObservable;
6623 }(Observable_1.Observable));
6624 exports.ArrayLikeObservable = ArrayLikeObservable;
6625
6626 },{"../Observable":28,"./EmptyObservable":83,"./ScalarObservable":90}],80:[function(require,module,exports){
6627 "use strict";
6628 var __extends = (this && this.__extends) || function (d, b) {
6629     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6630     function __() { this.constructor = d; }
6631     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6632 };
6633 var Observable_1 = require('../Observable');
6634 var ScalarObservable_1 = require('./ScalarObservable');
6635 var EmptyObservable_1 = require('./EmptyObservable');
6636 var isScheduler_1 = require('../util/isScheduler');
6637 /**
6638  * We need this JSDoc comment for affecting ESDoc.
6639  * @extends {Ignored}
6640  * @hide true
6641  */
6642 var ArrayObservable = (function (_super) {
6643     __extends(ArrayObservable, _super);
6644     function ArrayObservable(array, scheduler) {
6645         _super.call(this);
6646         this.array = array;
6647         this.scheduler = scheduler;
6648         if (!scheduler && array.length === 1) {
6649             this._isScalar = true;
6650             this.value = array[0];
6651         }
6652     }
6653     ArrayObservable.create = function (array, scheduler) {
6654         return new ArrayObservable(array, scheduler);
6655     };
6656     /**
6657      * Creates an Observable that emits some values you specify as arguments,
6658      * immediately one after the other, and then emits a complete notification.
6659      *
6660      * <span class="informal">Emits the arguments you provide, then completes.
6661      * </span>
6662      *
6663      * <img src="./img/of.png" width="100%">
6664      *
6665      * This static operator is useful for creating a simple Observable that only
6666      * emits the arguments given, and the complete notification thereafter. It can
6667      * be used for composing with other Observables, such as with {@link concat}.
6668      * By default, it uses a `null` Scheduler, which means the `next`
6669      * notifications are sent synchronously, although with a different Scheduler
6670      * it is possible to determine when those notifications will be delivered.
6671      *
6672      * @example <caption>Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second.</caption>
6673      * var numbers = Rx.Observable.of(10, 20, 30);
6674      * var letters = Rx.Observable.of('a', 'b', 'c');
6675      * var interval = Rx.Observable.interval(1000);
6676      * var result = numbers.concat(letters).concat(interval);
6677      * result.subscribe(x => console.log(x));
6678      *
6679      * @see {@link create}
6680      * @see {@link empty}
6681      * @see {@link never}
6682      * @see {@link throw}
6683      *
6684      * @param {...T} values Arguments that represent `next` values to be emitted.
6685      * @param {Scheduler} [scheduler] A {@link Scheduler} to use for scheduling
6686      * the emissions of the `next` notifications.
6687      * @return {Observable<T>} An Observable that emits each given input value.
6688      * @static true
6689      * @name of
6690      * @owner Observable
6691      */
6692     ArrayObservable.of = function () {
6693         var array = [];
6694         for (var _i = 0; _i < arguments.length; _i++) {
6695             array[_i - 0] = arguments[_i];
6696         }
6697         var scheduler = array[array.length - 1];
6698         if (isScheduler_1.isScheduler(scheduler)) {
6699             array.pop();
6700         }
6701         else {
6702             scheduler = null;
6703         }
6704         var len = array.length;
6705         if (len > 1) {
6706             return new ArrayObservable(array, scheduler);
6707         }
6708         else if (len === 1) {
6709             return new ScalarObservable_1.ScalarObservable(array[0], scheduler);
6710         }
6711         else {
6712             return new EmptyObservable_1.EmptyObservable(scheduler);
6713         }
6714     };
6715     ArrayObservable.dispatch = function (state) {
6716         var array = state.array, index = state.index, count = state.count, subscriber = state.subscriber;
6717         if (index >= count) {
6718             subscriber.complete();
6719             return;
6720         }
6721         subscriber.next(array[index]);
6722         if (subscriber.closed) {
6723             return;
6724         }
6725         state.index = index + 1;
6726         this.schedule(state);
6727     };
6728     ArrayObservable.prototype._subscribe = function (subscriber) {
6729         var index = 0;
6730         var array = this.array;
6731         var count = array.length;
6732         var scheduler = this.scheduler;
6733         if (scheduler) {
6734             return scheduler.schedule(ArrayObservable.dispatch, 0, {
6735                 array: array, index: index, count: count, subscriber: subscriber
6736             });
6737         }
6738         else {
6739             for (var i = 0; i < count && !subscriber.closed; i++) {
6740                 subscriber.next(array[i]);
6741             }
6742             subscriber.complete();
6743         }
6744     };
6745     return ArrayObservable;
6746 }(Observable_1.Observable));
6747 exports.ArrayObservable = ArrayObservable;
6748
6749 },{"../Observable":28,"../util/isScheduler":155,"./EmptyObservable":83,"./ScalarObservable":90}],81:[function(require,module,exports){
6750 "use strict";
6751 var __extends = (this && this.__extends) || function (d, b) {
6752     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6753     function __() { this.constructor = d; }
6754     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6755 };
6756 var Subject_1 = require('../Subject');
6757 var Observable_1 = require('../Observable');
6758 var Subscriber_1 = require('../Subscriber');
6759 var Subscription_1 = require('../Subscription');
6760 /**
6761  * @class ConnectableObservable<T>
6762  */
6763 var ConnectableObservable = (function (_super) {
6764     __extends(ConnectableObservable, _super);
6765     function ConnectableObservable(source, subjectFactory) {
6766         _super.call(this);
6767         this.source = source;
6768         this.subjectFactory = subjectFactory;
6769         this._refCount = 0;
6770     }
6771     ConnectableObservable.prototype._subscribe = function (subscriber) {
6772         return this.getSubject().subscribe(subscriber);
6773     };
6774     ConnectableObservable.prototype.getSubject = function () {
6775         var subject = this._subject;
6776         if (!subject || subject.isStopped) {
6777             this._subject = this.subjectFactory();
6778         }
6779         return this._subject;
6780     };
6781     ConnectableObservable.prototype.connect = function () {
6782         var connection = this._connection;
6783         if (!connection) {
6784             connection = this._connection = new Subscription_1.Subscription();
6785             connection.add(this.source
6786                 .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
6787             if (connection.closed) {
6788                 this._connection = null;
6789                 connection = Subscription_1.Subscription.EMPTY;
6790             }
6791             else {
6792                 this._connection = connection;
6793             }
6794         }
6795         return connection;
6796     };
6797     ConnectableObservable.prototype.refCount = function () {
6798         return this.lift(new RefCountOperator(this));
6799     };
6800     return ConnectableObservable;
6801 }(Observable_1.Observable));
6802 exports.ConnectableObservable = ConnectableObservable;
6803 var ConnectableSubscriber = (function (_super) {
6804     __extends(ConnectableSubscriber, _super);
6805     function ConnectableSubscriber(destination, connectable) {
6806         _super.call(this, destination);
6807         this.connectable = connectable;
6808     }
6809     ConnectableSubscriber.prototype._error = function (err) {
6810         this._unsubscribe();
6811         _super.prototype._error.call(this, err);
6812     };
6813     ConnectableSubscriber.prototype._complete = function () {
6814         this._unsubscribe();
6815         _super.prototype._complete.call(this);
6816     };
6817     ConnectableSubscriber.prototype._unsubscribe = function () {
6818         var connectable = this.connectable;
6819         if (connectable) {
6820             this.connectable = null;
6821             var connection = connectable._connection;
6822             connectable._refCount = 0;
6823             connectable._subject = null;
6824             connectable._connection = null;
6825             if (connection) {
6826                 connection.unsubscribe();
6827             }
6828         }
6829     };
6830     return ConnectableSubscriber;
6831 }(Subject_1.SubjectSubscriber));
6832 var RefCountOperator = (function () {
6833     function RefCountOperator(connectable) {
6834         this.connectable = connectable;
6835     }
6836     RefCountOperator.prototype.call = function (subscriber, source) {
6837         var connectable = this.connectable;
6838         connectable._refCount++;
6839         var refCounter = new RefCountSubscriber(subscriber, connectable);
6840         var subscription = source._subscribe(refCounter);
6841         if (!refCounter.closed) {
6842             refCounter.connection = connectable.connect();
6843         }
6844         return subscription;
6845     };
6846     return RefCountOperator;
6847 }());
6848 var RefCountSubscriber = (function (_super) {
6849     __extends(RefCountSubscriber, _super);
6850     function RefCountSubscriber(destination, connectable) {
6851         _super.call(this, destination);
6852         this.connectable = connectable;
6853     }
6854     RefCountSubscriber.prototype._unsubscribe = function () {
6855         var connectable = this.connectable;
6856         if (!connectable) {
6857             this.connection = null;
6858             return;
6859         }
6860         this.connectable = null;
6861         var refCount = connectable._refCount;
6862         if (refCount <= 0) {
6863             this.connection = null;
6864             return;
6865         }
6866         connectable._refCount = refCount - 1;
6867         if (refCount > 1) {
6868             this.connection = null;
6869             return;
6870         }
6871         ///
6872         // Compare the local RefCountSubscriber's connection Subscription to the
6873         // connection Subscription on the shared ConnectableObservable. In cases
6874         // where the ConnectableObservable source synchronously emits values, and
6875         // the RefCountSubscriber's dowstream Observers synchronously unsubscribe,
6876         // execution continues to here before the RefCountOperator has a chance to
6877         // supply the RefCountSubscriber with the shared connection Subscription.
6878         // For example:
6879         // ```
6880         // Observable.range(0, 10)
6881         //   .publish()
6882         //   .refCount()
6883         //   .take(5)
6884         //   .subscribe();
6885         // ```
6886         // In order to account for this case, RefCountSubscriber should only dispose
6887         // the ConnectableObservable's shared connection Subscription if the
6888         // connection Subscription exists, *and* either:
6889         //   a. RefCountSubscriber doesn't have a reference to the shared connection
6890         //      Subscription yet, or,
6891         //   b. RefCountSubscriber's connection Subscription reference is identical
6892         //      to the shared connection Subscription
6893         ///
6894         var connection = this.connection;
6895         var sharedConnection = connectable._connection;
6896         this.connection = null;
6897         if (sharedConnection && (!connection || sharedConnection === connection)) {
6898             sharedConnection.unsubscribe();
6899         }
6900     };
6901     return RefCountSubscriber;
6902 }(Subscriber_1.Subscriber));
6903
6904 },{"../Observable":28,"../Subject":33,"../Subscriber":35,"../Subscription":36}],82:[function(require,module,exports){
6905 "use strict";
6906 var __extends = (this && this.__extends) || function (d, b) {
6907     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6908     function __() { this.constructor = d; }
6909     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6910 };
6911 var Observable_1 = require('../Observable');
6912 var subscribeToResult_1 = require('../util/subscribeToResult');
6913 var OuterSubscriber_1 = require('../OuterSubscriber');
6914 /**
6915  * We need this JSDoc comment for affecting ESDoc.
6916  * @extends {Ignored}
6917  * @hide true
6918  */
6919 var DeferObservable = (function (_super) {
6920     __extends(DeferObservable, _super);
6921     function DeferObservable(observableFactory) {
6922         _super.call(this);
6923         this.observableFactory = observableFactory;
6924     }
6925     /**
6926      * Creates an Observable that, on subscribe, calls an Observable factory to
6927      * make an Observable for each new Observer.
6928      *
6929      * <span class="informal">Creates the Observable lazily, that is, only when it
6930      * is subscribed.
6931      * </span>
6932      *
6933      * <img src="./img/defer.png" width="100%">
6934      *
6935      * `defer` allows you to create the Observable only when the Observer
6936      * subscribes, and create a fresh Observable for each Observer. It waits until
6937      * an Observer subscribes to it, and then it generates an Observable,
6938      * typically with an Observable factory function. It does this afresh for each
6939      * subscriber, so although each subscriber may think it is subscribing to the
6940      * same Observable, in fact each subscriber gets its own individual
6941      * Observable.
6942      *
6943      * @example <caption>Subscribe to either an Observable of clicks or an Observable of interval, at random</caption>
6944      * var clicksOrInterval = Rx.Observable.defer(function () {
6945      *   if (Math.random() > 0.5) {
6946      *     return Rx.Observable.fromEvent(document, 'click');
6947      *   } else {
6948      *     return Rx.Observable.interval(1000);
6949      *   }
6950      * });
6951      * clicksOrInterval.subscribe(x => console.log(x));
6952      *
6953      * @see {@link create}
6954      *
6955      * @param {function(): Observable|Promise} observableFactory The Observable
6956      * factory function to invoke for each Observer that subscribes to the output
6957      * Observable. May also return a Promise, which will be converted on the fly
6958      * to an Observable.
6959      * @return {Observable} An Observable whose Observers' subscriptions trigger
6960      * an invocation of the given Observable factory function.
6961      * @static true
6962      * @name defer
6963      * @owner Observable
6964      */
6965     DeferObservable.create = function (observableFactory) {
6966         return new DeferObservable(observableFactory);
6967     };
6968     DeferObservable.prototype._subscribe = function (subscriber) {
6969         return new DeferSubscriber(subscriber, this.observableFactory);
6970     };
6971     return DeferObservable;
6972 }(Observable_1.Observable));
6973 exports.DeferObservable = DeferObservable;
6974 var DeferSubscriber = (function (_super) {
6975     __extends(DeferSubscriber, _super);
6976     function DeferSubscriber(destination, factory) {
6977         _super.call(this, destination);
6978         this.factory = factory;
6979         this.tryDefer();
6980     }
6981     DeferSubscriber.prototype.tryDefer = function () {
6982         try {
6983             this._callFactory();
6984         }
6985         catch (err) {
6986             this._error(err);
6987         }
6988     };
6989     DeferSubscriber.prototype._callFactory = function () {
6990         var result = this.factory();
6991         if (result) {
6992             this.add(subscribeToResult_1.subscribeToResult(this, result));
6993         }
6994     };
6995     return DeferSubscriber;
6996 }(OuterSubscriber_1.OuterSubscriber));
6997
6998 },{"../Observable":28,"../OuterSubscriber":30,"../util/subscribeToResult":157}],83:[function(require,module,exports){
6999 "use strict";
7000 var __extends = (this && this.__extends) || function (d, b) {
7001     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7002     function __() { this.constructor = d; }
7003     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7004 };
7005 var Observable_1 = require('../Observable');
7006 /**
7007  * We need this JSDoc comment for affecting ESDoc.
7008  * @extends {Ignored}
7009  * @hide true
7010  */
7011 var EmptyObservable = (function (_super) {
7012     __extends(EmptyObservable, _super);
7013     function EmptyObservable(scheduler) {
7014         _super.call(this);
7015         this.scheduler = scheduler;
7016     }
7017     /**
7018      * Creates an Observable that emits no items to the Observer and immediately
7019      * emits a complete notification.
7020      *
7021      * <span class="informal">Just emits 'complete', and nothing else.
7022      * </span>
7023      *
7024      * <img src="./img/empty.png" width="100%">
7025      *
7026      * This static operator is useful for creating a simple Observable that only
7027      * emits the complete notification. It can be used for composing with other
7028      * Observables, such as in a {@link mergeMap}.
7029      *
7030      * @example <caption>Emit the number 7, then complete.</caption>
7031      * var result = Rx.Observable.empty().startWith(7);
7032      * result.subscribe(x => console.log(x));
7033      *
7034      * @example <caption>Map and flatten only odd numbers to the sequence 'a', 'b', 'c'</caption>
7035      * var interval = Rx.Observable.interval(1000);
7036      * var result = interval.mergeMap(x =>
7037      *   x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.empty()
7038      * );
7039      * result.subscribe(x => console.log(x));
7040      *
7041      * @see {@link create}
7042      * @see {@link never}
7043      * @see {@link of}
7044      * @see {@link throw}
7045      *
7046      * @param {Scheduler} [scheduler] A {@link Scheduler} to use for scheduling
7047      * the emission of the complete notification.
7048      * @return {Observable} An "empty" Observable: emits only the complete
7049      * notification.
7050      * @static true
7051      * @name empty
7052      * @owner Observable
7053      */
7054     EmptyObservable.create = function (scheduler) {
7055         return new EmptyObservable(scheduler);
7056     };
7057     EmptyObservable.dispatch = function (arg) {
7058         var subscriber = arg.subscriber;
7059         subscriber.complete();
7060     };
7061     EmptyObservable.prototype._subscribe = function (subscriber) {
7062         var scheduler = this.scheduler;
7063         if (scheduler) {
7064             return scheduler.schedule(EmptyObservable.dispatch, 0, { subscriber: subscriber });
7065         }
7066         else {
7067             subscriber.complete();
7068         }
7069     };
7070     return EmptyObservable;
7071 }(Observable_1.Observable));
7072 exports.EmptyObservable = EmptyObservable;
7073
7074 },{"../Observable":28}],84:[function(require,module,exports){
7075 "use strict";
7076 var __extends = (this && this.__extends) || function (d, b) {
7077     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7078     function __() { this.constructor = d; }
7079     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7080 };
7081 var Observable_1 = require('../Observable');
7082 /**
7083  * We need this JSDoc comment for affecting ESDoc.
7084  * @extends {Ignored}
7085  * @hide true
7086  */
7087 var ErrorObservable = (function (_super) {
7088     __extends(ErrorObservable, _super);
7089     function ErrorObservable(error, scheduler) {
7090         _super.call(this);
7091         this.error = error;
7092         this.scheduler = scheduler;
7093     }
7094     /**
7095      * Creates an Observable that emits no items to the Observer and immediately
7096      * emits an error notification.
7097      *
7098      * <span class="informal">Just emits 'error', and nothing else.
7099      * </span>
7100      *
7101      * <img src="./img/throw.png" width="100%">
7102      *
7103      * This static operator is useful for creating a simple Observable that only
7104      * emits the error notification. It can be used for composing with other
7105      * Observables, such as in a {@link mergeMap}.
7106      *
7107      * @example <caption>Emit the number 7, then emit an error.</caption>
7108      * var result = Rx.Observable.throw(new Error('oops!')).startWith(7);
7109      * result.subscribe(x => console.log(x), e => console.error(e));
7110      *
7111      * @example <caption>Map and flattens numbers to the sequence 'a', 'b', 'c', but throw an error for 13</caption>
7112      * var interval = Rx.Observable.interval(1000);
7113      * var result = interval.mergeMap(x =>
7114      *   x === 13 ?
7115      *     Rx.Observable.throw('Thirteens are bad') :
7116      *     Rx.Observable.of('a', 'b', 'c')
7117      * );
7118      * result.subscribe(x => console.log(x), e => console.error(e));
7119      *
7120      * @see {@link create}
7121      * @see {@link empty}
7122      * @see {@link never}
7123      * @see {@link of}
7124      *
7125      * @param {any} error The particular Error to pass to the error notification.
7126      * @param {Scheduler} [scheduler] A {@link Scheduler} to use for scheduling
7127      * the emission of the error notification.
7128      * @return {Observable} An error Observable: emits only the error notification
7129      * using the given error argument.
7130      * @static true
7131      * @name throw
7132      * @owner Observable
7133      */
7134     ErrorObservable.create = function (error, scheduler) {
7135         return new ErrorObservable(error, scheduler);
7136     };
7137     ErrorObservable.dispatch = function (arg) {
7138         var error = arg.error, subscriber = arg.subscriber;
7139         subscriber.error(error);
7140     };
7141     ErrorObservable.prototype._subscribe = function (subscriber) {
7142         var error = this.error;
7143         var scheduler = this.scheduler;
7144         if (scheduler) {
7145             return scheduler.schedule(ErrorObservable.dispatch, 0, {
7146                 error: error, subscriber: subscriber
7147             });
7148         }
7149         else {
7150             subscriber.error(error);
7151         }
7152     };
7153     return ErrorObservable;
7154 }(Observable_1.Observable));
7155 exports.ErrorObservable = ErrorObservable;
7156
7157 },{"../Observable":28}],85:[function(require,module,exports){
7158 "use strict";
7159 var __extends = (this && this.__extends) || function (d, b) {
7160     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7161     function __() { this.constructor = d; }
7162     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7163 };
7164 var Observable_1 = require('../Observable');
7165 var tryCatch_1 = require('../util/tryCatch');
7166 var isFunction_1 = require('../util/isFunction');
7167 var errorObject_1 = require('../util/errorObject');
7168 var Subscription_1 = require('../Subscription');
7169 function isNodeStyleEventEmmitter(sourceObj) {
7170     return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
7171 }
7172 function isJQueryStyleEventEmitter(sourceObj) {
7173     return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
7174 }
7175 function isNodeList(sourceObj) {
7176     return !!sourceObj && sourceObj.toString() === '[object NodeList]';
7177 }
7178 function isHTMLCollection(sourceObj) {
7179     return !!sourceObj && sourceObj.toString() === '[object HTMLCollection]';
7180 }
7181 function isEventTarget(sourceObj) {
7182     return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
7183 }
7184 /**
7185  * We need this JSDoc comment for affecting ESDoc.
7186  * @extends {Ignored}
7187  * @hide true
7188  */
7189 var FromEventObservable = (function (_super) {
7190     __extends(FromEventObservable, _super);
7191     function FromEventObservable(sourceObj, eventName, selector, options) {
7192         _super.call(this);
7193         this.sourceObj = sourceObj;
7194         this.eventName = eventName;
7195         this.selector = selector;
7196         this.options = options;
7197     }
7198     /* tslint:enable:max-line-length */
7199     /**
7200      * Creates an Observable that emits events of a specific type coming from the
7201      * given event target.
7202      *
7203      * <span class="informal">Creates an Observable from DOM events, or Node
7204      * EventEmitter events or others.</span>
7205      *
7206      * <img src="./img/fromEvent.png" width="100%">
7207      *
7208      * Creates an Observable by attaching an event listener to an "event target",
7209      * which may be an object with `addEventListener` and `removeEventListener`,
7210      * a Node.js EventEmitter, a jQuery style EventEmitter, a NodeList from the
7211      * DOM, or an HTMLCollection from the DOM. The event handler is attached when
7212      * the output Observable is subscribed, and removed when the Subscription is
7213      * unsubscribed.
7214      *
7215      * @example <caption>Emits clicks happening on the DOM document</caption>
7216      * var clicks = Rx.Observable.fromEvent(document, 'click');
7217      * clicks.subscribe(x => console.log(x));
7218      *
7219      * @see {@link from}
7220      * @see {@link fromEventPattern}
7221      *
7222      * @param {EventTargetLike} target The DOMElement, event target, Node.js
7223      * EventEmitter, NodeList or HTMLCollection to attach the event handler to.
7224      * @param {string} eventName The event name of interest, being emitted by the
7225      * `target`.
7226      * @parm {EventListenerOptions} [options] Options to pass through to addEventListener
7227      * @param {SelectorMethodSignature<T>} [selector] An optional function to
7228      * post-process results. It takes the arguments from the event handler and
7229      * should return a single value.
7230      * @return {Observable<T>}
7231      * @static true
7232      * @name fromEvent
7233      * @owner Observable
7234      */
7235     FromEventObservable.create = function (target, eventName, options, selector) {
7236         if (isFunction_1.isFunction(options)) {
7237             selector = options;
7238             options = undefined;
7239         }
7240         return new FromEventObservable(target, eventName, selector, options);
7241     };
7242     FromEventObservable.setupSubscription = function (sourceObj, eventName, handler, subscriber, options) {
7243         var unsubscribe;
7244         if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
7245             for (var i = 0, len = sourceObj.length; i < len; i++) {
7246                 FromEventObservable.setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
7247             }
7248         }
7249         else if (isEventTarget(sourceObj)) {
7250             var source_1 = sourceObj;
7251             sourceObj.addEventListener(eventName, handler, options);
7252             unsubscribe = function () { return source_1.removeEventListener(eventName, handler); };
7253         }
7254         else if (isJQueryStyleEventEmitter(sourceObj)) {
7255             var source_2 = sourceObj;
7256             sourceObj.on(eventName, handler);
7257             unsubscribe = function () { return source_2.off(eventName, handler); };
7258         }
7259         else if (isNodeStyleEventEmmitter(sourceObj)) {
7260             var source_3 = sourceObj;
7261             sourceObj.addListener(eventName, handler);
7262             unsubscribe = function () { return source_3.removeListener(eventName, handler); };
7263         }
7264         subscriber.add(new Subscription_1.Subscription(unsubscribe));
7265     };
7266     FromEventObservable.prototype._subscribe = function (subscriber) {
7267         var sourceObj = this.sourceObj;
7268         var eventName = this.eventName;
7269         var options = this.options;
7270         var selector = this.selector;
7271         var handler = selector ? function () {
7272             var args = [];
7273             for (var _i = 0; _i < arguments.length; _i++) {
7274                 args[_i - 0] = arguments[_i];
7275             }
7276             var result = tryCatch_1.tryCatch(selector).apply(void 0, args);
7277             if (result === errorObject_1.errorObject) {
7278                 subscriber.error(errorObject_1.errorObject.e);
7279             }
7280             else {
7281                 subscriber.next(result);
7282             }
7283         } : function (e) { return subscriber.next(e); };
7284         FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber, options);
7285     };
7286     return FromEventObservable;
7287 }(Observable_1.Observable));
7288 exports.FromEventObservable = FromEventObservable;
7289
7290 },{"../Observable":28,"../Subscription":36,"../util/errorObject":150,"../util/isFunction":152,"../util/tryCatch":159}],86:[function(require,module,exports){
7291 "use strict";
7292 var __extends = (this && this.__extends) || function (d, b) {
7293     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7294     function __() { this.constructor = d; }
7295     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7296 };
7297 var isArray_1 = require('../util/isArray');
7298 var isPromise_1 = require('../util/isPromise');
7299 var PromiseObservable_1 = require('./PromiseObservable');
7300 var IteratorObservable_1 = require('./IteratorObservable');
7301 var ArrayObservable_1 = require('./ArrayObservable');
7302 var ArrayLikeObservable_1 = require('./ArrayLikeObservable');
7303 var iterator_1 = require('../symbol/iterator');
7304 var Observable_1 = require('../Observable');
7305 var observeOn_1 = require('../operator/observeOn');
7306 var observable_1 = require('../symbol/observable');
7307 var isArrayLike = (function (x) { return x && typeof x.length === 'number'; });
7308 /**
7309  * We need this JSDoc comment for affecting ESDoc.
7310  * @extends {Ignored}
7311  * @hide true
7312  */
7313 var FromObservable = (function (_super) {
7314     __extends(FromObservable, _super);
7315     function FromObservable(ish, scheduler) {
7316         _super.call(this, null);
7317         this.ish = ish;
7318         this.scheduler = scheduler;
7319     }
7320     /**
7321      * Creates an Observable from an Array, an array-like object, a Promise, an
7322      * iterable object, or an Observable-like object.
7323      *
7324      * <span class="informal">Converts almost anything to an Observable.</span>
7325      *
7326      * <img src="./img/from.png" width="100%">
7327      *
7328      * Convert various other objects and data types into Observables. `from`
7329      * converts a Promise or an array-like or an
7330      * [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)
7331      * object into an Observable that emits the items in that promise or array or
7332      * iterable. A String, in this context, is treated as an array of characters.
7333      * Observable-like objects (contains a function named with the ES2015 Symbol
7334      * for Observable) can also be converted through this operator.
7335      *
7336      * @example <caption>Converts an array to an Observable</caption>
7337      * var array = [10, 20, 30];
7338      * var result = Rx.Observable.from(array);
7339      * result.subscribe(x => console.log(x));
7340      *
7341      * @example <caption>Convert an infinite iterable (from a generator) to an Observable</caption>
7342      * function* generateDoubles(seed) {
7343      *   var i = seed;
7344      *   while (true) {
7345      *     yield i;
7346      *     i = 2 * i; // double it
7347      *   }
7348      * }
7349      *
7350      * var iterator = generateDoubles(3);
7351      * var result = Rx.Observable.from(iterator).take(10);
7352      * result.subscribe(x => console.log(x));
7353      *
7354      * @see {@link create}
7355      * @see {@link fromEvent}
7356      * @see {@link fromEventPattern}
7357      * @see {@link fromPromise}
7358      *
7359      * @param {ObservableInput<T>} ish A subscribable object, a Promise, an
7360      * Observable-like, an Array, an iterable or an array-like object to be
7361      * converted.
7362      * @param {Scheduler} [scheduler] The scheduler on which to schedule the
7363      * emissions of values.
7364      * @return {Observable<T>} The Observable whose values are originally from the
7365      * input object that was converted.
7366      * @static true
7367      * @name from
7368      * @owner Observable
7369      */
7370     FromObservable.create = function (ish, scheduler) {
7371         if (ish != null) {
7372             if (typeof ish[observable_1.$$observable] === 'function') {
7373                 if (ish instanceof Observable_1.Observable && !scheduler) {
7374                     return ish;
7375                 }
7376                 return new FromObservable(ish, scheduler);
7377             }
7378             else if (isArray_1.isArray(ish)) {
7379                 return new ArrayObservable_1.ArrayObservable(ish, scheduler);
7380             }
7381             else if (isPromise_1.isPromise(ish)) {
7382                 return new PromiseObservable_1.PromiseObservable(ish, scheduler);
7383             }
7384             else if (typeof ish[iterator_1.$$iterator] === 'function' || typeof ish === 'string') {
7385                 return new IteratorObservable_1.IteratorObservable(ish, scheduler);
7386             }
7387             else if (isArrayLike(ish)) {
7388                 return new ArrayLikeObservable_1.ArrayLikeObservable(ish, scheduler);
7389             }
7390         }
7391         throw new TypeError((ish !== null && typeof ish || ish) + ' is not observable');
7392     };
7393     FromObservable.prototype._subscribe = function (subscriber) {
7394         var ish = this.ish;
7395         var scheduler = this.scheduler;
7396         if (scheduler == null) {
7397             return ish[observable_1.$$observable]().subscribe(subscriber);
7398         }
7399         else {
7400             return ish[observable_1.$$observable]().subscribe(new observeOn_1.ObserveOnSubscriber(subscriber, scheduler, 0));
7401         }
7402     };
7403     return FromObservable;
7404 }(Observable_1.Observable));
7405 exports.FromObservable = FromObservable;
7406
7407 },{"../Observable":28,"../operator/observeOn":120,"../symbol/iterator":142,"../symbol/observable":143,"../util/isArray":151,"../util/isPromise":154,"./ArrayLikeObservable":79,"./ArrayObservable":80,"./IteratorObservable":87,"./PromiseObservable":89}],87:[function(require,module,exports){
7408 "use strict";
7409 var __extends = (this && this.__extends) || function (d, b) {
7410     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7411     function __() { this.constructor = d; }
7412     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7413 };
7414 var root_1 = require('../util/root');
7415 var Observable_1 = require('../Observable');
7416 var iterator_1 = require('../symbol/iterator');
7417 /**
7418  * We need this JSDoc comment for affecting ESDoc.
7419  * @extends {Ignored}
7420  * @hide true
7421  */
7422 var IteratorObservable = (function (_super) {
7423     __extends(IteratorObservable, _super);
7424     function IteratorObservable(iterator, scheduler) {
7425         _super.call(this);
7426         this.scheduler = scheduler;
7427         if (iterator == null) {
7428             throw new Error('iterator cannot be null.');
7429         }
7430         this.iterator = getIterator(iterator);
7431     }
7432     IteratorObservable.create = function (iterator, scheduler) {
7433         return new IteratorObservable(iterator, scheduler);
7434     };
7435     IteratorObservable.dispatch = function (state) {
7436         var index = state.index, hasError = state.hasError, iterator = state.iterator, subscriber = state.subscriber;
7437         if (hasError) {
7438             subscriber.error(state.error);
7439             return;
7440         }
7441         var result = iterator.next();
7442         if (result.done) {
7443             subscriber.complete();
7444             return;
7445         }
7446         subscriber.next(result.value);
7447         state.index = index + 1;
7448         if (subscriber.closed) {
7449             return;
7450         }
7451         this.schedule(state);
7452     };
7453     IteratorObservable.prototype._subscribe = function (subscriber) {
7454         var index = 0;
7455         var _a = this, iterator = _a.iterator, scheduler = _a.scheduler;
7456         if (scheduler) {
7457             return scheduler.schedule(IteratorObservable.dispatch, 0, {
7458                 index: index, iterator: iterator, subscriber: subscriber
7459             });
7460         }
7461         else {
7462             do {
7463                 var result = iterator.next();
7464                 if (result.done) {
7465                     subscriber.complete();
7466                     break;
7467                 }
7468                 else {
7469                     subscriber.next(result.value);
7470                 }
7471                 if (subscriber.closed) {
7472                     break;
7473                 }
7474             } while (true);
7475         }
7476     };
7477     return IteratorObservable;
7478 }(Observable_1.Observable));
7479 exports.IteratorObservable = IteratorObservable;
7480 var StringIterator = (function () {
7481     function StringIterator(str, idx, len) {
7482         if (idx === void 0) { idx = 0; }
7483         if (len === void 0) { len = str.length; }
7484         this.str = str;
7485         this.idx = idx;
7486         this.len = len;
7487     }
7488     StringIterator.prototype[iterator_1.$$iterator] = function () { return (this); };
7489     StringIterator.prototype.next = function () {
7490         return this.idx < this.len ? {
7491             done: false,
7492             value: this.str.charAt(this.idx++)
7493         } : {
7494             done: true,
7495             value: undefined
7496         };
7497     };
7498     return StringIterator;
7499 }());
7500 var ArrayIterator = (function () {
7501     function ArrayIterator(arr, idx, len) {
7502         if (idx === void 0) { idx = 0; }
7503         if (len === void 0) { len = toLength(arr); }
7504         this.arr = arr;
7505         this.idx = idx;
7506         this.len = len;
7507     }
7508     ArrayIterator.prototype[iterator_1.$$iterator] = function () { return this; };
7509     ArrayIterator.prototype.next = function () {
7510         return this.idx < this.len ? {
7511             done: false,
7512             value: this.arr[this.idx++]
7513         } : {
7514             done: true,
7515             value: undefined
7516         };
7517     };
7518     return ArrayIterator;
7519 }());
7520 function getIterator(obj) {
7521     var i = obj[iterator_1.$$iterator];
7522     if (!i && typeof obj === 'string') {
7523         return new StringIterator(obj);
7524     }
7525     if (!i && obj.length !== undefined) {
7526         return new ArrayIterator(obj);
7527     }
7528     if (!i) {
7529         throw new TypeError('object is not iterable');
7530     }
7531     return obj[iterator_1.$$iterator]();
7532 }
7533 var maxSafeInteger = Math.pow(2, 53) - 1;
7534 function toLength(o) {
7535     var len = +o.length;
7536     if (isNaN(len)) {
7537         return 0;
7538     }
7539     if (len === 0 || !numberIsFinite(len)) {
7540         return len;
7541     }
7542     len = sign(len) * Math.floor(Math.abs(len));
7543     if (len <= 0) {
7544         return 0;
7545     }
7546     if (len > maxSafeInteger) {
7547         return maxSafeInteger;
7548     }
7549     return len;
7550 }
7551 function numberIsFinite(value) {
7552     return typeof value === 'number' && root_1.root.isFinite(value);
7553 }
7554 function sign(value) {
7555     var valueAsNumber = +value;
7556     if (valueAsNumber === 0) {
7557         return valueAsNumber;
7558     }
7559     if (isNaN(valueAsNumber)) {
7560         return valueAsNumber;
7561     }
7562     return valueAsNumber < 0 ? -1 : 1;
7563 }
7564
7565 },{"../Observable":28,"../symbol/iterator":142,"../util/root":156}],88:[function(require,module,exports){
7566 "use strict";
7567 var __extends = (this && this.__extends) || function (d, b) {
7568     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7569     function __() { this.constructor = d; }
7570     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7571 };
7572 var Observable_1 = require('../Observable');
7573 var ConnectableObservable_1 = require('../observable/ConnectableObservable');
7574 var MulticastObservable = (function (_super) {
7575     __extends(MulticastObservable, _super);
7576     function MulticastObservable(source, subjectFactory, selector) {
7577         _super.call(this);
7578         this.source = source;
7579         this.subjectFactory = subjectFactory;
7580         this.selector = selector;
7581     }
7582     MulticastObservable.prototype._subscribe = function (subscriber) {
7583         var _a = this, selector = _a.selector, source = _a.source;
7584         var connectable = new ConnectableObservable_1.ConnectableObservable(source, this.subjectFactory);
7585         var subscription = selector(connectable).subscribe(subscriber);
7586         subscription.add(connectable.connect());
7587         return subscription;
7588     };
7589     return MulticastObservable;
7590 }(Observable_1.Observable));
7591 exports.MulticastObservable = MulticastObservable;
7592
7593 },{"../Observable":28,"../observable/ConnectableObservable":81}],89:[function(require,module,exports){
7594 "use strict";
7595 var __extends = (this && this.__extends) || function (d, b) {
7596     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7597     function __() { this.constructor = d; }
7598     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7599 };
7600 var root_1 = require('../util/root');
7601 var Observable_1 = require('../Observable');
7602 /**
7603  * We need this JSDoc comment for affecting ESDoc.
7604  * @extends {Ignored}
7605  * @hide true
7606  */
7607 var PromiseObservable = (function (_super) {
7608     __extends(PromiseObservable, _super);
7609     function PromiseObservable(promise, scheduler) {
7610         _super.call(this);
7611         this.promise = promise;
7612         this.scheduler = scheduler;
7613     }
7614     /**
7615      * Converts a Promise to an Observable.
7616      *
7617      * <span class="informal">Returns an Observable that just emits the Promise's
7618      * resolved value, then completes.</span>
7619      *
7620      * Converts an ES2015 Promise or a Promises/A+ spec compliant Promise to an
7621      * Observable. If the Promise resolves with a value, the output Observable
7622      * emits that resolved value as a `next`, and then completes. If the Promise
7623      * is rejected, then the output Observable emits the corresponding Error.
7624      *
7625      * @example <caption>Convert the Promise returned by Fetch to an Observable</caption>
7626      * var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
7627      * result.subscribe(x => console.log(x), e => console.error(e));
7628      *
7629      * @see {@link bindCallback}
7630      * @see {@link from}
7631      *
7632      * @param {Promise<T>} promise The promise to be converted.
7633      * @param {Scheduler} [scheduler] An optional Scheduler to use for scheduling
7634      * the delivery of the resolved value (or the rejection).
7635      * @return {Observable<T>} An Observable which wraps the Promise.
7636      * @static true
7637      * @name fromPromise
7638      * @owner Observable
7639      */
7640     PromiseObservable.create = function (promise, scheduler) {
7641         return new PromiseObservable(promise, scheduler);
7642     };
7643     PromiseObservable.prototype._subscribe = function (subscriber) {
7644         var _this = this;
7645         var promise = this.promise;
7646         var scheduler = this.scheduler;
7647         if (scheduler == null) {
7648             if (this._isScalar) {
7649                 if (!subscriber.closed) {
7650                     subscriber.next(this.value);
7651                     subscriber.complete();
7652                 }
7653             }
7654             else {
7655                 promise.then(function (value) {
7656                     _this.value = value;
7657                     _this._isScalar = true;
7658                     if (!subscriber.closed) {
7659                         subscriber.next(value);
7660                         subscriber.complete();
7661                     }
7662                 }, function (err) {
7663                     if (!subscriber.closed) {
7664                         subscriber.error(err);
7665                     }
7666                 })
7667                     .then(null, function (err) {
7668                     // escape the promise trap, throw unhandled errors
7669                     root_1.root.setTimeout(function () { throw err; });
7670                 });
7671             }
7672         }
7673         else {
7674             if (this._isScalar) {
7675                 if (!subscriber.closed) {
7676                     return scheduler.schedule(dispatchNext, 0, { value: this.value, subscriber: subscriber });
7677                 }
7678             }
7679             else {
7680                 promise.then(function (value) {
7681                     _this.value = value;
7682                     _this._isScalar = true;
7683                     if (!subscriber.closed) {
7684                         subscriber.add(scheduler.schedule(dispatchNext, 0, { value: value, subscriber: subscriber }));
7685                     }
7686                 }, function (err) {
7687                     if (!subscriber.closed) {
7688                         subscriber.add(scheduler.schedule(dispatchError, 0, { err: err, subscriber: subscriber }));
7689                     }
7690                 })
7691                     .then(null, function (err) {
7692                     // escape the promise trap, throw unhandled errors
7693                     root_1.root.setTimeout(function () { throw err; });
7694                 });
7695             }
7696         }
7697     };
7698     return PromiseObservable;
7699 }(Observable_1.Observable));
7700 exports.PromiseObservable = PromiseObservable;
7701 function dispatchNext(arg) {
7702     var value = arg.value, subscriber = arg.subscriber;
7703     if (!subscriber.closed) {
7704         subscriber.next(value);
7705         subscriber.complete();
7706     }
7707 }
7708 function dispatchError(arg) {
7709     var err = arg.err, subscriber = arg.subscriber;
7710     if (!subscriber.closed) {
7711         subscriber.error(err);
7712     }
7713 }
7714
7715 },{"../Observable":28,"../util/root":156}],90:[function(require,module,exports){
7716 "use strict";
7717 var __extends = (this && this.__extends) || function (d, b) {
7718     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7719     function __() { this.constructor = d; }
7720     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7721 };
7722 var Observable_1 = require('../Observable');
7723 /**
7724  * We need this JSDoc comment for affecting ESDoc.
7725  * @extends {Ignored}
7726  * @hide true
7727  */
7728 var ScalarObservable = (function (_super) {
7729     __extends(ScalarObservable, _super);
7730     function ScalarObservable(value, scheduler) {
7731         _super.call(this);
7732         this.value = value;
7733         this.scheduler = scheduler;
7734         this._isScalar = true;
7735         if (scheduler) {
7736             this._isScalar = false;
7737         }
7738     }
7739     ScalarObservable.create = function (value, scheduler) {
7740         return new ScalarObservable(value, scheduler);
7741     };
7742     ScalarObservable.dispatch = function (state) {
7743         var done = state.done, value = state.value, subscriber = state.subscriber;
7744         if (done) {
7745             subscriber.complete();
7746             return;
7747         }
7748         subscriber.next(value);
7749         if (subscriber.closed) {
7750             return;
7751         }
7752         state.done = true;
7753         this.schedule(state);
7754     };
7755     ScalarObservable.prototype._subscribe = function (subscriber) {
7756         var value = this.value;
7757         var scheduler = this.scheduler;
7758         if (scheduler) {
7759             return scheduler.schedule(ScalarObservable.dispatch, 0, {
7760                 done: false, value: value, subscriber: subscriber
7761             });
7762         }
7763         else {
7764             subscriber.next(value);
7765             if (!subscriber.closed) {
7766                 subscriber.complete();
7767             }
7768         }
7769     };
7770     return ScalarObservable;
7771 }(Observable_1.Observable));
7772 exports.ScalarObservable = ScalarObservable;
7773
7774 },{"../Observable":28}],91:[function(require,module,exports){
7775 "use strict";
7776 var isScheduler_1 = require('../util/isScheduler');
7777 var isArray_1 = require('../util/isArray');
7778 var ArrayObservable_1 = require('./ArrayObservable');
7779 var combineLatest_1 = require('../operator/combineLatest');
7780 /* tslint:enable:max-line-length */
7781 /**
7782  * Combines multiple Observables to create an Observable whose values are
7783  * calculated from the latest values of each of its input Observables.
7784  *
7785  * <span class="informal">Whenever any input Observable emits a value, it
7786  * computes a formula using the latest values from all the inputs, then emits
7787  * the output of that formula.</span>
7788  *
7789  * <img src="./img/combineLatest.png" width="100%">
7790  *
7791  * `combineLatest` combines the values from all the Observables passed as
7792  * arguments. This is done by subscribing to each Observable, in order, and
7793  * collecting an array of each of the most recent values any time any of the
7794  * input Observables emits, then either taking that array and passing it as
7795  * arguments to an optional `project` function and emitting the return value of
7796  * that, or just emitting the array of recent values directly if there is no
7797  * `project` function.
7798  *
7799  * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
7800  * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
7801  * var height = Rx.Observable.of(1.76, 1.77, 1.78);
7802  * var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => w / (h * h));
7803  * bmi.subscribe(x => console.log('BMI is ' + x));
7804  *
7805  * @see {@link combineAll}
7806  * @see {@link merge}
7807  * @see {@link withLatestFrom}
7808  *
7809  * @param {Observable} observable1 An input Observable to combine with the
7810  * source Observable.
7811  * @param {Observable} observable2 An input Observable to combine with the
7812  * source Observable. More than one input Observables may be given as argument.
7813  * @param {function} [project] An optional function to project the values from
7814  * the combined latest values into a new value on the output Observable.
7815  * @param {Scheduler} [scheduler=null] The Scheduler to use for subscribing to
7816  * each input Observable.
7817  * @return {Observable} An Observable of projected values from the most recent
7818  * values from each input Observable, or an array of the most recent values from
7819  * each input Observable.
7820  * @static true
7821  * @name combineLatest
7822  * @owner Observable
7823  */
7824 function combineLatest() {
7825     var observables = [];
7826     for (var _i = 0; _i < arguments.length; _i++) {
7827         observables[_i - 0] = arguments[_i];
7828     }
7829     var project = null;
7830     var scheduler = null;
7831     if (isScheduler_1.isScheduler(observables[observables.length - 1])) {
7832         scheduler = observables.pop();
7833     }
7834     if (typeof observables[observables.length - 1] === 'function') {
7835         project = observables.pop();
7836     }
7837     // if the first and only other argument besides the resultSelector is an array
7838     // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
7839     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
7840         observables = observables[0];
7841     }
7842     return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new combineLatest_1.CombineLatestOperator(project));
7843 }
7844 exports.combineLatest = combineLatest;
7845
7846 },{"../operator/combineLatest":104,"../util/isArray":151,"../util/isScheduler":155,"./ArrayObservable":80}],92:[function(require,module,exports){
7847 "use strict";
7848 var DeferObservable_1 = require('./DeferObservable');
7849 exports.defer = DeferObservable_1.DeferObservable.create;
7850
7851 },{"./DeferObservable":82}],93:[function(require,module,exports){
7852 "use strict";
7853 var EmptyObservable_1 = require('./EmptyObservable');
7854 exports.empty = EmptyObservable_1.EmptyObservable.create;
7855
7856 },{"./EmptyObservable":83}],94:[function(require,module,exports){
7857 "use strict";
7858 var FromObservable_1 = require('./FromObservable');
7859 exports.from = FromObservable_1.FromObservable.create;
7860
7861 },{"./FromObservable":86}],95:[function(require,module,exports){
7862 "use strict";
7863 var FromEventObservable_1 = require('./FromEventObservable');
7864 exports.fromEvent = FromEventObservable_1.FromEventObservable.create;
7865
7866 },{"./FromEventObservable":85}],96:[function(require,module,exports){
7867 "use strict";
7868 var PromiseObservable_1 = require('./PromiseObservable');
7869 exports.fromPromise = PromiseObservable_1.PromiseObservable.create;
7870
7871 },{"./PromiseObservable":89}],97:[function(require,module,exports){
7872 "use strict";
7873 var merge_1 = require('../operator/merge');
7874 exports.merge = merge_1.mergeStatic;
7875
7876 },{"../operator/merge":116}],98:[function(require,module,exports){
7877 "use strict";
7878 var ArrayObservable_1 = require('./ArrayObservable');
7879 exports.of = ArrayObservable_1.ArrayObservable.of;
7880
7881 },{"./ArrayObservable":80}],99:[function(require,module,exports){
7882 "use strict";
7883 var ErrorObservable_1 = require('./ErrorObservable');
7884 exports._throw = ErrorObservable_1.ErrorObservable.create;
7885
7886 },{"./ErrorObservable":84}],100:[function(require,module,exports){
7887 "use strict";
7888 var zip_1 = require('../operator/zip');
7889 exports.zip = zip_1.zipStatic;
7890
7891 },{"../operator/zip":134}],101:[function(require,module,exports){
7892 "use strict";
7893 var __extends = (this && this.__extends) || function (d, b) {
7894     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7895     function __() { this.constructor = d; }
7896     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7897 };
7898 var OuterSubscriber_1 = require('../OuterSubscriber');
7899 var subscribeToResult_1 = require('../util/subscribeToResult');
7900 /**
7901  * Buffers the source Observable values until `closingNotifier` emits.
7902  *
7903  * <span class="informal">Collects values from the past as an array, and emits
7904  * that array only when another Observable emits.</span>
7905  *
7906  * <img src="./img/buffer.png" width="100%">
7907  *
7908  * Buffers the incoming Observable values until the given `closingNotifier`
7909  * Observable emits a value, at which point it emits the buffer on the output
7910  * Observable and starts a new buffer internally, awaiting the next time
7911  * `closingNotifier` emits.
7912  *
7913  * @example <caption>On every click, emit array of most recent interval events</caption>
7914  * var clicks = Rx.Observable.fromEvent(document, 'click');
7915  * var interval = Rx.Observable.interval(1000);
7916  * var buffered = interval.buffer(clicks);
7917  * buffered.subscribe(x => console.log(x));
7918  *
7919  * @see {@link bufferCount}
7920  * @see {@link bufferTime}
7921  * @see {@link bufferToggle}
7922  * @see {@link bufferWhen}
7923  * @see {@link window}
7924  *
7925  * @param {Observable<any>} closingNotifier An Observable that signals the
7926  * buffer to be emitted on the output Observable.
7927  * @return {Observable<T[]>} An Observable of buffers, which are arrays of
7928  * values.
7929  * @method buffer
7930  * @owner Observable
7931  */
7932 function buffer(closingNotifier) {
7933     return this.lift(new BufferOperator(closingNotifier));
7934 }
7935 exports.buffer = buffer;
7936 var BufferOperator = (function () {
7937     function BufferOperator(closingNotifier) {
7938         this.closingNotifier = closingNotifier;
7939     }
7940     BufferOperator.prototype.call = function (subscriber, source) {
7941         return source._subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
7942     };
7943     return BufferOperator;
7944 }());
7945 /**
7946  * We need this JSDoc comment for affecting ESDoc.
7947  * @ignore
7948  * @extends {Ignored}
7949  */
7950 var BufferSubscriber = (function (_super) {
7951     __extends(BufferSubscriber, _super);
7952     function BufferSubscriber(destination, closingNotifier) {
7953         _super.call(this, destination);
7954         this.buffer = [];
7955         this.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
7956     }
7957     BufferSubscriber.prototype._next = function (value) {
7958         this.buffer.push(value);
7959     };
7960     BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
7961         var buffer = this.buffer;
7962         this.buffer = [];
7963         this.destination.next(buffer);
7964     };
7965     return BufferSubscriber;
7966 }(OuterSubscriber_1.OuterSubscriber));
7967
7968 },{"../OuterSubscriber":30,"../util/subscribeToResult":157}],102:[function(require,module,exports){
7969 "use strict";
7970 var __extends = (this && this.__extends) || function (d, b) {
7971     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7972     function __() { this.constructor = d; }
7973     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7974 };
7975 var Subscriber_1 = require('../Subscriber');
7976 /**
7977  * Buffers the source Observable values until the size hits the maximum
7978  * `bufferSize` given.
7979  *
7980  * <span class="informal">Collects values from the past as an array, and emits
7981  * that array only when its size reaches `bufferSize`.</span>
7982  *
7983  * <img src="./img/bufferCount.png" width="100%">
7984  *
7985  * Buffers a number of values from the source Observable by `bufferSize` then
7986  * emits the buffer and clears it, and starts a new buffer each
7987  * `startBufferEvery` values. If `startBufferEvery` is not provided or is
7988  * `null`, then new buffers are started immediately at the start of the source
7989  * and when each buffer closes and is emitted.
7990  *
7991  * @example <caption>Emit the last two click events as an array</caption>
7992  * var clicks = Rx.Observable.fromEvent(document, 'click');
7993  * var buffered = clicks.bufferCount(2);
7994  * buffered.subscribe(x => console.log(x));
7995  *
7996  * @example <caption>On every click, emit the last two click events as an array</caption>
7997  * var clicks = Rx.Observable.fromEvent(document, 'click');
7998  * var buffered = clicks.bufferCount(2, 1);
7999  * buffered.subscribe(x => console.log(x));
8000  *
8001  * @see {@link buffer}
8002  * @see {@link bufferTime}
8003  * @see {@link bufferToggle}
8004  * @see {@link bufferWhen}
8005  * @see {@link pairwise}
8006  * @see {@link windowCount}
8007  *
8008  * @param {number} bufferSize The maximum size of the buffer emitted.
8009  * @param {number} [startBufferEvery] Interval at which to start a new buffer.
8010  * For example if `startBufferEvery` is `2`, then a new buffer will be started
8011  * on every other value from the source. A new buffer is started at the
8012  * beginning of the source by default.
8013  * @return {Observable<T[]>} An Observable of arrays of buffered values.
8014  * @method bufferCount
8015  * @owner Observable
8016  */
8017 function bufferCount(bufferSize, startBufferEvery) {
8018     if (startBufferEvery === void 0) { startBufferEvery = null; }
8019     return this.lift(new BufferCountOperator(bufferSize, startBufferEvery));
8020 }
8021 exports.bufferCount = bufferCount;
8022 var BufferCountOperator = (function () {
8023     function BufferCountOperator(bufferSize, startBufferEvery) {
8024         this.bufferSize = bufferSize;
8025         this.startBufferEvery = startBufferEvery;
8026     }
8027     BufferCountOperator.prototype.call = function (subscriber, source) {
8028         return source._subscribe(new BufferCountSubscriber(subscriber, this.bufferSize, this.startBufferEvery));
8029     };
8030     return BufferCountOperator;
8031 }());
8032 /**
8033  * We need this JSDoc comment for affecting ESDoc.
8034  * @ignore
8035  * @extends {Ignored}
8036  */
8037 var BufferCountSubscriber = (function (_super) {
8038     __extends(BufferCountSubscriber, _super);
8039     function BufferCountSubscriber(destination, bufferSize, startBufferEvery) {
8040         _super.call(this, destination);
8041         this.bufferSize = bufferSize;
8042         this.startBufferEvery = startBufferEvery;
8043         this.buffers = [[]];
8044         this.count = 0;
8045     }
8046     BufferCountSubscriber.prototype._next = function (value) {
8047         var count = (this.count += 1);
8048         var destination = this.destination;
8049         var bufferSize = this.bufferSize;
8050         var startBufferEvery = (this.startBufferEvery == null) ? bufferSize : this.startBufferEvery;
8051         var buffers = this.buffers;
8052         var len = buffers.length;
8053         var remove = -1;
8054         if (count % startBufferEvery === 0) {
8055             buffers.push([]);
8056         }
8057         for (var i = 0; i < len; i++) {
8058             var buffer = buffers[i];
8059             buffer.push(value);
8060             if (buffer.length === bufferSize) {
8061                 remove = i;
8062                 destination.next(buffer);
8063             }
8064         }
8065         if (remove !== -1) {
8066             buffers.splice(remove, 1);
8067         }
8068     };
8069     BufferCountSubscriber.prototype._complete = function () {
8070         var destination = this.destination;
8071         var buffers = this.buffers;
8072         while (buffers.length > 0) {
8073             var buffer = buffers.shift();
8074             if (buffer.length > 0) {
8075                 destination.next(buffer);
8076             }
8077         }
8078         _super.prototype._complete.call(this);
8079     };
8080     return BufferCountSubscriber;
8081 }(Subscriber_1.Subscriber));
8082
8083 },{"../Subscriber":35}],103:[function(require,module,exports){
8084 "use strict";
8085 var __extends = (this && this.__extends) || function (d, b) {
8086     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8087     function __() { this.constructor = d; }
8088     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8089 };
8090 var OuterSubscriber_1 = require('../OuterSubscriber');
8091 var subscribeToResult_1 = require('../util/subscribeToResult');
8092 /**
8093  * Catches errors on the observable to be handled by returning a new observable or throwing an error.
8094  * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
8095  *  is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
8096  *  is returned by the `selector` will be used to continue the observable chain.
8097  * @return {Observable} an observable that originates from either the source or the observable returned by the
8098  *  catch `selector` function.
8099  * @method catch
8100  * @owner Observable
8101  */
8102 function _catch(selector) {
8103     var operator = new CatchOperator(selector);
8104     var caught = this.lift(operator);
8105     return (operator.caught = caught);
8106 }
8107 exports._catch = _catch;
8108 var CatchOperator = (function () {
8109     function CatchOperator(selector) {
8110         this.selector = selector;
8111     }
8112     CatchOperator.prototype.call = function (subscriber, source) {
8113         return source._subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
8114     };
8115     return CatchOperator;
8116 }());
8117 /**
8118  * We need this JSDoc comment for affecting ESDoc.
8119  * @ignore
8120  * @extends {Ignored}
8121  */
8122 var CatchSubscriber = (function (_super) {
8123     __extends(CatchSubscriber, _super);
8124     function CatchSubscriber(destination, selector, caught) {
8125         _super.call(this, destination);
8126         this.selector = selector;
8127         this.caught = caught;
8128     }
8129     // NOTE: overriding `error` instead of `_error` because we don't want
8130     // to have this flag this subscriber as `isStopped`.
8131     CatchSubscriber.prototype.error = function (err) {
8132         if (!this.isStopped) {
8133             var result = void 0;
8134             try {
8135                 result = this.selector(err, this.caught);
8136             }
8137             catch (err) {
8138                 this.destination.error(err);
8139                 return;
8140             }
8141             this.unsubscribe();
8142             this.destination.remove(this);
8143             subscribeToResult_1.subscribeToResult(this, result);
8144         }
8145     };
8146     return CatchSubscriber;
8147 }(OuterSubscriber_1.OuterSubscriber));
8148
8149 },{"../OuterSubscriber":30,"../util/subscribeToResult":157}],104:[function(require,module,exports){
8150 "use strict";
8151 var __extends = (this && this.__extends) || function (d, b) {
8152     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8153     function __() { this.constructor = d; }
8154     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8155 };
8156 var ArrayObservable_1 = require('../observable/ArrayObservable');
8157 var isArray_1 = require('../util/isArray');
8158 var OuterSubscriber_1 = require('../OuterSubscriber');
8159 var subscribeToResult_1 = require('../util/subscribeToResult');
8160 var none = {};
8161 /**
8162  * Combines multiple Observables to create an Observable whose values are
8163  * calculated from the latest values of each of its input Observables.
8164  *
8165  * <span class="informal">Whenever any input Observable emits a value, it
8166  * computes a formula using the latest values from all the inputs, then emits
8167  * the output of that formula.</span>
8168  *
8169  * <img src="./img/combineLatest.png" width="100%">
8170  *
8171  * `combineLatest` combines the values from this Observable with values from
8172  * Observables passed as arguments. This is done by subscribing to each
8173  * Observable, in order, and collecting an array of each of the most recent
8174  * values any time any of the input Observables emits, then either taking that
8175  * array and passing it as arguments to an optional `project` function and
8176  * emitting the return value of that, or just emitting the array of recent
8177  * values directly if there is no `project` function.
8178  *
8179  * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
8180  * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8181  * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8182  * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
8183  * bmi.subscribe(x => console.log('BMI is ' + x));
8184  *
8185  * @see {@link combineAll}
8186  * @see {@link merge}
8187  * @see {@link withLatestFrom}
8188  *
8189  * @param {Observable} other An input Observable to combine with the source
8190  * Observable. More than one input Observables may be given as argument.
8191  * @param {function} [project] An optional function to project the values from
8192  * the combined latest values into a new value on the output Observable.
8193  * @return {Observable} An Observable of projected values from the most recent
8194  * values from each input Observable, or an array of the most recent values from
8195  * each input Observable.
8196  * @method combineLatest
8197  * @owner Observable
8198  */
8199 function combineLatest() {
8200     var observables = [];
8201     for (var _i = 0; _i < arguments.length; _i++) {
8202         observables[_i - 0] = arguments[_i];
8203     }
8204     var project = null;
8205     if (typeof observables[observables.length - 1] === 'function') {
8206         project = observables.pop();
8207     }
8208     // if the first and only other argument besides the resultSelector is an array
8209     // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
8210     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
8211         observables = observables[0];
8212     }
8213     observables.unshift(this);
8214     return new ArrayObservable_1.ArrayObservable(observables).lift(new CombineLatestOperator(project));
8215 }
8216 exports.combineLatest = combineLatest;
8217 /* tslint:enable:max-line-length */
8218 var CombineLatestOperator = (function () {
8219     function CombineLatestOperator(project) {
8220         this.project = project;
8221     }
8222     CombineLatestOperator.prototype.call = function (subscriber, source) {
8223         return source._subscribe(new CombineLatestSubscriber(subscriber, this.project));
8224     };
8225     return CombineLatestOperator;
8226 }());
8227 exports.CombineLatestOperator = CombineLatestOperator;
8228 /**
8229  * We need this JSDoc comment for affecting ESDoc.
8230  * @ignore
8231  * @extends {Ignored}
8232  */
8233 var CombineLatestSubscriber = (function (_super) {
8234     __extends(CombineLatestSubscriber, _super);
8235     function CombineLatestSubscriber(destination, project) {
8236         _super.call(this, destination);
8237         this.project = project;
8238         this.active = 0;
8239         this.values = [];
8240         this.observables = [];
8241     }
8242     CombineLatestSubscriber.prototype._next = function (observable) {
8243         this.values.push(none);
8244         this.observables.push(observable);
8245     };
8246     CombineLatestSubscriber.prototype._complete = function () {
8247         var observables = this.observables;
8248         var len = observables.length;
8249         if (len === 0) {
8250             this.destination.complete();
8251         }
8252         else {
8253             this.active = len;
8254             this.toRespond = len;
8255             for (var i = 0; i < len; i++) {
8256                 var observable = observables[i];
8257                 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
8258             }
8259         }
8260     };
8261     CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
8262         if ((this.active -= 1) === 0) {
8263             this.destination.complete();
8264         }
8265     };
8266     CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8267         var values = this.values;
8268         var oldVal = values[outerIndex];
8269         var toRespond = !this.toRespond
8270             ? 0
8271             : oldVal === none ? --this.toRespond : this.toRespond;
8272         values[outerIndex] = innerValue;
8273         if (toRespond === 0) {
8274             if (this.project) {
8275                 this._tryProject(values);
8276             }
8277             else {
8278                 this.destination.next(values.slice());
8279             }
8280         }
8281     };
8282     CombineLatestSubscriber.prototype._tryProject = function (values) {
8283         var result;
8284         try {
8285             result = this.project.apply(this, values);
8286         }
8287         catch (err) {
8288             this.destination.error(err);
8289             return;
8290         }
8291         this.destination.next(result);
8292     };
8293     return CombineLatestSubscriber;
8294 }(OuterSubscriber_1.OuterSubscriber));
8295 exports.CombineLatestSubscriber = CombineLatestSubscriber;
8296
8297 },{"../OuterSubscriber":30,"../observable/ArrayObservable":80,"../util/isArray":151,"../util/subscribeToResult":157}],105:[function(require,module,exports){
8298 "use strict";
8299 var isScheduler_1 = require('../util/isScheduler');
8300 var ArrayObservable_1 = require('../observable/ArrayObservable');
8301 var mergeAll_1 = require('./mergeAll');
8302 /**
8303  * Creates an output Observable which sequentially emits all values from every
8304  * given input Observable after the current Observable.
8305  *
8306  * <span class="informal">Concatenates multiple Observables together by
8307  * sequentially emitting their values, one Observable after the other.</span>
8308  *
8309  * <img src="./img/concat.png" width="100%">
8310  *
8311  * Joins this Observable with multiple other Observables by subscribing to them
8312  * one at a time, starting with the source, and merging their results into the
8313  * output Observable. Will wait for each Observable to complete before moving
8314  * on to the next.
8315  *
8316  * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
8317  * var timer = Rx.Observable.interval(1000).take(4);
8318  * var sequence = Rx.Observable.range(1, 10);
8319  * var result = timer.concat(sequence);
8320  * result.subscribe(x => console.log(x));
8321  *
8322  * @example <caption>Concatenate 3 Observables</caption>
8323  * var timer1 = Rx.Observable.interval(1000).take(10);
8324  * var timer2 = Rx.Observable.interval(2000).take(6);
8325  * var timer3 = Rx.Observable.interval(500).take(10);
8326  * var result = timer1.concat(timer2, timer3);
8327  * result.subscribe(x => console.log(x));
8328  *
8329  * @see {@link concatAll}
8330  * @see {@link concatMap}
8331  * @see {@link concatMapTo}
8332  *
8333  * @param {Observable} other An input Observable to concatenate after the source
8334  * Observable. More than one input Observables may be given as argument.
8335  * @param {Scheduler} [scheduler=null] An optional Scheduler to schedule each
8336  * Observable subscription on.
8337  * @return {Observable} All values of each passed Observable merged into a
8338  * single Observable, in order, in serial fashion.
8339  * @method concat
8340  * @owner Observable
8341  */
8342 function concat() {
8343     var observables = [];
8344     for (var _i = 0; _i < arguments.length; _i++) {
8345         observables[_i - 0] = arguments[_i];
8346     }
8347     return concatStatic.apply(void 0, [this].concat(observables));
8348 }
8349 exports.concat = concat;
8350 /* tslint:enable:max-line-length */
8351 /**
8352  * Creates an output Observable which sequentially emits all values from every
8353  * given input Observable after the current Observable.
8354  *
8355  * <span class="informal">Concatenates multiple Observables together by
8356  * sequentially emitting their values, one Observable after the other.</span>
8357  *
8358  * <img src="./img/concat.png" width="100%">
8359  *
8360  * Joins multiple Observables together by subscribing to them one at a time and
8361  * merging their results into the output Observable. Will wait for each
8362  * Observable to complete before moving on to the next.
8363  *
8364  * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
8365  * var timer = Rx.Observable.interval(1000).take(4);
8366  * var sequence = Rx.Observable.range(1, 10);
8367  * var result = Rx.Observable.concat(timer, sequence);
8368  * result.subscribe(x => console.log(x));
8369  *
8370  * @example <caption>Concatenate 3 Observables</caption>
8371  * var timer1 = Rx.Observable.interval(1000).take(10);
8372  * var timer2 = Rx.Observable.interval(2000).take(6);
8373  * var timer3 = Rx.Observable.interval(500).take(10);
8374  * var result = Rx.Observable.concat(timer1, timer2, timer3);
8375  * result.subscribe(x => console.log(x));
8376  *
8377  * @see {@link concatAll}
8378  * @see {@link concatMap}
8379  * @see {@link concatMapTo}
8380  *
8381  * @param {Observable} input1 An input Observable to concatenate with others.
8382  * @param {Observable} input2 An input Observable to concatenate with others.
8383  * More than one input Observables may be given as argument.
8384  * @param {Scheduler} [scheduler=null] An optional Scheduler to schedule each
8385  * Observable subscription on.
8386  * @return {Observable} All values of each passed Observable merged into a
8387  * single Observable, in order, in serial fashion.
8388  * @static true
8389  * @name concat
8390  * @owner Observable
8391  */
8392 function concatStatic() {
8393     var observables = [];
8394     for (var _i = 0; _i < arguments.length; _i++) {
8395         observables[_i - 0] = arguments[_i];
8396     }
8397     var scheduler = null;
8398     var args = observables;
8399     if (isScheduler_1.isScheduler(args[observables.length - 1])) {
8400         scheduler = args.pop();
8401     }
8402     return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(1));
8403 }
8404 exports.concatStatic = concatStatic;
8405
8406 },{"../observable/ArrayObservable":80,"../util/isScheduler":155,"./mergeAll":117}],106:[function(require,module,exports){
8407 "use strict";
8408 var __extends = (this && this.__extends) || function (d, b) {
8409     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8410     function __() { this.constructor = d; }
8411     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8412 };
8413 var Subscriber_1 = require('../Subscriber');
8414 var async_1 = require('../scheduler/async');
8415 /**
8416  * Emits a value from the source Observable only after a particular time span
8417  * has passed without another source emission.
8418  *
8419  * <span class="informal">It's like {@link delay}, but passes only the most
8420  * recent value from each burst of emissions.</span>
8421  *
8422  * <img src="./img/debounceTime.png" width="100%">
8423  *
8424  * `debounceTime` delays values emitted by the source Observable, but drops
8425  * previous pending delayed emissions if a new value arrives on the source
8426  * Observable. This operator keeps track of the most recent value from the
8427  * source Observable, and emits that only when `dueTime` enough time has passed
8428  * without any other value appearing on the source Observable. If a new value
8429  * appears before `dueTime` silence occurs, the previous value will be dropped
8430  * and will not be emitted on the output Observable.
8431  *
8432  * This is a rate-limiting operator, because it is impossible for more than one
8433  * value to be emitted in any time window of duration `dueTime`, but it is also
8434  * a delay-like operator since output emissions do not occur at the same time as
8435  * they did on the source Observable. Optionally takes a {@link Scheduler} for
8436  * managing timers.
8437  *
8438  * @example <caption>Emit the most recent click after a burst of clicks</caption>
8439  * var clicks = Rx.Observable.fromEvent(document, 'click');
8440  * var result = clicks.debounceTime(1000);
8441  * result.subscribe(x => console.log(x));
8442  *
8443  * @see {@link auditTime}
8444  * @see {@link debounce}
8445  * @see {@link delay}
8446  * @see {@link sampleTime}
8447  * @see {@link throttleTime}
8448  *
8449  * @param {number} dueTime The timeout duration in milliseconds (or the time
8450  * unit determined internally by the optional `scheduler`) for the window of
8451  * time required to wait for emission silence before emitting the most recent
8452  * source value.
8453  * @param {Scheduler} [scheduler=async] The {@link Scheduler} to use for
8454  * managing the timers that handle the timeout for each value.
8455  * @return {Observable} An Observable that delays the emissions of the source
8456  * Observable by the specified `dueTime`, and may drop some values if they occur
8457  * too frequently.
8458  * @method debounceTime
8459  * @owner Observable
8460  */
8461 function debounceTime(dueTime, scheduler) {
8462     if (scheduler === void 0) { scheduler = async_1.async; }
8463     return this.lift(new DebounceTimeOperator(dueTime, scheduler));
8464 }
8465 exports.debounceTime = debounceTime;
8466 var DebounceTimeOperator = (function () {
8467     function DebounceTimeOperator(dueTime, scheduler) {
8468         this.dueTime = dueTime;
8469         this.scheduler = scheduler;
8470     }
8471     DebounceTimeOperator.prototype.call = function (subscriber, source) {
8472         return source._subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
8473     };
8474     return DebounceTimeOperator;
8475 }());
8476 /**
8477  * We need this JSDoc comment for affecting ESDoc.
8478  * @ignore
8479  * @extends {Ignored}
8480  */
8481 var DebounceTimeSubscriber = (function (_super) {
8482     __extends(DebounceTimeSubscriber, _super);
8483     function DebounceTimeSubscriber(destination, dueTime, scheduler) {
8484         _super.call(this, destination);
8485         this.dueTime = dueTime;
8486         this.scheduler = scheduler;
8487         this.debouncedSubscription = null;
8488         this.lastValue = null;
8489         this.hasValue = false;
8490     }
8491     DebounceTimeSubscriber.prototype._next = function (value) {
8492         this.clearDebounce();
8493         this.lastValue = value;
8494         this.hasValue = true;
8495         this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
8496     };
8497     DebounceTimeSubscriber.prototype._complete = function () {
8498         this.debouncedNext();
8499         this.destination.complete();
8500     };
8501     DebounceTimeSubscriber.prototype.debouncedNext = function () {
8502         this.clearDebounce();
8503         if (this.hasValue) {
8504             this.destination.next(this.lastValue);
8505             this.lastValue = null;
8506             this.hasValue = false;
8507         }
8508     };
8509     DebounceTimeSubscriber.prototype.clearDebounce = function () {
8510         var debouncedSubscription = this.debouncedSubscription;
8511         if (debouncedSubscription !== null) {
8512             this.remove(debouncedSubscription);
8513             debouncedSubscription.unsubscribe();
8514             this.debouncedSubscription = null;
8515         }
8516     };
8517     return DebounceTimeSubscriber;
8518 }(Subscriber_1.Subscriber));
8519 function dispatchNext(subscriber) {
8520     subscriber.debouncedNext();
8521 }
8522
8523 },{"../Subscriber":35,"../scheduler/async":140}],107:[function(require,module,exports){
8524 "use strict";
8525 var __extends = (this && this.__extends) || function (d, b) {
8526     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8527     function __() { this.constructor = d; }
8528     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8529 };
8530 var OuterSubscriber_1 = require('../OuterSubscriber');
8531 var subscribeToResult_1 = require('../util/subscribeToResult');
8532 /**
8533  * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
8534  * 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.
8535  * If a comparator function is not provided, an equality check is used by default.
8536  * As the internal HashSet of this operator grows larger and larger, care should be taken in the domain of inputs this operator may see.
8537  * An optional parameter is also provided such that an Observable can be provided to queue the internal HashSet to flush the values it holds.
8538  * @param {function} [compare] optional comparison function called to test if an item is distinct from previous items in the source.
8539  * @param {Observable} [flushes] optional Observable for flushing the internal HashSet of the operator.
8540  * @return {Observable} an Observable that emits items from the source Observable with distinct values.
8541  * @method distinct
8542  * @owner Observable
8543  */
8544 function distinct(compare, flushes) {
8545     return this.lift(new DistinctOperator(compare, flushes));
8546 }
8547 exports.distinct = distinct;
8548 var DistinctOperator = (function () {
8549     function DistinctOperator(compare, flushes) {
8550         this.compare = compare;
8551         this.flushes = flushes;
8552     }
8553     DistinctOperator.prototype.call = function (subscriber, source) {
8554         return source._subscribe(new DistinctSubscriber(subscriber, this.compare, this.flushes));
8555     };
8556     return DistinctOperator;
8557 }());
8558 /**
8559  * We need this JSDoc comment for affecting ESDoc.
8560  * @ignore
8561  * @extends {Ignored}
8562  */
8563 var DistinctSubscriber = (function (_super) {
8564     __extends(DistinctSubscriber, _super);
8565     function DistinctSubscriber(destination, compare, flushes) {
8566         _super.call(this, destination);
8567         this.values = [];
8568         if (typeof compare === 'function') {
8569             this.compare = compare;
8570         }
8571         if (flushes) {
8572             this.add(subscribeToResult_1.subscribeToResult(this, flushes));
8573         }
8574     }
8575     DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8576         this.values.length = 0;
8577     };
8578     DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
8579         this._error(error);
8580     };
8581     DistinctSubscriber.prototype._next = function (value) {
8582         var found = false;
8583         var values = this.values;
8584         var len = values.length;
8585         try {
8586             for (var i = 0; i < len; i++) {
8587                 if (this.compare(values[i], value)) {
8588                     found = true;
8589                     return;
8590                 }
8591             }
8592         }
8593         catch (err) {
8594             this.destination.error(err);
8595             return;
8596         }
8597         this.values.push(value);
8598         this.destination.next(value);
8599     };
8600     DistinctSubscriber.prototype.compare = function (x, y) {
8601         return x === y;
8602     };
8603     return DistinctSubscriber;
8604 }(OuterSubscriber_1.OuterSubscriber));
8605 exports.DistinctSubscriber = DistinctSubscriber;
8606
8607 },{"../OuterSubscriber":30,"../util/subscribeToResult":157}],108:[function(require,module,exports){
8608 "use strict";
8609 var __extends = (this && this.__extends) || function (d, b) {
8610     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8611     function __() { this.constructor = d; }
8612     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8613 };
8614 var Subscriber_1 = require('../Subscriber');
8615 var tryCatch_1 = require('../util/tryCatch');
8616 var errorObject_1 = require('../util/errorObject');
8617 /**
8618  * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
8619  * 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.
8620  * If a comparator function is not provided, an equality check is used by default.
8621  * @param {function} [compare] optional comparison function called to test if an item is distinct from the previous item in the source.
8622  * @return {Observable} an Observable that emits items from the source Observable with distinct values.
8623  * @method distinctUntilChanged
8624  * @owner Observable
8625  */
8626 function distinctUntilChanged(compare, keySelector) {
8627     return this.lift(new DistinctUntilChangedOperator(compare, keySelector));
8628 }
8629 exports.distinctUntilChanged = distinctUntilChanged;
8630 var DistinctUntilChangedOperator = (function () {
8631     function DistinctUntilChangedOperator(compare, keySelector) {
8632         this.compare = compare;
8633         this.keySelector = keySelector;
8634     }
8635     DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
8636         return source._subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
8637     };
8638     return DistinctUntilChangedOperator;
8639 }());
8640 /**
8641  * We need this JSDoc comment for affecting ESDoc.
8642  * @ignore
8643  * @extends {Ignored}
8644  */
8645 var DistinctUntilChangedSubscriber = (function (_super) {
8646     __extends(DistinctUntilChangedSubscriber, _super);
8647     function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
8648         _super.call(this, destination);
8649         this.keySelector = keySelector;
8650         this.hasKey = false;
8651         if (typeof compare === 'function') {
8652             this.compare = compare;
8653         }
8654     }
8655     DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
8656         return x === y;
8657     };
8658     DistinctUntilChangedSubscriber.prototype._next = function (value) {
8659         var keySelector = this.keySelector;
8660         var key = value;
8661         if (keySelector) {
8662             key = tryCatch_1.tryCatch(this.keySelector)(value);
8663             if (key === errorObject_1.errorObject) {
8664                 return this.destination.error(errorObject_1.errorObject.e);
8665             }
8666         }
8667         var result = false;
8668         if (this.hasKey) {
8669             result = tryCatch_1.tryCatch(this.compare)(this.key, key);
8670             if (result === errorObject_1.errorObject) {
8671                 return this.destination.error(errorObject_1.errorObject.e);
8672             }
8673         }
8674         else {
8675             this.hasKey = true;
8676         }
8677         if (Boolean(result) === false) {
8678             this.key = key;
8679             this.destination.next(value);
8680         }
8681     };
8682     return DistinctUntilChangedSubscriber;
8683 }(Subscriber_1.Subscriber));
8684
8685 },{"../Subscriber":35,"../util/errorObject":150,"../util/tryCatch":159}],109:[function(require,module,exports){
8686 "use strict";
8687 var __extends = (this && this.__extends) || function (d, b) {
8688     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8689     function __() { this.constructor = d; }
8690     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8691 };
8692 var Subscriber_1 = require('../Subscriber');
8693 /**
8694  * Perform a side effect for every emission on the source Observable, but return
8695  * an Observable that is identical to the source.
8696  *
8697  * <span class="informal">Intercepts each emission on the source and runs a
8698  * function, but returns an output which is identical to the source.</span>
8699  *
8700  * <img src="./img/do.png" width="100%">
8701  *
8702  * Returns a mirrored Observable of the source Observable, but modified so that
8703  * the provided Observer is called to perform a side effect for every value,
8704  * error, and completion emitted by the source. Any errors that are thrown in
8705  * the aforementioned Observer or handlers are safely sent down the error path
8706  * of the output Observable.
8707  *
8708  * This operator is useful for debugging your Observables for the correct values
8709  * or performing other side effects.
8710  *
8711  * Note: this is different to a `subscribe` on the Observable. If the Observable
8712  * returned by `do` is not subscribed, the side effects specified by the
8713  * Observer will never happen. `do` therefore simply spies on existing
8714  * execution, it does not trigger an execution to happen like `subscribe` does.
8715  *
8716  * @example <caption>Map every every click to the clientX position of that click, while also logging the click event</caption>
8717  * var clicks = Rx.Observable.fromEvent(document, 'click');
8718  * var positions = clicks
8719  *   .do(ev => console.log(ev))
8720  *   .map(ev => ev.clientX);
8721  * positions.subscribe(x => console.log(x));
8722  *
8723  * @see {@link map}
8724  * @see {@link subscribe}
8725  *
8726  * @param {Observer|function} [nextOrObserver] A normal Observer object or a
8727  * callback for `next`.
8728  * @param {function} [error] Callback for errors in the source.
8729  * @param {function} [complete] Callback for the completion of the source.
8730  * @return {Observable} An Observable identical to the source, but runs the
8731  * specified Observer or callback(s) for each item.
8732  * @method do
8733  * @name do
8734  * @owner Observable
8735  */
8736 function _do(nextOrObserver, error, complete) {
8737     return this.lift(new DoOperator(nextOrObserver, error, complete));
8738 }
8739 exports._do = _do;
8740 var DoOperator = (function () {
8741     function DoOperator(nextOrObserver, error, complete) {
8742         this.nextOrObserver = nextOrObserver;
8743         this.error = error;
8744         this.complete = complete;
8745     }
8746     DoOperator.prototype.call = function (subscriber, source) {
8747         return source._subscribe(new DoSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
8748     };
8749     return DoOperator;
8750 }());
8751 /**
8752  * We need this JSDoc comment for affecting ESDoc.
8753  * @ignore
8754  * @extends {Ignored}
8755  */
8756 var DoSubscriber = (function (_super) {
8757     __extends(DoSubscriber, _super);
8758     function DoSubscriber(destination, nextOrObserver, error, complete) {
8759         _super.call(this, destination);
8760         var safeSubscriber = new Subscriber_1.Subscriber(nextOrObserver, error, complete);
8761         safeSubscriber.syncErrorThrowable = true;
8762         this.add(safeSubscriber);
8763         this.safeSubscriber = safeSubscriber;
8764     }
8765     DoSubscriber.prototype._next = function (value) {
8766         var safeSubscriber = this.safeSubscriber;
8767         safeSubscriber.next(value);
8768         if (safeSubscriber.syncErrorThrown) {
8769             this.destination.error(safeSubscriber.syncErrorValue);
8770         }
8771         else {
8772             this.destination.next(value);
8773         }
8774     };
8775     DoSubscriber.prototype._error = function (err) {
8776         var safeSubscriber = this.safeSubscriber;
8777         safeSubscriber.error(err);
8778         if (safeSubscriber.syncErrorThrown) {
8779             this.destination.error(safeSubscriber.syncErrorValue);
8780         }
8781         else {
8782             this.destination.error(err);
8783         }
8784     };
8785     DoSubscriber.prototype._complete = function () {
8786         var safeSubscriber = this.safeSubscriber;
8787         safeSubscriber.complete();
8788         if (safeSubscriber.syncErrorThrown) {
8789             this.destination.error(safeSubscriber.syncErrorValue);
8790         }
8791         else {
8792             this.destination.complete();
8793         }
8794     };
8795     return DoSubscriber;
8796 }(Subscriber_1.Subscriber));
8797
8798 },{"../Subscriber":35}],110:[function(require,module,exports){
8799 "use strict";
8800 var __extends = (this && this.__extends) || function (d, b) {
8801     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8802     function __() { this.constructor = d; }
8803     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8804 };
8805 var tryCatch_1 = require('../util/tryCatch');
8806 var errorObject_1 = require('../util/errorObject');
8807 var OuterSubscriber_1 = require('../OuterSubscriber');
8808 var subscribeToResult_1 = require('../util/subscribeToResult');
8809 /**
8810  * Recursively projects each source value to an Observable which is merged in
8811  * the output Observable.
8812  *
8813  * <span class="informal">It's similar to {@link mergeMap}, but applies the
8814  * projection function to every source value as well as every output value.
8815  * It's recursive.</span>
8816  *
8817  * <img src="./img/expand.png" width="100%">
8818  *
8819  * Returns an Observable that emits items based on applying a function that you
8820  * supply to each item emitted by the source Observable, where that function
8821  * returns an Observable, and then merging those resulting Observables and
8822  * emitting the results of this merger. *Expand* will re-emit on the output
8823  * Observable every source value. Then, each output value is given to the
8824  * `project` function which returns an inner Observable to be merged on the
8825  * output Observable. Those output values resulting from the projection are also
8826  * given to the `project` function to produce new output values. This is how
8827  * *expand* behaves recursively.
8828  *
8829  * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
8830  * var clicks = Rx.Observable.fromEvent(document, 'click');
8831  * var powersOfTwo = clicks
8832  *   .mapTo(1)
8833  *   .expand(x => Rx.Observable.of(2 * x).delay(1000))
8834  *   .take(10);
8835  * powersOfTwo.subscribe(x => console.log(x));
8836  *
8837  * @see {@link mergeMap}
8838  * @see {@link mergeScan}
8839  *
8840  * @param {function(value: T, index: number) => Observable} project A function
8841  * that, when applied to an item emitted by the source or the output Observable,
8842  * returns an Observable.
8843  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
8844  * Observables being subscribed to concurrently.
8845  * @param {Scheduler} [scheduler=null] The Scheduler to use for subscribing to
8846  * each projected inner Observable.
8847  * @return {Observable} An Observable that emits the source values and also
8848  * result of applying the projection function to each value emitted on the
8849  * output Observable and and merging the results of the Observables obtained
8850  * from this transformation.
8851  * @method expand
8852  * @owner Observable
8853  */
8854 function expand(project, concurrent, scheduler) {
8855     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
8856     if (scheduler === void 0) { scheduler = undefined; }
8857     concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
8858     return this.lift(new ExpandOperator(project, concurrent, scheduler));
8859 }
8860 exports.expand = expand;
8861 var ExpandOperator = (function () {
8862     function ExpandOperator(project, concurrent, scheduler) {
8863         this.project = project;
8864         this.concurrent = concurrent;
8865         this.scheduler = scheduler;
8866     }
8867     ExpandOperator.prototype.call = function (subscriber, source) {
8868         return source._subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
8869     };
8870     return ExpandOperator;
8871 }());
8872 exports.ExpandOperator = ExpandOperator;
8873 /**
8874  * We need this JSDoc comment for affecting ESDoc.
8875  * @ignore
8876  * @extends {Ignored}
8877  */
8878 var ExpandSubscriber = (function (_super) {
8879     __extends(ExpandSubscriber, _super);
8880     function ExpandSubscriber(destination, project, concurrent, scheduler) {
8881         _super.call(this, destination);
8882         this.project = project;
8883         this.concurrent = concurrent;
8884         this.scheduler = scheduler;
8885         this.index = 0;
8886         this.active = 0;
8887         this.hasCompleted = false;
8888         if (concurrent < Number.POSITIVE_INFINITY) {
8889             this.buffer = [];
8890         }
8891     }
8892     ExpandSubscriber.dispatch = function (arg) {
8893         var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
8894         subscriber.subscribeToProjection(result, value, index);
8895     };
8896     ExpandSubscriber.prototype._next = function (value) {
8897         var destination = this.destination;
8898         if (destination.closed) {
8899             this._complete();
8900             return;
8901         }
8902         var index = this.index++;
8903         if (this.active < this.concurrent) {
8904             destination.next(value);
8905             var result = tryCatch_1.tryCatch(this.project)(value, index);
8906             if (result === errorObject_1.errorObject) {
8907                 destination.error(errorObject_1.errorObject.e);
8908             }
8909             else if (!this.scheduler) {
8910                 this.subscribeToProjection(result, value, index);
8911             }
8912             else {
8913                 var state = { subscriber: this, result: result, value: value, index: index };
8914                 this.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
8915             }
8916         }
8917         else {
8918             this.buffer.push(value);
8919         }
8920     };
8921     ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
8922         this.active++;
8923         this.add(subscribeToResult_1.subscribeToResult(this, result, value, index));
8924     };
8925     ExpandSubscriber.prototype._complete = function () {
8926         this.hasCompleted = true;
8927         if (this.hasCompleted && this.active === 0) {
8928             this.destination.complete();
8929         }
8930     };
8931     ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8932         this._next(innerValue);
8933     };
8934     ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
8935         var buffer = this.buffer;
8936         this.remove(innerSub);
8937         this.active--;
8938         if (buffer && buffer.length > 0) {
8939             this._next(buffer.shift());
8940         }
8941         if (this.hasCompleted && this.active === 0) {
8942             this.destination.complete();
8943         }
8944     };
8945     return ExpandSubscriber;
8946 }(OuterSubscriber_1.OuterSubscriber));
8947 exports.ExpandSubscriber = ExpandSubscriber;
8948
8949 },{"../OuterSubscriber":30,"../util/errorObject":150,"../util/subscribeToResult":157,"../util/tryCatch":159}],111:[function(require,module,exports){
8950 "use strict";
8951 var __extends = (this && this.__extends) || function (d, b) {
8952     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8953     function __() { this.constructor = d; }
8954     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8955 };
8956 var Subscriber_1 = require('../Subscriber');
8957 /**
8958  * Filter items emitted by the source Observable by only emitting those that
8959  * satisfy a specified predicate.
8960  *
8961  * <span class="informal">Like
8962  * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
8963  * it only emits a value from the source if it passes a criterion function.</span>
8964  *
8965  * <img src="./img/filter.png" width="100%">
8966  *
8967  * Similar to the well-known `Array.prototype.filter` method, this operator
8968  * takes values from the source Observable, passes them through a `predicate`
8969  * function and only emits those values that yielded `true`.
8970  *
8971  * @example <caption>Emit only click events whose target was a DIV element</caption>
8972  * var clicks = Rx.Observable.fromEvent(document, 'click');
8973  * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
8974  * clicksOnDivs.subscribe(x => console.log(x));
8975  *
8976  * @see {@link distinct}
8977  * @see {@link distinctKey}
8978  * @see {@link distinctUntilChanged}
8979  * @see {@link distinctUntilKeyChanged}
8980  * @see {@link ignoreElements}
8981  * @see {@link partition}
8982  * @see {@link skip}
8983  *
8984  * @param {function(value: T, index: number): boolean} predicate A function that
8985  * evaluates each value emitted by the source Observable. If it returns `true`,
8986  * the value is emitted, if `false` the value is not passed to the output
8987  * Observable. The `index` parameter is the number `i` for the i-th source
8988  * emission that has happened since the subscription, starting from the number
8989  * `0`.
8990  * @param {any} [thisArg] An optional argument to determine the value of `this`
8991  * in the `predicate` function.
8992  * @return {Observable} An Observable of values from the source that were
8993  * allowed by the `predicate` function.
8994  * @method filter
8995  * @owner Observable
8996  */
8997 function filter(predicate, thisArg) {
8998     return this.lift(new FilterOperator(predicate, thisArg));
8999 }
9000 exports.filter = filter;
9001 var FilterOperator = (function () {
9002     function FilterOperator(predicate, thisArg) {
9003         this.predicate = predicate;
9004         this.thisArg = thisArg;
9005     }
9006     FilterOperator.prototype.call = function (subscriber, source) {
9007         return source._subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
9008     };
9009     return FilterOperator;
9010 }());
9011 /**
9012  * We need this JSDoc comment for affecting ESDoc.
9013  * @ignore
9014  * @extends {Ignored}
9015  */
9016 var FilterSubscriber = (function (_super) {
9017     __extends(FilterSubscriber, _super);
9018     function FilterSubscriber(destination, predicate, thisArg) {
9019         _super.call(this, destination);
9020         this.predicate = predicate;
9021         this.thisArg = thisArg;
9022         this.count = 0;
9023         this.predicate = predicate;
9024     }
9025     // the try catch block below is left specifically for
9026     // optimization and perf reasons. a tryCatcher is not necessary here.
9027     FilterSubscriber.prototype._next = function (value) {
9028         var result;
9029         try {
9030             result = this.predicate.call(this.thisArg, value, this.count++);
9031         }
9032         catch (err) {
9033             this.destination.error(err);
9034             return;
9035         }
9036         if (result) {
9037             this.destination.next(value);
9038         }
9039     };
9040     return FilterSubscriber;
9041 }(Subscriber_1.Subscriber));
9042
9043 },{"../Subscriber":35}],112:[function(require,module,exports){
9044 "use strict";
9045 var __extends = (this && this.__extends) || function (d, b) {
9046     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9047     function __() { this.constructor = d; }
9048     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9049 };
9050 var Subscriber_1 = require('../Subscriber');
9051 var Subscription_1 = require('../Subscription');
9052 /**
9053  * Returns an Observable that mirrors the source Observable, but will call a specified function when
9054  * the source terminates on complete or error.
9055  * @param {function} callback function to be called when source terminates.
9056  * @return {Observable} an Observable that mirrors the source, but will call the specified function on termination.
9057  * @method finally
9058  * @owner Observable
9059  */
9060 function _finally(callback) {
9061     return this.lift(new FinallyOperator(callback));
9062 }
9063 exports._finally = _finally;
9064 var FinallyOperator = (function () {
9065     function FinallyOperator(callback) {
9066         this.callback = callback;
9067     }
9068     FinallyOperator.prototype.call = function (subscriber, source) {
9069         return source._subscribe(new FinallySubscriber(subscriber, this.callback));
9070     };
9071     return FinallyOperator;
9072 }());
9073 /**
9074  * We need this JSDoc comment for affecting ESDoc.
9075  * @ignore
9076  * @extends {Ignored}
9077  */
9078 var FinallySubscriber = (function (_super) {
9079     __extends(FinallySubscriber, _super);
9080     function FinallySubscriber(destination, callback) {
9081         _super.call(this, destination);
9082         this.add(new Subscription_1.Subscription(callback));
9083     }
9084     return FinallySubscriber;
9085 }(Subscriber_1.Subscriber));
9086
9087 },{"../Subscriber":35,"../Subscription":36}],113:[function(require,module,exports){
9088 "use strict";
9089 var __extends = (this && this.__extends) || function (d, b) {
9090     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9091     function __() { this.constructor = d; }
9092     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9093 };
9094 var Subscriber_1 = require('../Subscriber');
9095 var EmptyError_1 = require('../util/EmptyError');
9096 /**
9097  * Emits only the first value (or the first value that meets some condition)
9098  * emitted by the source Observable.
9099  *
9100  * <span class="informal">Emits only the first value. Or emits only the first
9101  * value that passes some test.</span>
9102  *
9103  * <img src="./img/first.png" width="100%">
9104  *
9105  * If called with no arguments, `first` emits the first value of the source
9106  * Observable, then completes. If called with a `predicate` function, `first`
9107  * emits the first value of the source that matches the specified condition. It
9108  * may also take a `resultSelector` function to produce the output value from
9109  * the input value, and a `defaultValue` to emit in case the source completes
9110  * before it is able to emit a valid value. Throws an error if `defaultValue`
9111  * was not provided and a matching element is not found.
9112  *
9113  * @example <caption>Emit only the first click that happens on the DOM</caption>
9114  * var clicks = Rx.Observable.fromEvent(document, 'click');
9115  * var result = clicks.first();
9116  * result.subscribe(x => console.log(x));
9117  *
9118  * @example <caption>Emits the first click that happens on a DIV</caption>
9119  * var clicks = Rx.Observable.fromEvent(document, 'click');
9120  * var result = clicks.first(ev => ev.target.tagName === 'DIV');
9121  * result.subscribe(x => console.log(x));
9122  *
9123  * @see {@link filter}
9124  * @see {@link find}
9125  * @see {@link take}
9126  *
9127  * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
9128  * callback if the Observable completes before any `next` notification was sent.
9129  *
9130  * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
9131  * An optional function called with each item to test for condition matching.
9132  * @param {function(value: T, index: number): R} [resultSelector] A function to
9133  * produce the value on the output Observable based on the values
9134  * and the indices of the source Observable. The arguments passed to this
9135  * function are:
9136  * - `value`: the value that was emitted on the source.
9137  * - `index`: the "index" of the value from the source.
9138  * @param {R} [defaultValue] The default value emitted in case no valid value
9139  * was found on the source.
9140  * @return {Observable<T|R>} an Observable of the first item that matches the
9141  * condition.
9142  * @method first
9143  * @owner Observable
9144  */
9145 function first(predicate, resultSelector, defaultValue) {
9146     return this.lift(new FirstOperator(predicate, resultSelector, defaultValue, this));
9147 }
9148 exports.first = first;
9149 var FirstOperator = (function () {
9150     function FirstOperator(predicate, resultSelector, defaultValue, source) {
9151         this.predicate = predicate;
9152         this.resultSelector = resultSelector;
9153         this.defaultValue = defaultValue;
9154         this.source = source;
9155     }
9156     FirstOperator.prototype.call = function (observer, source) {
9157         return source._subscribe(new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
9158     };
9159     return FirstOperator;
9160 }());
9161 /**
9162  * We need this JSDoc comment for affecting ESDoc.
9163  * @ignore
9164  * @extends {Ignored}
9165  */
9166 var FirstSubscriber = (function (_super) {
9167     __extends(FirstSubscriber, _super);
9168     function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) {
9169         _super.call(this, destination);
9170         this.predicate = predicate;
9171         this.resultSelector = resultSelector;
9172         this.defaultValue = defaultValue;
9173         this.source = source;
9174         this.index = 0;
9175         this.hasCompleted = false;
9176     }
9177     FirstSubscriber.prototype._next = function (value) {
9178         var index = this.index++;
9179         if (this.predicate) {
9180             this._tryPredicate(value, index);
9181         }
9182         else {
9183             this._emit(value, index);
9184         }
9185     };
9186     FirstSubscriber.prototype._tryPredicate = function (value, index) {
9187         var result;
9188         try {
9189             result = this.predicate(value, index, this.source);
9190         }
9191         catch (err) {
9192             this.destination.error(err);
9193             return;
9194         }
9195         if (result) {
9196             this._emit(value, index);
9197         }
9198     };
9199     FirstSubscriber.prototype._emit = function (value, index) {
9200         if (this.resultSelector) {
9201             this._tryResultSelector(value, index);
9202             return;
9203         }
9204         this._emitFinal(value);
9205     };
9206     FirstSubscriber.prototype._tryResultSelector = function (value, index) {
9207         var result;
9208         try {
9209             result = this.resultSelector(value, index);
9210         }
9211         catch (err) {
9212             this.destination.error(err);
9213             return;
9214         }
9215         this._emitFinal(result);
9216     };
9217     FirstSubscriber.prototype._emitFinal = function (value) {
9218         var destination = this.destination;
9219         destination.next(value);
9220         destination.complete();
9221         this.hasCompleted = true;
9222     };
9223     FirstSubscriber.prototype._complete = function () {
9224         var destination = this.destination;
9225         if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') {
9226             destination.next(this.defaultValue);
9227             destination.complete();
9228         }
9229         else if (!this.hasCompleted) {
9230             destination.error(new EmptyError_1.EmptyError);
9231         }
9232     };
9233     return FirstSubscriber;
9234 }(Subscriber_1.Subscriber));
9235
9236 },{"../Subscriber":35,"../util/EmptyError":147}],114:[function(require,module,exports){
9237 "use strict";
9238 var __extends = (this && this.__extends) || function (d, b) {
9239     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9240     function __() { this.constructor = d; }
9241     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9242 };
9243 var Subscriber_1 = require('../Subscriber');
9244 var EmptyError_1 = require('../util/EmptyError');
9245 /**
9246  * Returns an Observable that emits only the last item emitted by the source Observable.
9247  * It optionally takes a predicate function as a parameter, in which case, rather than emitting
9248  * the last item from the source Observable, the resulting Observable will emit the last item
9249  * from the source Observable that satisfies the predicate.
9250  *
9251  * <img src="./img/last.png" width="100%">
9252  *
9253  * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
9254  * callback if the Observable completes before any `next` notification was sent.
9255  * @param {function} predicate - the condition any source emitted item has to satisfy.
9256  * @return {Observable} an Observable that emits only the last item satisfying the given condition
9257  * from the source, or an NoSuchElementException if no such items are emitted.
9258  * @throws - Throws if no items that match the predicate are emitted by the source Observable.
9259  * @method last
9260  * @owner Observable
9261  */
9262 function last(predicate, resultSelector, defaultValue) {
9263     return this.lift(new LastOperator(predicate, resultSelector, defaultValue, this));
9264 }
9265 exports.last = last;
9266 var LastOperator = (function () {
9267     function LastOperator(predicate, resultSelector, defaultValue, source) {
9268         this.predicate = predicate;
9269         this.resultSelector = resultSelector;
9270         this.defaultValue = defaultValue;
9271         this.source = source;
9272     }
9273     LastOperator.prototype.call = function (observer, source) {
9274         return source._subscribe(new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
9275     };
9276     return LastOperator;
9277 }());
9278 /**
9279  * We need this JSDoc comment for affecting ESDoc.
9280  * @ignore
9281  * @extends {Ignored}
9282  */
9283 var LastSubscriber = (function (_super) {
9284     __extends(LastSubscriber, _super);
9285     function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) {
9286         _super.call(this, destination);
9287         this.predicate = predicate;
9288         this.resultSelector = resultSelector;
9289         this.defaultValue = defaultValue;
9290         this.source = source;
9291         this.hasValue = false;
9292         this.index = 0;
9293         if (typeof defaultValue !== 'undefined') {
9294             this.lastValue = defaultValue;
9295             this.hasValue = true;
9296         }
9297     }
9298     LastSubscriber.prototype._next = function (value) {
9299         var index = this.index++;
9300         if (this.predicate) {
9301             this._tryPredicate(value, index);
9302         }
9303         else {
9304             if (this.resultSelector) {
9305                 this._tryResultSelector(value, index);
9306                 return;
9307             }
9308             this.lastValue = value;
9309             this.hasValue = true;
9310         }
9311     };
9312     LastSubscriber.prototype._tryPredicate = function (value, index) {
9313         var result;
9314         try {
9315             result = this.predicate(value, index, this.source);
9316         }
9317         catch (err) {
9318             this.destination.error(err);
9319             return;
9320         }
9321         if (result) {
9322             if (this.resultSelector) {
9323                 this._tryResultSelector(value, index);
9324                 return;
9325             }
9326             this.lastValue = value;
9327             this.hasValue = true;
9328         }
9329     };
9330     LastSubscriber.prototype._tryResultSelector = function (value, index) {
9331         var result;
9332         try {
9333             result = this.resultSelector(value, index);
9334         }
9335         catch (err) {
9336             this.destination.error(err);
9337             return;
9338         }
9339         this.lastValue = result;
9340         this.hasValue = true;
9341     };
9342     LastSubscriber.prototype._complete = function () {
9343         var destination = this.destination;
9344         if (this.hasValue) {
9345             destination.next(this.lastValue);
9346             destination.complete();
9347         }
9348         else {
9349             destination.error(new EmptyError_1.EmptyError);
9350         }
9351     };
9352     return LastSubscriber;
9353 }(Subscriber_1.Subscriber));
9354
9355 },{"../Subscriber":35,"../util/EmptyError":147}],115:[function(require,module,exports){
9356 "use strict";
9357 var __extends = (this && this.__extends) || function (d, b) {
9358     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9359     function __() { this.constructor = d; }
9360     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9361 };
9362 var Subscriber_1 = require('../Subscriber');
9363 /**
9364  * Applies a given `project` function to each value emitted by the source
9365  * Observable, and emits the resulting values as an Observable.
9366  *
9367  * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
9368  * it passes each source value through a transformation function to get
9369  * corresponding output values.</span>
9370  *
9371  * <img src="./img/map.png" width="100%">
9372  *
9373  * Similar to the well known `Array.prototype.map` function, this operator
9374  * applies a projection to each value and emits that projection in the output
9375  * Observable.
9376  *
9377  * @example <caption>Map every every click to the clientX position of that click</caption>
9378  * var clicks = Rx.Observable.fromEvent(document, 'click');
9379  * var positions = clicks.map(ev => ev.clientX);
9380  * positions.subscribe(x => console.log(x));
9381  *
9382  * @see {@link mapTo}
9383  * @see {@link pluck}
9384  *
9385  * @param {function(value: T, index: number): R} project The function to apply
9386  * to each `value` emitted by the source Observable. The `index` parameter is
9387  * the number `i` for the i-th emission that has happened since the
9388  * subscription, starting from the number `0`.
9389  * @param {any} [thisArg] An optional argument to define what `this` is in the
9390  * `project` function.
9391  * @return {Observable<R>} An Observable that emits the values from the source
9392  * Observable transformed by the given `project` function.
9393  * @method map
9394  * @owner Observable
9395  */
9396 function map(project, thisArg) {
9397     if (typeof project !== 'function') {
9398         throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
9399     }
9400     return this.lift(new MapOperator(project, thisArg));
9401 }
9402 exports.map = map;
9403 var MapOperator = (function () {
9404     function MapOperator(project, thisArg) {
9405         this.project = project;
9406         this.thisArg = thisArg;
9407     }
9408     MapOperator.prototype.call = function (subscriber, source) {
9409         return source._subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
9410     };
9411     return MapOperator;
9412 }());
9413 exports.MapOperator = MapOperator;
9414 /**
9415  * We need this JSDoc comment for affecting ESDoc.
9416  * @ignore
9417  * @extends {Ignored}
9418  */
9419 var MapSubscriber = (function (_super) {
9420     __extends(MapSubscriber, _super);
9421     function MapSubscriber(destination, project, thisArg) {
9422         _super.call(this, destination);
9423         this.project = project;
9424         this.count = 0;
9425         this.thisArg = thisArg || this;
9426     }
9427     // NOTE: This looks unoptimized, but it's actually purposefully NOT
9428     // using try/catch optimizations.
9429     MapSubscriber.prototype._next = function (value) {
9430         var result;
9431         try {
9432             result = this.project.call(this.thisArg, value, this.count++);
9433         }
9434         catch (err) {
9435             this.destination.error(err);
9436             return;
9437         }
9438         this.destination.next(result);
9439     };
9440     return MapSubscriber;
9441 }(Subscriber_1.Subscriber));
9442
9443 },{"../Subscriber":35}],116:[function(require,module,exports){
9444 "use strict";
9445 var ArrayObservable_1 = require('../observable/ArrayObservable');
9446 var mergeAll_1 = require('./mergeAll');
9447 var isScheduler_1 = require('../util/isScheduler');
9448 /**
9449  * Creates an output Observable which concurrently emits all values from every
9450  * given input Observable.
9451  *
9452  * <span class="informal">Flattens multiple Observables together by blending
9453  * their values into one Observable.</span>
9454  *
9455  * <img src="./img/merge.png" width="100%">
9456  *
9457  * `merge` subscribes to each given input Observable (either the source or an
9458  * Observable given as argument), and simply forwards (without doing any
9459  * transformation) all the values from all the input Observables to the output
9460  * Observable. The output Observable only completes once all input Observables
9461  * have completed. Any error delivered by an input Observable will be immediately
9462  * emitted on the output Observable.
9463  *
9464  * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
9465  * var clicks = Rx.Observable.fromEvent(document, 'click');
9466  * var timer = Rx.Observable.interval(1000);
9467  * var clicksOrTimer = clicks.merge(timer);
9468  * clicksOrTimer.subscribe(x => console.log(x));
9469  *
9470  * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
9471  * var timer1 = Rx.Observable.interval(1000).take(10);
9472  * var timer2 = Rx.Observable.interval(2000).take(6);
9473  * var timer3 = Rx.Observable.interval(500).take(10);
9474  * var concurrent = 2; // the argument
9475  * var merged = timer1.merge(timer2, timer3, concurrent);
9476  * merged.subscribe(x => console.log(x));
9477  *
9478  * @see {@link mergeAll}
9479  * @see {@link mergeMap}
9480  * @see {@link mergeMapTo}
9481  * @see {@link mergeScan}
9482  *
9483  * @param {Observable} other An input Observable to merge with the source
9484  * Observable. More than one input Observables may be given as argument.
9485  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9486  * Observables being subscribed to concurrently.
9487  * @param {Scheduler} [scheduler=null] The Scheduler to use for managing
9488  * concurrency of input Observables.
9489  * @return {Observable} an Observable that emits items that are the result of
9490  * every input Observable.
9491  * @method merge
9492  * @owner Observable
9493  */
9494 function merge() {
9495     var observables = [];
9496     for (var _i = 0; _i < arguments.length; _i++) {
9497         observables[_i - 0] = arguments[_i];
9498     }
9499     observables.unshift(this);
9500     return mergeStatic.apply(this, observables);
9501 }
9502 exports.merge = merge;
9503 /* tslint:enable:max-line-length */
9504 /**
9505  * Creates an output Observable which concurrently emits all values from every
9506  * given input Observable.
9507  *
9508  * <span class="informal">Flattens multiple Observables together by blending
9509  * their values into one Observable.</span>
9510  *
9511  * <img src="./img/merge.png" width="100%">
9512  *
9513  * `merge` subscribes to each given input Observable (as arguments), and simply
9514  * forwards (without doing any transformation) all the values from all the input
9515  * Observables to the output Observable. The output Observable only completes
9516  * once all input Observables have completed. Any error delivered by an input
9517  * Observable will be immediately emitted on the output Observable.
9518  *
9519  * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
9520  * var clicks = Rx.Observable.fromEvent(document, 'click');
9521  * var timer = Rx.Observable.interval(1000);
9522  * var clicksOrTimer = Rx.Observable.merge(clicks, timer);
9523  * clicksOrTimer.subscribe(x => console.log(x));
9524  *
9525  * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
9526  * var timer1 = Rx.Observable.interval(1000).take(10);
9527  * var timer2 = Rx.Observable.interval(2000).take(6);
9528  * var timer3 = Rx.Observable.interval(500).take(10);
9529  * var concurrent = 2; // the argument
9530  * var merged = Rx.Observable.merge(timer1, timer2, timer3, concurrent);
9531  * merged.subscribe(x => console.log(x));
9532  *
9533  * @see {@link mergeAll}
9534  * @see {@link mergeMap}
9535  * @see {@link mergeMapTo}
9536  * @see {@link mergeScan}
9537  *
9538  * @param {Observable} input1 An input Observable to merge with others.
9539  * @param {Observable} input2 An input Observable to merge with others.
9540  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9541  * Observables being subscribed to concurrently.
9542  * @param {Scheduler} [scheduler=null] The Scheduler to use for managing
9543  * concurrency of input Observables.
9544  * @return {Observable} an Observable that emits items that are the result of
9545  * every input Observable.
9546  * @static true
9547  * @name merge
9548  * @owner Observable
9549  */
9550 function mergeStatic() {
9551     var observables = [];
9552     for (var _i = 0; _i < arguments.length; _i++) {
9553         observables[_i - 0] = arguments[_i];
9554     }
9555     var concurrent = Number.POSITIVE_INFINITY;
9556     var scheduler = null;
9557     var last = observables[observables.length - 1];
9558     if (isScheduler_1.isScheduler(last)) {
9559         scheduler = observables.pop();
9560         if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
9561             concurrent = observables.pop();
9562         }
9563     }
9564     else if (typeof last === 'number') {
9565         concurrent = observables.pop();
9566     }
9567     if (observables.length === 1) {
9568         return observables[0];
9569     }
9570     return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(concurrent));
9571 }
9572 exports.mergeStatic = mergeStatic;
9573
9574 },{"../observable/ArrayObservable":80,"../util/isScheduler":155,"./mergeAll":117}],117:[function(require,module,exports){
9575 "use strict";
9576 var __extends = (this && this.__extends) || function (d, b) {
9577     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9578     function __() { this.constructor = d; }
9579     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9580 };
9581 var OuterSubscriber_1 = require('../OuterSubscriber');
9582 var subscribeToResult_1 = require('../util/subscribeToResult');
9583 /**
9584  * Converts a higher-order Observable into a first-order Observable which
9585  * concurrently delivers all values that are emitted on the inner Observables.
9586  *
9587  * <span class="informal">Flattens an Observable-of-Observables.</span>
9588  *
9589  * <img src="./img/mergeAll.png" width="100%">
9590  *
9591  * `mergeAll` subscribes to an Observable that emits Observables, also known as
9592  * a higher-order Observable. Each time it observes one of these emitted inner
9593  * Observables, it subscribes to that and delivers all the values from the
9594  * inner Observable on the output Observable. The output Observable only
9595  * completes once all inner Observables have completed. Any error delivered by
9596  * a inner Observable will be immediately emitted on the output Observable.
9597  *
9598  * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
9599  * var clicks = Rx.Observable.fromEvent(document, 'click');
9600  * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
9601  * var firstOrder = higherOrder.mergeAll();
9602  * firstOrder.subscribe(x => console.log(x));
9603  *
9604  * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
9605  * var clicks = Rx.Observable.fromEvent(document, 'click');
9606  * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
9607  * var firstOrder = higherOrder.mergeAll(2);
9608  * firstOrder.subscribe(x => console.log(x));
9609  *
9610  * @see {@link combineAll}
9611  * @see {@link concatAll}
9612  * @see {@link exhaust}
9613  * @see {@link merge}
9614  * @see {@link mergeMap}
9615  * @see {@link mergeMapTo}
9616  * @see {@link mergeScan}
9617  * @see {@link switch}
9618  * @see {@link zipAll}
9619  *
9620  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
9621  * Observables being subscribed to concurrently.
9622  * @return {Observable} An Observable that emits values coming from all the
9623  * inner Observables emitted by the source Observable.
9624  * @method mergeAll
9625  * @owner Observable
9626  */
9627 function mergeAll(concurrent) {
9628     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9629     return this.lift(new MergeAllOperator(concurrent));
9630 }
9631 exports.mergeAll = mergeAll;
9632 var MergeAllOperator = (function () {
9633     function MergeAllOperator(concurrent) {
9634         this.concurrent = concurrent;
9635     }
9636     MergeAllOperator.prototype.call = function (observer, source) {
9637         return source._subscribe(new MergeAllSubscriber(observer, this.concurrent));
9638     };
9639     return MergeAllOperator;
9640 }());
9641 exports.MergeAllOperator = MergeAllOperator;
9642 /**
9643  * We need this JSDoc comment for affecting ESDoc.
9644  * @ignore
9645  * @extends {Ignored}
9646  */
9647 var MergeAllSubscriber = (function (_super) {
9648     __extends(MergeAllSubscriber, _super);
9649     function MergeAllSubscriber(destination, concurrent) {
9650         _super.call(this, destination);
9651         this.concurrent = concurrent;
9652         this.hasCompleted = false;
9653         this.buffer = [];
9654         this.active = 0;
9655     }
9656     MergeAllSubscriber.prototype._next = function (observable) {
9657         if (this.active < this.concurrent) {
9658             this.active++;
9659             this.add(subscribeToResult_1.subscribeToResult(this, observable));
9660         }
9661         else {
9662             this.buffer.push(observable);
9663         }
9664     };
9665     MergeAllSubscriber.prototype._complete = function () {
9666         this.hasCompleted = true;
9667         if (this.active === 0 && this.buffer.length === 0) {
9668             this.destination.complete();
9669         }
9670     };
9671     MergeAllSubscriber.prototype.notifyComplete = function (innerSub) {
9672         var buffer = this.buffer;
9673         this.remove(innerSub);
9674         this.active--;
9675         if (buffer.length > 0) {
9676             this._next(buffer.shift());
9677         }
9678         else if (this.active === 0 && this.hasCompleted) {
9679             this.destination.complete();
9680         }
9681     };
9682     return MergeAllSubscriber;
9683 }(OuterSubscriber_1.OuterSubscriber));
9684 exports.MergeAllSubscriber = MergeAllSubscriber;
9685
9686 },{"../OuterSubscriber":30,"../util/subscribeToResult":157}],118:[function(require,module,exports){
9687 "use strict";
9688 var __extends = (this && this.__extends) || function (d, b) {
9689     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9690     function __() { this.constructor = d; }
9691     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9692 };
9693 var subscribeToResult_1 = require('../util/subscribeToResult');
9694 var OuterSubscriber_1 = require('../OuterSubscriber');
9695 /**
9696  * Projects each source value to an Observable which is merged in the output
9697  * Observable.
9698  *
9699  * <span class="informal">Maps each value to an Observable, then flattens all of
9700  * these inner Observables using {@link mergeAll}.</span>
9701  *
9702  * <img src="./img/mergeMap.png" width="100%">
9703  *
9704  * Returns an Observable that emits items based on applying a function that you
9705  * supply to each item emitted by the source Observable, where that function
9706  * returns an Observable, and then merging those resulting Observables and
9707  * emitting the results of this merger.
9708  *
9709  * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
9710  * var letters = Rx.Observable.of('a', 'b', 'c');
9711  * var result = letters.mergeMap(x =>
9712  *   Rx.Observable.interval(1000).map(i => x+i)
9713  * );
9714  * result.subscribe(x => console.log(x));
9715  *
9716  * @see {@link concatMap}
9717  * @see {@link exhaustMap}
9718  * @see {@link merge}
9719  * @see {@link mergeAll}
9720  * @see {@link mergeMapTo}
9721  * @see {@link mergeScan}
9722  * @see {@link switchMap}
9723  *
9724  * @param {function(value: T, ?index: number): Observable} project A function
9725  * that, when applied to an item emitted by the source Observable, returns an
9726  * Observable.
9727  * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
9728  * A function to produce the value on the output Observable based on the values
9729  * and the indices of the source (outer) emission and the inner Observable
9730  * emission. The arguments passed to this function are:
9731  * - `outerValue`: the value that came from the source
9732  * - `innerValue`: the value that came from the projected Observable
9733  * - `outerIndex`: the "index" of the value that came from the source
9734  * - `innerIndex`: the "index" of the value from the projected Observable
9735  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9736  * Observables being subscribed to concurrently.
9737  * @return {Observable} An Observable that emits the result of applying the
9738  * projection function (and the optional `resultSelector`) to each item emitted
9739  * by the source Observable and merging the results of the Observables obtained
9740  * from this transformation.
9741  * @method mergeMap
9742  * @owner Observable
9743  */
9744 function mergeMap(project, resultSelector, concurrent) {
9745     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9746     if (typeof resultSelector === 'number') {
9747         concurrent = resultSelector;
9748         resultSelector = null;
9749     }
9750     return this.lift(new MergeMapOperator(project, resultSelector, concurrent));
9751 }
9752 exports.mergeMap = mergeMap;
9753 var MergeMapOperator = (function () {
9754     function MergeMapOperator(project, resultSelector, concurrent) {
9755         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9756         this.project = project;
9757         this.resultSelector = resultSelector;
9758         this.concurrent = concurrent;
9759     }
9760     MergeMapOperator.prototype.call = function (observer, source) {
9761         return source._subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent));
9762     };
9763     return MergeMapOperator;
9764 }());
9765 exports.MergeMapOperator = MergeMapOperator;
9766 /**
9767  * We need this JSDoc comment for affecting ESDoc.
9768  * @ignore
9769  * @extends {Ignored}
9770  */
9771 var MergeMapSubscriber = (function (_super) {
9772     __extends(MergeMapSubscriber, _super);
9773     function MergeMapSubscriber(destination, project, resultSelector, concurrent) {
9774         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9775         _super.call(this, destination);
9776         this.project = project;
9777         this.resultSelector = resultSelector;
9778         this.concurrent = concurrent;
9779         this.hasCompleted = false;
9780         this.buffer = [];
9781         this.active = 0;
9782         this.index = 0;
9783     }
9784     MergeMapSubscriber.prototype._next = function (value) {
9785         if (this.active < this.concurrent) {
9786             this._tryNext(value);
9787         }
9788         else {
9789             this.buffer.push(value);
9790         }
9791     };
9792     MergeMapSubscriber.prototype._tryNext = function (value) {
9793         var result;
9794         var index = this.index++;
9795         try {
9796             result = this.project(value, index);
9797         }
9798         catch (err) {
9799             this.destination.error(err);
9800             return;
9801         }
9802         this.active++;
9803         this._innerSub(result, value, index);
9804     };
9805     MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
9806         this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index));
9807     };
9808     MergeMapSubscriber.prototype._complete = function () {
9809         this.hasCompleted = true;
9810         if (this.active === 0 && this.buffer.length === 0) {
9811             this.destination.complete();
9812         }
9813     };
9814     MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9815         if (this.resultSelector) {
9816             this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex);
9817         }
9818         else {
9819             this.destination.next(innerValue);
9820         }
9821     };
9822     MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
9823         var result;
9824         try {
9825             result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
9826         }
9827         catch (err) {
9828             this.destination.error(err);
9829             return;
9830         }
9831         this.destination.next(result);
9832     };
9833     MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
9834         var buffer = this.buffer;
9835         this.remove(innerSub);
9836         this.active--;
9837         if (buffer.length > 0) {
9838             this._next(buffer.shift());
9839         }
9840         else if (this.active === 0 && this.hasCompleted) {
9841             this.destination.complete();
9842         }
9843     };
9844     return MergeMapSubscriber;
9845 }(OuterSubscriber_1.OuterSubscriber));
9846 exports.MergeMapSubscriber = MergeMapSubscriber;
9847
9848 },{"../OuterSubscriber":30,"../util/subscribeToResult":157}],119:[function(require,module,exports){
9849 "use strict";
9850 var MulticastObservable_1 = require('../observable/MulticastObservable');
9851 var ConnectableObservable_1 = require('../observable/ConnectableObservable');
9852 /**
9853  * Returns an Observable that emits the results of invoking a specified selector on items
9854  * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.
9855  *
9856  * <img src="./img/multicast.png" width="100%">
9857  *
9858  * @param {Function|Subject} Factory function to create an intermediate subject through
9859  * which the source sequence's elements will be multicast to the selector function
9860  * or Subject to push source elements into.
9861  * @param {Function} Optional selector function that can use the multicasted source stream
9862  * as many times as needed, without causing multiple subscriptions to the source stream.
9863  * Subscribers to the given source will receive all notifications of the source from the
9864  * time of the subscription forward.
9865  * @return {Observable} an Observable that emits the results of invoking the selector
9866  * on the items emitted by a `ConnectableObservable` that shares a single subscription to
9867  * the underlying stream.
9868  * @method multicast
9869  * @owner Observable
9870  */
9871 function multicast(subjectOrSubjectFactory, selector) {
9872     var subjectFactory;
9873     if (typeof subjectOrSubjectFactory === 'function') {
9874         subjectFactory = subjectOrSubjectFactory;
9875     }
9876     else {
9877         subjectFactory = function subjectFactory() {
9878             return subjectOrSubjectFactory;
9879         };
9880     }
9881     return !selector ?
9882         new ConnectableObservable_1.ConnectableObservable(this, subjectFactory) :
9883         new MulticastObservable_1.MulticastObservable(this, subjectFactory, selector);
9884 }
9885 exports.multicast = multicast;
9886
9887 },{"../observable/ConnectableObservable":81,"../observable/MulticastObservable":88}],120:[function(require,module,exports){
9888 "use strict";
9889 var __extends = (this && this.__extends) || function (d, b) {
9890     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9891     function __() { this.constructor = d; }
9892     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9893 };
9894 var Subscriber_1 = require('../Subscriber');
9895 var Notification_1 = require('../Notification');
9896 /**
9897  * @see {@link Notification}
9898  *
9899  * @param scheduler
9900  * @param delay
9901  * @return {Observable<R>|WebSocketSubject<T>|Observable<T>}
9902  * @method observeOn
9903  * @owner Observable
9904  */
9905 function observeOn(scheduler, delay) {
9906     if (delay === void 0) { delay = 0; }
9907     return this.lift(new ObserveOnOperator(scheduler, delay));
9908 }
9909 exports.observeOn = observeOn;
9910 var ObserveOnOperator = (function () {
9911     function ObserveOnOperator(scheduler, delay) {
9912         if (delay === void 0) { delay = 0; }
9913         this.scheduler = scheduler;
9914         this.delay = delay;
9915     }
9916     ObserveOnOperator.prototype.call = function (subscriber, source) {
9917         return source._subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
9918     };
9919     return ObserveOnOperator;
9920 }());
9921 exports.ObserveOnOperator = ObserveOnOperator;
9922 /**
9923  * We need this JSDoc comment for affecting ESDoc.
9924  * @ignore
9925  * @extends {Ignored}
9926  */
9927 var ObserveOnSubscriber = (function (_super) {
9928     __extends(ObserveOnSubscriber, _super);
9929     function ObserveOnSubscriber(destination, scheduler, delay) {
9930         if (delay === void 0) { delay = 0; }
9931         _super.call(this, destination);
9932         this.scheduler = scheduler;
9933         this.delay = delay;
9934     }
9935     ObserveOnSubscriber.dispatch = function (arg) {
9936         var notification = arg.notification, destination = arg.destination;
9937         notification.observe(destination);
9938     };
9939     ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
9940         this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
9941     };
9942     ObserveOnSubscriber.prototype._next = function (value) {
9943         this.scheduleMessage(Notification_1.Notification.createNext(value));
9944     };
9945     ObserveOnSubscriber.prototype._error = function (err) {
9946         this.scheduleMessage(Notification_1.Notification.createError(err));
9947     };
9948     ObserveOnSubscriber.prototype._complete = function () {
9949         this.scheduleMessage(Notification_1.Notification.createComplete());
9950     };
9951     return ObserveOnSubscriber;
9952 }(Subscriber_1.Subscriber));
9953 exports.ObserveOnSubscriber = ObserveOnSubscriber;
9954 var ObserveOnMessage = (function () {
9955     function ObserveOnMessage(notification, destination) {
9956         this.notification = notification;
9957         this.destination = destination;
9958     }
9959     return ObserveOnMessage;
9960 }());
9961 exports.ObserveOnMessage = ObserveOnMessage;
9962
9963 },{"../Notification":27,"../Subscriber":35}],121:[function(require,module,exports){
9964 "use strict";
9965 var __extends = (this && this.__extends) || function (d, b) {
9966     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9967     function __() { this.constructor = d; }
9968     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9969 };
9970 var Subscriber_1 = require('../Subscriber');
9971 /**
9972  * Groups pairs of consecutive emissions together and emits them as an array of
9973  * two values.
9974  *
9975  * <span class="informal">Puts the current value and previous value together as
9976  * an array, and emits that.</span>
9977  *
9978  * <img src="./img/pairwise.png" width="100%">
9979  *
9980  * The Nth emission from the source Observable will cause the output Observable
9981  * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
9982  * pair. For this reason, `pairwise` emits on the second and subsequent
9983  * emissions from the source Observable, but not on the first emission, because
9984  * there is no previous value in that case.
9985  *
9986  * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
9987  * var clicks = Rx.Observable.fromEvent(document, 'click');
9988  * var pairs = clicks.pairwise();
9989  * var distance = pairs.map(pair => {
9990  *   var x0 = pair[0].clientX;
9991  *   var y0 = pair[0].clientY;
9992  *   var x1 = pair[1].clientX;
9993  *   var y1 = pair[1].clientY;
9994  *   return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
9995  * });
9996  * distance.subscribe(x => console.log(x));
9997  *
9998  * @see {@link buffer}
9999  * @see {@link bufferCount}
10000  *
10001  * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
10002  * consecutive values from the source Observable.
10003  * @method pairwise
10004  * @owner Observable
10005  */
10006 function pairwise() {
10007     return this.lift(new PairwiseOperator());
10008 }
10009 exports.pairwise = pairwise;
10010 var PairwiseOperator = (function () {
10011     function PairwiseOperator() {
10012     }
10013     PairwiseOperator.prototype.call = function (subscriber, source) {
10014         return source._subscribe(new PairwiseSubscriber(subscriber));
10015     };
10016     return PairwiseOperator;
10017 }());
10018 /**
10019  * We need this JSDoc comment for affecting ESDoc.
10020  * @ignore
10021  * @extends {Ignored}
10022  */
10023 var PairwiseSubscriber = (function (_super) {
10024     __extends(PairwiseSubscriber, _super);
10025     function PairwiseSubscriber(destination) {
10026         _super.call(this, destination);
10027         this.hasPrev = false;
10028     }
10029     PairwiseSubscriber.prototype._next = function (value) {
10030         if (this.hasPrev) {
10031             this.destination.next([this.prev, value]);
10032         }
10033         else {
10034             this.hasPrev = true;
10035         }
10036         this.prev = value;
10037     };
10038     return PairwiseSubscriber;
10039 }(Subscriber_1.Subscriber));
10040
10041 },{"../Subscriber":35}],122:[function(require,module,exports){
10042 "use strict";
10043 var map_1 = require('./map');
10044 /**
10045  * Maps each source value (an object) to its specified nested property.
10046  *
10047  * <span class="informal">Like {@link map}, but meant only for picking one of
10048  * the nested properties of every emitted object.</span>
10049  *
10050  * <img src="./img/pluck.png" width="100%">
10051  *
10052  * Given a list of strings describing a path to an object property, retrieves
10053  * the value of a specified nested property from all values in the source
10054  * Observable. If a property can't be resolved, it will return `undefined` for
10055  * that value.
10056  *
10057  * @example <caption>Map every every click to the tagName of the clicked target element</caption>
10058  * var clicks = Rx.Observable.fromEvent(document, 'click');
10059  * var tagNames = clicks.pluck('target', 'tagName');
10060  * tagNames.subscribe(x => console.log(x));
10061  *
10062  * @see {@link map}
10063  *
10064  * @param {...string} properties The nested properties to pluck from each source
10065  * value (an object).
10066  * @return {Observable} Returns a new Observable of property values from the
10067  * source values.
10068  * @method pluck
10069  * @owner Observable
10070  */
10071 function pluck() {
10072     var properties = [];
10073     for (var _i = 0; _i < arguments.length; _i++) {
10074         properties[_i - 0] = arguments[_i];
10075     }
10076     var length = properties.length;
10077     if (length === 0) {
10078         throw new Error('list of properties cannot be empty.');
10079     }
10080     return map_1.map.call(this, plucker(properties, length));
10081 }
10082 exports.pluck = pluck;
10083 function plucker(props, length) {
10084     var mapper = function (x) {
10085         var currentProp = x;
10086         for (var i = 0; i < length; i++) {
10087             var p = currentProp[props[i]];
10088             if (typeof p !== 'undefined') {
10089                 currentProp = p;
10090             }
10091             else {
10092                 return undefined;
10093             }
10094         }
10095         return currentProp;
10096     };
10097     return mapper;
10098 }
10099
10100 },{"./map":115}],123:[function(require,module,exports){
10101 "use strict";
10102 var Subject_1 = require('../Subject');
10103 var multicast_1 = require('./multicast');
10104 /**
10105  * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
10106  * before it begins emitting items to those Observers that have subscribed to it.
10107  *
10108  * <img src="./img/publish.png" width="100%">
10109  *
10110  * @param {Function} Optional selector function which can use the multicasted source sequence as many times as needed,
10111  * without causing multiple subscriptions to the source sequence.
10112  * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
10113  * @return a ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
10114  * @method publish
10115  * @owner Observable
10116  */
10117 function publish(selector) {
10118     return selector ? multicast_1.multicast.call(this, function () { return new Subject_1.Subject(); }, selector) :
10119         multicast_1.multicast.call(this, new Subject_1.Subject());
10120 }
10121 exports.publish = publish;
10122
10123 },{"../Subject":33,"./multicast":119}],124:[function(require,module,exports){
10124 "use strict";
10125 var ReplaySubject_1 = require('../ReplaySubject');
10126 var multicast_1 = require('./multicast');
10127 /**
10128  * @param bufferSize
10129  * @param windowTime
10130  * @param scheduler
10131  * @return {ConnectableObservable<T>}
10132  * @method publishReplay
10133  * @owner Observable
10134  */
10135 function publishReplay(bufferSize, windowTime, scheduler) {
10136     if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
10137     if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
10138     return multicast_1.multicast.call(this, new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler));
10139 }
10140 exports.publishReplay = publishReplay;
10141
10142 },{"../ReplaySubject":31,"./multicast":119}],125:[function(require,module,exports){
10143 "use strict";
10144 var __extends = (this && this.__extends) || function (d, b) {
10145     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10146     function __() { this.constructor = d; }
10147     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10148 };
10149 var Subscriber_1 = require('../Subscriber');
10150 /**
10151  * Applies an accumulator function over the source Observable, and returns each
10152  * intermediate result, with an optional seed value.
10153  *
10154  * <span class="informal">It's like {@link reduce}, but emits the current
10155  * accumulation whenever the source emits a value.</span>
10156  *
10157  * <img src="./img/scan.png" width="100%">
10158  *
10159  * Combines together all values emitted on the source, using an accumulator
10160  * function that knows how to join a new source value into the accumulation from
10161  * the past. Is similar to {@link reduce}, but emits the intermediate
10162  * accumulations.
10163  *
10164  * Returns an Observable that applies a specified `accumulator` function to each
10165  * item emitted by the source Observable. If a `seed` value is specified, then
10166  * that value will be used as the initial value for the accumulator. If no seed
10167  * value is specified, the first item of the source is used as the seed.
10168  *
10169  * @example <caption>Count the number of click events</caption>
10170  * var clicks = Rx.Observable.fromEvent(document, 'click');
10171  * var ones = clicks.mapTo(1);
10172  * var seed = 0;
10173  * var count = ones.scan((acc, one) => acc + one, seed);
10174  * count.subscribe(x => console.log(x));
10175  *
10176  * @see {@link expand}
10177  * @see {@link mergeScan}
10178  * @see {@link reduce}
10179  *
10180  * @param {function(acc: R, value: T, index: number): R} accumulator
10181  * The accumulator function called on each source value.
10182  * @param {T|R} [seed] The initial accumulation value.
10183  * @return {Observable<R>} An observable of the accumulated values.
10184  * @method scan
10185  * @owner Observable
10186  */
10187 function scan(accumulator, seed) {
10188     return this.lift(new ScanOperator(accumulator, seed));
10189 }
10190 exports.scan = scan;
10191 var ScanOperator = (function () {
10192     function ScanOperator(accumulator, seed) {
10193         this.accumulator = accumulator;
10194         this.seed = seed;
10195     }
10196     ScanOperator.prototype.call = function (subscriber, source) {
10197         return source._subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed));
10198     };
10199     return ScanOperator;
10200 }());
10201 /**
10202  * We need this JSDoc comment for affecting ESDoc.
10203  * @ignore
10204  * @extends {Ignored}
10205  */
10206 var ScanSubscriber = (function (_super) {
10207     __extends(ScanSubscriber, _super);
10208     function ScanSubscriber(destination, accumulator, seed) {
10209         _super.call(this, destination);
10210         this.accumulator = accumulator;
10211         this.index = 0;
10212         this.accumulatorSet = false;
10213         this.seed = seed;
10214         this.accumulatorSet = typeof seed !== 'undefined';
10215     }
10216     Object.defineProperty(ScanSubscriber.prototype, "seed", {
10217         get: function () {
10218             return this._seed;
10219         },
10220         set: function (value) {
10221             this.accumulatorSet = true;
10222             this._seed = value;
10223         },
10224         enumerable: true,
10225         configurable: true
10226     });
10227     ScanSubscriber.prototype._next = function (value) {
10228         if (!this.accumulatorSet) {
10229             this.seed = value;
10230             this.destination.next(value);
10231         }
10232         else {
10233             return this._tryNext(value);
10234         }
10235     };
10236     ScanSubscriber.prototype._tryNext = function (value) {
10237         var index = this.index++;
10238         var result;
10239         try {
10240             result = this.accumulator(this.seed, value, index);
10241         }
10242         catch (err) {
10243             this.destination.error(err);
10244         }
10245         this.seed = result;
10246         this.destination.next(result);
10247     };
10248     return ScanSubscriber;
10249 }(Subscriber_1.Subscriber));
10250
10251 },{"../Subscriber":35}],126:[function(require,module,exports){
10252 "use strict";
10253 var multicast_1 = require('./multicast');
10254 var Subject_1 = require('../Subject');
10255 function shareSubjectFactory() {
10256     return new Subject_1.Subject();
10257 }
10258 /**
10259  * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
10260  * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
10261  * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
10262  * This is an alias for .publish().refCount().
10263  *
10264  * <img src="./img/share.png" width="100%">
10265  *
10266  * @return {Observable<T>} an Observable that upon connection causes the source Observable to emit items to its Observers
10267  * @method share
10268  * @owner Observable
10269  */
10270 function share() {
10271     return multicast_1.multicast.call(this, shareSubjectFactory).refCount();
10272 }
10273 exports.share = share;
10274 ;
10275
10276 },{"../Subject":33,"./multicast":119}],127:[function(require,module,exports){
10277 "use strict";
10278 var __extends = (this && this.__extends) || function (d, b) {
10279     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10280     function __() { this.constructor = d; }
10281     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10282 };
10283 var Subscriber_1 = require('../Subscriber');
10284 /**
10285  * Returns an Observable that skips `n` items emitted by an Observable.
10286  *
10287  * <img src="./img/skip.png" width="100%">
10288  *
10289  * @param {Number} the `n` of times, items emitted by source Observable should be skipped.
10290  * @return {Observable} an Observable that skips values emitted by the source Observable.
10291  *
10292  * @method skip
10293  * @owner Observable
10294  */
10295 function skip(total) {
10296     return this.lift(new SkipOperator(total));
10297 }
10298 exports.skip = skip;
10299 var SkipOperator = (function () {
10300     function SkipOperator(total) {
10301         this.total = total;
10302     }
10303     SkipOperator.prototype.call = function (subscriber, source) {
10304         return source._subscribe(new SkipSubscriber(subscriber, this.total));
10305     };
10306     return SkipOperator;
10307 }());
10308 /**
10309  * We need this JSDoc comment for affecting ESDoc.
10310  * @ignore
10311  * @extends {Ignored}
10312  */
10313 var SkipSubscriber = (function (_super) {
10314     __extends(SkipSubscriber, _super);
10315     function SkipSubscriber(destination, total) {
10316         _super.call(this, destination);
10317         this.total = total;
10318         this.count = 0;
10319     }
10320     SkipSubscriber.prototype._next = function (x) {
10321         if (++this.count > this.total) {
10322             this.destination.next(x);
10323         }
10324     };
10325     return SkipSubscriber;
10326 }(Subscriber_1.Subscriber));
10327
10328 },{"../Subscriber":35}],128:[function(require,module,exports){
10329 "use strict";
10330 var __extends = (this && this.__extends) || function (d, b) {
10331     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10332     function __() { this.constructor = d; }
10333     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10334 };
10335 var OuterSubscriber_1 = require('../OuterSubscriber');
10336 var subscribeToResult_1 = require('../util/subscribeToResult');
10337 /**
10338  * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
10339  *
10340  * <img src="./img/skipUntil.png" width="100%">
10341  *
10342  * @param {Observable} the second Observable that has to emit an item before the source Observable's elements begin to
10343  * be mirrored by the resulting Observable.
10344  * @return {Observable<T>} an Observable that skips items from the source Observable until the second Observable emits
10345  * an item, then emits the remaining items.
10346  * @method skipUntil
10347  * @owner Observable
10348  */
10349 function skipUntil(notifier) {
10350     return this.lift(new SkipUntilOperator(notifier));
10351 }
10352 exports.skipUntil = skipUntil;
10353 var SkipUntilOperator = (function () {
10354     function SkipUntilOperator(notifier) {
10355         this.notifier = notifier;
10356     }
10357     SkipUntilOperator.prototype.call = function (subscriber, source) {
10358         return source._subscribe(new SkipUntilSubscriber(subscriber, this.notifier));
10359     };
10360     return SkipUntilOperator;
10361 }());
10362 /**
10363  * We need this JSDoc comment for affecting ESDoc.
10364  * @ignore
10365  * @extends {Ignored}
10366  */
10367 var SkipUntilSubscriber = (function (_super) {
10368     __extends(SkipUntilSubscriber, _super);
10369     function SkipUntilSubscriber(destination, notifier) {
10370         _super.call(this, destination);
10371         this.hasValue = false;
10372         this.isInnerStopped = false;
10373         this.add(subscribeToResult_1.subscribeToResult(this, notifier));
10374     }
10375     SkipUntilSubscriber.prototype._next = function (value) {
10376         if (this.hasValue) {
10377             _super.prototype._next.call(this, value);
10378         }
10379     };
10380     SkipUntilSubscriber.prototype._complete = function () {
10381         if (this.isInnerStopped) {
10382             _super.prototype._complete.call(this);
10383         }
10384         else {
10385             this.unsubscribe();
10386         }
10387     };
10388     SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10389         this.hasValue = true;
10390     };
10391     SkipUntilSubscriber.prototype.notifyComplete = function () {
10392         this.isInnerStopped = true;
10393         if (this.isStopped) {
10394             _super.prototype._complete.call(this);
10395         }
10396     };
10397     return SkipUntilSubscriber;
10398 }(OuterSubscriber_1.OuterSubscriber));
10399
10400 },{"../OuterSubscriber":30,"../util/subscribeToResult":157}],129:[function(require,module,exports){
10401 "use strict";
10402 var ArrayObservable_1 = require('../observable/ArrayObservable');
10403 var ScalarObservable_1 = require('../observable/ScalarObservable');
10404 var EmptyObservable_1 = require('../observable/EmptyObservable');
10405 var concat_1 = require('./concat');
10406 var isScheduler_1 = require('../util/isScheduler');
10407 /**
10408  * Returns an Observable that emits the items in a specified Iterable before it begins to emit items emitted by the
10409  * source Observable.
10410  *
10411  * <img src="./img/startWith.png" width="100%">
10412  *
10413  * @param {Values} an Iterable that contains the items you want the modified Observable to emit first.
10414  * @return {Observable} an Observable that emits the items in the specified Iterable and then emits the items
10415  * emitted by the source Observable.
10416  * @method startWith
10417  * @owner Observable
10418  */
10419 function startWith() {
10420     var array = [];
10421     for (var _i = 0; _i < arguments.length; _i++) {
10422         array[_i - 0] = arguments[_i];
10423     }
10424     var scheduler = array[array.length - 1];
10425     if (isScheduler_1.isScheduler(scheduler)) {
10426         array.pop();
10427     }
10428     else {
10429         scheduler = null;
10430     }
10431     var len = array.length;
10432     if (len === 1) {
10433         return concat_1.concatStatic(new ScalarObservable_1.ScalarObservable(array[0], scheduler), this);
10434     }
10435     else if (len > 1) {
10436         return concat_1.concatStatic(new ArrayObservable_1.ArrayObservable(array, scheduler), this);
10437     }
10438     else {
10439         return concat_1.concatStatic(new EmptyObservable_1.EmptyObservable(scheduler), this);
10440     }
10441 }
10442 exports.startWith = startWith;
10443
10444 },{"../observable/ArrayObservable":80,"../observable/EmptyObservable":83,"../observable/ScalarObservable":90,"../util/isScheduler":155,"./concat":105}],130:[function(require,module,exports){
10445 "use strict";
10446 var __extends = (this && this.__extends) || function (d, b) {
10447     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10448     function __() { this.constructor = d; }
10449     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10450 };
10451 var OuterSubscriber_1 = require('../OuterSubscriber');
10452 var subscribeToResult_1 = require('../util/subscribeToResult');
10453 /**
10454  * Projects each source value to an Observable which is merged in the output
10455  * Observable, emitting values only from the most recently projected Observable.
10456  *
10457  * <span class="informal">Maps each value to an Observable, then flattens all of
10458  * these inner Observables using {@link switch}.</span>
10459  *
10460  * <img src="./img/switchMap.png" width="100%">
10461  *
10462  * Returns an Observable that emits items based on applying a function that you
10463  * supply to each item emitted by the source Observable, where that function
10464  * returns an (so-called "inner") Observable. Each time it observes one of these
10465  * inner Observables, the output Observable begins emitting the items emitted by
10466  * that inner Observable. When a new inner Observable is emitted, `switchMap`
10467  * stops emitting items from the earlier-emitted inner Observable and begins
10468  * emitting items from the new one. It continues to behave like this for
10469  * subsequent inner Observables.
10470  *
10471  * @example <caption>Rerun an interval Observable on every click event</caption>
10472  * var clicks = Rx.Observable.fromEvent(document, 'click');
10473  * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
10474  * result.subscribe(x => console.log(x));
10475  *
10476  * @see {@link concatMap}
10477  * @see {@link exhaustMap}
10478  * @see {@link mergeMap}
10479  * @see {@link switch}
10480  * @see {@link switchMapTo}
10481  *
10482  * @param {function(value: T, ?index: number): Observable} project A function
10483  * that, when applied to an item emitted by the source Observable, returns an
10484  * Observable.
10485  * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
10486  * A function to produce the value on the output Observable based on the values
10487  * and the indices of the source (outer) emission and the inner Observable
10488  * emission. The arguments passed to this function are:
10489  * - `outerValue`: the value that came from the source
10490  * - `innerValue`: the value that came from the projected Observable
10491  * - `outerIndex`: the "index" of the value that came from the source
10492  * - `innerIndex`: the "index" of the value from the projected Observable
10493  * @return {Observable} An Observable that emits the result of applying the
10494  * projection function (and the optional `resultSelector`) to each item emitted
10495  * by the source Observable and taking only the values from the most recently
10496  * projected inner Observable.
10497  * @method switchMap
10498  * @owner Observable
10499  */
10500 function switchMap(project, resultSelector) {
10501     return this.lift(new SwitchMapOperator(project, resultSelector));
10502 }
10503 exports.switchMap = switchMap;
10504 var SwitchMapOperator = (function () {
10505     function SwitchMapOperator(project, resultSelector) {
10506         this.project = project;
10507         this.resultSelector = resultSelector;
10508     }
10509     SwitchMapOperator.prototype.call = function (subscriber, source) {
10510         return source._subscribe(new SwitchMapSubscriber(subscriber, this.project, this.resultSelector));
10511     };
10512     return SwitchMapOperator;
10513 }());
10514 /**
10515  * We need this JSDoc comment for affecting ESDoc.
10516  * @ignore
10517  * @extends {Ignored}
10518  */
10519 var SwitchMapSubscriber = (function (_super) {
10520     __extends(SwitchMapSubscriber, _super);
10521     function SwitchMapSubscriber(destination, project, resultSelector) {
10522         _super.call(this, destination);
10523         this.project = project;
10524         this.resultSelector = resultSelector;
10525         this.index = 0;
10526     }
10527     SwitchMapSubscriber.prototype._next = function (value) {
10528         var result;
10529         var index = this.index++;
10530         try {
10531             result = this.project(value, index);
10532         }
10533         catch (error) {
10534             this.destination.error(error);
10535             return;
10536         }
10537         this._innerSub(result, value, index);
10538     };
10539     SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
10540         var innerSubscription = this.innerSubscription;
10541         if (innerSubscription) {
10542             innerSubscription.unsubscribe();
10543         }
10544         this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index));
10545     };
10546     SwitchMapSubscriber.prototype._complete = function () {
10547         var innerSubscription = this.innerSubscription;
10548         if (!innerSubscription || innerSubscription.closed) {
10549             _super.prototype._complete.call(this);
10550         }
10551     };
10552     SwitchMapSubscriber.prototype._unsubscribe = function () {
10553         this.innerSubscription = null;
10554     };
10555     SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
10556         this.remove(innerSub);
10557         this.innerSubscription = null;
10558         if (this.isStopped) {
10559             _super.prototype._complete.call(this);
10560         }
10561     };
10562     SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10563         if (this.resultSelector) {
10564             this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex);
10565         }
10566         else {
10567             this.destination.next(innerValue);
10568         }
10569     };
10570     SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
10571         var result;
10572         try {
10573             result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
10574         }
10575         catch (err) {
10576             this.destination.error(err);
10577             return;
10578         }
10579         this.destination.next(result);
10580     };
10581     return SwitchMapSubscriber;
10582 }(OuterSubscriber_1.OuterSubscriber));
10583
10584 },{"../OuterSubscriber":30,"../util/subscribeToResult":157}],131:[function(require,module,exports){
10585 "use strict";
10586 var __extends = (this && this.__extends) || function (d, b) {
10587     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10588     function __() { this.constructor = d; }
10589     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10590 };
10591 var Subscriber_1 = require('../Subscriber');
10592 var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError');
10593 var EmptyObservable_1 = require('../observable/EmptyObservable');
10594 /**
10595  * Emits only the first `count` values emitted by the source Observable.
10596  *
10597  * <span class="informal">Takes the first `count` values from the source, then
10598  * completes.</span>
10599  *
10600  * <img src="./img/take.png" width="100%">
10601  *
10602  * `take` returns an Observable that emits only the first `count` values emitted
10603  * by the source Observable. If the source emits fewer than `count` values then
10604  * all of its values are emitted. After that, it completes, regardless if the
10605  * source completes.
10606  *
10607  * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
10608  * var interval = Rx.Observable.interval(1000);
10609  * var five = interval.take(5);
10610  * five.subscribe(x => console.log(x));
10611  *
10612  * @see {@link takeLast}
10613  * @see {@link takeUntil}
10614  * @see {@link takeWhile}
10615  * @see {@link skip}
10616  *
10617  * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
10618  * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
10619  *
10620  * @param {number} count The maximum number of `next` values to emit.
10621  * @return {Observable<T>} An Observable that emits only the first `count`
10622  * values emitted by the source Observable, or all of the values from the source
10623  * if the source emits fewer than `count` values.
10624  * @method take
10625  * @owner Observable
10626  */
10627 function take(count) {
10628     if (count === 0) {
10629         return new EmptyObservable_1.EmptyObservable();
10630     }
10631     else {
10632         return this.lift(new TakeOperator(count));
10633     }
10634 }
10635 exports.take = take;
10636 var TakeOperator = (function () {
10637     function TakeOperator(total) {
10638         this.total = total;
10639         if (this.total < 0) {
10640             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
10641         }
10642     }
10643     TakeOperator.prototype.call = function (subscriber, source) {
10644         return source._subscribe(new TakeSubscriber(subscriber, this.total));
10645     };
10646     return TakeOperator;
10647 }());
10648 /**
10649  * We need this JSDoc comment for affecting ESDoc.
10650  * @ignore
10651  * @extends {Ignored}
10652  */
10653 var TakeSubscriber = (function (_super) {
10654     __extends(TakeSubscriber, _super);
10655     function TakeSubscriber(destination, total) {
10656         _super.call(this, destination);
10657         this.total = total;
10658         this.count = 0;
10659     }
10660     TakeSubscriber.prototype._next = function (value) {
10661         var total = this.total;
10662         if (++this.count <= total) {
10663             this.destination.next(value);
10664             if (this.count === total) {
10665                 this.destination.complete();
10666                 this.unsubscribe();
10667             }
10668         }
10669     };
10670     return TakeSubscriber;
10671 }(Subscriber_1.Subscriber));
10672
10673 },{"../Subscriber":35,"../observable/EmptyObservable":83,"../util/ArgumentOutOfRangeError":146}],132:[function(require,module,exports){
10674 "use strict";
10675 var __extends = (this && this.__extends) || function (d, b) {
10676     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10677     function __() { this.constructor = d; }
10678     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10679 };
10680 var OuterSubscriber_1 = require('../OuterSubscriber');
10681 var subscribeToResult_1 = require('../util/subscribeToResult');
10682 /**
10683  * Emits the values emitted by the source Observable until a `notifier`
10684  * Observable emits a value.
10685  *
10686  * <span class="informal">Lets values pass until a second Observable,
10687  * `notifier`, emits something. Then, it completes.</span>
10688  *
10689  * <img src="./img/takeUntil.png" width="100%">
10690  *
10691  * `takeUntil` subscribes and begins mirroring the source Observable. It also
10692  * monitors a second Observable, `notifier` that you provide. If the `notifier`
10693  * emits a value or a complete notification, the output Observable stops
10694  * mirroring the source Observable and completes.
10695  *
10696  * @example <caption>Tick every second until the first click happens</caption>
10697  * var interval = Rx.Observable.interval(1000);
10698  * var clicks = Rx.Observable.fromEvent(document, 'click');
10699  * var result = interval.takeUntil(clicks);
10700  * result.subscribe(x => console.log(x));
10701  *
10702  * @see {@link take}
10703  * @see {@link takeLast}
10704  * @see {@link takeWhile}
10705  * @see {@link skip}
10706  *
10707  * @param {Observable} notifier The Observable whose first emitted value will
10708  * cause the output Observable of `takeUntil` to stop emitting values from the
10709  * source Observable.
10710  * @return {Observable<T>} An Observable that emits the values from the source
10711  * Observable until such time as `notifier` emits its first value.
10712  * @method takeUntil
10713  * @owner Observable
10714  */
10715 function takeUntil(notifier) {
10716     return this.lift(new TakeUntilOperator(notifier));
10717 }
10718 exports.takeUntil = takeUntil;
10719 var TakeUntilOperator = (function () {
10720     function TakeUntilOperator(notifier) {
10721         this.notifier = notifier;
10722     }
10723     TakeUntilOperator.prototype.call = function (subscriber, source) {
10724         return source._subscribe(new TakeUntilSubscriber(subscriber, this.notifier));
10725     };
10726     return TakeUntilOperator;
10727 }());
10728 /**
10729  * We need this JSDoc comment for affecting ESDoc.
10730  * @ignore
10731  * @extends {Ignored}
10732  */
10733 var TakeUntilSubscriber = (function (_super) {
10734     __extends(TakeUntilSubscriber, _super);
10735     function TakeUntilSubscriber(destination, notifier) {
10736         _super.call(this, destination);
10737         this.notifier = notifier;
10738         this.add(subscribeToResult_1.subscribeToResult(this, notifier));
10739     }
10740     TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10741         this.complete();
10742     };
10743     TakeUntilSubscriber.prototype.notifyComplete = function () {
10744         // noop
10745     };
10746     return TakeUntilSubscriber;
10747 }(OuterSubscriber_1.OuterSubscriber));
10748
10749 },{"../OuterSubscriber":30,"../util/subscribeToResult":157}],133:[function(require,module,exports){
10750 "use strict";
10751 var __extends = (this && this.__extends) || function (d, b) {
10752     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10753     function __() { this.constructor = d; }
10754     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10755 };
10756 var OuterSubscriber_1 = require('../OuterSubscriber');
10757 var subscribeToResult_1 = require('../util/subscribeToResult');
10758 /**
10759  * Combines the source Observable with other Observables to create an Observable
10760  * whose values are calculated from the latest values of each, only when the
10761  * source emits.
10762  *
10763  * <span class="informal">Whenever the source Observable emits a value, it
10764  * computes a formula using that value plus the latest values from other input
10765  * Observables, then emits the output of that formula.</span>
10766  *
10767  * <img src="./img/withLatestFrom.png" width="100%">
10768  *
10769  * `withLatestFrom` combines each value from the source Observable (the
10770  * instance) with the latest values from the other input Observables only when
10771  * the source emits a value, optionally using a `project` function to determine
10772  * the value to be emitted on the output Observable. All input Observables must
10773  * emit at least one value before the output Observable will emit a value.
10774  *
10775  * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
10776  * var clicks = Rx.Observable.fromEvent(document, 'click');
10777  * var timer = Rx.Observable.interval(1000);
10778  * var result = clicks.withLatestFrom(timer);
10779  * result.subscribe(x => console.log(x));
10780  *
10781  * @see {@link combineLatest}
10782  *
10783  * @param {Observable} other An input Observable to combine with the source
10784  * Observable. More than one input Observables may be given as argument.
10785  * @param {Function} [project] Projection function for combining values
10786  * together. Receives all values in order of the Observables passed, where the
10787  * first parameter is a value from the source Observable. (e.g.
10788  * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
10789  * passed, arrays will be emitted on the output Observable.
10790  * @return {Observable} An Observable of projected values from the most recent
10791  * values from each input Observable, or an array of the most recent values from
10792  * each input Observable.
10793  * @method withLatestFrom
10794  * @owner Observable
10795  */
10796 function withLatestFrom() {
10797     var args = [];
10798     for (var _i = 0; _i < arguments.length; _i++) {
10799         args[_i - 0] = arguments[_i];
10800     }
10801     var project;
10802     if (typeof args[args.length - 1] === 'function') {
10803         project = args.pop();
10804     }
10805     var observables = args;
10806     return this.lift(new WithLatestFromOperator(observables, project));
10807 }
10808 exports.withLatestFrom = withLatestFrom;
10809 /* tslint:enable:max-line-length */
10810 var WithLatestFromOperator = (function () {
10811     function WithLatestFromOperator(observables, project) {
10812         this.observables = observables;
10813         this.project = project;
10814     }
10815     WithLatestFromOperator.prototype.call = function (subscriber, source) {
10816         return source._subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
10817     };
10818     return WithLatestFromOperator;
10819 }());
10820 /**
10821  * We need this JSDoc comment for affecting ESDoc.
10822  * @ignore
10823  * @extends {Ignored}
10824  */
10825 var WithLatestFromSubscriber = (function (_super) {
10826     __extends(WithLatestFromSubscriber, _super);
10827     function WithLatestFromSubscriber(destination, observables, project) {
10828         _super.call(this, destination);
10829         this.observables = observables;
10830         this.project = project;
10831         this.toRespond = [];
10832         var len = observables.length;
10833         this.values = new Array(len);
10834         for (var i = 0; i < len; i++) {
10835             this.toRespond.push(i);
10836         }
10837         for (var i = 0; i < len; i++) {
10838             var observable = observables[i];
10839             this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
10840         }
10841     }
10842     WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10843         this.values[outerIndex] = innerValue;
10844         var toRespond = this.toRespond;
10845         if (toRespond.length > 0) {
10846             var found = toRespond.indexOf(outerIndex);
10847             if (found !== -1) {
10848                 toRespond.splice(found, 1);
10849             }
10850         }
10851     };
10852     WithLatestFromSubscriber.prototype.notifyComplete = function () {
10853         // noop
10854     };
10855     WithLatestFromSubscriber.prototype._next = function (value) {
10856         if (this.toRespond.length === 0) {
10857             var args = [value].concat(this.values);
10858             if (this.project) {
10859                 this._tryProject(args);
10860             }
10861             else {
10862                 this.destination.next(args);
10863             }
10864         }
10865     };
10866     WithLatestFromSubscriber.prototype._tryProject = function (args) {
10867         var result;
10868         try {
10869             result = this.project.apply(this, args);
10870         }
10871         catch (err) {
10872             this.destination.error(err);
10873             return;
10874         }
10875         this.destination.next(result);
10876     };
10877     return WithLatestFromSubscriber;
10878 }(OuterSubscriber_1.OuterSubscriber));
10879
10880 },{"../OuterSubscriber":30,"../util/subscribeToResult":157}],134:[function(require,module,exports){
10881 "use strict";
10882 var __extends = (this && this.__extends) || function (d, b) {
10883     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10884     function __() { this.constructor = d; }
10885     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10886 };
10887 var ArrayObservable_1 = require('../observable/ArrayObservable');
10888 var isArray_1 = require('../util/isArray');
10889 var Subscriber_1 = require('../Subscriber');
10890 var OuterSubscriber_1 = require('../OuterSubscriber');
10891 var subscribeToResult_1 = require('../util/subscribeToResult');
10892 var iterator_1 = require('../symbol/iterator');
10893 /**
10894  * @param observables
10895  * @return {Observable<R>}
10896  * @method zip
10897  * @owner Observable
10898  */
10899 function zipProto() {
10900     var observables = [];
10901     for (var _i = 0; _i < arguments.length; _i++) {
10902         observables[_i - 0] = arguments[_i];
10903     }
10904     observables.unshift(this);
10905     return zipStatic.apply(this, observables);
10906 }
10907 exports.zipProto = zipProto;
10908 /* tslint:enable:max-line-length */
10909 /**
10910  * @param observables
10911  * @return {Observable<R>}
10912  * @static true
10913  * @name zip
10914  * @owner Observable
10915  */
10916 function zipStatic() {
10917     var observables = [];
10918     for (var _i = 0; _i < arguments.length; _i++) {
10919         observables[_i - 0] = arguments[_i];
10920     }
10921     var project = observables[observables.length - 1];
10922     if (typeof project === 'function') {
10923         observables.pop();
10924     }
10925     return new ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project));
10926 }
10927 exports.zipStatic = zipStatic;
10928 var ZipOperator = (function () {
10929     function ZipOperator(project) {
10930         this.project = project;
10931     }
10932     ZipOperator.prototype.call = function (subscriber, source) {
10933         return source._subscribe(new ZipSubscriber(subscriber, this.project));
10934     };
10935     return ZipOperator;
10936 }());
10937 exports.ZipOperator = ZipOperator;
10938 /**
10939  * We need this JSDoc comment for affecting ESDoc.
10940  * @ignore
10941  * @extends {Ignored}
10942  */
10943 var ZipSubscriber = (function (_super) {
10944     __extends(ZipSubscriber, _super);
10945     function ZipSubscriber(destination, project, values) {
10946         if (values === void 0) { values = Object.create(null); }
10947         _super.call(this, destination);
10948         this.index = 0;
10949         this.iterators = [];
10950         this.active = 0;
10951         this.project = (typeof project === 'function') ? project : null;
10952         this.values = values;
10953     }
10954     ZipSubscriber.prototype._next = function (value) {
10955         var iterators = this.iterators;
10956         var index = this.index++;
10957         if (isArray_1.isArray(value)) {
10958             iterators.push(new StaticArrayIterator(value));
10959         }
10960         else if (typeof value[iterator_1.$$iterator] === 'function') {
10961             iterators.push(new StaticIterator(value[iterator_1.$$iterator]()));
10962         }
10963         else {
10964             iterators.push(new ZipBufferIterator(this.destination, this, value, index));
10965         }
10966     };
10967     ZipSubscriber.prototype._complete = function () {
10968         var iterators = this.iterators;
10969         var len = iterators.length;
10970         this.active = len;
10971         for (var i = 0; i < len; i++) {
10972             var iterator = iterators[i];
10973             if (iterator.stillUnsubscribed) {
10974                 this.add(iterator.subscribe(iterator, i));
10975             }
10976             else {
10977                 this.active--; // not an observable
10978             }
10979         }
10980     };
10981     ZipSubscriber.prototype.notifyInactive = function () {
10982         this.active--;
10983         if (this.active === 0) {
10984             this.destination.complete();
10985         }
10986     };
10987     ZipSubscriber.prototype.checkIterators = function () {
10988         var iterators = this.iterators;
10989         var len = iterators.length;
10990         var destination = this.destination;
10991         // abort if not all of them have values
10992         for (var i = 0; i < len; i++) {
10993             var iterator = iterators[i];
10994             if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
10995                 return;
10996             }
10997         }
10998         var shouldComplete = false;
10999         var args = [];
11000         for (var i = 0; i < len; i++) {
11001             var iterator = iterators[i];
11002             var result = iterator.next();
11003             // check to see if it's completed now that you've gotten
11004             // the next value.
11005             if (iterator.hasCompleted()) {
11006                 shouldComplete = true;
11007             }
11008             if (result.done) {
11009                 destination.complete();
11010                 return;
11011             }
11012             args.push(result.value);
11013         }
11014         if (this.project) {
11015             this._tryProject(args);
11016         }
11017         else {
11018             destination.next(args);
11019         }
11020         if (shouldComplete) {
11021             destination.complete();
11022         }
11023     };
11024     ZipSubscriber.prototype._tryProject = function (args) {
11025         var result;
11026         try {
11027             result = this.project.apply(this, args);
11028         }
11029         catch (err) {
11030             this.destination.error(err);
11031             return;
11032         }
11033         this.destination.next(result);
11034     };
11035     return ZipSubscriber;
11036 }(Subscriber_1.Subscriber));
11037 exports.ZipSubscriber = ZipSubscriber;
11038 var StaticIterator = (function () {
11039     function StaticIterator(iterator) {
11040         this.iterator = iterator;
11041         this.nextResult = iterator.next();
11042     }
11043     StaticIterator.prototype.hasValue = function () {
11044         return true;
11045     };
11046     StaticIterator.prototype.next = function () {
11047         var result = this.nextResult;
11048         this.nextResult = this.iterator.next();
11049         return result;
11050     };
11051     StaticIterator.prototype.hasCompleted = function () {
11052         var nextResult = this.nextResult;
11053         return nextResult && nextResult.done;
11054     };
11055     return StaticIterator;
11056 }());
11057 var StaticArrayIterator = (function () {
11058     function StaticArrayIterator(array) {
11059         this.array = array;
11060         this.index = 0;
11061         this.length = 0;
11062         this.length = array.length;
11063     }
11064     StaticArrayIterator.prototype[iterator_1.$$iterator] = function () {
11065         return this;
11066     };
11067     StaticArrayIterator.prototype.next = function (value) {
11068         var i = this.index++;
11069         var array = this.array;
11070         return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
11071     };
11072     StaticArrayIterator.prototype.hasValue = function () {
11073         return this.array.length > this.index;
11074     };
11075     StaticArrayIterator.prototype.hasCompleted = function () {
11076         return this.array.length === this.index;
11077     };
11078     return StaticArrayIterator;
11079 }());
11080 /**
11081  * We need this JSDoc comment for affecting ESDoc.
11082  * @ignore
11083  * @extends {Ignored}
11084  */
11085 var ZipBufferIterator = (function (_super) {
11086     __extends(ZipBufferIterator, _super);
11087     function ZipBufferIterator(destination, parent, observable, index) {
11088         _super.call(this, destination);
11089         this.parent = parent;
11090         this.observable = observable;
11091         this.index = index;
11092         this.stillUnsubscribed = true;
11093         this.buffer = [];
11094         this.isComplete = false;
11095     }
11096     ZipBufferIterator.prototype[iterator_1.$$iterator] = function () {
11097         return this;
11098     };
11099     // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next
11100     //    this is legit because `next()` will never be called by a subscription in this case.
11101     ZipBufferIterator.prototype.next = function () {
11102         var buffer = this.buffer;
11103         if (buffer.length === 0 && this.isComplete) {
11104             return { value: null, done: true };
11105         }
11106         else {
11107             return { value: buffer.shift(), done: false };
11108         }
11109     };
11110     ZipBufferIterator.prototype.hasValue = function () {
11111         return this.buffer.length > 0;
11112     };
11113     ZipBufferIterator.prototype.hasCompleted = function () {
11114         return this.buffer.length === 0 && this.isComplete;
11115     };
11116     ZipBufferIterator.prototype.notifyComplete = function () {
11117         if (this.buffer.length > 0) {
11118             this.isComplete = true;
11119             this.parent.notifyInactive();
11120         }
11121         else {
11122             this.destination.complete();
11123         }
11124     };
11125     ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11126         this.buffer.push(innerValue);
11127         this.parent.checkIterators();
11128     };
11129     ZipBufferIterator.prototype.subscribe = function (value, index) {
11130         return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
11131     };
11132     return ZipBufferIterator;
11133 }(OuterSubscriber_1.OuterSubscriber));
11134
11135 },{"../OuterSubscriber":30,"../Subscriber":35,"../observable/ArrayObservable":80,"../symbol/iterator":142,"../util/isArray":151,"../util/subscribeToResult":157}],135:[function(require,module,exports){
11136 "use strict";
11137 var __extends = (this && this.__extends) || function (d, b) {
11138     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11139     function __() { this.constructor = d; }
11140     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11141 };
11142 var Subscription_1 = require('../Subscription');
11143 /**
11144  * A unit of work to be executed in a {@link Scheduler}. An action is typically
11145  * created from within a Scheduler and an RxJS user does not need to concern
11146  * themselves about creating and manipulating an Action.
11147  *
11148  * ```ts
11149  * class Action<T> extends Subscription {
11150  *   new (scheduler: Scheduler, work: (state?: T) => void);
11151  *   schedule(state?: T, delay: number = 0): Subscription;
11152  * }
11153  * ```
11154  *
11155  * @class Action<T>
11156  */
11157 var Action = (function (_super) {
11158     __extends(Action, _super);
11159     function Action(scheduler, work) {
11160         _super.call(this);
11161     }
11162     /**
11163      * Schedules this action on its parent Scheduler for execution. May be passed
11164      * some context object, `state`. May happen at some point in the future,
11165      * according to the `delay` parameter, if specified.
11166      * @param {T} [state] Some contextual data that the `work` function uses when
11167      * called by the Scheduler.
11168      * @param {number} [delay] Time to wait before executing the work, where the
11169      * time unit is implicit and defined by the Scheduler.
11170      * @return {void}
11171      */
11172     Action.prototype.schedule = function (state, delay) {
11173         if (delay === void 0) { delay = 0; }
11174         return this;
11175     };
11176     return Action;
11177 }(Subscription_1.Subscription));
11178 exports.Action = Action;
11179
11180 },{"../Subscription":36}],136:[function(require,module,exports){
11181 "use strict";
11182 var __extends = (this && this.__extends) || function (d, b) {
11183     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11184     function __() { this.constructor = d; }
11185     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11186 };
11187 var root_1 = require('../util/root');
11188 var Action_1 = require('./Action');
11189 /**
11190  * We need this JSDoc comment for affecting ESDoc.
11191  * @ignore
11192  * @extends {Ignored}
11193  */
11194 var AsyncAction = (function (_super) {
11195     __extends(AsyncAction, _super);
11196     function AsyncAction(scheduler, work) {
11197         _super.call(this, scheduler, work);
11198         this.scheduler = scheduler;
11199         this.work = work;
11200         this.pending = false;
11201     }
11202     AsyncAction.prototype.schedule = function (state, delay) {
11203         if (delay === void 0) { delay = 0; }
11204         if (this.closed) {
11205             return this;
11206         }
11207         // Always replace the current state with the new state.
11208         this.state = state;
11209         // Set the pending flag indicating that this action has been scheduled, or
11210         // has recursively rescheduled itself.
11211         this.pending = true;
11212         var id = this.id;
11213         var scheduler = this.scheduler;
11214         //
11215         // Important implementation note:
11216         //
11217         // Actions only execute once by default, unless rescheduled from within the
11218         // scheduled callback. This allows us to implement single and repeat
11219         // actions via the same code path, without adding API surface area, as well
11220         // as mimic traditional recursion but across asynchronous boundaries.
11221         //
11222         // However, JS runtimes and timers distinguish between intervals achieved by
11223         // serial `setTimeout` calls vs. a single `setInterval` call. An interval of
11224         // serial `setTimeout` calls can be individually delayed, which delays
11225         // scheduling the next `setTimeout`, and so on. `setInterval` attempts to
11226         // guarantee the interval callback will be invoked more precisely to the
11227         // interval period, regardless of load.
11228         //
11229         // Therefore, we use `setInterval` to schedule single and repeat actions.
11230         // If the action reschedules itself with the same delay, the interval is not
11231         // canceled. If the action doesn't reschedule, or reschedules with a
11232         // different delay, the interval will be canceled after scheduled callback
11233         // execution.
11234         //
11235         if (id != null) {
11236             this.id = this.recycleAsyncId(scheduler, id, delay);
11237         }
11238         this.delay = delay;
11239         // If this action has already an async Id, don't request a new one.
11240         this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
11241         return this;
11242     };
11243     AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
11244         if (delay === void 0) { delay = 0; }
11245         return root_1.root.setInterval(scheduler.flush.bind(scheduler, this), delay);
11246     };
11247     AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
11248         if (delay === void 0) { delay = 0; }
11249         // If this action is rescheduled with the same delay time, don't clear the interval id.
11250         if (delay !== null && this.delay === delay) {
11251             return id;
11252         }
11253         // Otherwise, if the action's delay time is different from the current delay,
11254         // clear the interval id
11255         return root_1.root.clearInterval(id) && undefined || undefined;
11256     };
11257     /**
11258      * Immediately executes this action and the `work` it contains.
11259      * @return {any}
11260      */
11261     AsyncAction.prototype.execute = function (state, delay) {
11262         if (this.closed) {
11263             return new Error('executing a cancelled action');
11264         }
11265         this.pending = false;
11266         var error = this._execute(state, delay);
11267         if (error) {
11268             return error;
11269         }
11270         else if (this.pending === false && this.id != null) {
11271             // Dequeue if the action didn't reschedule itself. Don't call
11272             // unsubscribe(), because the action could reschedule later.
11273             // For example:
11274             // ```
11275             // scheduler.schedule(function doWork(counter) {
11276             //   /* ... I'm a busy worker bee ... */
11277             //   var originalAction = this;
11278             //   /* wait 100ms before rescheduling the action */
11279             //   setTimeout(function () {
11280             //     originalAction.schedule(counter + 1);
11281             //   }, 100);
11282             // }, 1000);
11283             // ```
11284             this.id = this.recycleAsyncId(this.scheduler, this.id, null);
11285         }
11286     };
11287     AsyncAction.prototype._execute = function (state, delay) {
11288         var errored = false;
11289         var errorValue = undefined;
11290         try {
11291             this.work(state);
11292         }
11293         catch (e) {
11294             errored = true;
11295             errorValue = !!e && e || new Error(e);
11296         }
11297         if (errored) {
11298             this.unsubscribe();
11299             return errorValue;
11300         }
11301     };
11302     AsyncAction.prototype._unsubscribe = function () {
11303         var id = this.id;
11304         var scheduler = this.scheduler;
11305         var actions = scheduler.actions;
11306         var index = actions.indexOf(this);
11307         this.work = null;
11308         this.delay = null;
11309         this.state = null;
11310         this.pending = false;
11311         this.scheduler = null;
11312         if (index !== -1) {
11313             actions.splice(index, 1);
11314         }
11315         if (id != null) {
11316             this.id = this.recycleAsyncId(scheduler, id, null);
11317         }
11318     };
11319     return AsyncAction;
11320 }(Action_1.Action));
11321 exports.AsyncAction = AsyncAction;
11322
11323 },{"../util/root":156,"./Action":135}],137:[function(require,module,exports){
11324 "use strict";
11325 var __extends = (this && this.__extends) || function (d, b) {
11326     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11327     function __() { this.constructor = d; }
11328     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11329 };
11330 var Scheduler_1 = require('../Scheduler');
11331 var AsyncScheduler = (function (_super) {
11332     __extends(AsyncScheduler, _super);
11333     function AsyncScheduler() {
11334         _super.apply(this, arguments);
11335         this.actions = [];
11336         /**
11337          * A flag to indicate whether the Scheduler is currently executing a batch of
11338          * queued actions.
11339          * @type {boolean}
11340          */
11341         this.active = false;
11342         /**
11343          * An internal ID used to track the latest asynchronous task such as those
11344          * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
11345          * others.
11346          * @type {any}
11347          */
11348         this.scheduled = undefined;
11349     }
11350     AsyncScheduler.prototype.flush = function (action) {
11351         var actions = this.actions;
11352         if (this.active) {
11353             actions.push(action);
11354             return;
11355         }
11356         var error;
11357         this.active = true;
11358         do {
11359             if (error = action.execute(action.state, action.delay)) {
11360                 break;
11361             }
11362         } while (action = actions.shift()); // exhaust the scheduler queue
11363         this.active = false;
11364         if (error) {
11365             while (action = actions.shift()) {
11366                 action.unsubscribe();
11367             }
11368             throw error;
11369         }
11370     };
11371     return AsyncScheduler;
11372 }(Scheduler_1.Scheduler));
11373 exports.AsyncScheduler = AsyncScheduler;
11374
11375 },{"../Scheduler":32}],138:[function(require,module,exports){
11376 "use strict";
11377 var __extends = (this && this.__extends) || function (d, b) {
11378     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11379     function __() { this.constructor = d; }
11380     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11381 };
11382 var AsyncAction_1 = require('./AsyncAction');
11383 /**
11384  * We need this JSDoc comment for affecting ESDoc.
11385  * @ignore
11386  * @extends {Ignored}
11387  */
11388 var QueueAction = (function (_super) {
11389     __extends(QueueAction, _super);
11390     function QueueAction(scheduler, work) {
11391         _super.call(this, scheduler, work);
11392         this.scheduler = scheduler;
11393         this.work = work;
11394     }
11395     QueueAction.prototype.schedule = function (state, delay) {
11396         if (delay === void 0) { delay = 0; }
11397         if (delay > 0) {
11398             return _super.prototype.schedule.call(this, state, delay);
11399         }
11400         this.delay = delay;
11401         this.state = state;
11402         this.scheduler.flush(this);
11403         return this;
11404     };
11405     QueueAction.prototype.execute = function (state, delay) {
11406         return (delay > 0 || this.closed) ?
11407             _super.prototype.execute.call(this, state, delay) :
11408             this._execute(state, delay);
11409     };
11410     QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
11411         if (delay === void 0) { delay = 0; }
11412         // If delay is greater than 0, enqueue as an async action.
11413         if (delay !== null && delay > 0) {
11414             return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
11415         }
11416         // Otherwise flush the scheduler starting with this action.
11417         return scheduler.flush(this);
11418     };
11419     return QueueAction;
11420 }(AsyncAction_1.AsyncAction));
11421 exports.QueueAction = QueueAction;
11422
11423 },{"./AsyncAction":136}],139:[function(require,module,exports){
11424 "use strict";
11425 var __extends = (this && this.__extends) || function (d, b) {
11426     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11427     function __() { this.constructor = d; }
11428     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11429 };
11430 var AsyncScheduler_1 = require('./AsyncScheduler');
11431 var QueueScheduler = (function (_super) {
11432     __extends(QueueScheduler, _super);
11433     function QueueScheduler() {
11434         _super.apply(this, arguments);
11435     }
11436     return QueueScheduler;
11437 }(AsyncScheduler_1.AsyncScheduler));
11438 exports.QueueScheduler = QueueScheduler;
11439
11440 },{"./AsyncScheduler":137}],140:[function(require,module,exports){
11441 "use strict";
11442 var AsyncAction_1 = require('./AsyncAction');
11443 var AsyncScheduler_1 = require('./AsyncScheduler');
11444 exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
11445
11446 },{"./AsyncAction":136,"./AsyncScheduler":137}],141:[function(require,module,exports){
11447 "use strict";
11448 var QueueAction_1 = require('./QueueAction');
11449 var QueueScheduler_1 = require('./QueueScheduler');
11450 exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
11451
11452 },{"./QueueAction":138,"./QueueScheduler":139}],142:[function(require,module,exports){
11453 "use strict";
11454 var root_1 = require('../util/root');
11455 var Symbol = root_1.root.Symbol;
11456 if (typeof Symbol === 'function') {
11457     if (Symbol.iterator) {
11458         exports.$$iterator = Symbol.iterator;
11459     }
11460     else if (typeof Symbol.for === 'function') {
11461         exports.$$iterator = Symbol.for('iterator');
11462     }
11463 }
11464 else {
11465     if (root_1.root.Set && typeof new root_1.root.Set()['@@iterator'] === 'function') {
11466         // Bug for mozilla version
11467         exports.$$iterator = '@@iterator';
11468     }
11469     else if (root_1.root.Map) {
11470         // es6-shim specific logic
11471         var keys = Object.getOwnPropertyNames(root_1.root.Map.prototype);
11472         for (var i = 0; i < keys.length; ++i) {
11473             var key = keys[i];
11474             if (key !== 'entries' && key !== 'size' && root_1.root.Map.prototype[key] === root_1.root.Map.prototype['entries']) {
11475                 exports.$$iterator = key;
11476                 break;
11477             }
11478         }
11479     }
11480     else {
11481         exports.$$iterator = '@@iterator';
11482     }
11483 }
11484
11485 },{"../util/root":156}],143:[function(require,module,exports){
11486 "use strict";
11487 var root_1 = require('../util/root');
11488 function getSymbolObservable(context) {
11489     var $$observable;
11490     var Symbol = context.Symbol;
11491     if (typeof Symbol === 'function') {
11492         if (Symbol.observable) {
11493             $$observable = Symbol.observable;
11494         }
11495         else {
11496             $$observable = Symbol('observable');
11497             Symbol.observable = $$observable;
11498         }
11499     }
11500     else {
11501         $$observable = '@@observable';
11502     }
11503     return $$observable;
11504 }
11505 exports.getSymbolObservable = getSymbolObservable;
11506 exports.$$observable = getSymbolObservable(root_1.root);
11507
11508 },{"../util/root":156}],144:[function(require,module,exports){
11509 "use strict";
11510 var root_1 = require('../util/root');
11511 var Symbol = root_1.root.Symbol;
11512 exports.$$rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ?
11513     Symbol.for('rxSubscriber') : '@@rxSubscriber';
11514
11515 },{"../util/root":156}],145:[function(require,module,exports){
11516 "use strict";
11517 var root_1 = require('./root');
11518 var RequestAnimationFrameDefinition = (function () {
11519     function RequestAnimationFrameDefinition(root) {
11520         if (root.requestAnimationFrame) {
11521             this.cancelAnimationFrame = root.cancelAnimationFrame.bind(root);
11522             this.requestAnimationFrame = root.requestAnimationFrame.bind(root);
11523         }
11524         else if (root.mozRequestAnimationFrame) {
11525             this.cancelAnimationFrame = root.mozCancelAnimationFrame.bind(root);
11526             this.requestAnimationFrame = root.mozRequestAnimationFrame.bind(root);
11527         }
11528         else if (root.webkitRequestAnimationFrame) {
11529             this.cancelAnimationFrame = root.webkitCancelAnimationFrame.bind(root);
11530             this.requestAnimationFrame = root.webkitRequestAnimationFrame.bind(root);
11531         }
11532         else if (root.msRequestAnimationFrame) {
11533             this.cancelAnimationFrame = root.msCancelAnimationFrame.bind(root);
11534             this.requestAnimationFrame = root.msRequestAnimationFrame.bind(root);
11535         }
11536         else if (root.oRequestAnimationFrame) {
11537             this.cancelAnimationFrame = root.oCancelAnimationFrame.bind(root);
11538             this.requestAnimationFrame = root.oRequestAnimationFrame.bind(root);
11539         }
11540         else {
11541             this.cancelAnimationFrame = root.clearTimeout.bind(root);
11542             this.requestAnimationFrame = function (cb) { return root.setTimeout(cb, 1000 / 60); };
11543         }
11544     }
11545     return RequestAnimationFrameDefinition;
11546 }());
11547 exports.RequestAnimationFrameDefinition = RequestAnimationFrameDefinition;
11548 exports.AnimationFrame = new RequestAnimationFrameDefinition(root_1.root);
11549
11550 },{"./root":156}],146:[function(require,module,exports){
11551 "use strict";
11552 var __extends = (this && this.__extends) || function (d, b) {
11553     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11554     function __() { this.constructor = d; }
11555     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11556 };
11557 /**
11558  * An error thrown when an element was queried at a certain index of an
11559  * Observable, but no such index or position exists in that sequence.
11560  *
11561  * @see {@link elementAt}
11562  * @see {@link take}
11563  * @see {@link takeLast}
11564  *
11565  * @class ArgumentOutOfRangeError
11566  */
11567 var ArgumentOutOfRangeError = (function (_super) {
11568     __extends(ArgumentOutOfRangeError, _super);
11569     function ArgumentOutOfRangeError() {
11570         var err = _super.call(this, 'argument out of range');
11571         this.name = err.name = 'ArgumentOutOfRangeError';
11572         this.stack = err.stack;
11573         this.message = err.message;
11574     }
11575     return ArgumentOutOfRangeError;
11576 }(Error));
11577 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError;
11578
11579 },{}],147:[function(require,module,exports){
11580 "use strict";
11581 var __extends = (this && this.__extends) || function (d, b) {
11582     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11583     function __() { this.constructor = d; }
11584     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11585 };
11586 /**
11587  * An error thrown when an Observable or a sequence was queried but has no
11588  * elements.
11589  *
11590  * @see {@link first}
11591  * @see {@link last}
11592  * @see {@link single}
11593  *
11594  * @class EmptyError
11595  */
11596 var EmptyError = (function (_super) {
11597     __extends(EmptyError, _super);
11598     function EmptyError() {
11599         var err = _super.call(this, 'no elements in sequence');
11600         this.name = err.name = 'EmptyError';
11601         this.stack = err.stack;
11602         this.message = err.message;
11603     }
11604     return EmptyError;
11605 }(Error));
11606 exports.EmptyError = EmptyError;
11607
11608 },{}],148:[function(require,module,exports){
11609 "use strict";
11610 var __extends = (this && this.__extends) || function (d, b) {
11611     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11612     function __() { this.constructor = d; }
11613     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11614 };
11615 /**
11616  * An error thrown when an action is invalid because the object has been
11617  * unsubscribed.
11618  *
11619  * @see {@link Subject}
11620  * @see {@link BehaviorSubject}
11621  *
11622  * @class ObjectUnsubscribedError
11623  */
11624 var ObjectUnsubscribedError = (function (_super) {
11625     __extends(ObjectUnsubscribedError, _super);
11626     function ObjectUnsubscribedError() {
11627         var err = _super.call(this, 'object unsubscribed');
11628         this.name = err.name = 'ObjectUnsubscribedError';
11629         this.stack = err.stack;
11630         this.message = err.message;
11631     }
11632     return ObjectUnsubscribedError;
11633 }(Error));
11634 exports.ObjectUnsubscribedError = ObjectUnsubscribedError;
11635
11636 },{}],149:[function(require,module,exports){
11637 "use strict";
11638 var __extends = (this && this.__extends) || function (d, b) {
11639     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11640     function __() { this.constructor = d; }
11641     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11642 };
11643 /**
11644  * An error thrown when one or more errors have occurred during the
11645  * `unsubscribe` of a {@link Subscription}.
11646  */
11647 var UnsubscriptionError = (function (_super) {
11648     __extends(UnsubscriptionError, _super);
11649     function UnsubscriptionError(errors) {
11650         _super.call(this);
11651         this.errors = errors;
11652         var err = Error.call(this, errors ?
11653             errors.length + " errors occurred during unsubscription:\n  " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n  ') : '');
11654         this.name = err.name = 'UnsubscriptionError';
11655         this.stack = err.stack;
11656         this.message = err.message;
11657     }
11658     return UnsubscriptionError;
11659 }(Error));
11660 exports.UnsubscriptionError = UnsubscriptionError;
11661
11662 },{}],150:[function(require,module,exports){
11663 "use strict";
11664 // typeof any so that it we don't have to cast when comparing a result to the error object
11665 exports.errorObject = { e: {} };
11666
11667 },{}],151:[function(require,module,exports){
11668 "use strict";
11669 exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
11670
11671 },{}],152:[function(require,module,exports){
11672 "use strict";
11673 function isFunction(x) {
11674     return typeof x === 'function';
11675 }
11676 exports.isFunction = isFunction;
11677
11678 },{}],153:[function(require,module,exports){
11679 "use strict";
11680 function isObject(x) {
11681     return x != null && typeof x === 'object';
11682 }
11683 exports.isObject = isObject;
11684
11685 },{}],154:[function(require,module,exports){
11686 "use strict";
11687 function isPromise(value) {
11688     return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
11689 }
11690 exports.isPromise = isPromise;
11691
11692 },{}],155:[function(require,module,exports){
11693 "use strict";
11694 function isScheduler(value) {
11695     return value && typeof value.schedule === 'function';
11696 }
11697 exports.isScheduler = isScheduler;
11698
11699 },{}],156:[function(require,module,exports){
11700 (function (global){
11701 "use strict";
11702 var objectTypes = {
11703     'boolean': false,
11704     'function': true,
11705     'object': true,
11706     'number': false,
11707     'string': false,
11708     'undefined': false
11709 };
11710 exports.root = (objectTypes[typeof self] && self) || (objectTypes[typeof window] && window);
11711 var freeGlobal = objectTypes[typeof global] && global;
11712 if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
11713     exports.root = freeGlobal;
11714 }
11715
11716 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
11717
11718 },{}],157:[function(require,module,exports){
11719 "use strict";
11720 var root_1 = require('./root');
11721 var isArray_1 = require('./isArray');
11722 var isPromise_1 = require('./isPromise');
11723 var Observable_1 = require('../Observable');
11724 var iterator_1 = require('../symbol/iterator');
11725 var InnerSubscriber_1 = require('../InnerSubscriber');
11726 var observable_1 = require('../symbol/observable');
11727 function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) {
11728     var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex);
11729     if (destination.closed) {
11730         return null;
11731     }
11732     if (result instanceof Observable_1.Observable) {
11733         if (result._isScalar) {
11734             destination.next(result.value);
11735             destination.complete();
11736             return null;
11737         }
11738         else {
11739             return result.subscribe(destination);
11740         }
11741     }
11742     if (isArray_1.isArray(result)) {
11743         for (var i = 0, len = result.length; i < len && !destination.closed; i++) {
11744             destination.next(result[i]);
11745         }
11746         if (!destination.closed) {
11747             destination.complete();
11748         }
11749     }
11750     else if (isPromise_1.isPromise(result)) {
11751         result.then(function (value) {
11752             if (!destination.closed) {
11753                 destination.next(value);
11754                 destination.complete();
11755             }
11756         }, function (err) { return destination.error(err); })
11757             .then(null, function (err) {
11758             // Escaping the Promise trap: globally throw unhandled errors
11759             root_1.root.setTimeout(function () { throw err; });
11760         });
11761         return destination;
11762     }
11763     else if (typeof result[iterator_1.$$iterator] === 'function') {
11764         var iterator = result[iterator_1.$$iterator]();
11765         do {
11766             var item = iterator.next();
11767             if (item.done) {
11768                 destination.complete();
11769                 break;
11770             }
11771             destination.next(item.value);
11772             if (destination.closed) {
11773                 break;
11774             }
11775         } while (true);
11776     }
11777     else if (typeof result[observable_1.$$observable] === 'function') {
11778         var obs = result[observable_1.$$observable]();
11779         if (typeof obs.subscribe !== 'function') {
11780             destination.error(new Error('invalid observable'));
11781         }
11782         else {
11783             return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex));
11784         }
11785     }
11786     else {
11787         destination.error(new TypeError('unknown type returned'));
11788     }
11789     return null;
11790 }
11791 exports.subscribeToResult = subscribeToResult;
11792
11793 },{"../InnerSubscriber":26,"../Observable":28,"../symbol/iterator":142,"../symbol/observable":143,"./isArray":151,"./isPromise":154,"./root":156}],158:[function(require,module,exports){
11794 "use strict";
11795 var Subscriber_1 = require('../Subscriber');
11796 var rxSubscriber_1 = require('../symbol/rxSubscriber');
11797 function toSubscriber(nextOrObserver, error, complete) {
11798     if (nextOrObserver) {
11799         if (nextOrObserver instanceof Subscriber_1.Subscriber) {
11800             return nextOrObserver;
11801         }
11802         if (nextOrObserver[rxSubscriber_1.$$rxSubscriber]) {
11803             return nextOrObserver[rxSubscriber_1.$$rxSubscriber]();
11804         }
11805     }
11806     if (!nextOrObserver && !error && !complete) {
11807         return new Subscriber_1.Subscriber();
11808     }
11809     return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
11810 }
11811 exports.toSubscriber = toSubscriber;
11812
11813 },{"../Subscriber":35,"../symbol/rxSubscriber":144}],159:[function(require,module,exports){
11814 "use strict";
11815 var errorObject_1 = require('./errorObject');
11816 var tryCatchTarget;
11817 function tryCatcher() {
11818     try {
11819         return tryCatchTarget.apply(this, arguments);
11820     }
11821     catch (e) {
11822         errorObject_1.errorObject.e = e;
11823         return errorObject_1.errorObject;
11824     }
11825 }
11826 function tryCatch(fn) {
11827     tryCatchTarget = fn;
11828     return tryCatcher;
11829 }
11830 exports.tryCatch = tryCatch;
11831 ;
11832
11833 },{"./errorObject":150}],160:[function(require,module,exports){
11834 // threejs.org/license
11835 (function(l,sa){"object"===typeof exports&&"undefined"!==typeof module?sa(exports):"function"===typeof define&&define.amd?define(["exports"],sa):sa(l.THREE=l.THREE||{})})(this,function(l){function sa(){}function B(a,b){this.x=a||0;this.y=b||0}function da(a,b,c,d,e,f,g,h,k,m){Object.defineProperty(this,"id",{value:ee++});this.uuid=T.generateUUID();this.sourceFile=this.name="";this.image=void 0!==a?a:da.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=void 0!==b?b:da.DEFAULT_MAPPING;this.wrapS=void 0!==c?
11836 c:1001;this.wrapT=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 B(0,0);this.repeat=new B(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=T.generateUUID();
11837 this.width=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 da(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=
11838 this.activeCubeFace=0}function ba(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 J(){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 Xa(a,b,c,d,e,f,g,h,k,m){a=void 0!==a?a:[];da.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>=
11839 d||0<d)return a;var e=b*c,f=fe[e];void 0===f&&(f=new Float32Array(e),fe[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 ge(a,b){var c=he[b];void 0===c&&(c=new Int32Array(b),he[b]=c);for(var d=0;d!==b;++d)c[d]=a.allocTextureUnit();return c}function Ie(a,b){a.uniform1f(this.addr,b)}function Je(a,b){a.uniform1i(this.addr,b)}function Ke(a,b){void 0===b.x?a.uniform2fv(this.addr,b):a.uniform2f(this.addr,b.x,b.y)}function Le(a,b){void 0!==b.x?a.uniform3f(this.addr,
11840 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 Me(a,b){void 0===b.x?a.uniform4fv(this.addr,b):a.uniform4f(this.addr,b.x,b.y,b.z,b.w)}function Ne(a,b){a.uniformMatrix2fv(this.addr,!1,b.elements||b)}function Oe(a,b){a.uniformMatrix3fv(this.addr,!1,b.elements||b)}function Pe(a,b){a.uniformMatrix4fv(this.addr,!1,b.elements||b)}function Qe(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTexture2D(b||ie,d)}function Re(a,b,c){var d=c.allocTextureUnit();
11841 a.uniform1i(this.addr,d);c.setTextureCube(b||je,d)}function ke(a,b){a.uniform2iv(this.addr,b)}function le(a,b){a.uniform3iv(this.addr,b)}function me(a,b){a.uniform4iv(this.addr,b)}function Se(a){switch(a){case 5126:return Ie;case 35664:return Ke;case 35665:return Le;case 35666:return Me;case 35674:return Ne;case 35675:return Oe;case 35676:return Pe;case 35678:return Qe;case 35680:return Re;case 5124:case 35670:return Je;case 35667:case 35671:return ke;case 35668:case 35672:return le;case 35669:case 35673:return me}}
11842 function Te(a,b){a.uniform1fv(this.addr,b)}function Ue(a,b){a.uniform1iv(this.addr,b)}function Ve(a,b){a.uniform2fv(this.addr,Fb(b,this.size,2))}function We(a,b){a.uniform3fv(this.addr,Fb(b,this.size,3))}function Xe(a,b){a.uniform4fv(this.addr,Fb(b,this.size,4))}function Ye(a,b){a.uniformMatrix2fv(this.addr,!1,Fb(b,this.size,4))}function Ze(a,b){a.uniformMatrix3fv(this.addr,!1,Fb(b,this.size,9))}function $e(a,b){a.uniformMatrix4fv(this.addr,!1,Fb(b,this.size,16))}function af(a,b,c){var d=b.length,
11843 e=ge(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTexture2D(b[a]||ie,e[a])}function bf(a,b,c){var d=b.length,e=ge(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTextureCube(b[a]||je,e[a])}function cf(a){switch(a){case 5126:return Te;case 35664:return Ve;case 35665:return We;case 35666:return Xe;case 35674:return Ye;case 35675:return Ze;case 35676:return $e;case 35678:return af;case 35680:return bf;case 5124:case 35670:return Ue;case 35667:case 35671:return ke;case 35668:case 35672:return le;
11844 case 35669:case 35673:return me}}function df(a,b,c){this.id=a;this.addr=c;this.setValue=Se(b.type)}function ef(a,b,c){this.id=a;this.addr=c;this.size=b.size;this.setValue=cf(b.type)}function ne(a){this.id=a;this.seq=[];this.map={}}function Ya(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(zd.lastIndex=0;;){var m=zd.exec(h),w=zd.lastIndex,
11845 n=m[1],p=m[3];"]"===m[2]&&(n|=0);if(void 0===p||"["===p&&w+2===k){h=g;e=void 0===p?new df(n,e,f):new ef(n,e,f);h.seq.push(e);h.map[e.id]=e;break}else p=g.map[n],void 0===p&&(p=new ne(n),n=g,g=p,n.seq.push(g),n.map[g.id]=g),g=p}}}function O(a,b,c){return void 0===b&&void 0===c?this.set(a):this.setRGB(a,b,c)}function mc(a,b){this.min=void 0!==a?a:new B(Infinity,Infinity);this.max=void 0!==b?b:new B(-Infinity,-Infinity)}function ff(a,b){var c,d,e,f,g,h,k,m,w,n,p=a.context,r=a.state,x,l,D,u,v,I;this.render=
11846 function(y,E,H){if(0!==b.length){y=new q;var F=H.w/H.z,M=.5*H.z,ca=.5*H.w,K=16/H.w,ja=new B(K*F,K),Aa=new q(1,1,0),eb=new B(1,1),Ka=new mc;Ka.min.set(H.x,H.y);Ka.max.set(H.x+(H.z-16),H.y+(H.w-16));if(void 0===u){var K=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),N=new Uint16Array([0,1,2,0,2,3]);x=p.createBuffer();l=p.createBuffer();p.bindBuffer(p.ARRAY_BUFFER,x);p.bufferData(p.ARRAY_BUFFER,K,p.STATIC_DRAW);p.bindBuffer(p.ELEMENT_ARRAY_BUFFER,l);p.bufferData(p.ELEMENT_ARRAY_BUFFER,N,p.STATIC_DRAW);
11847 v=p.createTexture();I=p.createTexture();r.bindTexture(p.TEXTURE_2D,v);p.texImage2D(p.TEXTURE_2D,0,p.RGB,16,16,0,p.RGB,p.UNSIGNED_BYTE,null);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST);r.bindTexture(p.TEXTURE_2D,I);p.texImage2D(p.TEXTURE_2D,0,p.RGBA,16,16,0,p.RGBA,p.UNSIGNED_BYTE,null);p.texParameteri(p.TEXTURE_2D,
11848 p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST);var K=D={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}",
11849 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}"},N=p.createProgram(),P=p.createShader(p.FRAGMENT_SHADER),
11850 R=p.createShader(p.VERTEX_SHADER),S="precision "+a.getPrecision()+" float;\n";p.shaderSource(P,S+K.fragmentShader);p.shaderSource(R,S+K.vertexShader);p.compileShader(P);p.compileShader(R);p.attachShader(N,P);p.attachShader(N,R);p.linkProgram(N);u=N;w=p.getAttribLocation(u,"position");n=p.getAttribLocation(u,"uv");c=p.getUniformLocation(u,"renderType");d=p.getUniformLocation(u,"map");e=p.getUniformLocation(u,"occlusionMap");f=p.getUniformLocation(u,"opacity");g=p.getUniformLocation(u,"color");h=p.getUniformLocation(u,
11851 "scale");k=p.getUniformLocation(u,"rotation");m=p.getUniformLocation(u,"screenPosition")}p.useProgram(u);r.initAttributes();r.enableAttribute(w);r.enableAttribute(n);r.disableUnusedAttributes();p.uniform1i(e,0);p.uniform1i(d,1);p.bindBuffer(p.ARRAY_BUFFER,x);p.vertexAttribPointer(w,2,p.FLOAT,!1,16,0);p.vertexAttribPointer(n,2,p.FLOAT,!1,16,8);p.bindBuffer(p.ELEMENT_ARRAY_BUFFER,l);r.disable(p.CULL_FACE);r.setDepthWrite(!1);N=0;for(P=b.length;N<P;N++)if(K=16/H.w,ja.set(K*F,K),R=b[N],y.set(R.matrixWorld.elements[12],
11852 R.matrixWorld.elements[13],R.matrixWorld.elements[14]),y.applyMatrix4(E.matrixWorldInverse),y.applyProjection(E.projectionMatrix),Aa.copy(y),eb.x=H.x+Aa.x*M+M-8,eb.y=H.y+Aa.y*ca+ca-8,!0===Ka.containsPoint(eb)){r.activeTexture(p.TEXTURE0);r.bindTexture(p.TEXTURE_2D,null);r.activeTexture(p.TEXTURE1);r.bindTexture(p.TEXTURE_2D,v);p.copyTexImage2D(p.TEXTURE_2D,0,p.RGB,eb.x,eb.y,16,16,0);p.uniform1i(c,0);p.uniform2f(h,ja.x,ja.y);p.uniform3f(m,Aa.x,Aa.y,Aa.z);r.disable(p.BLEND);r.enable(p.DEPTH_TEST);p.drawElements(p.TRIANGLES,
11853 6,p.UNSIGNED_SHORT,0);r.activeTexture(p.TEXTURE0);r.bindTexture(p.TEXTURE_2D,I);p.copyTexImage2D(p.TEXTURE_2D,0,p.RGBA,eb.x,eb.y,16,16,0);p.uniform1i(c,1);r.disable(p.DEPTH_TEST);r.activeTexture(p.TEXTURE1);r.bindTexture(p.TEXTURE_2D,v);p.drawElements(p.TRIANGLES,6,p.UNSIGNED_SHORT,0);R.positionScreen.copy(Aa);R.customUpdateCallback?R.customUpdateCallback(R):R.updateLensFlares();p.uniform1i(c,2);r.enable(p.BLEND);for(var S=0,gf=R.lensFlares.length;S<gf;S++){var V=R.lensFlares[S];.001<V.opacity&&.001<
11854 V.scale&&(Aa.x=V.x,Aa.y=V.y,Aa.z=V.z,K=V.size*V.scale/H.w,ja.x=K*F,ja.y=K,p.uniform3f(m,Aa.x,Aa.y,Aa.z),p.uniform2f(h,ja.x,ja.y),p.uniform1f(k,V.rotation),p.uniform1f(f,V.opacity),p.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),p.drawElements(p.TRIANGLES,6,p.UNSIGNED_SHORT,0))}}r.enable(p.CULL_FACE);r.enable(p.DEPTH_TEST);r.setDepthWrite(!0);a.resetGLState()}}}function hf(a,b){var c,d,e,f,g,h,k,m,w,n,p,r,x,l,
11855 D,u,v;function I(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:b.id-a.id}var y=a.context,E=a.state,H,F,M,ca,K=new q,ja=new ba,Aa=new q;this.render=function(q,Ka){if(0!==b.length){if(void 0===M){var N=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]);H=y.createBuffer();F=y.createBuffer();y.bindBuffer(y.ARRAY_BUFFER,H);y.bufferData(y.ARRAY_BUFFER,N,y.STATIC_DRAW);y.bindBuffer(y.ELEMENT_ARRAY_BUFFER,F);y.bufferData(y.ELEMENT_ARRAY_BUFFER,
11856 P,y.STATIC_DRAW);var N=y.createProgram(),P=y.createShader(y.VERTEX_SHADER),R=y.createShader(y.FRAGMENT_SHADER);y.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"));
11857 y.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"));
11858 y.compileShader(P);y.compileShader(R);y.attachShader(N,P);y.attachShader(N,R);y.linkProgram(N);M=N;u=y.getAttribLocation(M,"position");v=y.getAttribLocation(M,"uv");c=y.getUniformLocation(M,"uvOffset");d=y.getUniformLocation(M,"uvScale");e=y.getUniformLocation(M,"rotation");f=y.getUniformLocation(M,"scale");g=y.getUniformLocation(M,"color");h=y.getUniformLocation(M,"map");k=y.getUniformLocation(M,"opacity");m=y.getUniformLocation(M,"modelViewMatrix");w=y.getUniformLocation(M,"projectionMatrix");n=
11859 y.getUniformLocation(M,"fogType");p=y.getUniformLocation(M,"fogDensity");r=y.getUniformLocation(M,"fogNear");x=y.getUniformLocation(M,"fogFar");l=y.getUniformLocation(M,"fogColor");D=y.getUniformLocation(M,"alphaTest");N=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");N.width=8;N.height=8;P=N.getContext("2d");P.fillStyle="white";P.fillRect(0,0,8,8);ca=new da(N);ca.needsUpdate=!0}y.useProgram(M);E.initAttributes();E.enableAttribute(u);E.enableAttribute(v);E.disableUnusedAttributes();
11860 E.disable(y.CULL_FACE);E.enable(y.BLEND);y.bindBuffer(y.ARRAY_BUFFER,H);y.vertexAttribPointer(u,2,y.FLOAT,!1,16,0);y.vertexAttribPointer(v,2,y.FLOAT,!1,16,8);y.bindBuffer(y.ELEMENT_ARRAY_BUFFER,F);y.uniformMatrix4fv(w,!1,Ka.projectionMatrix.elements);E.activeTexture(y.TEXTURE0);y.uniform1i(h,0);P=N=0;(R=q.fog)?(y.uniform3f(l,R.color.r,R.color.g,R.color.b),R&&R.isFog?(y.uniform1f(r,R.near),y.uniform1f(x,R.far),y.uniform1i(n,1),P=N=1):R&&R.isFogExp2&&(y.uniform1f(p,R.density),y.uniform1i(n,2),P=N=2)):
11861 (y.uniform1i(n,0),P=N=0);for(var R=0,S=b.length;R<S;R++){var B=b[R];B.modelViewMatrix.multiplyMatrices(Ka.matrixWorldInverse,B.matrixWorld);B.z=-B.modelViewMatrix.elements[14]}b.sort(I);for(var V=[],R=0,S=b.length;R<S;R++){var B=b[R],ta=B.material;!1!==ta.visible&&(y.uniform1f(D,ta.alphaTest),y.uniformMatrix4fv(m,!1,B.modelViewMatrix.elements),B.matrixWorld.decompose(K,ja,Aa),V[0]=Aa.x,V[1]=Aa.y,B=0,q.fog&&ta.fog&&(B=P),N!==B&&(y.uniform1i(n,B),N=B),null!==ta.map?(y.uniform2f(c,ta.map.offset.x,ta.map.offset.y),
11862 y.uniform2f(d,ta.map.repeat.x,ta.map.repeat.y)):(y.uniform2f(c,0,0),y.uniform2f(d,1,1)),y.uniform1f(k,ta.opacity),y.uniform3f(g,ta.color.r,ta.color.g,ta.color.b),y.uniform1f(e,ta.rotation),y.uniform2fv(f,V),E.setBlending(ta.blending,ta.blendEquation,ta.blendSrc,ta.blendDst),E.setDepthTest(ta.depthTest),E.setDepthWrite(ta.depthWrite),ta.map?a.setTexture2D(ta.map,0):a.setTexture2D(ca,0),y.drawElements(y.TRIANGLES,6,y.UNSIGNED_SHORT,0))}E.enable(y.CULL_FACE);a.resetGLState()}}}function U(){Object.defineProperty(this,
11863 "id",{value:oe++});this.uuid=T.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=
11864 !1;this.alphaTest=this.polygonOffsetUnits=this.polygonOffsetFactor=0;this.premultipliedAlpha=!1;this.overdraw=0;this._needsUpdate=this.visible=!0}function Fa(a){U.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=
11865 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 Za(a){U.call(this);this.type="MeshDepthMaterial";this.depthPacking=3200;this.morphTargets=
11866 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 Ba(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 Ca(a,b){this.center=void 0!==a?a:new q;this.radius=void 0!==b?b:0}function Ia(){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.")}
11867 function va(a,b){this.normal=void 0!==a?a:new q(1,0,0);this.constant=void 0!==b?b:0}function nc(a,b,c,d,e,f){this.planes=[void 0!==a?a:new va,void 0!==b?b:new va,void 0!==c?c:new va,void 0!==d?d:new va,void 0!==e?e:new va,void 0!==f?f:new va]}function pe(a,b,c,d){function e(b,c,d,e){var f=b.geometry,g;g=D;var h=b.customDepthMaterial;d&&(g=u,h=b.customDistanceMaterial);h?g=h:(h=!1,c.morphTargets&&(f&&f.isBufferGeometry?h=f.morphAttributes&&f.morphAttributes.position&&0<f.morphAttributes.position.length:
11868 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;ja.renderSingleSided&&2==h&&(h=0);ja.renderReverseSided&&(0===h?h=1:1===h&&(h=0));g.side=h;g.clipShadows=c.clipShadows;g.clippingPlanes=c.clippingPlanes;g.wireframeLinewidth=
11869 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 nc,m=new J,
11870 w=b.shadows,n=new B,p=new B(d.maxTextureSize,d.maxTextureSize),r=new q,x=new q,l=[],D=Array(4),u=Array(4),v={},I=[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)],y=[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)],E=[new ga,new ga,new ga,new ga,new ga,new ga];b=new Za;b.depthPacking=3201;b.clipping=!0;d=Gb.distanceRGBA;for(var H=La.clone(d.uniforms),F=0;4!==F;++F){var M=0!==(F&1),ca=0!==(F&2),K=b.clone();K.morphTargets=M;K.skinning=
11871 ca;D[F]=K;M=new Fa({defines:{USE_SHADOWMAP:""},uniforms:H,vertexShader:d.vertexShader,fragmentShader:d.fragmentShader,morphTargets:M,skinning:ca,clipping:!0});u[F]=M}var ja=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!==ja.enabled&&(!1!==ja.autoUpdate||!1!==ja.needsUpdate)&&0!==w.length){h.clearColor(1,1,1,1);h.disable(g.BLEND);h.setDepthTest(!0);h.setScissorTest(!1);for(var v,u,q=0,D=w.length;q<
11872 D;q++){var H=w[q],F=H.shadow;if(void 0===F)console.warn("THREE.WebGLShadowMap:",H,"has no shadow.");else{var M=F.camera;n.copy(F.mapSize);n.min(p);if(H&&H.isPointLight){v=6;u=!0;var K=n.x,ca=n.y;E[0].set(2*K,ca,K,ca);E[1].set(0,ca,K,ca);E[2].set(3*K,ca,K,ca);E[3].set(K,ca,K,ca);E[4].set(3*K,0,K,ca);E[5].set(K,0,K,ca);n.x*=4;n.y*=2}else v=1,u=!1;null===F.map&&(F.map=new Db(n.x,n.y,{minFilter:1003,magFilter:1003,format:1023}),M.updateProjectionMatrix());F&&F.isSpotLightShadow&&F.update(H);K=F.map;F=
11873 F.matrix;x.setFromMatrixPosition(H.matrixWorld);M.position.copy(x);a.setRenderTarget(K);a.clear();for(K=0;K<v;K++){u?(r.copy(M.position),r.add(I[K]),M.up.copy(y[K]),M.lookAt(r),h.viewport(E[K])):(r.setFromMatrixPosition(H.target.matrixWorld),M.lookAt(r));M.updateMatrixWorld();M.matrixWorldInverse.getInverse(M.matrixWorld);F.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1);F.multiply(M.projectionMatrix);F.multiply(M.matrixWorldInverse);m.multiplyMatrices(M.projectionMatrix,M.matrixWorldInverse);k.setFromMatrix(m);
11874 l.length=0;f(b,d,M);for(var ca=0,B=l.length;ca<B;ca++){var C=l[ca],z=c.update(C),G=C.material;if(G&&G.isMultiMaterial)for(var $a=z.groups,G=G.materials,Ad=0,Da=$a.length;Ad<Da;Ad++){var Ra=$a[Ad],Pa=G[Ra.materialIndex];!0===Pa.visible&&(Pa=e(C,Pa,u,x),a.renderBufferDirect(M,null,z,Pa,C,Ra))}else Pa=e(C,G,u,x),a.renderBufferDirect(M,null,z,Pa,C,null)}}}}v=a.getClearColor();u=a.getClearAlpha();a.setClearColor(v,u);ja.needsUpdate=!1}}}function ab(a,b){this.origin=void 0!==a?a:new q;this.direction=void 0!==
11875 b?b:new q}function bb(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._order=d||bb.DefaultOrder}function Yc(){this.mask=1}function z(){Object.defineProperty(this,"id",{value:qe++});this.uuid=T.generateUUID();this.name="";this.type="Object3D";this.parent=null;this.children=[];this.up=z.DefaultUp.clone();var a=new q,b=new bb,c=new ba,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,{position:{enumerable:!0,
11876 value:a},rotation:{enumerable:!0,value:b},quaternion:{enumerable:!0,value:c},scale:{enumerable:!0,value:d},modelViewMatrix:{value:new J},normalMatrix:{value:new Ia}});this.matrix=new J;this.matrixWorld=new J;this.matrixAutoUpdate=z.DefaultMatrixAutoUpdate;this.matrixWorldNeedsUpdate=!1;this.layers=new Yc;this.visible=!0;this.receiveShadow=this.castShadow=!1;this.frustumCulled=!0;this.renderOrder=0;this.userData={};this.onBeforeRender=function(){};this.onAfterRender=function(){}}function gb(a,b){this.start=
11877 void 0!==a?a:new q;this.end=void 0!==b?b:new q}function wa(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 ea(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 O;this.vertexColors=Array.isArray(e)?e:[];this.materialIndex=void 0!==f?f:0}function Ma(a){U.call(this);this.type="MeshBasicMaterial";this.color=new O(16777215);this.aoMap=this.map=null;this.aoMapIntensity=
11878 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 C(a,b,c){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.uuid=T.generateUUID();this.array=a;this.itemSize=b;this.count=void 0!==a?a.length/b:0;this.normalized=!0===c;
11879 this.dynamic=!1;this.updateRange={offset:0,count:-1};this.version=0}function Zc(a,b){return new C(new Uint16Array(a),b)}function $c(a,b){return new C(new Uint32Array(a),b)}function ha(a,b){return new C(new Float32Array(a),b)}function Q(){Object.defineProperty(this,"id",{value:ad++});this.uuid=T.generateUUID();this.name="";this.type="Geometry";this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=
11880 [];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.lineDistancesNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.uvsNeedUpdate=this.verticesNeedUpdate=this.elementsNeedUpdate=!1}function re(){Object.defineProperty(this,"id",{value:ad++});this.uuid=T.generateUUID();this.name="";this.type="DirectGeometry";this.indices=[];this.vertices=[];this.normals=[];this.colors=[];this.uvs=[];this.uvs2=[];this.groups=[];this.morphTargets={};this.skinWeights=[];this.skinIndices=[];
11881 this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.uvsNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.verticesNeedUpdate=!1}function G(){Object.defineProperty(this,"id",{value:ad++});this.uuid=T.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 ya(a,b){z.call(this);this.type="Mesh";this.geometry=void 0!==
11882 a?a:new G;this.material=void 0!==b?b:new Ma({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,B,C){var Ka=f/m,N=g/B,P=f/2,R=g/2,S=k/2;g=m+1;for(var z=B+1,V=f=0,G=new q,L=0;L<z;L++)for(var O=L*N-R,J=0;J<g;J++)G[a]=(J*Ka-P)*d,G[b]=O*e,G[c]=S,n[l]=G.x,n[l+1]=G.y,n[l+2]=G.z,G[a]=0,G[b]=0,G[c]=0<k?1:-1,p[l]=G.x,p[l+1]=G.y,p[l+2]=G.z,r[t]=J/m,r[t+1]=1-L/B,l+=3,t+=2,f+=1;for(L=0;L<B;L++)for(J=0;J<m;J++)a=u+J+g*(L+1),b=u+(J+1)+
11883 g*(L+1),c=u+(J+1)+g*L,w[D]=u+J+g*L,w[D+1]=a,w[D+2]=c,w[D+3]=a,w[D+4]=b,w[D+5]=c,D+=6,V+=6;h.addGroup(v,V,C);v+=V;u+=f}G.call(this);this.type="BoxBufferGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};var h=this;d=Math.floor(d)||1;e=Math.floor(e)||1;f=Math.floor(f)||1;var k=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),w=new (65535<m?Uint32Array:Uint16Array)(m),
11884 n=new Float32Array(3*k),p=new Float32Array(3*k),r=new Float32Array(2*k),l=0,t=0,D=0,u=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","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 C(w,1));this.addAttribute("position",new C(n,3));this.addAttribute("normal",new C(p,3));this.addAttribute("uv",new C(r,2))}function ib(a,b,c,d){G.call(this);this.type="PlaneBufferGeometry";this.parameters=
11885 {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);for(var w=new Float32Array(g*h*2),n=0,p=0,r=0;r<h;r++)for(var l=r*m-f,t=0;t<g;t++)b[n]=t*k-e,b[n+1]=-l,a[n+2]=1,w[p]=t/c,w[p+1]=1-r/d,n+=3,p+=2;n=0;e=new (65535<b.length/3?Uint32Array:Uint16Array)(c*d*6);for(r=0;r<d;r++)for(t=0;t<c;t++)f=t+g*(r+1),h=t+1+g*(r+1),k=t+1+g*r,e[n]=t+g*r,e[n+1]=f,e[n+2]=k,e[n+3]=f,e[n+4]=
11886 h,e[n+5]=k,n+=6;this.setIndex(new C(e,1));this.addAttribute("position",new C(b,3));this.addAttribute("normal",new C(a,3));this.addAttribute("uv",new C(w,2))}function Z(){z.call(this);this.type="Camera";this.matrixWorldInverse=new J;this.projectionMatrix=new J}function Ea(a,b,c,d){Z.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=
11887 0;this.updateProjectionMatrix()}function Hb(a,b,c,d,e,f){Z.call(this);this.type="OrthographicCamera";this.zoom=1;this.view=null;this.left=a;this.right=b;this.top=c;this.bottom=d;this.near=void 0!==e?e:.1;this.far=void 0!==f?f:2E3;this.updateProjectionMatrix()}function jf(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):(e=a.UNSIGNED_SHORT,f=2)},render:function(b,h){a.drawElements(d,h,e,b*f);
11888 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===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 kf(a,b,c){var d;return{setMode:function(a){d=a},render:function(b,
11889 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");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&&g.isInterleavedBufferAttribute?g.data.count:g.count;f.drawArraysInstancedANGLE(d,0,g,e.maxInstancedCount);c.calls++;c.vertices+=g*e.maxInstancedCount;d===a.TRIANGLES&&
11890 (c.faces+=e.maxInstancedCount*g/3)}}}}function lf(){var a={};return{get:function(b){if(void 0!==a[b.id])return a[b.id];var c;switch(b.type){case "DirectionalLight":c={direction:new q,color:new O,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new B};break;case "SpotLight":c={position:new q,direction:new q,color:new O,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new B};break;case "PointLight":c={position:new q,color:new O,distance:0,decay:0,shadow:!1,
11891 shadowBias:0,shadowRadius:1,shadowMapSize:new B};break;case "HemisphereLight":c={direction:new q,skyColor:new O,groundColor:new O}}return a[b.id]=c}}}function mf(a){a=a.split("\n");for(var b=0;b<a.length;b++)a[b]=b+1+": "+a[b];return a.join("\n")}function se(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()",
11892 b===a.VERTEX_SHADER?"vertex":"fragment",a.getShaderInfoLog(d),mf(c));return d}function te(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 Bd(a,b){var c=te(b);return"vec4 "+a+"( vec4 value ) { return "+
11893 c[0]+"ToLinear"+c[1]+"; }"}function nf(a,b){var c=te(b);return"vec4 "+a+"( vec4 value ) { return LinearTo"+c[0]+c[1]+"; }"}function of(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 pf(a,b,c){a=a||{};return[a.derivatives||b.envMapCubeUV||b.bumpMap||b.normalMap||b.flatShading?"#extension GL_OES_standard_derivatives : enable":
11894 "",(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(oc).join("\n")}function qf(a){var b=[],c;for(c in a){var d=a[c];!1!==d&&b.push("#define "+c+" "+d)}return b.join("\n")}function oc(a){return""!==a}function ue(a,b){return a.replace(/NUM_DIR_LIGHTS/g,
11895 b.numDirLights).replace(/NUM_SPOT_LIGHTS/g,b.numSpotLights).replace(/NUM_POINT_LIGHTS/g,b.numPointLights).replace(/NUM_HEMI_LIGHTS/g,b.numHemiLights)}function Cd(a){return a.replace(/#include +<([\w\d.]+)>/g,function(a,c){var d=X[c];if(void 0===d)throw Error("Can not resolve #include <"+c+">");return Cd(d)})}function ve(a){return a.replace(/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,function(a,c,d,e){a="";for(c=parseInt(c);c<parseInt(d);c++)a+=e.replace(/\[ i \]/g,"[ "+c+
11896 " ]");return a})}function rf(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 w="ENVMAP_TYPE_CUBE",n="ENVMAP_MODE_REFLECTION",p="ENVMAP_BLENDING_MULTIPLY";if(d.envMap){switch(c.envMap.mapping){case 301:case 302:w="ENVMAP_TYPE_CUBE";break;case 306:case 307:w="ENVMAP_TYPE_CUBE_UV";break;case 303:case 304:w="ENVMAP_TYPE_EQUIREC";
11897 break;case 305:w="ENVMAP_TYPE_SPHERE"}switch(c.envMap.mapping){case 302:case 304:n="ENVMAP_MODE_REFRACTION"}switch(c.combine){case 0:p="ENVMAP_BLENDING_MULTIPLY";break;case 1:p="ENVMAP_BLENDING_MIX";break;case 2:p="ENVMAP_BLENDING_ADD"}}var r=0<a.gammaFactor?a.gammaFactor:1,f=pf(f,d,a.extensions),l=qf(g),t=e.createProgram();c.isRawShaderMaterial?(g=[l,"\n"].filter(oc).join("\n"),m=[f,l,"\n"].filter(oc).join("\n")):(g=["precision "+d.precision+" float;","precision "+d.precision+" int;","#define SHADER_NAME "+
11898 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 "+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.displacementMap&&d.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",d.specularMap?"#define USE_SPECULARMAP":
11899 "",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":"",d.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+
11900 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;","uniform vec3 cameraPosition;","attribute vec3 position;",
11901 "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;","\t\tattribute vec3 morphTarget5;",
11902 "\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(oc).join("\n"),m=[f,"precision "+d.precision+" float;","precision "+d.precision+" int;","#define SHADER_NAME "+c.__webglShader.name,l,d.alphaTest?"#define ALPHATEST "+d.alphaTest:"","#define GAMMA_FACTOR "+r,d.useFog&&d.fog?"#define USE_FOG":"",d.useFog&&d.fogExp?"#define FOG_EXP2":"",d.map?"#define USE_MAP":
11903 "",d.envMap?"#define USE_ENVMAP":"",d.envMap?"#define "+w:"",d.envMap?"#define "+n:"",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.specularMap?"#define USE_SPECULARMAP":"",d.roughnessMap?"#define USE_ROUGHNESSMAP":"",d.metalnessMap?"#define USE_METALNESSMAP":"",d.alphaMap?"#define USE_ALPHAMAP":"",d.vertexColors?"#define USE_COLOR":
11904 "",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":"",d.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",d.logarithmicDepthBuffer&&
11905 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?X.tonemapping_pars_fragment:"",0!==d.toneMapping?of("toneMapping",d.toneMapping):"",d.outputEncoding||d.mapEncoding||d.envMapEncoding||d.emissiveMapEncoding?X.encodings_pars_fragment:"",d.mapEncoding?Bd("mapTexelToLinear",d.mapEncoding):
11906 "",d.envMapEncoding?Bd("envMapTexelToLinear",d.envMapEncoding):"",d.emissiveMapEncoding?Bd("emissiveMapTexelToLinear",d.emissiveMapEncoding):"",d.outputEncoding?nf("linearToOutputTexel",d.outputEncoding):"",d.depthPacking?"#define DEPTH_PACKING "+c.depthPacking:"","\n"].filter(oc).join("\n"));h=Cd(h,d);h=ue(h,d);k=Cd(k,d);k=ue(k,d);c.isShaderMaterial||(h=ve(h),k=ve(k));k=m+k;h=se(e,e.VERTEX_SHADER,g+h);k=se(e,e.FRAGMENT_SHADER,k);e.attachShader(t,h);e.attachShader(t,k);void 0!==c.index0AttributeName?
11907 e.bindAttribLocation(t,0,c.index0AttributeName):!0===d.morphTargets&&e.bindAttribLocation(t,0,"position");e.linkProgram(t);d=e.getProgramInfoLog(t);w=e.getShaderInfoLog(h);n=e.getShaderInfoLog(k);r=p=!0;if(!1===e.getProgramParameter(t,e.LINK_STATUS))p=!1,console.error("THREE.WebGLProgram: shader error: ",e.getError(),"gl.VALIDATE_STATUS",e.getProgramParameter(t,e.VALIDATE_STATUS),"gl.getProgramInfoLog",d,w,n);else if(""!==d)console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",d);else if(""===
11908 w||""===n)r=!1;r&&(this.diagnostics={runnable:p,material:c,programLog:d,vertexShader:{log:w,prefix:g},fragmentShader:{log:n,prefix:m}});e.deleteShader(h);e.deleteShader(k);var q;this.getUniforms=function(){void 0===q&&(q=new Ya(e,t,a));return q};var u;this.getAttributes=function(){if(void 0===u){for(var a={},b=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES),c=0;c<b;c++){var d=e.getActiveAttrib(t,c).name;a[d]=e.getAttribLocation(t,d)}u=a}return u};this.destroy=function(){e.deleteProgram(t);this.program=
11909 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=sf++;this.code=b;this.usedTimes=1;this.program=t;this.vertexShader=h;this.fragmentShader=k;return this}function tf(a,b){function c(a,b){var c;a?a&&a.isTexture?c=a.encoding:a&&a.isWebGLRenderTarget&&(console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead."),
11910 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",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points"},f="precision supportsVertexTextures map mapEncoding envMap envMapMode envMapEncoding lightMap aoMap emissiveMap emissiveMapEncoding bumpMap normalMap displacementMap specularMap roughnessMap metalnessMap alphaMap combine vertexColors fog useFog fogExp flatShading sizeAttenuation logarithmicDepthBuffer skinning maxBones useVertexTexture morphTargets morphNormals maxMorphTargets maxMorphNormals premultipliedAlpha numDirLights numPointLights numSpotLights numHemiLights shadowMapEnabled shadowMapType toneMapping physicallyCorrectLights alphaTest doubleSided flipSided numClippingPlanes numClipIntersection depthPacking".split(" ");
11911 this.getParameters=function(d,f,k,m,w,n){var p=e[d.type],r;b.floatVertexTextures&&n&&n.skeleton&&n.skeleton.useVertexTexture?r=1024:(r=Math.floor((b.maxVertexUniforms-20)/4),void 0!==n&&n&&n.isSkinnedMesh&&(r=Math.min(n.skeleton.bones.length,r),r<n.skeleton.bones.length&&console.warn("WebGLRenderer: too many bones - "+n.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&&
11912 console.warn("THREE.WebGLProgram.getParameters:",d.precision,"not supported, using",l,"instead."));var t=a.getCurrentRenderTarget();return{shaderID:p,precision:l,supportsVertexTextures:b.vertexTextures,outputEncoding:c(t?t.texture:null,a.gammaOutput),map:!!d.map,mapEncoding:c(d.map,a.gammaInput),envMap:!!d.envMap,envMapMode:d.envMap&&d.envMap.mapping,envMapEncoding:c(d.envMap,a.gammaInput),envMapCubeUV:!!d.envMap&&(306===d.envMap.mapping||307===d.envMap.mapping),lightMap:!!d.lightMap,aoMap:!!d.aoMap,
11913 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,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,maxBones:r,useVertexTexture:b.floatVertexTextures&&
11914 n&&n.skeleton&&n.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,numHemiLights:f.hemi.length,numClippingPlanes:m,numClipIntersection:w,shadowMapEnabled:a.shadowMap.enabled&&n.receiveShadow&&0<f.shadows.length,shadowMapType:a.shadowMap.type,toneMapping:a.toneMapping,physicallyCorrectLights:a.physicallyCorrectLights,
11915 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=function(b,c,e){for(var f,w=0,n=d.length;w<n;w++){var p=d[w];if(p.code===
11916 e){f=p;++f.usedTimes;break}}void 0===f&&(f=new rf(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 uf(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);h=b.get(a);h.wireframe&&e(h.wireframe);b["delete"](a);c.memory.geometries--}
11917 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 G).setFromObject(a)),e=b._bufferGeometry);f[b.id]=e;c.memory.geometries++;return e}}}function vf(a,
11918 b,c){function d(c,d){var e=c.isInterleavedBufferAttribute?c.data:c,k=b.get(e);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),k.version=e.version):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."):
11919 (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 uf(a,b,c);return{getAttributeBuffer:function(a){return a.isInterleavedBufferAttribute?b.get(a.data).__webglBuffer:b.get(a).__webglBuffer},getWireframeAttribute:function(c){var e=b.get(c);if(void 0!==e.wireframe)return e.wireframe;var h=[],k=c.index,m=c.attributes;c=m.position;if(null!==k)for(var k=k.array,
11920 m=0,w=k.length;m<w;m+=3){var n=k[m+0],p=k[m+1],r=k[m+2];h.push(n,p,p,r,r,n)}else for(k=m.position.array,m=0,w=k.length/3-1;m<w;m+=3)n=m+0,p=m+1,r=m+2,h.push(n,p,p,r,r,n);h=new C(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);for(var k in h)d(h[k],a.ARRAY_BUFFER);b=c.morphAttributes;for(k in b)for(var h=
11921 b[k],m=0,w=h.length;m<w;m++)d(h[m],a.ARRAY_BUFFER);return c}}}function wf(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 ("+a.width+"x"+a.height+"). Resized to "+d.width+"x"+d.height,a);return d}return a}
11922 function k(a){return T.isPowerOfTwo(a.width)&&T.isPowerOfTwo(a.height)}function m(b){return 1003===b||1004===b||1005===b?a.NEAREST:a.LINEAR}function w(b){b=b.target;b.removeEventListener("dispose",w);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 n(b){b=b.target;b.removeEventListener("dispose",n);var c=d.get(b),e=d.get(b.texture);if(b){void 0!==
11923 e.__webglTexture&&a.deleteTexture(e.__webglTexture);b.depthTexture&&b.depthTexture.dispose();if(b&&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 p(b,g){var m=d.get(b);if(0<b.version&&m.__version!==b.version){var p=b.image;
11924 if(void 0===p)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",b);else if(!1===p.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",w),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,b.flipY);a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,
11925 b.premultiplyAlpha);a.pixelStorei(a.UNPACK_ALIGNMENT,b.unpackAlignment);var n=h(b.image,e.maxTextureSize);if((1001!==b.wrapS||1001!==b.wrapT||1003!==b.minFilter&&1006!==b.minFilter)&&!1===k(n))if(p=n,p instanceof HTMLImageElement||p instanceof HTMLCanvasElement){var l=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");l.width=T.nearestPowerOfTwo(p.width);l.height=T.nearestPowerOfTwo(p.height);l.getContext("2d").drawImage(p,0,0,l.width,l.height);console.warn("THREE.WebGLRenderer: image is not power of two ("+
11926 p.width+"x"+p.height+"). Resized to "+l.width+"x"+l.height,p);n=l}else n=p;var p=k(n),l=f(b.format),x=f(b.type);r(a.TEXTURE_2D,b,p);var t=b.mipmaps;if(b&&b.isDepthTexture){t=a.DEPTH_COMPONENT;if(1015===b.type){if(!u)throw Error("Float Depth Texture only supported in WebGL2.0");t=a.DEPTH_COMPONENT32F}else u&&(t=a.DEPTH_COMPONENT16);1027===b.format&&(t=a.DEPTH_STENCIL);c.texImage2D(a.TEXTURE_2D,0,t,n.width,n.height,0,l,x,null)}else if(b&&b.isDataTexture)if(0<t.length&&p){for(var K=0,ja=t.length;K<ja;K++)n=
11927 t[K],c.texImage2D(a.TEXTURE_2D,K,l,n.width,n.height,0,l,x,n.data);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,l,n.width,n.height,0,l,x,n.data);else if(b&&b.isCompressedTexture)for(K=0,ja=t.length;K<ja;K++)n=t[K],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(l)?c.compressedTexImage2D(a.TEXTURE_2D,K,l,n.width,n.height,0,n.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):c.texImage2D(a.TEXTURE_2D,
11928 K,l,n.width,n.height,0,l,x,n.data);else if(0<t.length&&p){K=0;for(ja=t.length;K<ja;K++)n=t[K],c.texImage2D(a.TEXTURE_2D,K,l,l,x,n);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,l,l,x,n);b.generateMipmaps&&p&&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,
11929 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,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&&
11930 1006!==g.minFilter&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.",g));!(h=b.get("EXT_texture_filter_anisotropic"))||1015===g.type&&null===b.get("OES_texture_float_linear")||1016===g.type&&null===b.get("OES_texture_half_float_linear")||!(1<g.anisotropy||d.get(g).__currentAnisotropy)||(a.texParameterf(c,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(g.anisotropy,e.getMaxAnisotropy())),d.get(g).__currentAnisotropy=
11931 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,0);a.bindFramebuffer(a.FRAMEBUFFER,null)}function t(b,c){a.bindRenderbuffer(a.RENDERBUFFER,b);c.depthBuffer&&!c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_COMPONENT16,c.width,c.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,
11932 b)):c.depthBuffer&&c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_STENCIL,c.width,c.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,b)):a.renderbufferStorage(a.RENDERBUFFER,a.RGBA4,c.width,c.height);a.bindRenderbuffer(a.RENDERBUFFER,null)}var q=g.memory,u="undefined"!==typeof WebGL2RenderingContext&&a instanceof WebGL2RenderingContext;this.setTexture2D=p;this.setTextureCube=function(b,g){var m=d.get(b);if(6===b.image.length)if(0<b.version&&
11933 m.__version!==b.version){m.__image__webglTextureCube||(b.addEventListener("dispose",w),m.__image__webglTextureCube=a.createTexture(),q.textures++);c.activeTexture(a.TEXTURE0+g);c.bindTexture(a.TEXTURE_CUBE_MAP,m.__image__webglTextureCube);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);for(var p=b&&b.isCompressedTexture,n=b.image[0]&&b.image[0].isDataTexture,l=[],x=0;6>x;x++)l[x]=p||n?n?b.image[x].image:b.image[x]:h(b.image[x],e.maxCubemapSize);var t=k(l[0]),u=f(b.format),ja=f(b.type);r(a.TEXTURE_CUBE_MAP,
11934 b,t);for(x=0;6>x;x++)if(p)for(var B,C=l[x].mipmaps,z=0,N=C.length;z<N;z++)B=C[z],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(u)?c.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+x,z,u,B.width,B.height,0,B.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+x,z,u,B.width,B.height,0,u,ja,B.data);else n?c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+x,0,u,l[x].width,
11935 l[x].height,0,u,ja,l[x].data):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+x,0,u,u,ja,l[x]);b.generateMipmaps&&t&&a.generateMipmap(a.TEXTURE_CUBE_MAP);m.__version=b.version;if(b.onUpdate)b.onUpdate(b)}else c.activeTexture(a.TEXTURE0+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",
11936 n);f.__webglTexture=a.createTexture();q.textures++;var g=b&&b.isWebGLRenderTargetCube,h=k(b);if(g){e.__webglFramebuffer=[];for(var m=0;6>m;m++)e.__webglFramebuffer[m]=a.createFramebuffer()}else e.__webglFramebuffer=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,
11937 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),c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=b&&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,
11938 e.__webglFramebuffer);if(!b.depthTexture||!b.depthTexture.isDepthTexture)throw Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");d.get(b.depthTexture).__webglTexture&&b.depthTexture.image.width===b.width&&b.depthTexture.image.height===b.height||(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0);p(b.depthTexture,0);e=d.get(b.depthTexture).__webglTexture;if(1026===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,
11939 a.DEPTH_ATTACHMENT,a.TEXTURE_2D,e,0);else if(1027===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.TEXTURE_2D,e,0);else throw Error("Unknown depthTexture format");}else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),t(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),t(e.__webglDepthbuffer,
11940 b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap=function(b){var e=b.texture;e.generateMipmaps&&k(b)&&1003!==e.minFilter&&1006!==e.minFilter&&(b=b&&b.isWebGLRenderTargetCube?a.TEXTURE_CUBE_MAP:a.TEXTURE_2D,e=d.get(e).__webglTexture,c.bindTexture(b,e),a.generateMipmap(b),c.bindTexture(b,null))}}function xf(){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 yf(a,b,c){function d(b,
11941 c,d){var e=new Uint8Array(4),f=a.createTexture();a.bindTexture(b,f);a.texParameteri(b,a.TEXTURE_MIN_FILTER,a.NEAREST);a.texParameteri(b,a.TEXTURE_MAG_FILTER,a.NEAREST);for(b=0;b<d;b++)a.texImage2D(c+b,0,a.RGBA,1,1,0,a.RGBA,a.UNSIGNED_BYTE,e);return f}function e(b){!0!==E[b]&&(a.enable(b),E[b]=!0)}function f(b){!1!==E[b]&&(a.disable(b),E[b]=!1)}function g(b,d,g,h,k,m,p,n){0!==b?e(a.BLEND):f(a.BLEND);if(b!==F||n!==G)2===b?n?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,a.ONE,
11942 a.ONE,a.ONE)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.SRC_ALPHA,a.ONE)):3===b?n?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.ZERO,a.ONE_MINUS_SRC_COLOR,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.ONE_MINUS_SRC_COLOR)):4===b?n?(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)):n?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),
11943 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)),F=b,G=n;if(5===b){k=k||d;m=m||g;p=p||h;if(d!==M||k!==B)a.blendEquationSeparate(c(d),c(k)),M=d,B=k;if(g!==ca||h!==K||m!==C||p!==z)a.blendFuncSeparate(c(g),c(h),c(m),c(p)),ca=g,K=h,C=m,z=p}else z=C=B=K=ca=M=null}function h(a){t.setFunc(a)}function k(b){N!==b&&(b?a.frontFace(a.CW):a.frontFace(a.CCW),
11944 N=b)}function m(b){0!==b?(e(a.CULL_FACE),b!==P&&(1===b?a.cullFace(a.BACK):2===b?a.cullFace(a.FRONT):a.cullFace(a.FRONT_AND_BACK))):f(a.CULL_FACE);P=b}function w(b){void 0===b&&(b=a.TEXTURE0+O-1);L!==b&&(a.activeTexture(b),L=b)}function n(a,b,c,d){l.setClear(a,b,c,d)}function p(a){t.setClear(a)}function r(a){q.setClear(a)}var l=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){c.set(b,
11945 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)}}},t=new function(){var b=!1,c=null,d=null,g=null;return{setTest:function(b){b?e(a.DEPTH_TEST):f(a.DEPTH_TEST)},setMask:function(d){c===d||b||(a.depthMask(d),c=d)},setFunc:function(b){if(d!==b){if(b)switch(b){case 0:a.depthFunc(a.NEVER);break;case 1:a.depthFunc(a.ALWAYS);break;case 2:a.depthFunc(a.LESS);break;case 3:a.depthFunc(a.LEQUAL);break;case 4:a.depthFunc(a.EQUAL);break;case 5:a.depthFunc(a.GEQUAL);
11946 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}}},q=new function(){var b=!1,c=null,d=null,g=null,h=null,k=null,m=null,p=null,n=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!==
11947 e)a.stencilFunc(b,c,e),d=b,g=c,h=e},setOp:function(b,c,d){if(k!==b||m!==c||p!==d)a.stencilOp(b,c,d),k=b,m=c,p=d},setLocked:function(a){b=a},setClear:function(b){n!==b&&(a.clearStencil(b),n=b)},reset:function(){b=!1;n=p=m=k=h=g=d=c=null}}},u=a.getParameter(a.MAX_VERTEX_ATTRIBS),v=new Uint8Array(u),I=new Uint8Array(u),y=new Uint8Array(u),E={},H=null,F=null,M=null,ca=null,K=null,B=null,C=null,z=null,G=!1,N=null,P=null,R=null,S=null,J=null,V=null,O=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS),L=null,Q={},
11948 T=new ga,U=new ga,fb={};fb[a.TEXTURE_2D]=d(a.TEXTURE_2D,a.TEXTURE_2D,1);fb[a.TEXTURE_CUBE_MAP]=d(a.TEXTURE_CUBE_MAP,a.TEXTURE_CUBE_MAP_POSITIVE_X,6);return{buffers:{color:l,depth:t,stencil:q},init:function(){n(0,0,0,1);p(1);r(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=v.length;a<b;a++)v[a]=0},enableAttribute:function(c){v[c]=1;0===I[c]&&(a.enableVertexAttribArray(c),I[c]=1);0!==y[c]&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,
11949 0),y[c]=0)},enableAttributeAndDivisor:function(b,c,d){v[b]=1;0===I[b]&&(a.enableVertexAttribArray(b),I[b]=1);y[b]!==c&&(d.vertexAttribDivisorANGLE(b,c),y[b]=c)},disableUnusedAttributes:function(){for(var b=0,c=I.length;b!==c;++b)I[b]!==v[b]&&(a.disableVertexAttribArray(b),I[b]=0)},enable:e,disable:f,getCompressedTextureFormats:function(){if(null===H&&(H=[],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),
11950 d=0;d<c.length;d++)H.push(c[d]);return H},setBlending:g,setColorWrite:function(a){l.setMask(a)},setDepthTest:function(a){t.setTest(a)},setDepthWrite:function(a){t.setMask(a)},setDepthFunc:h,setStencilTest:function(a){q.setTest(a)},setStencilWrite:function(a){q.setMask(a)},setStencilFunc:function(a,b,c){q.setFunc(a,b,c)},setStencilOp:function(a,b,c){q.setOp(a,b,c)},setFlipSided:k,setCullFace:m,setLineWidth:function(b){b!==R&&(a.lineWidth(b),R=b)},setPolygonOffset:function(b,c,d){if(b){if(e(a.POLYGON_OFFSET_FILL),
11951 S!==c||J!==d)a.polygonOffset(c,d),S=c,J=d}else f(a.POLYGON_OFFSET_FILL)},getScissorTest:function(){return V},setScissorTest:function(b){(V=b)?e(a.SCISSOR_TEST):f(a.SCISSOR_TEST)},activeTexture:w,bindTexture:function(b,c){null===L&&w();var d=Q[L];void 0===d&&(d={type:void 0,texture:void 0},Q[L]=d);if(d.type!==b||d.texture!==c)a.bindTexture(b,c||fb[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,
11952 arguments)}catch(b){console.error(b)}},clearColor:n,clearDepth:p,clearStencil:r,scissor:function(b){!1===T.equals(b)&&(a.scissor(b.x,b.y,b.z,b.w),T.copy(b))},viewport:function(b){!1===U.equals(b)&&(a.viewport(b.x,b.y,b.z,b.w),U.copy(b))},reset:function(){for(var b=0;b<I.length;b++)1===I[b]&&(a.disableVertexAttribArray(b),I[b]=0);E={};L=H=null;Q={};P=N=F=null;l.reset();t.reset();q.reset()}}}function zf(a,b,c){function d(b){if("highp"===b){if(0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.HIGH_FLOAT).precision&&
11953 0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.HIGH_FLOAT).precision)return"highp";b="mediump"}return"mediump"===b&&0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.MEDIUM_FLOAT).precision&&0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,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),
11954 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),w=a.getParameter(a.MAX_VERTEX_ATTRIBS),n=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS),p=a.getParameter(a.MAX_VARYING_VECTORS),r=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS),l=0<h,t=!!b.get("OES_texture_float");return{getMaxAnisotropy:function(){if(void 0!==e)return e;var c=b.get("EXT_texture_filter_anisotropic");return e=null!==c?a.getParameter(c.MAX_TEXTURE_MAX_ANISOTROPY_EXT):
11955 0},getMaxPrecision:d,precision:f,logarithmicDepthBuffer:c,maxTextures:g,maxVertexTextures:h,maxTextureSize:k,maxCubemapSize:m,maxAttributes:w,maxVertexUniforms:n,maxVaryings:p,maxFragmentUniforms:r,vertexTextures:l,floatFragmentTextures:t,floatVertexTextures:l&&t}}function Af(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");
11956 break;case "EXT_texture_filter_anisotropic":d=a.getExtension("EXT_texture_filter_anisotropic")||a.getExtension("MOZ_EXT_texture_filter_anisotropic")||a.getExtension("WEBKIT_EXT_texture_filter_anisotropic");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")||
11957 a.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case "WEBGL_compressed_texture_etc1":d=a.getExtension("WEBGL_compressed_texture_etc1");break;default:d=a.getExtension(c)}null===d&&console.warn("THREE.WebGLRenderer: "+c+" extension not supported.");return b[c]=d}}}function Bf(){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;
11958 k.getNormalMatrix(b);if(null===g||g.length<e)g=new Float32Array(e);for(e=0;e!==f;++e,d+=4)h.copy(a[e]).applyMatrix4(b,k),h.normal.toArray(g,d),g[d+3]=h.constant}m.value=g;m.needsUpdate=!0}c.numPlanes=f;return g}var c=this,d=null,e=0,f=!1,g=!1,h=new va,k=new Ia,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=
11959 !1;a()};this.setState=function(c,h,k,r,l,t){if(!f||null===c||0===c.length||g&&!k)g?b(null):a();else{k=g?0:e;var q=4*k,u=l.clippingState||null;m.value=u;u=b(c,r,q,t);for(c=0;c!==q;++c)u[c]=d[c];l.clippingState=u;this.numIntersection=h?this.numPlanes:0;this.numPlanes+=k}}}function Dd(a){function b(a,b,c,d){!0===M&&(a*=d,b*=d,c*=d);Y.clearColor(a,b,c,d)}function c(){Y.init();Y.scissor(X.copy(ha).multiplyScalar(Qa));Y.viewport($a.copy(fa).multiplyScalar(Qa));b(Da.r,Da.g,Da.b,Ra)}function d(){W=Q=null;
11960 U="";L=-1;Y.reset()}function e(a){a.preventDefault();d();c();ea.clear()}function f(a){a=a.target;a.removeEventListener("dispose",f);g(a);ea["delete"](a)}function g(a){var b=ea.get(a).program;a.program=void 0;void 0!==b&&va.releaseProgram(b)}function h(a,b){return Math.abs(b[0])-Math.abs(a[0])}function k(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-
11961 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 m(a,b){return a.object.renderOrder!==b.object.renderOrder?a.object.renderOrder-b.object.renderOrder:a.z!==b.z?b.z-a.z:a.id-b.id}function w(a,b,c,d,e){var f;c.transparent?(d=z,f=++Ka):(d=B,f=++C);f=d[f];void 0!==f?(f.id=a.id,f.object=a,f.geometry=b,f.material=c,f.z=Z.z,f.group=e):(f={id:a.id,object:a,geometry:b,material:c,z:Z.z,group:e},d.push(f))}function n(a){if(!oa.intersectsSphere(a))return!1;
11962 var b=ba.numPlanes;if(0===b)return!0;var c=S.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!==a.visible){if(0!==(a.layers.mask&b.layers.mask))if(a.isLight)K.push(a);else if(a.isSprite){var c;(c=!1===a.frustumCulled)||(na.center.set(0,0,0),na.radius=.7071067811865476,na.applyMatrix4(a.matrixWorld),c=!0===n(na));c&&P.push(a)}else if(a.isLensFlare)R.push(a);else if(a.isImmediateRenderObject)!0===S.sortObjects&&(Z.setFromMatrixPosition(a.matrixWorld),
11963 Z.applyProjection(ra)),w(a,null,a.material,Z.z,null);else if(a.isMesh||a.isLine||a.isPoints)if(a.isSkinnedMesh&&a.skeleton.update(),(c=!1===a.frustumCulled)||(c=a.geometry,null===c.boundingSphere&&c.computeBoundingSphere(),na.copy(c.boundingSphere).applyMatrix4(a.matrixWorld),c=!0===n(na)),c){var d=a.material;if(!0===d.visible)if(!0===S.sortObjects&&(Z.setFromMatrixPosition(a.matrixWorld),Z.applyProjection(ra)),c=qa.update(a),d.isMultiMaterial)for(var e=c.groups,f=d.materials,d=0,g=e.length;d<g;d++){var h=
11964 e[d],k=f[h.materialIndex];!0===k.visible&&w(a,c,k,Z.z,h)}else w(a,c,d,Z.z,null)}c=a.children;d=0;for(g=c.length;d<g;d++)p(c[d],b)}}function r(a,b,c,d){for(var e=0,f=a.length;e<f;e++){var g=a[e],h=g.object,k=g.geometry,m=void 0===d?g.material:d,g=g.group;h.modelViewMatrix.multiplyMatrices(c.matrixWorldInverse,h.matrixWorld);h.normalMatrix.getNormalMatrix(h.modelViewMatrix);h.onBeforeRender(S,b,c,k,m,g);if(h.isImmediateRenderObject){l(m);var p=t(c,b.fog,m,h);U="";h.render(function(a){S.renderBufferImmediate(a,
11965 p,m)})}else S.renderBufferDirect(c,b.fog,k,m,h,g);h.onAfterRender(S,b,c,k,m,g)}}function l(a){2===a.side?Y.disable(A.CULL_FACE):Y.enable(A.CULL_FACE);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,
11966 a.polygonOffsetFactor,a.polygonOffsetUnits)}function t(a,b,c,d){da=0;var e=ea.get(c);pa&&(sa||a!==W)&&ba.setState(c.clippingPlanes,c.clipIntersection,c.clipShadows,a,e,a===W&&c.id===L);!1===c.needsUpdate&&(void 0===e.program?c.needsUpdate=!0:c.fog&&e.fog!==b?c.needsUpdate=!0:c.lights&&e.lightsHash!==aa.hash?c.needsUpdate=!0:void 0===e.numClippingPlanes||e.numClippingPlanes===ba.numPlanes&&e.numIntersection===ba.numIntersection||(c.needsUpdate=!0));if(c.needsUpdate){a:{var h=ea.get(c),k=va.getParameters(c,
11967 aa,b,ba.numPlanes,ba.numIntersection,d),m=va.getProgramCode(c,k),p=h.program,n=!0;if(void 0===p)c.addEventListener("dispose",f);else if(p.code!==m)g(c);else if(void 0!==k.shaderID)break a;else n=!1;n&&(k.shaderID?(p=Gb[k.shaderID],h.__webglShader={name:c.type,uniforms:La.clone(p.uniforms),vertexShader:p.vertexShader,fragmentShader:p.fragmentShader}):h.__webglShader={name:c.type,uniforms:c.uniforms,vertexShader:c.vertexShader,fragmentShader:c.fragmentShader},c.__webglShader=h.__webglShader,p=va.acquireProgram(c,
11968 k,m),h.program=p,c.program=p);k=p.getAttributes();if(c.morphTargets)for(m=c.numSupportedMorphTargets=0;m<S.maxMorphTargets;m++)0<=k["morphTarget"+m]&&c.numSupportedMorphTargets++;if(c.morphNormals)for(m=c.numSupportedMorphNormals=0;m<S.maxMorphNormals;m++)0<=k["morphNormal"+m]&&c.numSupportedMorphNormals++;k=h.__webglShader.uniforms;if(!c.isShaderMaterial&&!c.isRawShaderMaterial||!0===c.clipping)h.numClippingPlanes=ba.numPlanes,h.numIntersection=ba.numIntersection,k.clippingPlanes=ba.uniform;h.fog=
11969 b;h.lightsHash=aa.hash;c.lights&&(k.ambientLightColor.value=aa.ambient,k.directionalLights.value=aa.directional,k.spotLights.value=aa.spot,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();
11970 k=Ya.seqWithValue(m.seq,k);h.uniformsList=k}c.needsUpdate=!1}var w=!1,n=p=!1,h=e.program,k=h.getUniforms(),m=e.__webglShader.uniforms;h.id!==Q&&(A.useProgram(h.program),Q=h.id,n=p=w=!0);c.id!==L&&(L=c.id,p=!0);if(w||a!==W){k.set(A,a,"projectionMatrix");ia.logarithmicDepthBuffer&&k.setValue(A,"logDepthBufFC",2/(Math.log(a.far+1)/Math.LN2));a!==W&&(W=a,n=p=!0);if(c.isShaderMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.envMap)w=k.map.cameraPosition,void 0!==w&&w.setValue(A,Z.setFromMatrixPosition(a.matrixWorld));
11971 (c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial||c.isMeshStandardMaterial||c.isShaderMaterial||c.skinning)&&k.setValue(A,"viewMatrix",a.matrixWorldInverse);k.set(A,S,"toneMappingExposure");k.set(A,S,"toneMappingWhitePoint")}c.skinning&&(k.setOptional(A,d,"bindMatrix"),k.setOptional(A,d,"bindMatrixInverse"),a=d.skeleton)&&(ia.floatVertexTextures&&a.useVertexTexture?(k.set(A,a,"boneTexture"),k.set(A,a,"boneTextureWidth"),k.set(A,a,"boneTextureHeight")):k.setOptional(A,a,"boneMatrices"));
11972 if(p){c.lights&&(a=n,m.ambientLightColor.needsUpdate=a,m.directionalLights.needsUpdate=a,m.pointLights.needsUpdate=a,m.spotLights.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.isMeshDepthMaterial){m.opacity.value=c.opacity;m.diffuse.value=c.color;c.emissive&&m.emissive.value.copy(c.emissive).multiplyScalar(c.emissiveIntensity);
11973 m.map.value=c.map;m.specularMap.value=c.specularMap;m.alphaMap.value=c.alphaMap;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!==r&&(r.isWebGLRenderTarget&&(r=r.texture),b=r.offset,r=r.repeat,m.offsetRepeat.value.set(b.x,
11974 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):c.isPointsMaterial?(m.diffuse.value=c.color,m.opacity.value=c.opacity,m.size.value=c.size*
11975 Qa,m.scale.value=.5*pc,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.lightMap&&(m.lightMap.value=c.lightMap,m.lightMapIntensity.value=c.lightMapIntensity),c.emissiveMap&&(m.emissiveMap.value=c.emissiveMap)):c.isMeshPhongMaterial?(m.specular.value=c.specular,m.shininess.value=Math.max(c.shininess,1E-4),c.lightMap&&(m.lightMap.value=c.lightMap,m.lightMapIntensity.value=c.lightMapIntensity),c.emissiveMap&&(m.emissiveMap.value=
11976 c.emissiveMap),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,m.displacementBias.value=c.displacementBias)):c.isMeshPhysicalMaterial?(m.clearCoat.value=c.clearCoat,m.clearCoatRoughness.value=c.clearCoatRoughness,D(m,c)):c.isMeshStandardMaterial?D(m,c):c.isMeshDepthMaterial?c.displacementMap&&
11977 (m.displacementMap.value=c.displacementMap,m.displacementScale.value=c.displacementScale,m.displacementBias.value=c.displacementBias):c.isMeshNormalMaterial&&(m.opacity.value=c.opacity);Ya.upload(A,e.uniformsList,m,S)}k.set(A,d,"modelViewMatrix");k.set(A,d,"normalMatrix");k.setValue(A,"modelMatrix",d.matrixWorld);return h}function D(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);
11978 b.lightMap&&(a.lightMap.value=b.lightMap,a.lightMapIntensity.value=b.lightMapIntensity);b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap);b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale);b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale));b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias);b.envMap&&(a.envMapIntensity.value=b.envMapIntensity)}function u(a){var b;
11979 if(1E3===a)return A.REPEAT;if(1001===a)return A.CLAMP_TO_EDGE;if(1002===a)return A.MIRRORED_REPEAT;if(1003===a)return A.NEAREST;if(1004===a)return A.NEAREST_MIPMAP_NEAREST;if(1005===a)return A.NEAREST_MIPMAP_LINEAR;if(1006===a)return A.LINEAR;if(1007===a)return A.LINEAR_MIPMAP_NEAREST;if(1008===a)return A.LINEAR_MIPMAP_LINEAR;if(1009===a)return A.UNSIGNED_BYTE;if(1017===a)return A.UNSIGNED_SHORT_4_4_4_4;if(1018===a)return A.UNSIGNED_SHORT_5_5_5_1;if(1019===a)return A.UNSIGNED_SHORT_5_6_5;if(1010===
11980 a)return A.BYTE;if(1011===a)return A.SHORT;if(1012===a)return A.UNSIGNED_SHORT;if(1013===a)return A.INT;if(1014===a)return A.UNSIGNED_INT;if(1015===a)return A.FLOAT;if(1016===a&&(b=ka.get("OES_texture_half_float"),null!==b))return b.HALF_FLOAT_OES;if(1021===a)return A.ALPHA;if(1022===a)return A.RGB;if(1023===a)return A.RGBA;if(1024===a)return A.LUMINANCE;if(1025===a)return A.LUMINANCE_ALPHA;if(1026===a)return A.DEPTH_COMPONENT;if(1027===a)return A.DEPTH_STENCIL;if(100===a)return A.FUNC_ADD;if(101===
11981 a)return A.FUNC_SUBTRACT;if(102===a)return A.FUNC_REVERSE_SUBTRACT;if(200===a)return A.ZERO;if(201===a)return A.ONE;if(202===a)return A.SRC_COLOR;if(203===a)return A.ONE_MINUS_SRC_COLOR;if(204===a)return A.SRC_ALPHA;if(205===a)return A.ONE_MINUS_SRC_ALPHA;if(206===a)return A.DST_ALPHA;if(207===a)return A.ONE_MINUS_DST_ALPHA;if(208===a)return A.DST_COLOR;if(209===a)return A.ONE_MINUS_DST_COLOR;if(210===a)return A.SRC_ALPHA_SATURATE;if(2001===a||2002===a||2003===a||2004===a)if(b=ka.get("WEBGL_compressed_texture_s3tc"),
11982 null!==b){if(2001===a)return b.COMPRESSED_RGB_S3TC_DXT1_EXT;if(2002===a)return b.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(2003===a)return b.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(2004===a)return b.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(2100===a||2101===a||2102===a||2103===a)if(b=ka.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===
11983 a&&(b=ka.get("WEBGL_compressed_texture_etc1"),null!==b))return b.COMPRESSED_RGB_ETC1_WEBGL;if(103===a||104===a)if(b=ka.get("EXT_blend_minmax"),null!==b){if(103===a)return b.MIN_EXT;if(104===a)return b.MAX_EXT}return 1020===a&&(b=ka.get("WEBGL_depth_texture"),null!==b)?b.UNSIGNED_INT_24_8_WEBGL:0}console.log("THREE.WebGLRenderer","82");a=a||{};var v=void 0!==a.canvas?a.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),I=void 0!==a.context?a.context:null,y=void 0!==a.alpha?a.alpha:
11984 !1,E=void 0!==a.depth?a.depth:!0,H=void 0!==a.stencil?a.stencil:!0,F=void 0!==a.antialias?a.antialias:!1,M=void 0!==a.premultipliedAlpha?a.premultipliedAlpha:!0,ca=void 0!==a.preserveDrawingBuffer?a.preserveDrawingBuffer:!1,K=[],B=[],C=-1,z=[],Ka=-1,N=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=
11985 this.gammaOutput=this.gammaInput=!1;this.toneMappingWhitePoint=this.toneMappingExposure=this.toneMapping=1;this.maxMorphTargets=8;this.maxMorphNormals=4;var S=this,Q=null,V=null,T=null,L=-1,U="",W=null,X=new ga,fb=null,$a=new ga,da=0,Da=new O(0),Ra=0,Pa=v.width,pc=v.height,Qa=1,ha=new ga(0,0,Pa,pc),la=!1,fa=new ga(0,0,Pa,pc),oa=new nc,ba=new Bf,pa=!1,sa=!1,na=new Ca,ra=new J,Z=new q,aa={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],
11986 spotShadowMatrix:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],shadows:[]},ma={calls:0,vertices:0,faces:0,points:0};this.info={render:ma,memory:{geometries:0,textures:0},programs:null};var A;try{y={alpha:y,depth:E,stencil:H,antialias:F,premultipliedAlpha:M,preserveDrawingBuffer:ca};A=I||v.getContext("webgl",y)||v.getContext("experimental-webgl",y);if(null===A){if(null!==v.getContext("webgl"))throw"Error creating WebGL context with your selected attributes.";throw"Error creating WebGL context.";
11987 }void 0===A.getShaderPrecisionFormat&&(A.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}});v.addEventListener("webglcontextlost",e,!1)}catch(Cf){console.error("THREE.WebGLRenderer: "+Cf)}var ka=new Af(A);ka.get("WEBGL_depth_texture");ka.get("OES_texture_float");ka.get("OES_texture_float_linear");ka.get("OES_texture_half_float");ka.get("OES_texture_half_float_linear");ka.get("OES_standard_derivatives");ka.get("ANGLE_instanced_arrays");ka.get("OES_element_index_uint")&&
11988 (G.MaxIndex=4294967296);var ia=new zf(A,ka,a),Y=new yf(A,ka,u),ea=new xf,ua=new wf(A,ka,Y,ea,ia,u,this.info),qa=new vf(A,ea,this.info),va=new tf(this,ia),za=new lf;this.info.programs=va.programs;var Ga=new kf(A,ka,ma),Ha=new jf(A,ka,ma),Ia=new Hb(-1,1,1,-1,0,1),wa=new Ea,Ba=new ya(new ib(2,2),new Ma({depthTest:!1,depthWrite:!1,fog:!1}));a=Gb.cube;var xa=new ya(new hb(5,5,5),new Fa({uniforms:a.uniforms,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1}));
11989 c();this.context=A;this.capabilities=ia;this.extensions=ka;this.properties=ea;this.state=Y;var Ja=new pe(this,aa,qa,ia);this.shadowMap=Ja;var Na=new hf(this,P),Oa=new ff(this,R);this.getContext=function(){return A};this.getContextAttributes=function(){return A.getContextAttributes()};this.forceContextLoss=function(){ka.get("WEBGL_lose_context").loseContext()};this.getMaxAnisotropy=function(){return ia.getMaxAnisotropy()};this.getPrecision=function(){return ia.precision};this.getPixelRatio=function(){return Qa};
11990 this.setPixelRatio=function(a){void 0!==a&&(Qa=a,this.setSize(fa.z,fa.w,!1))};this.getSize=function(){return{width:Pa,height:pc}};this.setSize=function(a,b,c){Pa=a;pc=b;v.width=a*Qa;v.height=b*Qa;!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(fa.set(a,b,c,d))};this.setScissor=function(a,b,c,d){Y.scissor(ha.set(a,b,c,d))};this.setScissorTest=function(a){Y.setScissorTest(la=a)};this.getClearColor=function(){return Da};this.setClearColor=
11991 function(a,c){Da.set(a);Ra=void 0!==c?c:1;b(Da.r,Da.g,Da.b,Ra)};this.getClearAlpha=function(){return Ra};this.setClearAlpha=function(a){Ra=a;b(Da.r,Da.g,Da.b,Ra)};this.clear=function(a,b,c){var d=0;if(void 0===a||a)d|=A.COLOR_BUFFER_BIT;if(void 0===b||b)d|=A.DEPTH_BUFFER_BIT;if(void 0===c||c)d|=A.STENCIL_BUFFER_BIT;A.clear(d)};this.clearColor=function(){this.clear(!0,!1,!1)};this.clearDepth=function(){this.clear(!1,!0,!1)};this.clearStencil=function(){this.clear(!1,!1,!0)};this.clearTarget=function(a,
11992 b,c,d){this.setRenderTarget(a);this.clear(b,c,d)};this.resetGLState=d;this.dispose=function(){z=[];Ka=-1;B=[];C=-1;v.removeEventListener("webglcontextlost",e,!1)};this.renderBufferImmediate=function(a,b,c){Y.initAttributes();var d=ea.get(a);a.hasPositions&&!d.position&&(d.position=A.createBuffer());a.hasNormals&&!d.normal&&(d.normal=A.createBuffer());a.hasUvs&&!d.uv&&(d.uv=A.createBuffer());a.hasColors&&!d.color&&(d.color=A.createBuffer());b=b.getAttributes();a.hasPositions&&(A.bindBuffer(A.ARRAY_BUFFER,
11993 d.position),A.bufferData(A.ARRAY_BUFFER,a.positionArray,A.DYNAMIC_DRAW),Y.enableAttribute(b.position),A.vertexAttribPointer(b.position,3,A.FLOAT,!1,0,0));if(a.hasNormals){A.bindBuffer(A.ARRAY_BUFFER,d.normal);if(!c.isMeshPhongMaterial&&!c.isMeshStandardMaterial&&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}A.bufferData(A.ARRAY_BUFFER,
11994 a.normalArray,A.DYNAMIC_DRAW);Y.enableAttribute(b.normal);A.vertexAttribPointer(b.normal,3,A.FLOAT,!1,0,0)}a.hasUvs&&c.map&&(A.bindBuffer(A.ARRAY_BUFFER,d.uv),A.bufferData(A.ARRAY_BUFFER,a.uvArray,A.DYNAMIC_DRAW),Y.enableAttribute(b.uv),A.vertexAttribPointer(b.uv,2,A.FLOAT,!1,0,0));a.hasColors&&0!==c.vertexColors&&(A.bindBuffer(A.ARRAY_BUFFER,d.color),A.bufferData(A.ARRAY_BUFFER,a.colorArray,A.DYNAMIC_DRAW),Y.enableAttribute(b.color),A.vertexAttribPointer(b.color,3,A.FLOAT,!1,0,0));Y.disableUnusedAttributes();
11995 A.drawArrays(A.TRIANGLES,0,a.count);a.count=0};this.renderBufferDirect=function(a,b,c,d,e,f){l(d);var g=t(a,b,d,e),k=!1;a=c.id+"_"+g.id+"_"+d.wireframe;a!==U&&(U=a,k=!0);b=e.morphTargetInfluences;if(void 0!==b){var m=[];a=0;for(var p=b.length;a<p;a++)k=b[a],m.push([k,a]);m.sort(h);8<m.length&&(m.length=8);var n=c.morphAttributes;a=0;for(p=m.length;a<p;a++)k=m[a],N[a]=k[0],0!==k[0]?(b=k[1],!0===d.morphTargets&&n.position&&c.addAttribute("morphTarget"+a,n.position[b]),!0===d.morphNormals&&n.normal&&
11996 c.addAttribute("morphNormal"+a,n.normal[b])):(!0===d.morphTargets&&c.removeAttribute("morphTarget"+a),!0===d.morphNormals&&c.removeAttribute("morphNormal"+a));a=m.length;for(b=N.length;a<b;a++)N[a]=0;g.getUniforms().setValue(A,"morphTargetInfluences",N);k=!0}b=c.index;p=c.attributes.position;m=1;!0===d.wireframe&&(b=qa.getWireframeAttribute(c),m=2);null!==b?(a=Ha,a.setIndex(b)):a=Ga;if(k){a:{var k=void 0,w;if(c&&c.isInstancedBufferGeometry&&(w=ka.get("ANGLE_instanced_arrays"),null===w)){console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");
11997 break a}void 0===k&&(k=0);Y.initAttributes();var n=c.attributes,g=g.getAttributes(),r=d.defaultAttributeValues,v;for(v in g){var q=g[v];if(0<=q){var u=n[v];if(void 0!==u){var y=A.FLOAT,D=u.array,H=u.normalized;D instanceof Float32Array?y=A.FLOAT:D instanceof Float64Array?console.warn("Unsupported data buffer format: Float64Array"):D instanceof Uint16Array?y=A.UNSIGNED_SHORT:D instanceof Int16Array?y=A.SHORT:D instanceof Uint32Array?y=A.UNSIGNED_INT:D instanceof Int32Array?y=A.INT:D instanceof Int8Array?
11998 y=A.BYTE:D instanceof Uint8Array&&(y=A.UNSIGNED_BYTE);var D=u.itemSize,F=qa.getAttributeBuffer(u);if(u.isInterleavedBufferAttribute){var I=u.data,E=I.stride,u=u.offset;I&&I.isInstancedInterleavedBuffer?(Y.enableAttributeAndDivisor(q,I.meshPerAttribute,w),void 0===c.maxInstancedCount&&(c.maxInstancedCount=I.meshPerAttribute*I.count)):Y.enableAttribute(q);A.bindBuffer(A.ARRAY_BUFFER,F);A.vertexAttribPointer(q,D,y,H,E*I.array.BYTES_PER_ELEMENT,(k*E+u)*I.array.BYTES_PER_ELEMENT)}else u.isInstancedBufferAttribute?
11999 (Y.enableAttributeAndDivisor(q,u.meshPerAttribute,w),void 0===c.maxInstancedCount&&(c.maxInstancedCount=u.meshPerAttribute*u.count)):Y.enableAttribute(q),A.bindBuffer(A.ARRAY_BUFFER,F),A.vertexAttribPointer(q,D,y,H,0,k*D*u.array.BYTES_PER_ELEMENT)}else if(void 0!==r&&(y=r[v],void 0!==y))switch(y.length){case 2:A.vertexAttrib2fv(q,y);break;case 3:A.vertexAttrib3fv(q,y);break;case 4:A.vertexAttrib4fv(q,y);break;default:A.vertexAttrib1fv(q,y)}}}Y.disableUnusedAttributes()}null!==b&&A.bindBuffer(A.ELEMENT_ARRAY_BUFFER,
12000 qa.getAttributeBuffer(b))}w=0;null!==b?w=b.count:void 0!==p&&(w=p.count);b=c.drawRange.start*m;p=null!==f?f.start*m:0;v=Math.max(b,p);f=Math.max(0,Math.min(w,b+c.drawRange.count*m,p+(null!==f?f.count*m:Infinity))-1-v+1);if(0!==f){if(e.isMesh)if(!0===d.wireframe)Y.setLineWidth(d.wireframeLinewidth*(null===V?Qa:1)),a.setMode(A.LINES);else switch(e.drawMode){case 0:a.setMode(A.TRIANGLES);break;case 1:a.setMode(A.TRIANGLE_STRIP);break;case 2:a.setMode(A.TRIANGLE_FAN)}else e.isLine?(d=d.linewidth,void 0===
12001 d&&(d=1),Y.setLineWidth(d*(null===V?Qa:1)),e.isLineSegments?a.setMode(A.LINES):a.setMode(A.LINE_STRIP)):e.isPoints&&a.setMode(A.POINTS);c&&c.isInstancedBufferGeometry?0<c.maxInstancedCount&&a.renderInstances(c,v,f):a.render(v,f)}};this.render=function(a,c,d,e){if(void 0!==c&&!0!==c.isCamera)console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");else{U="";L=-1;W=null;!0===a.autoUpdate&&a.updateMatrixWorld();null===c.parent&&c.updateMatrixWorld();c.matrixWorldInverse.getInverse(c.matrixWorld);
12002 ra.multiplyMatrices(c.projectionMatrix,c.matrixWorldInverse);oa.setFromMatrix(ra);K.length=0;Ka=C=-1;P.length=0;R.length=0;sa=this.localClippingEnabled;pa=ba.init(this.clippingPlanes,sa,c);p(a,c);B.length=C+1;z.length=Ka+1;!0===S.sortObjects&&(B.sort(k),z.sort(m));pa&&ba.beginShadows();for(var f=K,g=0,h=0,n=f.length;h<n;h++){var w=f[h];w.castShadow&&(aa.shadows[g++]=w)}aa.shadows.length=g;Ja.render(a,c);for(var f=K,l=w=0,x=0,t,v,q,u,y=c.matrixWorldInverse,D=0,H=0,F=0,I=0,g=0,h=f.length;g<h;g++)if(n=
12003 f[g],t=n.color,v=n.intensity,q=n.distance,u=n.shadow&&n.shadow.map?n.shadow.map.texture:null,n.isAmbientLight)w+=t.r*v,l+=t.g*v,x+=t.b*v;else if(n.isDirectionalLight){var E=za.get(n);E.color.copy(n.color).multiplyScalar(n.intensity);E.direction.setFromMatrixPosition(n.matrixWorld);Z.setFromMatrixPosition(n.target.matrixWorld);E.direction.sub(Z);E.direction.transformDirection(y);if(E.shadow=n.castShadow)E.shadowBias=n.shadow.bias,E.shadowRadius=n.shadow.radius,E.shadowMapSize=n.shadow.mapSize;aa.directionalShadowMap[D]=
12004 u;aa.directionalShadowMatrix[D]=n.shadow.matrix;aa.directional[D++]=E}else if(n.isSpotLight){E=za.get(n);E.position.setFromMatrixPosition(n.matrixWorld);E.position.applyMatrix4(y);E.color.copy(t).multiplyScalar(v);E.distance=q;E.direction.setFromMatrixPosition(n.matrixWorld);Z.setFromMatrixPosition(n.target.matrixWorld);E.direction.sub(Z);E.direction.transformDirection(y);E.coneCos=Math.cos(n.angle);E.penumbraCos=Math.cos(n.angle*(1-n.penumbra));E.decay=0===n.distance?0:n.decay;if(E.shadow=n.castShadow)E.shadowBias=
12005 n.shadow.bias,E.shadowRadius=n.shadow.radius,E.shadowMapSize=n.shadow.mapSize;aa.spotShadowMap[F]=u;aa.spotShadowMatrix[F]=n.shadow.matrix;aa.spot[F++]=E}else if(n.isPointLight){E=za.get(n);E.position.setFromMatrixPosition(n.matrixWorld);E.position.applyMatrix4(y);E.color.copy(n.color).multiplyScalar(n.intensity);E.distance=n.distance;E.decay=0===n.distance?0:n.decay;if(E.shadow=n.castShadow)E.shadowBias=n.shadow.bias,E.shadowRadius=n.shadow.radius,E.shadowMapSize=n.shadow.mapSize;aa.pointShadowMap[H]=
12006 u;void 0===aa.pointShadowMatrix[H]&&(aa.pointShadowMatrix[H]=new J);Z.setFromMatrixPosition(n.matrixWorld).negate();aa.pointShadowMatrix[H].identity().setPosition(Z);aa.point[H++]=E}else n.isHemisphereLight&&(E=za.get(n),E.direction.setFromMatrixPosition(n.matrixWorld),E.direction.transformDirection(y),E.direction.normalize(),E.skyColor.copy(n.color).multiplyScalar(v),E.groundColor.copy(n.groundColor).multiplyScalar(v),aa.hemi[I++]=E);aa.ambient[0]=w;aa.ambient[1]=l;aa.ambient[2]=x;aa.directional.length=
12007 D;aa.spot.length=F;aa.point.length=H;aa.hemi.length=I;aa.hash=D+","+H+","+F+","+I+","+aa.shadows.length;pa&&ba.endShadows();ma.calls=0;ma.vertices=0;ma.faces=0;ma.points=0;void 0===d&&(d=null);this.setRenderTarget(d);f=a.background;null===f?b(Da.r,Da.g,Da.b,Ra):f&&f.isColor&&(b(f.r,f.g,f.b,1),e=!0);(this.autoClear||e)&&this.clear(this.autoClearColor,this.autoClearDepth,this.autoClearStencil);f&&f.isCubeTexture?(wa.projectionMatrix.copy(c.projectionMatrix),wa.matrixWorld.extractRotation(c.matrixWorld),
12008 wa.matrixWorldInverse.getInverse(wa.matrixWorld),xa.material.uniforms.tCube.value=f,xa.modelViewMatrix.multiplyMatrices(wa.matrixWorldInverse,xa.matrixWorld),qa.update(xa),S.renderBufferDirect(wa,null,xa.geometry,xa.material,xa,null)):f&&f.isTexture&&(Ba.material.map=f,qa.update(Ba),S.renderBufferDirect(Ia,null,Ba.geometry,Ba.material,Ba,null));a.overrideMaterial?(e=a.overrideMaterial,r(B,a,c,e),r(z,a,c,e)):(Y.setBlending(0),r(B,a,c),r(z,a,c));Na.render(a,c);Oa.render(a,c,$a);d&&ua.updateRenderTargetMipmap(d);
12009 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=da;a>=ia.maxTextures&&console.warn("WebGLRenderer: trying to use "+a+" texture units while this GPU supports only "+ia.maxTextures);da+=1;return a};this.setTexture2D=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTarget&&(a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),
12010 a=!0),b=b.texture);ua.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);ua.setTexture2D(b,c)}}();this.setTextureCube=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);b&&b.isCubeTexture||Array.isArray(b.image)&&
12011 6===b.image.length?ua.setTextureCube(b,c):ua.setTextureCubeDynamic(b,c)}}();this.getCurrentRenderTarget=function(){return V};this.setRenderTarget=function(a){(V=a)&&void 0===ea.get(a).__webglFramebuffer&&ua.setupRenderTarget(a);var b=a&&a.isWebGLRenderTargetCube,c;a?(c=ea.get(a),c=b?c.__webglFramebuffer[a.activeCubeFace]:c.__webglFramebuffer,X.copy(a.scissor),fb=a.scissorTest,$a.copy(a.viewport)):(c=null,X.copy(ha).multiplyScalar(Qa),fb=la,$a.copy(fa).multiplyScalar(Qa));T!==c&&(A.bindFramebuffer(A.FRAMEBUFFER,
12012 c),T=c);Y.scissor(X);Y.setScissorTest(fb);Y.viewport($a);b&&(b=ea.get(a.texture),A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,b.__webglTexture,a.activeMipMapLevel))};this.readRenderTargetPixels=function(a,b,c,d,e,f){if(!1===(a&&a.isWebGLRenderTarget))console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");else{var g=ea.get(a).__webglFramebuffer;if(g){var h=!1;g!==T&&(A.bindFramebuffer(A.FRAMEBUFFER,
12013 g),h=!0);try{var k=a.texture,m=k.format,n=k.type;1023!==m&&u(m)!==A.getParameter(A.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===n||u(n)===A.getParameter(A.IMPLEMENTATION_COLOR_READ_TYPE)||1015===n&&(ka.get("OES_texture_float")||ka.get("WEBGL_color_buffer_float"))||1016===n&&ka.get("EXT_color_buffer_half_float")?A.checkFramebufferStatus(A.FRAMEBUFFER)===A.FRAMEBUFFER_COMPLETE?0<=b&&
12014 b<=a.width-d&&0<=c&&c<=a.height-e&&A.readPixels(b,c,d,e,u(m),u(n),f):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."):console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.")}finally{h&&A.bindFramebuffer(A.FRAMEBUFFER,T)}}}}}function Ib(a,b){this.name="";this.color=new O(a);this.density=void 0!==b?b:2.5E-4}function Jb(a,b,c){this.name="";this.color=
12015 new O(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function jb(){z.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function Ed(a,b,c,d,e){z.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){U.call(this);this.type="SpriteMaterial";this.color=new O(16777215);this.map=null;this.rotation=0;this.lights=this.fog=!1;this.setValues(a)}function qc(a){z.call(this);
12016 this.type="Sprite";this.material=void 0!==a?a:new kb}function rc(){z.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function lb(a,b,c,d,e,f,g,h,k,m,w,n){da.call(this,null,f,g,h,k,m,d,e,w,n);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=!1;this.unpackAlignment=1}function bd(a,b,c){this.useVertexTexture=void 0!==c?c:!0;this.identityMatrix=new J;a=a||[];this.bones=a.slice(0);
12017 this.useVertexTexture?(a=Math.sqrt(4*this.bones.length),a=T.nextPowerOfTwo(Math.ceil(a)),this.boneTextureHeight=this.boneTextureWidth=a=Math.max(a,4),this.boneMatrices=new Float32Array(this.boneTextureWidth*this.boneTextureHeight*4),this.boneTexture=new lb(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."),
12018 this.boneInverses=[],b=0,a=this.bones.length;b<a;b++)this.boneInverses.push(new J)}function cd(a){z.call(this);this.type="Bone";this.skin=a}function dd(a,b,c){ya.call(this,a,b);this.type="SkinnedMesh";this.bindMode="attached";this.bindMatrix=new J;this.bindMatrixInverse=new J;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 cd(this),a.push(b),b.name=d.name,b.position.fromArray(d.pos),b.quaternion.fromArray(d.rotq),
12019 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]?a[d.parent].add(a[e]):this.add(a[e])}this.normalizeSkinWeights();this.updateMatrixWorld(!0);this.bind(new bd(a,void 0,c),this.matrixWorld)}function oa(a){U.call(this);this.type="LineBasicMaterial";this.color=new O(16777215);this.linewidth=1;this.linejoin=this.linecap="round";this.lights=!1;this.setValues(a)}function Ta(a,b,c){if(1===c)return console.warn("THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead."),
12020 new la(a,b);z.call(this);this.type="Line";this.geometry=void 0!==a?a:new G;this.material=void 0!==b?b:new oa({color:16777215*Math.random()})}function la(a,b){Ta.call(this,a,b);this.type="LineSegments"}function xa(a){U.call(this);this.type="PointsMaterial";this.color=new O(16777215);this.map=null;this.size=1;this.sizeAttenuation=!0;this.lights=!1;this.setValues(a)}function Kb(a,b){z.call(this);this.type="Points";this.geometry=void 0!==a?a:new G;this.material=void 0!==b?b:new xa({color:16777215*Math.random()})}
12021 function sc(){z.call(this);this.type="Group"}function ed(a,b,c,d,e,f,g,h,k){function m(){requestAnimationFrame(m);a.readyState>=a.HAVE_CURRENT_DATA&&(w.needsUpdate=!0)}da.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1;var w=this;m()}function Lb(a,b,c,d,e,f,g,h,k,m,w,n){da.call(this,null,f,g,h,k,m,d,e,w,n);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1}function fd(a,b,c,d,e,f,g,h,k){da.call(this,a,b,c,d,e,f,g,h,k);this.needsUpdate=!0}function tc(a,b,c,d,e,f,g,
12022 h,k,m){m=void 0!==m?m:1026;if(1026!==m&&1027!==m)throw Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");da.call(this,null,d,e,f,g,h,m,c,k);this.image={width:a,height:b};this.type=void 0!==c?c:1012;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}G.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);
12023 a=0;for(var m=g.length;a<m;a++)for(var w=g[a],n=0;3>n;n++){c[0]=w[e[n]];c[1]=w[e[(n+1)%3]];c.sort(b);var p=c.toString();void 0===d[p]&&(k[2*h]=c[0],k[2*h+1]=c[1],d[p]=!0,h++)}c=new Float32Array(6*h);a=0;for(m=h;a<m;a++)for(n=0;2>n;n++)d=f[k[2*a+n]],h=6*a+3*n,c[h+0]=d.x,c[h+1]=d.y,c[h+2]=d.z;this.addAttribute("position",new C(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);
12024 g=0;for(w=e.length;g<w;++g){a=e[g];n=a.start;p=a.count;a=n;for(var r=n+p;a<r;a+=3)for(n=0;3>n;n++)c[0]=m[a+n],c[1]=m[a+(n+1)%3],c.sort(b),p=c.toString(),void 0===d[p]&&(k[2*h]=c[0],k[2*h+1]=c[1],d[p]=!0,h++)}c=new Float32Array(6*h);a=0;for(m=h;a<m;a++)for(n=0;2>n;n++)h=6*a+3*n,d=k[2*a+n],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(n=0;3>n;n++)h=18*a+6*n,k=9*a+3*n,c[h+0]=f[k],c[h+1]=f[k+1],
12025 c[h+2]=f[k+2],d=9*a+(n+1)%3*3,c[h+3]=f[d],c[h+4]=f[d+1],c[h+5]=f[d+2];this.addAttribute("position",new C(c,3))}}function Nb(a,b,c){G.call(this);this.type="ParametricBufferGeometry";this.parameters={func:a,slices:b,stacks:c};var d=[],e=[],f,g,h,k,m,w=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 n;for(f=0;f<c;f++)for(g=0;g<b;g++)h=f*w+g,k=f*w+g+1,m=(f+1)*w+g+1,n=(f+1)*w+g,a.push(h,k,n),a.push(k,m,n);this.setIndex((65535<a.length?$c:Zc)(a,1));this.addAttribute("position",
12026 ha(d,3));this.addAttribute("uv",ha(e,2));this.computeVertexNormals()}function uc(a,b,c){Q.call(this);this.type="ParametricGeometry";this.parameters={func:a,slices:b,stacks:c};this.fromBufferGeometry(new Nb(a,b,c));this.mergeVertices()}function ua(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)}G.call(this);this.type="PolyhedronBufferGeometry";this.parameters=
12027 {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,D=g,u=Math.pow(2,a),v=[],I,y;for(I=0;I<=u;I++){v[I]=[];var E=k.clone().lerp(D,I/u),H=l.clone().lerp(D,I/u),F=u-I;for(y=0;y<=F;y++)v[I][y]=0===y&&I===u?E:E.clone().lerp(H,y/F)}for(I=0;I<u;I++)for(y=0;y<2*(u-I)-1;y++)k=Math.floor(y/2),0===y%2?(e(v[I][k+1]),e(v[I+1][k]),e(v[I][k])):(e(v[I][k+1]),e(v[I+1][k+1]),e(v[I+1][k]))}})(d||
12028 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 B,f=new B,l=new B,D=0,u=0;D<h.length;D+=9,u+=6){a.set(h[D+0],h[D+1],h[D+2]);b.set(h[D+3],h[D+4],h[D+5]);c.set(h[D+6],h[D+
12029 7],h[D+8]);e.set(k[u+0],k[u+1]);f.set(k[u+2],k[u+3]);l.set(k[u+4],k[u+5]);d.copy(a).add(b).add(c).divideScalar(3);var v=Math.atan2(d.z,-d.x);g(e,u+0,a,v);g(f,u+2,b,v);g(l,u+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",ha(h,3));this.addAttribute("normal",ha(h.slice(),3));this.addAttribute("uv",ha(k,2));this.normalizeNormals();this.boundingSphere=new Ca(new q,
12030 c)}function Ob(a,b){ua.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 vc(a,b){Q.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Ob(a,b));this.mergeVertices()}function Pb(a,b){ua.call(this,[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],a,b);this.type="OctahedronBufferGeometry";this.parameters=
12031 {radius:a,detail:b}}function wc(a,b){Q.call(this);this.type="OctahedronGeometry";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;ua.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";this.parameters=
12032 {radius:a,detail:b}}function xc(a,b){Q.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Qb(a,b));this.mergeVertices()}function Rb(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;ua.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,0,18,16,6,10,2,
12033 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 yc(a,b){Q.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Rb(a,b));this.mergeVertices()}function zc(a,b,c,d){Q.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};
12034 this.fromBufferGeometry(new ua(a,b,c,d));this.mergeVertices()}function Sb(a,b,c,d,e){function f(e){var f=a.getPointAt(e/b),m=g.normals[e];e=g.binormals[e];for(n=0;n<=d;n++){var w=n/d*Math.PI*2,l=Math.sin(w),w=-Math.cos(w);k.x=w*m.x+l*e.x;k.y=w*m.y+l*e.y;k.z=w*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;p.push(h.x,h.y,h.z)}}G.call(this);this.type="TubeBufferGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};b=b||64;c=c||
12035 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 B,w,n,p=[],r=[],l=[],t=[];for(w=0;w<b;w++)f(w);f(!1===e?b:0);for(w=0;w<=b;w++)for(n=0;n<=d;n++)m.x=w/b,m.y=n/d,l.push(m.x,m.y);(function(){for(n=1;n<=b;n++)for(w=1;w<=d;w++){var a=(d+1)*n+(w-1),c=(d+1)*n+w,e=(d+1)*(n-1)+w;t.push((d+1)*(n-1)+(w-1),a,e);t.push(a,c,e)}})();this.setIndex((65535<t.length?$c:Zc)(t,1));this.addAttribute("position",ha(p,3));
12036 this.addAttribute("normal",ha(r,3));this.addAttribute("uv",ha(l,2))}function Ac(a,b,c,d,e,f){Q.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 Sb(a,b,c,d,e);this.tangents=a.tangents;this.normals=a.normals;this.binormals=a.binormals;this.fromBufferGeometry(a);this.mergeVertices()}function Tb(a,b,c,d,e,f){function g(a,b,c,d,e){var f=Math.sin(a);b=c/b*a;c=Math.cos(b);
12037 e.x=d*(2+c)*.5*Math.cos(a);e.y=d*(2+c)*f*.5;e.z=d*Math.sin(b)*.5}G.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 C(new (65535<k?Uint32Array:Uint16Array)(k),1),m=new C(new Float32Array(3*h),3),w=new C(new Float32Array(3*h),3),h=new C(new Float32Array(2*h),2),n,p,r=0,l=0,t=new q,D=new q,u=new B,v=new q,I=new q,y=new q,E=new q,
12038 H=new q;for(n=0;n<=c;++n)for(p=n/c*e*Math.PI*2,g(p,e,f,a,v),g(p+.01,e,f,a,I),E.subVectors(I,v),H.addVectors(I,v),y.crossVectors(E,H),H.crossVectors(y,E),y.normalize(),H.normalize(),p=0;p<=d;++p){var F=p/d*Math.PI*2,M=-b*Math.cos(F),F=b*Math.sin(F);t.x=v.x+(M*H.x+F*y.x);t.y=v.y+(M*H.y+F*y.y);t.z=v.z+(M*H.z+F*y.z);m.setXYZ(r,t.x,t.y,t.z);D.subVectors(t,v).normalize();w.setXYZ(r,D.x,D.y,D.z);u.x=n/c;u.y=p/d;h.setXY(r,u.x,u.y);r++}for(p=1;p<=c;p++)for(n=1;n<=d;n++)a=(d+1)*p+(n-1),b=(d+1)*p+n,e=(d+1)*
12039 (p-1)+n,k.setX(l,(d+1)*(p-1)+(n-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",w);this.addAttribute("uv",h)}function Bc(a,b,c,d,e,f,g){Q.call(this);this.type="TorusKnotGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};void 0!==g&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.");this.fromBufferGeometry(new Tb(a,
12040 b,c,d,e,f));this.mergeVertices()}function Ub(a,b,c,d,e){G.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,w=0,n=0,p=new q,r=new q,l=new q,t,D;for(t=0;t<=c;t++)for(D=0;D<=d;D++){var u=D/d*e,v=t/c*Math.PI*2;r.x=(a+b*Math.cos(v))*
12041 Math.cos(u);r.y=(a+b*Math.cos(v))*Math.sin(u);r.z=b*Math.sin(v);h[m]=r.x;h[m+1]=r.y;h[m+2]=r.z;p.x=a*Math.cos(u);p.y=a*Math.sin(u);l.subVectors(r,p).normalize();k[m]=l.x;k[m+1]=l.y;k[m+2]=l.z;f[w]=D/d;f[w+1]=t/c;m+=3;w+=2}for(t=1;t<=c;t++)for(D=1;D<=d;D++)a=(d+1)*(t-1)+D-1,b=(d+1)*(t-1)+D,e=(d+1)*t+D,g[n]=(d+1)*t+D-1,g[n+1]=a,g[n+2]=e,g[n+3]=a,g[n+4]=b,g[n+5]=e,n+=6;this.setIndex(new C(g,1));this.addAttribute("position",new C(h,3));this.addAttribute("normal",new C(k,3));this.addAttribute("uv",new C(f,
12042 2))}function Cc(a,b,c,d,e){Q.call(this);this.type="TorusGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};this.fromBufferGeometry(new Ub(a,b,c,d,e))}function za(a,b){"undefined"!==typeof a&&(Q.call(this),this.type="ExtrudeGeometry",a=Array.isArray(a)?a:[a],this.addShapeList(a,b),this.computeFaceNormals())}function Dc(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."),new Q;
12043 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);za.call(this,c,b);this.type="TextGeometry"}function mb(a,b,c,d,e,f,g){G.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)||
12044 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 C(new Float32Array(3*k),3),w=new C(new Float32Array(3*k),3),k=new C(new Float32Array(2*k),2),n=0,p=[],l=new q,x=0;x<=c;x++){for(var t=[],D=x/c,u=0;u<=b;u++){var v=u/b,I=-a*Math.cos(d+v*e)*Math.sin(f+D*g),y=a*Math.cos(f+D*g),E=a*Math.sin(d+v*e)*Math.sin(f+D*g);l.set(I,y,E).normalize();m.setXYZ(n,I,y,E);w.setXYZ(n,l.x,l.y,l.z);k.setXY(n,v,1-D);t.push(n);n++}p.push(t)}d=[];for(x=0;x<
12045 c;x++)for(u=0;u<b;u++)e=p[x][u+1],g=p[x][u],n=p[x+1][u],l=p[x+1][u+1],(0!==x||0<f)&&d.push(e,g,l),(x!==c-1||h<Math.PI)&&d.push(g,n,l);this.setIndex(new (65535<m.count?$c:Zc)(d,1));this.addAttribute("position",m);this.addAttribute("normal",w);this.addAttribute("uv",k);this.boundingSphere=new Ca(new q,a)}function Vb(a,b,c,d,e,f,g){Q.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,
12046 b,c,d,e,f,g))}function Wb(a,b,c,d,e,f){G.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 C(new (65535<h?Uint32Array:Uint16Array)(h),1),k=new C(new Float32Array(3*g),3),m=new C(new Float32Array(3*g),3),g=new C(new Float32Array(2*g),2),w=0,n=0,p,l=a,x=(b-a)/
12047 d,t=new q,D=new B,u;for(a=0;a<=d;a++){for(u=0;u<=c;u++)p=e+u/c*f,t.x=l*Math.cos(p),t.y=l*Math.sin(p),k.setXYZ(w,t.x,t.y,t.z),m.setXYZ(w,0,0,1),D.x=(t.x/b+1)/2,D.y=(t.y/b+1)/2,g.setXY(w,D.x,D.y),w++;l+=x}for(a=0;a<d;a++)for(b=a*(c+1),u=0;u<c;u++)e=p=u+b,f=p+c+1,w=p+c+2,p+=1,h.setX(n,e),n++,h.setX(n,f),n++,h.setX(n,w),n++,h.setX(n,e),n++,h.setX(n,w),n++,h.setX(n,p),n++;this.setIndex(h);this.addAttribute("position",k);this.addAttribute("normal",m);this.addAttribute("uv",g)}function Ec(a,b,c,d,e,f){Q.call(this);
12048 this.type="RingGeometry";this.parameters={innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};this.fromBufferGeometry(new Wb(a,b,c,d,e,f))}function Fc(a,b,c,d){Q.call(this);this.type="PlaneGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};this.fromBufferGeometry(new ib(a,b,c,d))}function Xb(a,b,c,d){G.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||
12049 2*Math.PI;d=T.clamp(d,0,2*Math.PI);for(var e=(b+1)*a.length,f=b*a.length*6,g=new C(new (65535<f?Uint32Array:Uint16Array)(f),1),h=new C(new Float32Array(3*e),3),k=new C(new Float32Array(2*e),2),m=0,w=0,n=1/b,p=new q,l=new B,e=0;e<=b;e++)for(var f=c+e*n*d,x=Math.sin(f),t=Math.cos(f),f=0;f<=a.length-1;f++)p.x=a[f].x*x,p.y=a[f].y,p.z=a[f].x*t,h.setXYZ(m,p.x,p.y,p.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,n=c+a.length+1,p=
12050 c+1,g.setX(w,c),w++,g.setX(w,m),w++,g.setX(w,p),w++,g.setX(w,m),w++,g.setX(w,n),w++,g.setX(w,p),w++;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 Gc(a,b,c,d){Q.call(this);
12051 this.type="LatheGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};this.fromBufferGeometry(new Xb(a,b,c,d));this.mergeVertices()}function cb(a,b){Q.call(this);this.type="ShapeGeometry";!1===Array.isArray(a)&&(a=[a]);this.addShapeList(a,b);this.computeFaceNormals()}function Yb(a,b){function c(a,b){return a-b}G.call(this);var d=Math.cos(T.DEG2RAD*(void 0!==b?b:1)),e=[0,0],f={},g=["a","b","c"],h;a&&a.isBufferGeometry?(h=new Q,h.fromBufferGeometry(a)):h=a.clone();h.mergeVertices();
12052 h.computeFaceNormals();var k=h.vertices;h=h.faces;for(var m=0,w=h.length;m<w;m++)for(var n=h[m],p=0;3>p;p++){e[0]=n[g[p]];e[1]=n[g[(p+1)%3]];e.sort(c);var l=e.toString();void 0===f[l]?f[l]={vert1:e[0],vert2:e[1],face1:m,face2:void 0}:f[l].face2=m}e=[];for(l in f)if(g=f[l],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 C(new Float32Array(e),3))}function Ua(a,
12053 b,c,d,e,f,g,h){function k(c){var e,f,k,n=new B,p=new q,l=0,w=!0===c?a:b,I=!0===c?1:-1;f=u;for(e=1;e<=d;e++)x.setXYZ(u,0,y*I,0),t.setXYZ(u,0,I,0),n.x=.5,n.y=.5,D.setXY(u,n.x,n.y),u++;k=u;for(e=0;e<=d;e++){var z=e/d*h+g,C=Math.cos(z),z=Math.sin(z);p.x=w*z;p.y=y*I;p.z=w*C;x.setXYZ(u,p.x,p.y,p.z);t.setXYZ(u,0,I,0);n.x=.5*C+.5;n.y=.5*z*I+.5;D.setXY(u,n.x,n.y);u++}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(E,l,!0===
12054 c?1:2);E+=l}G.call(this);this.type="CylinderBufferGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};var m=this;a=void 0!==a?a:20;b=void 0!==b?b:20;c=void 0!==c?c:100;d=Math.floor(d)||8;e=Math.floor(e)||1;f=void 0!==f?f:!1;g=void 0!==g?g:0;h=void 0!==h?h:2*Math.PI;var l=0;!1===f&&(0<a&&l++,0<b&&l++);var n=function(){var a=(d+1)*(e+1);!1===f&&(a+=(d+1)*l+d*l);return a}(),p=function(){var a=d*e*6;!1===f&&(a+=d*l*3);
12055 return a}(),r=new C(new (65535<p?Uint32Array:Uint16Array)(p),1),x=new C(new Float32Array(3*n),3),t=new C(new Float32Array(3*n),3),D=new C(new Float32Array(2*n),2),u=0,v=0,I=[],y=c/2,E=0;(function(){var f,k,n=new q,p=new q,l=0,w=(b-a)/c;for(k=0;k<=e;k++){var B=[],z=k/e,C=z*(b-a)+a;for(f=0;f<=d;f++){var N=f/d,P=N*h+g,R=Math.sin(P),P=Math.cos(P);p.x=C*R;p.y=-z*c+y;p.z=C*P;x.setXYZ(u,p.x,p.y,p.z);n.set(R,w,P).normalize();t.setXYZ(u,n.x,n.y,n.z);D.setXY(u,N,1-z);B.push(u);u++}I.push(B)}for(f=0;f<d;f++)for(k=
12056 0;k<e;k++)n=I[k+1][f],p=I[k+1][f+1],w=I[k][f+1],r.setX(v,I[k][f]),v++,r.setX(v,n),v++,r.setX(v,w),v++,r.setX(v,n),v++,r.setX(v,p),v++,r.setX(v,w),v++,l+=6;m.addGroup(E,l,0);E+=l})();!1===f&&(0<a&&k(!0),0<b&&k(!1));this.setIndex(r);this.addAttribute("position",x);this.addAttribute("normal",t);this.addAttribute("uv",D)}function nb(a,b,c,d,e,f,g,h){Q.call(this);this.type="CylinderGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,
12057 thetaLength:h};this.fromBufferGeometry(new Ua(a,b,c,d,e,f,g,h));this.mergeVertices()}function Hc(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 Ic(a,b,c,d,e,f,g){Ua.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){G.call(this);
12058 this.type="CircleBufferGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};a=a||50;b=void 0!==b?Math.max(3,b):8;c=void 0!==c?c:0;d=void 0!==d?d:2*Math.PI;var e=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 C(new Uint16Array(c),
12059 1));this.addAttribute("position",new C(f,3));this.addAttribute("normal",new C(g,3));this.addAttribute("uv",new C(e,2));this.boundingSphere=new Ca(new q,a)}function Jc(a,b,c,d){Q.call(this);this.type="CircleGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};this.fromBufferGeometry(new Zb(a,b,c,d))}function ob(a,b,c,d,e,f){Q.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};this.fromBufferGeometry(new hb(a,
12060 b,c,d,e,f));this.mergeVertices()}function $b(){Fa.call(this,{uniforms:La.merge([W.lights,{opacity:{value:1}}]),vertexShader:X.shadow_vert,fragmentShader:X.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 ac(a){Fa.call(this,a);this.type="RawShaderMaterial"}function Kc(a){this.uuid=T.generateUUID();this.type="MultiMaterial";this.materials=a instanceof
12061 Array?a:[];this.visible=!0}function Oa(a){U.call(this);this.defines={STANDARD:""};this.type="MeshStandardMaterial";this.color=new O(16777215);this.metalness=this.roughness=.5;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new O(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new B(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=
12062 this.alphaMap=this.metalnessMap=this.roughnessMap=null;this.envMapIntensity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function pb(a){Oa.call(this);this.defines={PHYSICAL:""};this.type="MeshPhysicalMaterial";this.reflectivity=.5;this.clearCoatRoughness=this.clearCoat=0;this.setValues(a)}function db(a){U.call(this);this.type="MeshPhongMaterial";this.color=
12063 new O(16777215);this.specular=new O(1118481);this.shininess=30;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new O(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new B(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;
12064 this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function qb(a){U.call(this,a);this.type="MeshNormalMaterial";this.wireframe=!1;this.wireframeLinewidth=1;this.morphTargets=this.lights=this.fog=!1;this.setValues(a)}function rb(a){U.call(this);this.type="MeshLambertMaterial";this.color=new O(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=
12065 new O(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=this.skinning=!1;this.setValues(a)}function sb(a){U.call(this);this.type="LineDashedMaterial";this.color=new O(16777215);this.scale=this.linewidth=1;this.dashSize=3;this.gapSize=1;this.lights=!1;this.setValues(a)}
12066 function Fd(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!==d.onLoad))d.onLoad()};this.itemError=function(a){if(void 0!==d.onError)d.onError(a)}}function Ja(a){this.manager=void 0!==a?a:Ga}function we(a){this.manager=void 0!==a?a:Ga;this._parser=null}function Gd(a){this.manager=
12067 void 0!==a?a:Ga;this._parser=null}function Lc(a){this.manager=void 0!==a?a:Ga}function Hd(a){this.manager=void 0!==a?a:Ga}function gd(a){this.manager=void 0!==a?a:Ga}function pa(a,b){z.call(this);this.type="Light";this.color=new O(a);this.intensity=void 0!==b?b:1;this.receiveShadow=void 0}function hd(a,b,c){pa.call(this,a,c);this.type="HemisphereLight";this.castShadow=void 0;this.position.copy(z.DefaultUp);this.updateMatrix();this.groundColor=new O(b)}function tb(a){this.camera=a;this.bias=0;this.radius=
12068 1;this.mapSize=new B(512,512);this.map=null;this.matrix=new J}function id(){tb.call(this,new Ea(50,1,.5,500))}function jd(a,b,c,d,e,f){pa.call(this,a,b);this.type="SpotLight";this.position.copy(z.DefaultUp);this.updateMatrix();this.target=new z;Object.defineProperty(this,"power",{get:function(){return this.intensity*Math.PI},set:function(a){this.intensity=a/Math.PI}});this.distance=void 0!==c?c:0;this.angle=void 0!==d?d:Math.PI/3;this.penumbra=void 0!==e?e:0;this.decay=void 0!==f?f:1;this.shadow=
12069 new id}function kd(a,b,c,d){pa.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 Ea(90,1,.5,500))}function ld(a){tb.call(this,new Hb(-5,5,5,-5,.5,500))}function md(a,b){pa.call(this,a,b);this.type="DirectionalLight";this.position.copy(z.DefaultUp);this.updateMatrix();this.target=new z;this.shadow=new ld}
12070 function nd(a,b){pa.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 od(a,b,c,d){qa.call(this,a,b,c,d);this._offsetNext=this._weightNext=this._offsetPrev=this._weightPrev=-0}function Mc(a,b,c,d){qa.call(this,a,b,c,d)}function pd(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");
12071 if(void 0===b||0===b.length)throw Error("no keyframes in track named "+a);this.name=a;this.times=ma.convertArray(b,this.TimeBufferType);this.values=ma.convertArray(c,this.ValueBufferType);this.setInterpolation(d||this.DefaultInterpolation);this.validate();this.optimize()}function bc(a,b,c,d){ub.call(this,a,b,c,d)}function qd(a,b,c,d){qa.call(this,a,b,c,d)}function Nc(a,b,c,d){ub.call(this,a,b,c,d)}function cc(a,b,c,d){ub.call(this,a,b,c,d)}function rd(a,b,c,d){ub.call(this,a,b,c,d)}function sd(a,
12072 b,c){ub.call(this,a,b,c)}function td(a,b,c,d){ub.call(this,a,b,c,d)}function vb(a,b,c,d){ub.apply(this,arguments)}function Ha(a,b,c){this.name=a;this.tracks=c;this.duration=void 0!==b?b:-1;this.uuid=T.generateUUID();0>this.duration&&this.resetDuration();this.optimize()}function ud(a){this.manager=void 0!==a?a:Ga;this.textures={}}function Id(a){this.manager=void 0!==a?a:Ga}function wb(){this.onLoadStart=function(){};this.onLoadProgress=function(){};this.onLoadComplete=function(){}}function Jd(a){"boolean"===
12073 typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),a=void 0);this.manager=void 0!==a?a:Ga;this.withCredentials=!1}function xe(a){this.manager=void 0!==a?a:Ga;this.texturePath=""}function ia(){}function Sa(a,b){this.v1=a;this.v2=b}function Oc(){this.curves=[];this.autoClose=!1}function Va(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=
12074 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(){Pc.apply(this,arguments);this.holes=[]}function Pc(a){Oc.call(this);this.currentPoint=new B;a&&this.fromPoints(a)}function Kd(){this.subPaths=[];this.currentPath=null}function Ld(a){this.data=a}function ye(a){this.manager=void 0!==a?a:Ga}function Md(){void 0===Nd&&(Nd=new (window.AudioContext||window.webkitAudioContext));return Nd}function Od(a){this.manager=
12075 void 0!==a?a:Ga}function ze(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new Ea;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new Ea;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=!1}function vd(a,b,c){z.call(this);this.type="CubeCamera";var d=new Ea(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new q(1,0,0));this.add(d);var e=new Ea(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new q(-1,0,0));this.add(e);var f=new Ea(90,1,a,b);f.up.set(0,0,1);f.lookAt(new q(0,
12076 1,0));this.add(f);var g=new Ea(90,1,a,b);g.up.set(0,0,-1);g.lookAt(new q(0,-1,0));this.add(g);var h=new Ea(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new q(0,0,1));this.add(h);var k=new Ea(90,1,a,b);k.up.set(0,-1,0);k.lookAt(new q(0,0,-1));this.add(k);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,p=c.texture.generateMipmaps;c.texture.generateMipmaps=!1;c.activeCubeFace=0;a.render(b,
12077 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=p;c.activeCubeFace=5;a.render(b,k,c);a.setRenderTarget(null)}}function Pd(){z.call(this);this.type="AudioListener";this.context=Md();this.gain=this.context.createGain();this.gain.connect(this.context.destination);this.filter=null}function dc(a){z.call(this);this.type="Audio";this.context=a.context;this.source=this.context.createBufferSource();
12078 this.source.onended=this.onEnded.bind(this);this.gain=this.context.createGain();this.gain.connect(a.getInput());this.autoplay=!1;this.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";this.filters=[]}function Qd(a){dc.call(this,a);this.panner=this.context.createPanner();this.panner.connect(this.gain)}function Rd(a,b){this.analyser=a.context.createAnalyser();this.analyser.fftSize=void 0!==b?b:2048;this.data=new Uint8Array(this.analyser.frequencyBinCount);
12079 a.getOutput().connect(this.analyser)}function wd(a,b,c){this.binding=a;this.valueSize=c;a=Float64Array;switch(b){case "quaternion":b=this._slerp;break;case "string":case "bool":a=Array;b=this._select;break;default:b=this._lerp}this.buffer=new a(4*c);this._mixBufferRegion=b;this.referenceCount=this.useCount=this.cumulativeWeight=0}function fa(a,b,c){this.path=b;this.parsedPath=c||fa.parseTrackName(b);this.node=fa.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function Sd(a){this.uuid=T.generateUUID();
12080 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},get inUse(){return this.total-e.nCachedObjects_}},get bindingsPerObject(){return e._bindings.length}}}function Td(a,b,c){this._mixer=a;this._clip=b;this._localRoot=c||null;a=b.tracks;
12081 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=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=
12082 !0;this.clampWhenFinished=!1;this.zeroSlopeAtEnd=this.zeroSlopeAtStart=!0}function Ud(a){this._root=a;this._initMemoryManager();this.time=this._accuIndex=0;this.timeScale=1}function Ae(a,b){"string"===typeof a&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),a=b);this.value=a}function Bb(){G.call(this);this.type="InstancedBufferGeometry";this.maxInstancedCount=void 0}function Vd(a,b,c,d){this.uuid=T.generateUUID();this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0===
12083 d}function ec(a,b){this.uuid=T.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.version=0}function fc(a,b,c){ec.call(this,a,b);this.meshPerAttribute=c||1}function gc(a,b,c){C.call(this,a,b);this.meshPerAttribute=c||1}function Wd(a,b,c,d){this.ray=new ab(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.");
12084 return this.Points}}})}function Be(a,b){return a.distance-b.distance}function Xd(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++)Xd(a[d],b,c,!0)}}function Yd(a){this.autoStart=void 0!==a?a:!0;this.elapsedTime=this.oldTime=this.startTime=0;this.running=!1}function Zd(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 na(a,b){ya.call(this,a,b);this.animationsMap={};this.animationsList=[];var c=this.geometry.morphTargets.length;
12085 this.createAnimation("__default",0,c-1,c/1);this.setAnimationWeight("__default",1)}function Qc(a){z.call(this);this.material=a;this.render=function(a){}}function Rc(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 G;b=new ha(6*b,3);c.addAttribute("position",b);la.call(this,c,new oa({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}
12086 function hc(a){z.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;a=new G;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 ha(b,3));b=new oa({fog:!1});this.cone=new la(a,b);this.add(this.cone);this.update()}function ic(a){this.bones=this.getBoneList(a);for(var b=new Q,
12087 c=0;c<this.bones.length;c++){var d=this.bones[c];d.parent&&d.parent.isBone&&(b.vertices.push(new q),b.vertices.push(new q),b.colors.push(new O(0,0,1)),b.colors.push(new O(0,1,0)))}b.dynamic=!0;c=new oa({vertexColors:2,depthTest:!1,depthWrite:!1,transparent:!0});la.call(this,b,c);this.root=a;this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.update()}function jc(a,b){this.light=a;this.light.updateMatrixWorld();var c=new mb(b,4,2),d=new Ma({wireframe:!0,fog:!1});d.color.copy(this.light.color).multiplyScalar(this.light.intensity);
12088 ya.call(this,c,d);this.matrix=this.light.matrixWorld;this.matrixAutoUpdate=!1}function kc(a,b){z.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.colors=[new O,new O];var c=new Vb(b,4,2);c.rotateX(-Math.PI/2);for(var d=0;8>d;d++)c.faces[d].color=this.colors[4>d?0:1];d=new Ma({vertexColors:1,wireframe:!0});this.lightSphere=new ya(c,d);this.add(this.lightSphere);this.update()}function Sc(a,b,c,d){b=b||1;c=new O(void 0!==c?c:4473924);d=new O(void 0!==
12089 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 n=k===e?c:d;n.toArray(h,m);m+=3;n.toArray(h,m);m+=3;n.toArray(h,m);m+=3;n.toArray(h,m);m+=3}a=new G;a.addAttribute("position",new ha(g,3));a.addAttribute("color",new ha(h,3));g=new oa({vertexColors:2});la.call(this,a,g)}function Tc(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.");
12090 c=new G;b=new ha(6*b,3);c.addAttribute("position",b);la.call(this,c,new oa({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function lc(a,b){z.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;void 0===b&&(b=1);var c=new G;c.addAttribute("position",new ha([-b,b,0,b,b,0,b,-b,0,-b,-b,0,-b,b,0],3));var d=new oa({fog:!1});this.add(new Ta(c,d));c=new G;c.addAttribute("position",new ha([0,0,0,0,0,1],3));this.add(new Ta(c,d));this.update()}
12091 function Uc(a){function b(a,b,d){c(a,d);c(b,d)}function c(a,b){d.vertices.push(new q);d.colors.push(new O(b));void 0===f[a]&&(f[a]=[]);f[a].push(d.vertices.length-1)}var d=new Q,e=new oa({color:16777215,vertexColors:1}),f={};b("n1","n2",16755200);b("n2","n4",16755200);b("n4","n3",16755200);b("n3","n1",16755200);b("f1","f2",16755200);b("f2","f4",16755200);b("f4","f3",16755200);b("f3","f1",16755200);b("n1","f1",16755200);b("n2","f2",16755200);b("n3","f3",16755200);b("n4","f4",16755200);b("p","n1",16711680);
12092 b("p","n2",16711680);b("p","n3",16711680);b("p","n4",16711680);b("u1","u2",43775);b("u2","u3",43775);b("u3","u1",43775);b("c","t",16777215);b("p","c",3355443);b("cn1","cn2",3355443);b("cn3","cn4",3355443);b("cf1","cf2",3355443);b("cf3","cf4",3355443);la.call(this,d,e);this.camera=a;this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.pointMap=f;this.update()}function Vc(a,b){var c=void 0!==b?b:8947848;this.object=a;this.box=
12093 new Ba;ya.call(this,new ob(1,1,1),new Ma({color:c,wireframe:!0}))}function Wc(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]),d=new Float32Array(24),e=new G;e.setIndex(new C(c,1));e.addAttribute("position",new C(d,3));la.call(this,e,new oa({color:b}));void 0!==a&&this.update(a)}function Cb(a,b,c,d,e,f){z.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 Ta(Ce,new oa({color:d}));
12094 this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new ya(De,new Ma({color:d}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);this.setDirection(a);this.setLength(c,e,f)}function xd(a){a=a||1;var b=new Float32Array([0,0,0,a,0,0,0,0,0,0,a,0,0,0,0,0,0,a]),c=new Float32Array([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1]);a=new G;a.addAttribute("position",new C(b,3));a.addAttribute("color",new C(c,3));b=new oa({vertexColors:2});la.call(this,a,b)}function Ee(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.");
12095 $d.call(this,a);this.type="catmullrom";this.closed=!0}function yd(a,b,c,d,e,f){Va.call(this,a,b,c,c,d,e,f)}void 0===Number.EPSILON&&(Number.EPSILON=Math.pow(2,-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*)\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");
12096 for(var b=Object(a),c=1;c<arguments.length;c++){var d=arguments[c];if(void 0!==d&&null!==d)for(var e in d)Object.prototype.hasOwnProperty.call(d,e)&&(b[e]=d[e])}return b}}();Object.assign(sa.prototype,{addEventListener:function(a,b){void 0===this._listeners&&(this._listeners={});var c=this._listeners;void 0===c[a]&&(c[a]=[]);-1===c[a].indexOf(b)&&c[a].push(b)},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)?!0:!1},
12097 removeEventListener:function(a,b){if(void 0!==this._listeners){var c=this._listeners[a];if(void 0!==c){var d=c.indexOf(b);-1!==d&&c.splice(d,1)}}},dispatchEvent:function(a){if(void 0!==this._listeners){var b=this._listeners[a.type];if(void 0!==b){a.target=this;var c=[],d,e=b.length;for(d=0;d<e;d++)c[d]=b[d];for(d=0;d<e;d++)c[d].call(this,a)}}}});var Fe={NoBlending:0,NormalBlending:1,AdditiveBlending:2,SubtractiveBlending:3,MultiplyBlending:4,CustomBlending:5},Ge={UVMapping:300,CubeReflectionMapping:301,
12098 CubeRefractionMapping:302,EquirectangularReflectionMapping:303,EquirectangularRefractionMapping:304,SphericalReflectionMapping:305,CubeUVReflectionMapping:306,CubeUVRefractionMapping:307},ae={RepeatWrapping:1E3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002},be={NearestFilter:1003,NearestMipMapNearestFilter:1004,NearestMipMapLinearFilter:1005,LinearFilter:1006,LinearMipMapNearestFilter:1007,LinearMipMapLinearFilter:1008},T={DEG2RAD:Math.PI/180,RAD2DEG:180/Math.PI,generateUUID:function(){var a=
12099 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),b=Array(36),c=0,d;return function(){for(var e=0;36>e;e++)8===e||13===e||18===e||23===e?b[e]="-":14===e?b[e]="4":(2>=c&&(c=33554432+16777216*Math.random()|0),d=c&15,c>>=4,b[e]=a[19===e?d&3|8:d]);return b.join("")}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a,b){return(a%b+b)%b},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},lerp:function(a,b,c){return(1-c)*a+c*b},smoothstep:function(a,
12100 b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*(3-2*a)},smootherstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*a*(a*(6*a-15)+10)},random16:function(){console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead.");return Math.random()},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*
12101 T.DEG2RAD},radToDeg:function(a){return a*T.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}};B.prototype={constructor:B,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=
12102 a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,b){if(void 0!==
12103 b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this},addScalar:function(a){this.x+=a;this.y+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),
12104 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;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,
12105 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 B,b=new B);a.set(c,c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.multiplyScalar(Math.max(a,Math.min(b,c))/c)},floor:function(){this.x=Math.floor(this.x);this.y=
12106 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);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*
12107 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))},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/
12108 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+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&&(c=0);b=b*a.itemSize+c;this.x=a.array[b];this.y=a.array[b+
12109 1];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}};da.DEFAULT_IMAGE=void 0;da.DEFAULT_MAPPING=300;da.prototype={constructor:da,isTexture:!0,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=
12110 a.minFilter;this.anisotropy=a.anisotropy;this.format=a.format;this.type=a.type;this.offset.copy(a.offset);this.repeat.copy(a.repeat);this.generateMipmaps=a.generateMipmaps;this.premultiplyAlpha=a.premultiplyAlpha;this.flipY=a.flipY;this.unpackAlignment=a.unpackAlignment;this.encoding=a.encoding;return this},toJSON:function(a){if(void 0!==a.textures[this.uuid])return a.textures[this.uuid];var b={metadata:{version:4.4,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,
12111 repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var c=this.image;void 0===c.uuid&&(c.uuid=T.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,
12112 0,0,c.width,c.height));g=2048<g.width||2048<g.height?g.toDataURL("image/jpeg",.6):g.toDataURL("image/png");d[e]={uuid:f,url:g}}b.image=c.uuid}return a.textures[this.uuid]=b},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(a){if(300===this.mapping){a.multiply(this.repeat);a.add(this.offset);if(0>a.x||1<a.x)switch(this.wrapS){case 1E3:a.x-=Math.floor(a.x);break;case 1001:a.x=0>a.x?0:1;break;case 1002:a.x=1===Math.abs(Math.floor(a.x)%2)?Math.ceil(a.x)-a.x:a.x-Math.floor(a.x)}if(0>
12113 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(da.prototype,sa.prototype);var ee=0;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;
12114 return this},setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;case 3:this.w=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,
12115 this.y,this.z,this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},
12116 addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;this.w-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(a){isFinite(a)?
12117 (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=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=
12118 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>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):
12119 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)/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);
12120 this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);this.w=Math.max(this.w,a.w);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));this.w=Math.max(a.w,Math.min(b.w,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);
12121 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);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);
12122 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*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)},
12123 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,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=
12124 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&&(c=0);b=b*a.itemSize+c;this.x=a.array[b];this.y=a.array[b+1];this.z=a.array[b+2];this.w=a.array[b+3];return this}};Object.assign(Db.prototype,sa.prototype,{isWebGLRenderTarget:!0,setSize:function(a,b){if(this.width!==a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0,
12125 0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone();this.depthBuffer=a.depthBuffer;this.stencilBuffer=a.stencilBuffer;this.depthTexture=a.depthTexture;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Eb.prototype=Object.create(Db.prototype);Eb.prototype.constructor=Eb;Eb.prototype.isWebGLRenderTargetCube=!0;ba.prototype={constructor:ba,get x(){return this._x},
12126 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=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();
12127 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/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=
12128 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+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=
12129 Math.cos(c);this.onChangeCallback();return this},setFromRotationMatrix:function(a){var b=a.elements,c=b[0];a=b[4];var d=b[8],e=b[1],f=b[5],g=b[9],h=b[2],k=b[6],b=b[10],m=c+f+b;0<m?(c=.5/Math.sqrt(m+1),this._w=.25/c,this._x=(k-g)*c,this._y=(d-h)*c,this._z=(e-a)*c):c>f&&c>b?(c=2*Math.sqrt(1+c-f-b),this._w=(k-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y=.25*c,this._z=(g+k)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+
12130 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,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*
12131 a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this},multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),
12132 this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z,f=a._w,g=b._x,h=b._y,k=b._z,m=b._w;this._x=c*m+f*g+d*k-e*h;this._y=d*m+f*h+e*g-c*k;this._z=e*m+f*k+c*h-d*g;this._w=f*m-c*g-d*h-e*k;this.onChangeCallback();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;
12133 0>g?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a);if(1<=g)return this._w=f,this._x=c,this._y=d,this._z=e,this;var h=Math.sqrt(1-g*g);if(.001>Math.abs(h))return this._w=.5*(f+this._w),this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var k=Math.atan2(h,g),g=Math.sin((1-b)*k)/h,h=Math.sin(b*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===
12134 this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+1];this._z=a[b+2];this._w=a[b+3];this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}};Object.assign(ba,{slerp:function(a,b,c,d){return c.copy(a).slerp(b,d)},slerpFlat:function(a,
12135 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],n=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==l||m!==n){f=1-g;var p=h*d+k*l+m*n+c*e,r=0<=p?1:-1,x=1-p*p;x>Number.EPSILON&&(x=Math.sqrt(x),p=Math.atan2(x,p*r),f=Math.sin(f*p)/x,g=Math.sin(g*p)/x);r*=g;h=h*f+d*r;k=k*f+l*r;m=m*f+n*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},
12136 setScalar:function(a){this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;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,
12137 this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},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+=
12138 a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=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."),
12139 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,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 ba);return this.applyQuaternion(a.setFromEuler(b))}}(),
12140 applyAxisAngle:function(){var a;return function(b,c){void 0===a&&(a=new ba);return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[3]*c+a[6]*d;this.y=a[1]*b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12];this.y=a[1]*b+a[5]*c+a[9]*d+a[13];this.z=a[2]*b+a[6]*c+a[10]*d+a[14];return this},applyProjection:function(a){var b=
12141 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]*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 J);
12142 a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyProjection(a)}}(),unproject:function(){var a;return function(b){void 0===a&&(a=new J);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/=
12143 a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);return this},max:function(a){this.x=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,
12144 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,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},
12145 roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x=-this.x;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)+
12146 Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*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,
12147 b);var c=this.x,d=this.y,e=this.z;this.x=d*a.z-e*a.y;this.y=e*a.x-c*a.z;this.z=c*a.y-d*a.x;return this},crossVectors:function(a,b){var c=a.x,d=a.y,e=a.z,f=b.x,g=b.y,h=b.z;this.x=d*h-e*g;this.y=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===
12148 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()*a.lengthSq());return Math.acos(T.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;
12149 this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)*a.radius;this.z=b*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 ).");
12150 var c=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&&(c=0);b=b*a.itemSize+c;this.x=a.array[b];this.y=a.array[b+1];this.z=a.array[b+2];return this}};J.prototype={constructor:J,isMatrix4:!0,
12151 set:function(a,b,c,d,e,f,g,h,k,m,l,n,p,r,x,t){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]=n;q[3]=p;q[7]=r;q[11]=x;q[15]=t;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 J).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]=a[13];b[14]=a[14];return this},extractBasis:function(a,
12152 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;c[1]=d[1]*e;c[2]=d[2]*e;c[4]=d[4]*f;c[5]=d[5]*f;c[6]=d[6]*
12153 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-l*d;b[9]=-c*g;b[2]=l-a*d;b[6]=m+k*d;b[10]=f*g}else"YXZ"===
12154 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-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*
12155 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-h;b[6]=d+g;b[10]=1-(a+l);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=
12156 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!==b?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),
12157 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],n=c[9],p=c[13],r=c[2],x=c[6],t=c[10],q=c[14],u=c[3],v=c[7],I=c[11],c=c[15],y=d[0],E=d[4],H=d[8],F=d[12],M=d[1],B=d[5],K=d[9],z=d[13],C=d[2],G=d[6],J=d[10],N=d[14],P=d[3],R=d[7],S=d[11],d=d[15];e[0]=f*y+g*M+h*C+k*P;e[4]=f*E+g*B+h*G+k*R;e[8]=f*H+g*K+h*J+k*S;e[12]=
12158 f*F+g*z+h*N+k*d;e[1]=m*y+l*M+n*C+p*P;e[5]=m*E+l*B+n*G+p*R;e[9]=m*H+l*K+n*J+p*S;e[13]=m*F+l*z+n*N+p*d;e[2]=r*y+x*M+t*C+q*P;e[6]=r*E+x*B+t*G+q*R;e[10]=r*H+x*K+t*J+q*S;e[14]=r*F+x*z+t*N+q*d;e[3]=u*y+v*M+I*C+c*P;e[7]=u*E+v*B+I*G+c*R;e[11]=u*H+v*K+I*J+c*S;e[15]=u*F+v*z+I*N+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]=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];
12159 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+=3)a.fromArray(b,c),a.applyMatrix4(this),a.toArray(b,c);return b}}(),applyToBuffer:function(){var a;return function(b,
12160 c,d){void 0===a&&(a=new q);void 0===c&&(c=0);void 0===d&&(d=b.length/b.itemSize);for(var e=0;e<d;e++,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],n=a[10],p=a[14];return a[3]*(+e*h*l-d*k*l-e*g*n+c*k*n+d*g*p-c*h*p)+a[7]*(+b*h*p-b*k*n+e*f*n-d*f*p+d*k*m-e*h*m)+a[11]*(+b*k*l-b*g*p-e*f*l+c*f*p+e*g*m-c*k*m)+a[15]*(-d*g*m-b*h*l+b*g*n+
12161 d*f*l-c*f*n+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},flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix3: .flattenToArrayOffset is deprecated - just 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.");
12162 return a.setFromMatrixColumn(this,3)}}(),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],n=d[7],p=d[8],r=d[9],x=d[10],t=d[11],q=d[12],u=d[13],v=d[14],d=d[15],I=r*v*n-u*x*n+u*l*t-m*v*t-r*l*d+m*x*d,y=q*x*n-p*v*n-q*l*t+k*v*t+p*l*d-k*x*d,E=p*u*n-q*r*n+q*m*t-k*u*t-p*m*d+k*r*d,H=q*r*l-p*u*l-q*m*x+k*u*x+p*m*v-k*r*v,F=e*I+f*y+g*E+h*H;if(0===F){if(!0===b)throw Error("THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0");
12163 console.warn("THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0");return this.identity()}F=1/F;c[0]=I*F;c[1]=(u*x*h-r*v*h-u*g*t+f*v*t+r*g*d-f*x*d)*F;c[2]=(m*v*h-u*l*h+u*g*n-f*v*n-m*g*d+f*l*d)*F;c[3]=(r*l*h-m*x*h-r*g*n+f*x*n+m*g*t-f*l*t)*F;c[4]=y*F;c[5]=(p*v*h-q*x*h+q*g*t-e*v*t-p*g*d+e*x*d)*F;c[6]=(q*l*h-k*v*h-q*g*n+e*v*n+k*g*d-e*l*d)*F;c[7]=(k*x*h-p*l*h+p*g*n-e*x*n-k*g*t+e*l*t)*F;c[8]=E*F;c[9]=(q*r*h-p*u*h-q*f*t+e*u*t+p*f*d-e*r*d)*F;c[10]=(k*u*h-q*m*h+q*f*n-e*u*n-k*f*d+e*m*d)*F;c[11]=
12164 (p*m*h-k*r*h-p*f*n+e*r*n+k*f*t-e*m*t)*F;c[12]=H*F;c[13]=(p*u*g-q*r*g+q*f*x-e*u*x-p*f*v+e*r*v)*F;c[14]=(q*m*g-k*u*g-q*f*l+e*u*l+k*f*v-e*m*v)*F;c[15]=(k*r*g-p*m*g+p*f*l-e*r*l-k*f*x+e*m*x)*F;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],
12165 a[8]*a[8]+a[9]*a[9]+a[10]*a[10]))},makeTranslation:function(a,b,c){this.set(1,0,0,a,0,1,0,b,0,0,1,c,0,0,0,1);return this},makeRotationX:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(1,0,0,0,0,b,-a,0,0,a,b,0,0,0,0,1);return this},makeRotationY:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,0,a,0,0,1,0,0,-a,0,b,0,0,0,0,1);return this},makeRotationZ:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,-a,0,0,a,b,0,0,0,0,1,0,0,0,0,1);return this},makeRotationAxis:function(a,b){var c=
12166 Math.cos(b),d=Math.sin(b),e=1-c,f=a.x,g=a.y,h=a.z,k=e*f,m=e*g;this.set(k*f+c,k*g-d*h,k*h+d*g,0,k*g+d*h,m*g+c,m*h-d*f,0,k*h-d*g,m*h+d*f,e*h*h+c,0,0,0,0,1);return this},makeScale:function(a,b,c){this.set(a,0,0,0,0,b,0,0,0,0,c,0,0,0,0,1);return this},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 J);var f=this.elements,g=a.set(f[0],f[1],f[2]).length(),h=a.set(f[4],
12167 f[5],f[6]).length(),k=a.set(f[8],f[9],f[10]).length();0>this.determinant()&&(g=-g);c.x=f[12];c.y=f[13];c.z=f[14];b.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);
12168 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]=0;g[11]=-1;g[15]=0;return this},makePerspective:function(a,b,c,d){a=c*Math.tan(T.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=
12169 this.elements;a=a.elements;for(var c=0;16>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;16>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;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}};Xa.prototype=Object.create(da.prototype);
12170 Xa.prototype.constructor=Xa;Xa.prototype.isCubeTexture=!0;Object.defineProperty(Xa.prototype,"images",{get:function(){return this.image},set:function(a){this.image=a}});var ie=new da,je=new Xa,fe=[],he=[];ne.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 zd=/([\w\d_]+)(\])?(\[|\.)?/g;Ya.prototype.setValue=function(a,b,c){b=this.map[b];void 0!==b&&b.setValue(a,c,this.renderer)};Ya.prototype.set=function(a,b,c){var d=this.map[c];
12171 void 0!==d&&d.setValue(a,b[c],this.renderer)};Ya.prototype.setOptional=function(a,b,c){b=b[c];void 0!==b&&this.setValue(a,c,b)};Ya.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)}};Ya.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 La={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=
12172 {},c;for(c in a){b[c]={};for(var d in a[c]){var e=a[c][d];e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture)?b[c][d]=e.clone():Array.isArray(e)?b[c][d]=e.slice():b[c][d]=e}}return b}},X={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",
12173 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",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",
12174 begin_vertex:"\nvec3 transformed = vec3( position );\n",beginnormal_vertex:"\nvec3 objectNormal = vec3( normal );\n",bsdfs:"bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) {\n\treturn any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) );\n}\nfloat 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}\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",
12175 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",
12176 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",
12177 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",
12178 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 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}\n",
12179 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",
12180 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",
12181 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",
12182 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",
12183 envmap_pars_fragment:"#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntenstiy;\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",
12184 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",
12185 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",
12186 lightmap_fragment:"#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_vertex:"vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n",
12187 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\tif ( testLightInRange( lightDistance, pointLight.distance ) ) {\n\t\t\tdirectLight.color = pointLight.color;\n\t\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.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_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 ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\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_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\t#include <normal_flip>\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = flipNormal * 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 = flipNormal * 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\t#include <normal_flip>\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 = flipNormal * 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 = flipNormal * 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( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * 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 = flipNormal * 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",
12188 lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n",lights_phong_pars_fragment:"varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\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\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n",
12189 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",
12190 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}\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_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",
12191 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 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",
12192 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",
12193 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",
12194 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",
12195 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",
12196 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",
12197 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",
12198 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",
12199 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",
12200 roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n",
12201 shadowmap_pars_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n",
12202 shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n",
12203 shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n",
12204 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",
12205 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",
12206 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",
12207 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",
12208 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",
12209 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",
12210 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",
12211 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",
12212 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",
12213 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",
12214 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",
12215 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 <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;\n\treflectedLight.directDiffuse = vec3( 0.0 );\n\treflectedLight.directSpecular = vec3( 0.0 );\n\treflectedLight.indirectDiffuse = diffuseColor.rgb;\n\treflectedLight.indirectSpecular = vec3( 0.0 );\n\t#include <aomap_fragment>\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",
12216 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",
12217 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",
12218 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",
12219 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 <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",
12220 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",
12221 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\nuniform float envMapIntensity;\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",
12222 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",
12223 normal_frag:"uniform float opacity;\nvarying vec3 vNormal;\n#include <common>\n#include <packing>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n\t#include <logdepthbuf_fragment>\n}\n",normal_vert:"varying vec3 vNormal;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvNormal = normalize( normalMatrix * normal );\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n",
12224 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",
12225 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",
12226 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"};O.prototype={constructor:O,
12227 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,
12228 c,d){b=T.euclideanModulo(b,1);c=T.clamp(c,0,1);d=T.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=
12229 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])/
12230 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=He[a],void 0!==
12231 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=
12232 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):
12233 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+=
12234 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=
12235 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 He={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,
12236 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,
12237 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,
12238 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,
12239 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,
12240 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},W={common:{diffuse:{value:new O(15658734)},opacity:{value:1},map:{value:null},offsetRepeat:{value:new ga(0,0,1,1)},specularMap:{value:null},alphaMap:{value:null},envMap:{value:null},flipEnvMap:{value:-1},
12241 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 B(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},
12242 fog:{fogDensity:{value:2.5E-4},fogNear:{value:1},fogFar:{value:2E3},fogColor:{value:new O(16777215)}},lights:{ambientLightColor:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},
12243 spotShadowMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}}},points:{diffuse:{value:new O(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},offsetRepeat:{value:new ga(0,0,1,1)}}},Gb={basic:{uniforms:La.merge([W.common,W.aomap,W.fog]),vertexShader:X.meshbasic_vert,
12244 fragmentShader:X.meshbasic_frag},lambert:{uniforms:La.merge([W.common,W.aomap,W.lightmap,W.emissivemap,W.fog,W.lights,{emissive:{value:new O(0)}}]),vertexShader:X.meshlambert_vert,fragmentShader:X.meshlambert_frag},phong:{uniforms:La.merge([W.common,W.aomap,W.lightmap,W.emissivemap,W.bumpmap,W.normalmap,W.displacementmap,W.fog,W.lights,{emissive:{value:new O(0)},specular:{value:new O(1118481)},shininess:{value:30}}]),vertexShader:X.meshphong_vert,fragmentShader:X.meshphong_frag},standard:{uniforms:La.merge([W.common,
12245 W.aomap,W.lightmap,W.emissivemap,W.bumpmap,W.normalmap,W.displacementmap,W.roughnessmap,W.metalnessmap,W.fog,W.lights,{emissive:{value:new O(0)},roughness:{value:.5},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:X.meshphysical_vert,fragmentShader:X.meshphysical_frag},points:{uniforms:La.merge([W.points,W.fog]),vertexShader:X.points_vert,fragmentShader:X.points_frag},dashed:{uniforms:La.merge([W.common,W.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:X.linedashed_vert,
12246 fragmentShader:X.linedashed_frag},depth:{uniforms:La.merge([W.common,W.displacementmap]),vertexShader:X.depth_vert,fragmentShader:X.depth_frag},normal:{uniforms:{opacity:{value:1}},vertexShader:X.normal_vert,fragmentShader:X.normal_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:X.cube_vert,fragmentShader:X.cube_frag},equirect:{uniforms:{tEquirect:{value:null},tFlip:{value:-1}},vertexShader:X.equirect_vert,fragmentShader:X.equirect_frag},distanceRGBA:{uniforms:{lightPos:{value:new q}},
12247 vertexShader:X.distanceRGBA_vert,fragmentShader:X.distanceRGBA_frag}};Gb.physical={uniforms:La.merge([Gb.standard.uniforms,{clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:X.meshphysical_vert,fragmentShader:X.meshphysical_frag};mc.prototype={constructor:mc,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 B;return function(b,
12248 c){var d=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(d);this.max.copy(b).add(d);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},makeEmpty:function(){this.min.x=this.min.y=Infinity;this.max.x=this.max.y=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y},getCenter:function(a){a=a||new B;return this.isEmpty()?a.set(0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},
12249 getSize:function(a){a=a||new B;return this.isEmpty()?a.set(0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&
12250 this.min.y<=a.min.y&&a.max.y<=this.max.y?!0:!1},getParameter:function(a,b){return(b||new B).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(a){return a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y?!1:!0},clampPoint:function(a,b){return(b||new B).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new B;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);
12251 this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}};U.prototype={constructor:U,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: '"+
12252 b+"' parameter is undefined.");else{var d=this[b];void 0===d?console.warn("THREE."+this.type+": '"+b+"' is not a property of this material."):d&&d.isColor?d.set(c):d&&d.isVector3&&c&&c.isVector3?d.copy(c):this[b]="overdraw"===b?Number(c):c}}},toJSON:function(a){function b(a){var b=[],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var c=void 0===a;c&&(a={textures:{},images:{}});var d={metadata:{version:4.4,type:"Material",generator:"Material.toJSON"}};d.uuid=this.uuid;d.type=this.type;
12253 ""!==this.name&&(d.name=this.name);this.color&&this.color.isColor&&(d.color=this.color.getHex());void 0!==this.roughness&&(d.roughness=this.roughness);void 0!==this.metalness&&(d.metalness=this.metalness);this.emissive&&this.emissive.isColor&&(d.emissive=this.emissive.getHex());this.specular&&this.specular.isColor&&(d.specular=this.specular.getHex());void 0!==this.shininess&&(d.shininess=this.shininess);this.map&&this.map.isTexture&&(d.map=this.map.toJSON(a).uuid);this.alphaMap&&this.alphaMap.isTexture&&
12254 (d.alphaMap=this.alphaMap.toJSON(a).uuid);this.lightMap&&this.lightMap.isTexture&&(d.lightMap=this.lightMap.toJSON(a).uuid);this.bumpMap&&this.bumpMap.isTexture&&(d.bumpMap=this.bumpMap.toJSON(a).uuid,d.bumpScale=this.bumpScale);this.normalMap&&this.normalMap.isTexture&&(d.normalMap=this.normalMap.toJSON(a).uuid,d.normalScale=this.normalScale.toArray());this.displacementMap&&this.displacementMap.isTexture&&(d.displacementMap=this.displacementMap.toJSON(a).uuid,d.displacementScale=this.displacementScale,
12255 d.displacementBias=this.displacementBias);this.roughnessMap&&this.roughnessMap.isTexture&&(d.roughnessMap=this.roughnessMap.toJSON(a).uuid);this.metalnessMap&&this.metalnessMap.isTexture&&(d.metalnessMap=this.metalnessMap.toJSON(a).uuid);this.emissiveMap&&this.emissiveMap.isTexture&&(d.emissiveMap=this.emissiveMap.toJSON(a).uuid);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=
12256 this.reflectivity);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;d.depthTest=this.depthTest;d.depthWrite=this.depthWrite;0<this.alphaTest&&
12257 (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;c&&(c=b(a.textures),a=b(a.images),0<c.length&&(d.textures=
12258 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=a.blendDstAlpha;this.blendEquationAlpha=a.blendEquationAlpha;
12259 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;a=a.clippingPlanes;var b=null;if(null!==a)for(var c=
12260 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(U.prototype,sa.prototype);var oe=0;Fa.prototype=Object.create(U.prototype);Fa.prototype.constructor=Fa;Fa.prototype.isShaderMaterial=!0;Fa.prototype.copy=function(a){U.prototype.copy.call(this,a);this.fragmentShader=a.fragmentShader;this.vertexShader=a.vertexShader;this.uniforms=La.clone(a.uniforms);
12261 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};Fa.prototype.toJSON=function(a){a=U.prototype.toJSON.call(this,a);a.uniforms=this.uniforms;a.vertexShader=this.vertexShader;a.fragmentShader=this.fragmentShader;return a};Za.prototype=Object.create(U.prototype);Za.prototype.constructor=
12262 Za;Za.prototype.isMeshDepthMaterial=!0;Za.prototype.copy=function(a){U.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};Ba.prototype={constructor:Ba,isBox3:!0,set:function(a,b){this.min.copy(a);
12263 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],n=a[h+2];m<b&&(b=m);l<c&&(c=l);n<d&&(d=n);m>e&&(e=m);l>f&&(f=l);n>g&&(g=n)}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);
12264 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();b.traverse(function(b){var e=b.geometry;if(void 0!==e)if(e&&e.isGeometry)for(var e=e.vertices,f=0,g=e.length;f<g;f++)a.copy(e[f]),a.applyMatrix4(b.matrixWorld),c.expandByPoint(a);else if(e&&e.isBufferGeometry&&(g=e.attributes.position,void 0!==g)){var h;g&&g.isInterleavedBufferAttribute?(e=g.data.array,f=g.offset,h=g.data.stride):
12265 (e=g.array,f=0,h=3);for(g=e.length;f<g;f+=h)a.fromArray(e,f),a.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=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;
12266 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);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||
12267 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?!0:!1},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)/(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||
12268 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*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*
12269 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()}}(),getBoundingSphere:function(){var a=new q;return function(b){b=b||new Ca;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);
12270 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);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,
12271 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);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}};Ca.prototype={constructor:Ca,set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a=
12272 new Ba;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);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)-
12273 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},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=
12274 a||new Ba;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)&&a.radius===this.radius}};Ia.prototype={constructor:Ia,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,
12275 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],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,
12276 c);return b}}(),applyToBuffer: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/b.itemSize);for(var e=0;e<d;e++,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;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],
12277 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],n=c[7],c=c[8],p=c*k-m*n,r=m*l-c*h,q=n*h-k*l,t=e*p+f*r+g*q;if(0===t){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()}t=
12278 1/t;d[0]=p*t;d[1]=(g*n-c*f)*t;d[2]=(m*f-g*k)*t;d[3]=r*t;d[4]=(c*e-g*l)*t;d[5]=(g*h-m*e)*t;d[6]=q*t;d[7]=(f*l-n*e)*t;d[8]=(k*e-f*h)*t;return this},transpose:function(){var a,b=this.elements;a=b[1];b[1]=b[3];b[3]=a;a=b[2];b[2]=b[6];b[6]=a;a=b[5];b[5]=b[7];b[7]=a;return this},flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix3: .flattenToArrayOffset is deprecated - just use .toArray instead.");return this.toArray(a,b)},getNormalMatrix:function(a){return this.setFromMatrix4(a).getInverse(this).transpose()},
12279 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}};va.prototype={constructor:va,set:function(a,b){this.normal.copy(a);
12280 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);
12281 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||
12282 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)},
12283 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 Ia;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===
12284 this.constant}};nc.prototype={constructor:nc,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],n=c[9],p=c[10],r=c[11],q=c[12],t=c[13],D=c[14],c=c[15];
12285 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+n,c+t).normalize();b[3].setComponents(f-d,m-h,r-n,c-t).normalize();b[4].setComponents(f-e,m-k,r-p,c-D).normalize();b[5].setComponents(f+e,m+k,r+p,c+D).normalize();return this},intersectsObject:function(){var a=new Ca;return function(b){var c=b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),
12286 intersectsSprite:function(){var a=new Ca;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?
12287 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}};ab.prototype={constructor:ab,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);
12288 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)},
12289 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);
12290 var h=.5*d.distanceTo(e),k=-this.direction.dot(b),m=c.dot(this.direction),l=-c.dot(b),n=c.lengthSq(),p=Math.abs(1-k*k),r;0<p?(d=k*l-m,e=k*m-l,r=h*p,0<=d?e>=-r?e<=r?(h=1/p,d*=h,e*=h,k=d*(d+k*e+2*m)+e*(k*d+e+2*l)+n):(e=h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+n):(e=-h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+n):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)+n):e<=r?(d=0,e=Math.min(Math.max(-h,-l),h),k=e*(e+2*l)+n):(d=Math.max(0,-(k*h+m)),e=0<d?h:Math.min(Math.max(-h,
12291 -l),h),k=-d*d+e*(e+2*l)+n)):(e=0<k?-h:h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+n);f&&f.copy(this.direction).multiplyScalar(d).add(this.origin);g&&g.copy(b).multiplyScalar(e).add(a);return k}}(),intersectSphere:function(){var a=new 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)<=
12292 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;
12293 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=
12294 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);
12295 this.direction.sub(this.origin);this.direction.normalize();return this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}};bb.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" ");bb.DefaultOrder="XYZ";bb.prototype={constructor:bb,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},
12296 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=T.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],n=e[6],e=e[10];b=b||
12297 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(n,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(n,-1,1)),.99999>Math.abs(n)?(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>
12298 Math.abs(l)?(this._x=Math.atan2(n,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(n,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();
12299 return this},setFromQuaternion:function(){var a;return function(b,c,d){void 0===a&&(a=new J);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 ba;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];
12300 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(){}};Yc.prototype={constructor:Yc,set:function(a){this.mask=1<<a},enable:function(a){this.mask|=1<<a},toggle:function(a){this.mask^=
12301 1<<a},disable:function(a){this.mask&=~(1<<a)},test:function(a){return 0!==(this.mask&a.mask)}};z.DefaultUp=new q(0,1,0);z.DefaultMatrixAutoUpdate=!0;Object.assign(z.prototype,sa.prototype,{isObject3D:!0,applyMatrix:function(a){this.matrix.multiplyMatrices(a,this.matrix);this.matrix.decompose(this.position,this.quaternion,this.scale)},setRotationFromAxisAngle:function(a,b){this.quaternion.setFromAxisAngle(a,b)},setRotationFromEuler:function(a){this.quaternion.setFromEuler(a,!0)},setRotationFromMatrix:function(a){this.quaternion.setFromRotationMatrix(a)},
12302 setRotationFromQuaternion:function(a){this.quaternion.copy(a)},rotateOnAxis:function(){var a=new ba;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;
12303 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=
12304 new J;return function(b){return b.applyMatrix4(a.getInverse(this.matrixWorld))}}(),lookAt:function(){var a=new J;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"}),
12305 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]===
12306 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 ba;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,c,b);return c}}(),getWorldRotation:function(){var a=new ba;return function(b){b=b||new bb;this.getWorldQuaternion(a);
12307 return b.setFromQuaternion(a,this.rotation.order,!1)}}(),getWorldScale:function(){var a=new q,b=new ba;return function(c){c=c||new q;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,b,c);return c}}(),getWorldDirection:function(){var a=new ba;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);
12308 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,
12309 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=
12310 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=
12311 [];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);
12312 this.matrix.copy(a.matrix);this.matrixWorld.copy(a.matrixWorld);this.matrixAutoUpdate=a.matrixAutoUpdate;this.matrixWorldNeedsUpdate=a.matrixWorldNeedsUpdate;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}});var qe=0;gb.prototype={constructor:gb,set:function(a,
12313 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)},at:function(a,b){var c=b||new q;
12314 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=T.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);return this},equals:function(a){return a.start.equals(this.start)&&
12315 a.end.equals(this.end)}};wa.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)}}();wa.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=h||new q;if(0===m)return h.set(-2,-1,-1);m=1/m;k=(k*f-e*g)*m;d=(d*g-
12316 e*f)*m;return h.set(1-k-d,d,k)}}();wa.containsPoint=function(){var a=new q;return function(b,c,d,e){b=wa.barycoordFromPoint(b,c,d,e,a);return 0<=b.x&&0<=b.y&&1>=b.x+b.y}}();wa.prototype={constructor:wa,set:function(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this},setFromPointsAndIndices:function(a,b,c,d){this.a.copy(a[b]);this.b.copy(a[c]);this.c.copy(a[d]);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a.copy(a.a);this.b.copy(a.b);this.c.copy(a.c);
12317 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 wa.normal(this.a,this.b,this.c,a)},plane:function(a){return(a||new va).setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return wa.barycoordFromPoint(a,this.a,this.b,this.c,b)},containsPoint:function(a){return wa.containsPoint(a,
12318 this.a,this.b,this.c)},closestPointToPoint:function(){var a,b,c,d;return function(e,f){void 0===a&&(a=new va,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=c.distanceToSquared(d);m<h&&(h=m,g.copy(d))}}return g}}(),equals:function(a){return a.a.equals(this.a)&&
12319 a.b.equals(this.b)&&a.c.equals(this.c)}};ea.prototype={constructor:ea,clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a=a.a;this.b=a.b;this.c=a.c;this.normal.copy(a.normal);this.color.copy(a.color);this.materialIndex=a.materialIndex;for(var b=0,c=a.vertexNormals.length;b<c;b++)this.vertexNormals[b]=a.vertexNormals[b].clone();b=0;for(c=a.vertexColors.length;b<c;b++)this.vertexColors[b]=a.vertexColors[b].clone();return this}};Ma.prototype=Object.create(U.prototype);Ma.prototype.constructor=
12320 Ma;Ma.prototype.isMeshBasicMaterial=!0;Ma.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;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;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=
12321 a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;return this};C.prototype={constructor:C,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/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=
12322 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<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",d),f=new O);b[c++]=f.r;b[c++]=f.g;b[c++]=f.b}return this},copyIndicesArray:function(a){for(var b=
12323 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 B);b[c++]=f.x;b[c++]=f.y}return this},copyVector3sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector3sArray(): vector is undefined",
12324 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},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*
12325 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*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]=
12326 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},clone:function(){return(new this.constructor).copy(this)}};Object.assign(Q.prototype,sa.prototype,{isGeometry:!0,applyMatrix:function(a){for(var b=(new Ia).getNormalMatrix(a),c=0,d=this.vertices.length;c<d;c++)this.vertices[c].applyMatrix4(a);c=0;for(d=this.faces.length;c<d;c++){a=this.faces[c];a.normal.applyMatrix3(b).normalize();for(var e=0,f=a.vertexNormals.length;e<
12327 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 J);a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a;return function(b){void 0===a&&(a=new J);a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a;return function(b){void 0===
12328 a&&(a=new J);a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a;return function(b,c,d){void 0===a&&(a=new J);a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a;return function(b,c,d){void 0===a&&(a=new J);a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a;return function(b){void 0===a&&(a=new z);a.lookAt(b);a.updateMatrix();this.applyMatrix(a.matrix)}}(),fromBufferGeometry:function(a){function b(a,b,d,e){var f=
12329 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 ea(a,b,d,f,r,e);c.faces.push(e);void 0!==k&&c.faceVertexUvs[0].push([n[a].clone(),n[b].clone(),n[d].clone()]);void 0!==m&&c.faceVertexUvs[1].push([p[a].clone(),p[b].clone(),p[d].clone()])}var c=this,d=null!==a.index?a.index.array:void 0,e=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!==
12330 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=[],n=[],p=[],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 O(h[e],h[e+1],h[e+2])),void 0!==k&&n.push(new B(k[r],k[r+1])),void 0!==m&&p.push(new B(m[r],m[r+1]));if(void 0!==d)if(f=a.groups,0<f.length)for(e=0;e<f.length;e++)for(var x=f[e],t=x.start,D=x.count,r=t,t=t+D;r<t;r+=3)b(d[r],d[r+1],d[r+
12331 2],x.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,a.y,a.z);return a},normalize:function(){this.computeBoundingSphere();var a=this.boundingSphere.center,b=this.boundingSphere.radius,
12332 b=0===b?1:1/b,c=new J;c.set(b,0,0,-b*a.x,0,b,0,-b*a.y,0,0,b,-b*a.z,0,0,0,1);this.applyMatrix(c);return this},computeFaceNormals:function(){for(var a=new 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===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,
12333 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<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?
12334 (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]=c.normal.clone(),d[1]=c.normal.clone(),d[2]=c.normal.clone())}0<this.faces.length&&(this.normalsNeedUpdate=
12335 !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]=e.vertexNormals[a].clone();var f=new Q;f.faces=this.faces;a=0;for(b=this.morphTargets.length;a<
12336 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();c=0;for(d=this.faces.length;c<d;c++)e=this.faces[c],h=g.faceNormals[c],k=g.vertexNormals[c],
12337 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},computeTangents:function(){console.warn("THREE.Geometry: .computeTangents() has been removed.")},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===
12338 this.boundingBox&&(this.boundingBox=new Ba);this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new Ca);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],n=this.colors,
12339 p=a.colors;void 0===c&&(c=0);void 0!==b&&(d=(new Ia).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=p.length;a<r;a++)n.push(p[a].clone());a=0;for(r=k.length;a<r;a++){var g=k[a],t=g.vertexNormals,p=g.vertexColors,n=new ea(g.a+e,g.b+e,g.c+e);n.normal.copy(g.normal);void 0!==d&&n.normal.applyMatrix3(d).normalize();b=0;for(f=t.length;b<f;b++)q=t[b].clone(),void 0!==d&&q.applyMatrix3(d).normalize(),n.vertexNormals.push(q);n.color.copy(g.color);
12340 b=0;for(f=p.length;b<f;b++)q=p[b],n.vertexColors.push(q.clone());n.materialIndex=g.materialIndex+c;h.push(n)}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<
12341 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=
12342 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()+
12343 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!==n[b])return n[b];n[b]=l.length;l.push(a.getHex());return n[b]}function d(a){var b=a.x.toString()+a.y.toString();if(void 0!==r[b])return r[b];r[b]=p.length/2;p.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!==
12344 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=[],n={},p=[],r={};for(g=0;g<this.faces.length;g++){var q=this.faces[g],t=void 0!==this.faceVertexUvs[0][g],D=0<q.normal.length(),u=0<q.vertexNormals.length,v=1!==q.color.r||1!==q.color.g||1!==q.color.b,I=0<q.vertexColors.length,y=0,y=a(y,0,0),y=a(y,1,!0),y=a(y,2,!1),y=a(y,3,t),y=a(y,4,D),y=a(y,5,u),y=a(y,6,
12345 v),y=a(y,7,I);h.push(y);h.push(q.a,q.b,q.c);h.push(q.materialIndex);t&&(t=this.faceVertexUvs[0][g],h.push(d(t[0]),d(t[1]),d(t[2])));D&&h.push(b(q.normal));u&&(D=q.vertexNormals,h.push(b(D[0]),b(D[1]),b(D[2])));v&&h.push(c(q.color));I&&(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<p.length&&(e.data.uvs=[p]);e.data.faces=h;return e},clone:function(){return(new Q).copy(this)},copy:function(a){this.vertices=[];this.faces=
12346 [];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},
12347 dispose:function(){this.dispatchEvent({type:"dispose"})}});var ad=0;Object.assign(re.prototype,sa.prototype,{computeBoundingBox:Q.prototype.computeBoundingBox,computeBoundingSphere:Q.prototype.computeBoundingSphere,computeFaceNormals:function(){console.warn("THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.")},computeVertexNormals:function(){console.warn("THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.")},computeGroups:function(a){var b,
12348 c=[],d;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,k;if(0<h){k=[];for(var m=0;m<h;m++)k[m]=[];this.morphTargets.position=k}var l=a.morphNormals,n=l.length,p;if(0<n){p=[];for(m=0;m<
12349 n;m++)p[m]=[];this.morphTargets.normal=p}for(var r=a.skinIndices,q=a.skinWeights,t=r.length===c.length,D=q.length===c.length,m=0;m<b.length;m++){var u=b[m];this.vertices.push(c[u.a],c[u.b],c[u.c]);var v=u.vertexNormals;3===v.length?this.normals.push(v[0],v[1],v[2]):(v=u.normal,this.normals.push(v,v,v));v=u.vertexColors;3===v.length?this.colors.push(v[0],v[1],v[2]):(v=u.color,this.colors.push(v,v,v));!0===e&&(v=d[0][m],void 0!==v?this.uvs.push(v[0],v[1],v[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ",
12350 m),this.uvs.push(new B,new B,new B)));!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 B,new B,new B)));for(v=0;v<h;v++){var I=g[v].vertices;k[v].push(I[u.a],I[u.b],I[u.c])}for(v=0;v<n;v++)I=l[v].vertexNormals[m],p[v].push(I.a,I.b,I.c);t&&this.skinIndices.push(r[u.a],r[u.b],r[u.c]);D&&this.skinWeights.push(q[u.a],q[u.b],q[u.c])}this.computeGroups(a);this.verticesNeedUpdate=a.verticesNeedUpdate;
12351 this.normalsNeedUpdate=a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.groupsNeedUpdate=a.groupsNeedUpdate;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Object.assign(G.prototype,sa.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 )."),
12352 this.addAttribute(a,new C(b,c));else if("index"===a)console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),this.setIndex(b);else return this.attributes[a]=b,this},getAttribute:function(a){return this.attributes[a]},removeAttribute:function(a){delete this.attributes[a];return this},addGroup:function(a,b,c){this.groups.push({start:a,count:b,materialIndex:void 0!==c?c:0})},clearGroups:function(){this.groups=[]},setDrawRange:function(a,b){this.drawRange.start=a;this.drawRange.count=
12353 b},applyMatrix:function(a){var b=this.attributes.position;void 0!==b&&(a.applyToVector3Array(b.array),b.needsUpdate=!0);b=this.attributes.normal;void 0!==b&&((new Ia).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 J);a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a;return function(b){void 0===
12354 a&&(a=new J);a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a;return function(b){void 0===a&&(a=new J);a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a;return function(b,c,d){void 0===a&&(a=new J);a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a;return function(b,c,d){void 0===a&&(a=new J);a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a;return function(b){void 0===a&&(a=
12355 new z);a.lookAt(b);a.updateMatrix();this.applyMatrix(a.matrix)}}(),center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();this.translate(a.x,a.y,a.z);return a},setFromObject:function(a){var b=a.geometry;if(a&&a.isPoints||a&&a.isLine){a=new ha(3*b.vertices.length,3);var c=new ha(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&&
12356 (a=new ha(b.lineDistances.length,1),this.addAttribute("lineDistance",a.copyArray(b.lineDistances)));null!==b.boundingSphere&&(this.boundingSphere=b.boundingSphere.clone());null!==b.boundingBox&&(this.boundingBox=b.boundingBox.clone())}else a&&a.isMesh&&b&&b.isGeometry&&this.fromGeometry(b);return this},updateFromObject:function(a){var b=a.geometry;if(a&&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=
12357 b.verticesNeedUpdate;c.normalsNeedUpdate=b.normalsNeedUpdate;c.colorsNeedUpdate=b.colorsNeedUpdate;c.uvsNeedUpdate=b.uvsNeedUpdate;c.groupsNeedUpdate=b.groupsNeedUpdate;b.verticesNeedUpdate=!1;b.normalsNeedUpdate=!1;b.colorsNeedUpdate=!1;b.uvsNeedUpdate=!1;b.groupsNeedUpdate=!1;b=c}!0===b.verticesNeedUpdate&&(c=this.attributes.position,void 0!==c&&(c.copyVector3sArray(b.vertices),c.needsUpdate=!0),b.verticesNeedUpdate=!1);!0===b.normalsNeedUpdate&&(c=this.attributes.normal,void 0!==c&&(c.copyVector3sArray(b.normals),
12358 c.needsUpdate=!0),b.normalsNeedUpdate=!1);!0===b.colorsNeedUpdate&&(c=this.attributes.color,void 0!==c&&(c.copyColorsArray(b.colors),c.needsUpdate=!0),b.colorsNeedUpdate=!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=
12359 b.groups,b.groupsNeedUpdate=!1);return this},fromGeometry:function(a){a.__directGeometry=(new re).fromGeometry(a);return this.fromDirectGeometry(a.__directGeometry)},fromDirectGeometry:function(a){var b=new Float32Array(3*a.vertices.length);this.addAttribute("position",(new C(b,3)).copyVector3sArray(a.vertices));0<a.normals.length&&(b=new Float32Array(3*a.normals.length),this.addAttribute("normal",(new C(b,3)).copyVector3sArray(a.normals)));0<a.colors.length&&(b=new Float32Array(3*a.colors.length),
12360 this.addAttribute("color",(new C(b,3)).copyColorsArray(a.colors)));0<a.uvs.length&&(b=new Float32Array(2*a.uvs.length),this.addAttribute("uv",(new C(b,2)).copyVector2sArray(a.uvs)));0<a.uvs2.length&&(b=new Float32Array(2*a.uvs2.length),this.addAttribute("uv2",(new C(b,2)).copyVector2sArray(a.uvs2)));0<a.indices.length&&(b=new (65535<a.vertices.length?Uint32Array:Uint16Array)(3*a.indices.length),this.setIndex((new C(b,1)).copyIndicesArray(a.indices)));this.groups=a.groups;for(var c in a.morphTargets){for(var b=
12361 [],d=a.morphTargets[c],e=0,f=d.length;e<f;e++){var g=d[e],h=new ha(3*g.length,3);b.push(h.copyVector3sArray(g))}this.morphAttributes[c]=b}0<a.skinIndices.length&&(c=new ha(4*a.skinIndices.length,4),this.addAttribute("skinIndex",c.copyVector4sArray(a.skinIndices)));0<a.skinWeights.length&&(c=new ha(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=
12362 a.boundingBox.clone());return this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new Ba);var a=this.attributes.position.array;void 0!==a?this.boundingBox.setFromArray(a):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=
12363 new Ba,b=new q;return function(){null===this.boundingSphere&&(this.boundingSphere=new Ca);var c=this.attributes.position;if(c){var c=c.array,d=this.boundingSphere.center;a.setFromArray(c);a.getCenter(d);for(var e=0,f=0,g=c.length;f<g;f+=3)b.fromArray(c,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.',
12364 this)}}}(),computeFaceNormals:function(){},computeVertexNormals:function(){var a=this.index,b=this.attributes,c=this.groups;if(b.position){var d=b.position.array;if(void 0===b.normal)this.addAttribute("normal",new C(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,n=new q,p=new q,r=new q,x=new q;if(a){a=a.array;0===c.length&&this.addGroup(0,a.length);for(var t=0,D=c.length;t<D;++t)for(f=c[t],g=f.start,h=f.count,f=g,g+=h;f<
12365 g;f+=3)h=3*a[f+0],k=3*a[f+1],m=3*a[f+2],l.fromArray(d,h),n.fromArray(d,k),p.fromArray(d,m),r.subVectors(p,n),x.subVectors(l,n),r.cross(x),e[h]+=r.x,e[h+1]+=r.y,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),n.fromArray(d,f+3),p.fromArray(d,f+6),r.subVectors(p,n),x.subVectors(l,n),r.cross(x),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=
12366 !0}},merge:function(a,b){if(!1===(a&&a.isBufferGeometry))console.error("THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.",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),
12367 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."),this;var a=new G,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 n=0;n<e;n++)g[k++]=f[h++]}a.addAttribute(d,new C(g,e))}return a},toJSON:function(){var a={metadata:{version:4.4,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};
12368 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]&&(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;
12369 0<c.length&&(a.data.groups=JSON.parse(JSON.stringify(c)));c=this.boundingSphere;null!==c&&(a.data.boundingSphere={center:c.center.toArray(),radius:c.radius});return a},clone:function(){return(new G).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"})}});
12370 G.MaxIndex=65535;ya.prototype=Object.assign(Object.create(z.prototype),{constructor:ya,isMesh:!0,setDrawMode:function(a){this.drawMode=a},copy:function(a){z.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,
12371 b,c,d,e,f,g){wa.barycoordFromPoint(a,b,c,d,t);e.multiplyScalar(t.x);f.multiplyScalar(t.y);g.multiplyScalar(t.z);e.add(f).add(g);return e.clone()}function b(a,b,c,d,e,f,g){var h=a.material;if(null===(1===h.side?c.intersectTriangle(f,e,d,!0,g):c.intersectTriangle(d,e,f,2!==h.side,g)))return null;u.copy(g);u.applyMatrix4(a.matrixWorld);c=b.ray.origin.distanceTo(u);return c<b.near||c>b.far?null:{distance:c,point:u.clone(),object:a}}function c(c,d,e,f,m,l,n,w){g.fromArray(f,3*l);h.fromArray(f,3*n);k.fromArray(f,
12372 3*w);if(c=b(c,d,e,g,h,k,D))m&&(p.fromArray(m,2*l),r.fromArray(m,2*n),x.fromArray(m,2*w),c.uv=a(D,g,h,k,p,r,x)),c.face=new ea(l,n,w,wa.normal(g,h,k)),c.faceIndex=l;return c}var d=new J,e=new ab,f=new Ca,g=new q,h=new q,k=new q,m=new q,l=new q,n=new q,p=new B,r=new B,x=new B,t=new q,D=new q,u=new q;return function(q,t){var u=this.geometry,E=this.material,H=this.matrixWorld;if(void 0!==E&&(null===u.boundingSphere&&u.computeBoundingSphere(),f.copy(u.boundingSphere),f.applyMatrix4(H),!1!==q.ray.intersectsSphere(f)&&
12373 (d.getInverse(H),e.copy(q.ray).applyMatrix4(d),null===u.boundingBox||!1!==e.intersectsBox(u.boundingBox)))){var F,M;if(u&&u.isBufferGeometry){var B,K,E=u.index,H=u.attributes,u=H.position.array;void 0!==H.uv&&(F=H.uv.array);if(null!==E)for(var H=E.array,z=0,C=H.length;z<C;z+=3){if(E=H[z],B=H[z+1],K=H[z+2],M=c(this,q,e,u,F,E,B,K))M.faceIndex=Math.floor(z/3),t.push(M)}else for(z=0,C=u.length;z<C;z+=9)if(E=z/3,B=E+1,K=E+2,M=c(this,q,e,u,F,E,B,K))M.index=E,t.push(M)}else if(u&&u.isGeometry){var G,J,H=
12374 E&&E.isMultiMaterial,z=!0===H?E.materials:null,C=u.vertices;B=u.faces;K=u.faceVertexUvs[0];0<K.length&&(F=K);for(var N=0,P=B.length;N<P;N++){var R=B[N];M=!0===H?z[R.materialIndex]:E;if(void 0!==M){K=C[R.a];G=C[R.b];J=C[R.c];if(!0===M.morphTargets){M=u.morphTargets;var S=this.morphTargetInfluences;g.set(0,0,0);h.set(0,0,0);k.set(0,0,0);for(var Q=0,V=M.length;Q<V;Q++){var O=S[Q];if(0!==O){var L=M[Q].vertices;g.addScaledVector(m.subVectors(L[R.a],K),O);h.addScaledVector(l.subVectors(L[R.b],G),O);k.addScaledVector(n.subVectors(L[R.c],
12375 J),O)}}g.add(K);h.add(G);k.add(J);K=g;G=h;J=k}if(M=b(this,q,e,K,G,J,D))F&&(S=F[N],p.copy(S[0]),r.copy(S[1]),x.copy(S[2]),M.uv=a(D,K,G,J,p,r,x)),M.face=R,M.faceIndex=N,t.push(M)}}}}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});hb.prototype=Object.create(G.prototype);hb.prototype.constructor=hb;ib.prototype=Object.create(G.prototype);ib.prototype.constructor=ib;Z.prototype=Object.create(z.prototype);Z.prototype.constructor=Z;Z.prototype.isCamera=!0;Z.prototype.getWorldDirection=
12376 function(){var a=new ba;return function(b){b=b||new q;this.getWorldQuaternion(a);return b.set(0,0,-1).applyQuaternion(a)}}();Z.prototype.lookAt=function(){var a=new J;return function(b){a.lookAt(this.position,b,this.up);this.quaternion.setFromRotationMatrix(a)}}();Z.prototype.clone=function(){return(new this.constructor).copy(this)};Z.prototype.copy=function(a){z.prototype.copy.call(this,a);this.matrixWorldInverse.copy(a.matrixWorldInverse);this.projectionMatrix.copy(a.projectionMatrix);return this};
12377 Ea.prototype=Object.assign(Object.create(Z.prototype),{constructor:Ea,isPerspectiveCamera:!0,copy:function(a){Z.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*T.RAD2DEG*Math.atan(a);this.updateProjectionMatrix()},getFocalLength:function(){var a=
12378 Math.tan(.5*T.DEG2RAD*this.fov);return.5*this.getFilmHeight()/a},getEffectiveFOV:function(){return 2*T.RAD2DEG*Math.atan(Math.tan(.5*T.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=
12379 null;this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=this.near,b=a*Math.tan(.5*T.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=z.prototype.toJSON.call(this,a);a.object.fov=this.fov;a.object.zoom=this.zoom;a.object.near=
12380 this.near;a.object.far=this.far;a.object.focus=this.focus;a.object.aspect=this.aspect;null!==this.view&&(a.object.view=Object.assign({},this.view));a.object.filmGauge=this.filmGauge;a.object.filmOffset=this.filmOffset;return a}});Hb.prototype=Object.assign(Object.create(Z.prototype),{constructor:Hb,isOrthographicCamera:!0,copy:function(a){Z.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=
12381 null===a.view?null:Object.assign({},a.view);return this},setViewOffset:function(a,b,c,d,e,f){this.view={fullWidth:a,fullHeight:b,offsetX:c,offsetY:d,width:e,height:f};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/
12382 (this.view.width/this.view.fullWidth),b=this.zoom/(this.view.height/this.view.fullHeight),f=(this.right-this.left)/this.view.width,d=(this.top-this.bottom)/this.view.height,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=z.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=
12383 this.bottom;a.object.near=this.near;a.object.far=this.far;null!==this.view&&(a.object.view=Object.assign({},this.view));return a}});var sf=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",
12384 color:this.color.getHex(),near:this.near,far:this.far}};jb.prototype=Object.create(z.prototype);jb.prototype.constructor=jb;jb.prototype.copy=function(a,b){z.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=z.prototype.toJSON.call(this,
12385 a);null!==this.background&&(b.object.background=this.background.toJSON(a));null!==this.fog&&(b.object.fog=this.fog.toJSON());return b};Ed.prototype=Object.assign(Object.create(z.prototype),{constructor:Ed,isLensFlare:!0,copy:function(a){z.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===
12386 c&&(c=0);void 0===f&&(f=1);void 0===e&&(e=new O(16777215));void 0===d&&(d=1);c=Math.min(c,Math.max(0,c));this.lensFlares.push({texture:a,size:b,distance:c,x:0,y:0,z:0,scale:1,rotation:0,opacity:f,color:e,blending:d})},updateLensFlares:function(){var a,b=this.lensFlares.length,c,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-
12387 c.rotation)}});kb.prototype=Object.create(U.prototype);kb.prototype.constructor=kb;kb.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.rotation=a.rotation;return this};qc.prototype=Object.assign(Object.create(z.prototype),{constructor:qc,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,
12388 face:null,object:this})}}(),clone:function(){return(new this.constructor(this.material)).copy(this)}});rc.prototype=Object.assign(Object.create(z.prototype),{constructor:rc,copy:function(a){z.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=
12389 this.levels,c=1,d=b.length;c<d&&!(a<b[c].distance);c++);return b[c-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-
12390 1].object.visible=!1,d[e].object.visible=!0;else break;for(;e<f;e++)d[e].object.visible=!1}}}(),toJSON:function(a){a=z.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}});lb.prototype=Object.create(da.prototype);lb.prototype.constructor=lb;lb.prototype.isDataTexture=!0;Object.assign(bd.prototype,{calculateInverses:function(){this.boneInverses=[];for(var a=0,b=this.bones.length;a<
12391 b;a++){var c=new J;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<c;b++)(a=this.bones[b])&&a.matrixWorld.getInverse(this.boneInverses[b]);b=0;for(c=this.bones.length;b<c;b++)if(a=this.bones[b])a.parent&&a.parent.isBone?(a.matrix.getInverse(a.parent.matrixWorld),a.matrix.multiply(a.matrixWorld)):a.matrix.copy(a.matrixWorld),a.matrix.decompose(a.position,a.quaternion,a.scale)},update:function(){var a=new J;return function(){for(var b=
12392 0,c=this.bones.length;b<c;b++)a.multiplyMatrices(this.bones[b]?this.bones[b].matrixWorld:this.identityMatrix,this.boneInverses[b]),a.toArray(this.boneMatrices,16*b);this.useVertexTexture&&(this.boneTexture.needsUpdate=!0)}}(),clone:function(){return new bd(this.bones,this.boneInverses,this.useVertexTexture)}});cd.prototype=Object.assign(Object.create(z.prototype),{constructor:cd,isBone:!0,copy:function(a){z.prototype.copy.call(this,a);this.skin=a.skin;return this}});dd.prototype=Object.assign(Object.create(ya.prototype),
12393 {constructor:dd,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);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&&
12394 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(),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){ya.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: "+
12395 this.bindMode)},clone:function(){return(new this.constructor(this.geometry,this.material,this.skeleton.useVertexTexture)).copy(this)}});oa.prototype=Object.create(U.prototype);oa.prototype.constructor=oa;oa.prototype.isLineBasicMaterial=!0;oa.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.linewidth=a.linewidth;this.linecap=a.linecap;this.linejoin=a.linejoin;return this};Ta.prototype=Object.assign(Object.create(z.prototype),{constructor:Ta,isLine:!0,raycast:function(){var a=
12396 new J,b=new ab,c=new Ca;return function(d,e){var f=d.linePrecision,f=f*f,g=this.geometry,h=this.matrixWorld;null===g.boundingSphere&&g.computeBoundingSphere();c.copy(g.boundingSphere);c.applyMatrix4(h);if(!1!==d.ray.intersectsSphere(c)){a.getInverse(h);b.copy(d.ray).applyMatrix4(a);var k=new q,m=new q,h=new q,l=new q,n=this&&this.isLineSegments?2:1;if(g&&g.isBufferGeometry){var p=g.index,r=g.attributes.position.array;if(null!==p)for(var p=p.array,g=0,x=p.length-1;g<x;g+=n){var t=p[g+1];k.fromArray(r,
12397 3*p[g]);m.fromArray(r,3*t);t=b.distanceSqToSegment(k,m,l,h);t>f||(l.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(l),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else for(g=0,x=r.length/3-1;g<x;g+=n)k.fromArray(r,3*g),m.fromArray(r,3*g+3),t=b.distanceSqToSegment(k,m,l,h),t>f||(l.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(l),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),
12398 index:g,face:null,faceIndex:null,object:this}))}else if(g&&g.isGeometry)for(k=g.vertices,m=k.length,g=0;g<m-1;g+=n)t=b.distanceSqToSegment(k[g],k[g+1],l,h),t>f||(l.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(l),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});la.prototype=Object.assign(Object.create(Ta.prototype),
12399 {constructor:la,isLineSegments:!0});xa.prototype=Object.create(U.prototype);xa.prototype.constructor=xa;xa.prototype.isPointsMaterial=!0;xa.prototype.copy=function(a){U.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(z.prototype),{constructor:Kb,isPoints:!0,raycast:function(){var a=new J,b=new ab,c=new Ca;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a);
12400 if(f<l){var h=b.closestPointToPoint(a);h.applyMatrix4(k);var m=d.ray.origin.distanceTo(h);m<d.near||m>d.far||e.push({distance:m,distanceToRay:Math.sqrt(f),point:h.clone(),index:c,face:null,object:g})}}var g=this,h=this.geometry,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),
12401 l=m*m,m=new q;if(h&&h.isBufferGeometry){var n=h.index,h=h.attributes.position.array;if(null!==n)for(var p=n.array,n=0,r=p.length;n<r;n++){var x=p[n];m.fromArray(h,3*x);f(m,x)}else for(n=0,p=h.length/3;n<p;n++)m.fromArray(h,3*n),f(m,n)}else for(m=h.vertices,n=0,p=m.length;n<p;n++)f(m[n],n)}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});sc.prototype=Object.assign(Object.create(z.prototype),{constructor:sc});ed.prototype=Object.create(da.prototype);ed.prototype.constructor=
12402 ed;Lb.prototype=Object.create(da.prototype);Lb.prototype.constructor=Lb;Lb.prototype.isCompressedTexture=!0;fd.prototype=Object.create(da.prototype);fd.prototype.constructor=fd;tc.prototype=Object.create(da.prototype);tc.prototype.constructor=tc;tc.prototype.isDepthTexture=!0;Mb.prototype=Object.create(G.prototype);Mb.prototype.constructor=Mb;Nb.prototype=Object.create(G.prototype);Nb.prototype.constructor=Nb;uc.prototype=Object.create(Q.prototype);uc.prototype.constructor=uc;ua.prototype=Object.create(G.prototype);
12403 ua.prototype.constructor=ua;Ob.prototype=Object.create(ua.prototype);Ob.prototype.constructor=Ob;vc.prototype=Object.create(Q.prototype);vc.prototype.constructor=vc;Pb.prototype=Object.create(ua.prototype);Pb.prototype.constructor=Pb;wc.prototype=Object.create(Q.prototype);wc.prototype.constructor=wc;Qb.prototype=Object.create(ua.prototype);Qb.prototype.constructor=Qb;xc.prototype=Object.create(Q.prototype);xc.prototype.constructor=xc;Rb.prototype=Object.create(ua.prototype);Rb.prototype.constructor=
12404 Rb;yc.prototype=Object.create(Q.prototype);yc.prototype.constructor=yc;zc.prototype=Object.create(Q.prototype);zc.prototype.constructor=zc;Sb.prototype=Object.create(G.prototype);Sb.prototype.constructor=Sb;Ac.prototype=Object.create(Q.prototype);Ac.prototype.constructor=Ac;Tb.prototype=Object.create(G.prototype);Tb.prototype.constructor=Tb;Bc.prototype=Object.create(Q.prototype);Bc.prototype.constructor=Bc;Ub.prototype=Object.create(G.prototype);Ub.prototype.constructor=Ub;Cc.prototype=Object.create(Q.prototype);
12405 Cc.prototype.constructor=Cc;var ra={area:function(a){for(var b=a.length,c=0,d=b-1,e=0;e<b;d=e++)c+=a[d].x*a[e].y-a[e].x*a[d].y;return.5*c},triangulate:function(){return function(a,b){var c=a.length;if(3>c)return null;var d=[],e=[],f=[],g,h,k;if(0<ra.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 n,
12406 p,r,q,t,D,u,v;n=a[e[g]].x;p=a[e[g]].y;r=a[e[h]].x;q=a[e[h]].y;t=a[e[k]].x;D=a[e[k]].y;if(0>=(r-n)*(D-p)-(q-p)*(t-n))l=!1;else{var I,y,E,H,F,M,B,z,C,G;I=t-r;y=D-q;E=n-t;H=p-D;F=r-n;M=q-p;for(l=0;l<c;l++)if(u=a[e[l]].x,v=a[e[l]].y,!(u===n&&v===p||u===r&&v===q||u===t&&v===D)&&(B=u-n,z=v-p,C=u-r,G=v-q,u-=t,v-=D,C=I*G-y*C,B=F*z-M*B,z=E*v-H*u,C>=-Number.EPSILON&&z>=-Number.EPSILON&&B>=-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++,
12407 k++)e[g]=e[k];c--;m=2*c}}return b?f:d}}(),triangulateShape:function(a,b){function c(a){var b=a.length;2<b&&a[b-1].equals(a[0])&&a.pop()}function d(a,b,c){return a.x!==b.x?a.x<b.x?a.x<=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<
12408 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];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=
12409 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]}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,n={};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!==n[l]&&console.warn("THREE.ShapeUtils: Duplicate point",
12410 l,g),n[l]=g;g=function(a,b){function c(a,b){var d=h.length-1,e=a-1;0>e&&(e=d);var g=a+1;g>d&&(g=0);d=f(h[a],h[e],h[g],k[b]);if(!d)return!1;d=k.length-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=
12411 a.concat(),k,m=[],l,n,p,q,w,B=[],z,C,G,J=0;for(l=b.length;J<l;J++)m.push(J);z=0;for(var N=2*m.length;0<m.length;){N--;if(0>N){console.log("Infinite Loop! Holes left:"+m.length+", Probably Hole outside Shape!");break}for(n=z;n<h.length;n++){p=h[n];l=-1;for(J=0;J<m.length;J++)if(q=m[J],w=p.x+":"+p.y+":"+q,void 0===B[w]){k=b[q];for(C=0;C<k.length;C++)if(q=k[C],c(n,C)&&!d(p,q)&&!g(p,q)){l=C;m.splice(J,1);z=h.slice(0,n+1);q=h.slice(n);C=k.slice(l);G=k.slice(0,l+1);h=z.concat(C).concat(G).concat(q);z=n;
12412 break}if(0<=l)break;B[w]=!0}if(0<=l)break}}return h}(a,b);var p=ra.triangulate(g,!1);g=0;for(h=p.length;g<h;g++)for(m=p[g],k=0;3>k;k++)l=m[k].x+":"+m[k].y,l=n[l],void 0!==l&&(m[k]=l);return p.concat()},isClockWise:function(a){return 0>ra.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}}()};za.prototype=Object.create(Q.prototype);za.prototype.constructor=
12413 za;za.prototype.addShapeList=function(a,b){for(var c=a.length,d=0;d<c;d++)this.addShape(a[d],b)};za.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=
12414 d*d+e*e;if(2>=f)return new B(d,e);f=Math.sqrt(f/2)}else a=!1,e>Number.EPSILON?d>Number.EPSILON&&(a=!0):e<-Number.EPSILON?d<-Number.EPSILON&&(a=!0):Math.sign(f)===Math.sign(g)&&(a=!0),a?(d=-f,f=Math.sqrt(h)):(d=e,e=f,f=Math.sqrt(h/2));return new B(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=T*e,h=T*(e+1),k=b+c+g,g=b+d+g,m=b+d+h,h=b+c+h,k=k+K,g=g+K,m=m+K,h=h+K;C.faces.push(new ea(k,g,h,null,null,1));C.faces.push(new ea(g,
12415 m,h,null,null,1));k=u.generateSideWallUV(C,k,g,m,h);C.faceVertexUvs[0].push([k[0],k[1],k[3]]);C.faceVertexUvs[0].push([k[1],k[2],k[3]])}}}function f(a,b,c){C.vertices.push(new q(a,b,c))}function g(a,b,c){a+=K;b+=K;c+=K;C.faces.push(new ea(a,b,c,null,null,0));a=u.generateTopUV(C,a,b,c);C.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,n=void 0!==b.bevelEnabled?
12416 b.bevelEnabled:!0,p=void 0!==b.curveSegments?b.curveSegments:12,r=void 0!==b.steps?b.steps:1,x=b.extrudePath,t,D=!1,u=void 0!==b.UVGenerator?b.UVGenerator:za.WorldUVGenerator,v,I,y,E;x&&(t=x.getSpacedPoints(r),D=!0,n=!1,v=void 0!==b.frames?b.frames:x.computeFrenetFrames(r,!1),I=new q,y=new q,E=new q);n||(m=k=l=0);var H,F,z,C=this,K=this.vertices.length,x=a.extractPoints(p),p=x.shape,G=x.holes;if(x=!ra.isClockWise(p)){p=p.reverse();F=0;for(z=G.length;F<z;F++)H=G[F],ra.isClockWise(H)&&(G[F]=H.reverse());
12417 x=!1}var J=ra.triangulateShape(p,G),Q=p;F=0;for(z=G.length;F<z;F++)H=G[F],p=p.concat(H);var O,N,P,R,S,T=p.length,V,U=J.length,x=[],L=0;P=Q.length;O=P-1;for(N=L+1;L<P;L++,O++,N++)O===P&&(O=0),N===P&&(N=0),x[L]=d(Q[L],Q[O],Q[N]);var W=[],X,Z=x.concat();F=0;for(z=G.length;F<z;F++){H=G[F];X=[];L=0;P=H.length;O=P-1;for(N=L+1;L<P;L++,O++,N++)O===P&&(O=0),N===P&&(N=0),X[L]=d(H[L],H[O],H[N]);W.push(X);Z=Z.concat(X)}for(O=0;O<l;O++){P=O/l;R=k*Math.cos(P*Math.PI/2);N=m*Math.sin(P*Math.PI/2);L=0;for(P=Q.length;L<
12418 P;L++)S=c(Q[L],x[L],N),f(S.x,S.y,-R);F=0;for(z=G.length;F<z;F++)for(H=G[F],X=W[F],L=0,P=H.length;L<P;L++)S=c(H[L],X[L],N),f(S.x,S.y,-R)}N=m;for(L=0;L<T;L++)S=n?c(p[L],Z[L],N):p[L],D?(y.copy(v.normals[0]).multiplyScalar(S.x),I.copy(v.binormals[0]).multiplyScalar(S.y),E.copy(t[0]).add(y).add(I),f(E.x,E.y,E.z)):f(S.x,S.y,0);for(P=1;P<=r;P++)for(L=0;L<T;L++)S=n?c(p[L],Z[L],N):p[L],D?(y.copy(v.normals[P]).multiplyScalar(S.x),I.copy(v.binormals[P]).multiplyScalar(S.y),E.copy(t[P]).add(y).add(I),f(E.x,E.y,
12419 E.z)):f(S.x,S.y,h/r*P);for(O=l-1;0<=O;O--){P=O/l;R=k*Math.cos(P*Math.PI/2);N=m*Math.sin(P*Math.PI/2);L=0;for(P=Q.length;L<P;L++)S=c(Q[L],x[L],N),f(S.x,S.y,h+R);F=0;for(z=G.length;F<z;F++)for(H=G[F],X=W[F],L=0,P=H.length;L<P;L++)S=c(H[L],X[L],N),D?f(S.x,S.y+t[r-1].y,t[r-1].x+R):f(S.x,S.y,h+R)}(function(){if(n){var a=0*T;for(L=0;L<U;L++)V=J[L],g(V[2]+a,V[1]+a,V[0]+a);a=T*(r+2*l);for(L=0;L<U;L++)V=J[L],g(V[0]+a,V[1]+a,V[2]+a)}else{for(L=0;L<U;L++)V=J[L],g(V[2],V[1],V[0]);for(L=0;L<U;L++)V=J[L],g(V[0]+
12420 T*r,V[1]+T*r,V[2]+T*r)}})();(function(){var a=0;e(Q,a);a+=Q.length;F=0;for(z=G.length;F<z;F++)H=G[F],e(H,a),a+=H.length})()};za.WorldUVGenerator={generateTopUV:function(a,b,c,d){a=a.vertices;b=a[b];c=a[c];d=a[d];return[new B(b.x,b.y),new B(c.x,c.y),new B(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 B(b.x,1-b.z),new B(c.x,1-c.z),new B(d.x,1-d.z),new B(e.x,1-e.z)]:[new B(b.y,1-b.z),new B(c.y,1-c.z),new B(d.y,1-d.z),new B(e.y,
12421 1-e.z)]}};Dc.prototype=Object.create(za.prototype);Dc.prototype.constructor=Dc;mb.prototype=Object.create(G.prototype);mb.prototype.constructor=mb;Vb.prototype=Object.create(Q.prototype);Vb.prototype.constructor=Vb;Wb.prototype=Object.create(G.prototype);Wb.prototype.constructor=Wb;Ec.prototype=Object.create(Q.prototype);Ec.prototype.constructor=Ec;Fc.prototype=Object.create(Q.prototype);Fc.prototype.constructor=Fc;Xb.prototype=Object.create(G.prototype);Xb.prototype.constructor=Xb;Gc.prototype=Object.create(Q.prototype);
12422 Gc.prototype.constructor=Gc;cb.prototype=Object.create(Q.prototype);cb.prototype.constructor=cb;cb.prototype.addShapeList=function(a,b){for(var c=0,d=a.length;c<d;c++)this.addShape(a[c],b);return this};cb.prototype.addShape=function(a,b){void 0===b&&(b={});var c=b.material,d=void 0===b.UVGenerator?za.WorldUVGenerator:b.UVGenerator,e,f,g,h=this.vertices.length;e=a.extractPoints(void 0!==b.curveSegments?b.curveSegments:12);var k=e.shape,m=e.holes;if(!ra.isClockWise(k))for(k=k.reverse(),e=0,f=m.length;e<
12423 f;e++)g=m[e],ra.isClockWise(g)&&(m[e]=g.reverse());var l=ra.triangulateShape(k,m);e=0;for(f=m.length;e<f;e++)g=m[e],k=k.concat(g);m=k.length;f=l.length;for(e=0;e<m;e++)g=k[e],this.vertices.push(new q(g.x,g.y,0));for(e=0;e<f;e++)m=l[e],k=m[0]+h,g=m[1]+h,m=m[2]+h,this.faces.push(new ea(k,g,m,null,null,c)),this.faceVertexUvs[0].push(d.generateTopUV(this,k,g,m))};Yb.prototype=Object.create(G.prototype);Yb.prototype.constructor=Yb;Ua.prototype=Object.create(G.prototype);Ua.prototype.constructor=Ua;nb.prototype=
12424 Object.create(Q.prototype);nb.prototype.constructor=nb;Hc.prototype=Object.create(nb.prototype);Hc.prototype.constructor=Hc;Ic.prototype=Object.create(Ua.prototype);Ic.prototype.constructor=Ic;Zb.prototype=Object.create(G.prototype);Zb.prototype.constructor=Zb;Jc.prototype=Object.create(Q.prototype);Jc.prototype.constructor=Jc;ob.prototype=Object.create(Q.prototype);ob.prototype.constructor=ob;var Na=Object.freeze({WireframeGeometry:Mb,ParametricGeometry:uc,ParametricBufferGeometry:Nb,TetrahedronGeometry:vc,
12425 TetrahedronBufferGeometry:Ob,OctahedronGeometry:wc,OctahedronBufferGeometry:Pb,IcosahedronGeometry:xc,IcosahedronBufferGeometry:Qb,DodecahedronGeometry:yc,DodecahedronBufferGeometry:Rb,PolyhedronGeometry:zc,PolyhedronBufferGeometry:ua,TubeGeometry:Ac,TubeBufferGeometry:Sb,TorusKnotGeometry:Bc,TorusKnotBufferGeometry:Tb,TorusGeometry:Cc,TorusBufferGeometry:Ub,TextGeometry:Dc,SphereBufferGeometry:mb,SphereGeometry:Vb,RingGeometry:Ec,RingBufferGeometry:Wb,PlaneBufferGeometry:ib,PlaneGeometry:Fc,LatheGeometry:Gc,
12426 LatheBufferGeometry:Xb,ShapeGeometry:cb,ExtrudeGeometry:za,EdgesGeometry:Yb,ConeGeometry:Hc,ConeBufferGeometry:Ic,CylinderGeometry:nb,CylinderBufferGeometry:Ua,CircleBufferGeometry:Zb,CircleGeometry:Jc,BoxBufferGeometry:hb,BoxGeometry:ob});$b.prototype=Object.create(Fa.prototype);$b.prototype.constructor=$b;$b.prototype.isShadowMaterial=!0;ac.prototype=Object.create(Fa.prototype);ac.prototype.constructor=ac;ac.prototype.isRawShaderMaterial=!0;Kc.prototype={constructor:Kc,isMultiMaterial:!0,toJSON:function(a){for(var b=
12427 {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=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}};Oa.prototype=Object.create(U.prototype);Oa.prototype.constructor=Oa;Oa.prototype.isMeshStandardMaterial=
12428 !0;Oa.prototype.copy=function(a){U.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=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);
12429 this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.roughnessMap=a.roughnessMap;this.metalnessMap=a.metalnessMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.envMapIntensity=a.envMapIntensity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=
12430 a.morphTargets;this.morphNormals=a.morphNormals;return this};pb.prototype=Object.create(Oa.prototype);pb.prototype.constructor=pb;pb.prototype.isMeshPhysicalMaterial=!0;pb.prototype.copy=function(a){Oa.prototype.copy.call(this,a);this.defines={PHYSICAL:""};this.reflectivity=a.reflectivity;this.clearCoat=a.clearCoat;this.clearCoatRoughness=a.clearCoatRoughness;return this};db.prototype=Object.create(U.prototype);db.prototype.constructor=db;db.prototype.isMeshPhongMaterial=!0;db.prototype.copy=function(a){U.prototype.copy.call(this,
12431 a);this.color.copy(a.color);this.specular.copy(a.specular);this.shininess=a.shininess;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=
12432 a.displacementScale;this.displacementBias=a.displacementBias;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};qb.prototype=
12433 Object.create(U.prototype);qb.prototype.constructor=qb;qb.prototype.isMeshNormalMaterial=!0;qb.prototype.copy=function(a){U.prototype.copy.call(this,a);this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;return this};rb.prototype=Object.create(U.prototype);rb.prototype.constructor=rb;rb.prototype.isMeshLambertMaterial=!0;rb.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;
12434 this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=
12435 a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};sb.prototype=Object.create(U.prototype);sb.prototype.constructor=sb;sb.prototype.isLineDashedMaterial=!0;sb.prototype.copy=function(a){U.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 Df=Object.freeze({ShadowMaterial:$b,SpriteMaterial:kb,RawShaderMaterial:ac,ShaderMaterial:Fa,PointsMaterial:xa,
12436 MultiMaterial:Kc,MeshPhysicalMaterial:pb,MeshStandardMaterial:Oa,MeshPhongMaterial:db,MeshNormalMaterial:qb,MeshLambertMaterial:rb,MeshDepthMaterial:Za,MeshBasicMaterial:Ma,LineDashedMaterial:sb,LineBasicMaterial:oa,Material:U}),ce={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={}}},Ga=new Fd;Object.assign(Ja.prototype,{load:function(a,b,c,d){void 0===
12437 a&&(a="");void 0!==this.path&&(a=this.path+a);var e=this,f=ce.get(a);if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;var g=a.match(/^data:(.*?)(;base64)?,(.*)$/);if(g){var h=g[1],k=!!g[2],g=g[3],g=window.decodeURIComponent(g);k&&(g=window.atob(g));try{var m,l=(this.responseType||"").toLowerCase();switch(l){case "arraybuffer":case "blob":m=new ArrayBuffer(g.length);for(var n=new Uint8Array(m),k=0;k<g.length;k++)n[k]=g.charCodeAt(k);"blob"===l&&(m=
12438 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&&d(q);e.manager.itemError(a)},0)}}else{var p=new XMLHttpRequest;p.open("GET",a,!0);p.addEventListener("load",function(c){var f=c.target.response;ce.add(a,f);200===this.status?(b&&b(f),e.manager.itemEnd(a)):0===this.status?(console.warn("THREE.XHRLoader: HTTP Status 0 received."),
12439 b&&b(f),e.manager.itemEnd(a)):(d&&d(c),e.manager.itemError(a))},!1);void 0!==c&&p.addEventListener("progress",function(a){c(a)},!1);p.addEventListener("error",function(b){d&&d(b);e.manager.itemError(a)},!1);void 0!==this.responseType&&(p.responseType=this.responseType);void 0!==this.withCredentials&&(p.withCredentials=this.withCredentials);p.overrideMimeType&&p.overrideMimeType("text/plain");p.send(null)}e.manager.itemStart(a);return p},setPath:function(a){this.path=a;return this},setResponseType:function(a){this.responseType=
12440 a;return this},setWithCredentials:function(a){this.withCredentials=a;return this}});Object.assign(we.prototype,{load:function(a,b,c,d){function e(e){k.load(a[e],function(a){a=f._parser(a,!0);g[e]={width:a.width,height:a.height,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 Ja(this.manager);k.setPath(this.path);k.setResponseType("arraybuffer");if(Array.isArray(a))for(var m=
12441 0,l=0,n=a.length;l<n;++l)e(l);else k.load(a,function(a){a=f._parser(a,!0);if(a.isCubemap)for(var c=a.mipmaps.length/a.mipmapCount,d=0;d<c;d++){g[d]={mipmaps:[]};for(var e=0;e<a.mipmapCount;e++)g[d].mipmaps.push(a.mipmaps[d*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;
12442 return this}});Object.assign(Gd.prototype,{load:function(a,b,c,d){var e=this,f=new lb,g=new Ja(this.manager);g.setResponseType("arraybuffer");g.load(a,function(a){if(a=e._parser(a))void 0!==a.image?f.image=a.image:void 0!==a.data&&(f.image.width=a.width,f.image.height=a.height,f.image.data=a.data),f.wrapS=void 0!==a.wrapS?a.wrapS:1001,f.wrapT=void 0!==a.wrapT?a.wrapT:1001,f.magFilter=void 0!==a.magFilter?a.magFilter:1006,f.minFilter=void 0!==a.minFilter?a.minFilter:1008,f.anisotropy=void 0!==a.anisotropy?
12443 a.anisotropy:1,void 0!==a.format&&(f.format=a.format),void 0!==a.type&&(f.type=a.type),void 0!==a.mipmaps&&(f.mipmaps=a.mipmaps),1===a.mipmapCount&&(f.minFilter=1006),f.needsUpdate=!0,b&&b(f,a)},c,d);return f}});Object.assign(Lc.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{var g=new Ja;g.setPath(this.path);
12444 g.setResponseType("blob");g.setWithCredentials(this.withCredentials);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(Hd.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 Xa,g=new Lc(this.manager);
12445 g.setCrossOrigin(this.crossOrigin);g.setPath(this.path);var h=0;for(c=0;c<a.length;++c)e(c);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(gd.prototype,{load:function(a,b,c,d){var e=new da,f=new Lc(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:
12446 1023;e.image=c;e.needsUpdate=!0;void 0!==b&&b(e)},c,d);return e},setCrossOrigin:function(a){this.crossOrigin=a;return this},setWithCredentials:function(a){this.withCredentials=a;return this},setPath:function(a){this.path=a;return this}});pa.prototype=Object.assign(Object.create(z.prototype),{constructor:pa,isLight:!0,copy:function(a){z.prototype.copy.call(this,a);this.color.copy(a.color);this.intensity=a.intensity;return this},toJSON:function(a){a=z.prototype.toJSON.call(this,a);a.object.color=this.color.getHex();
12447 a.object.intensity=this.intensity;void 0!==this.groundColor&&(a.object.groundColor=this.groundColor.getHex());void 0!==this.distance&&(a.object.distance=this.distance);void 0!==this.angle&&(a.object.angle=this.angle);void 0!==this.decay&&(a.object.decay=this.decay);void 0!==this.penumbra&&(a.object.penumbra=this.penumbra);void 0!==this.shadow&&(a.object.shadow=this.shadow.toJSON());return a}});hd.prototype=Object.assign(Object.create(pa.prototype),{constructor:hd,isHemisphereLight:!0,copy:function(a){pa.prototype.copy.call(this,
12448 a);this.groundColor.copy(a.groundColor);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;
12449 return a}});id.prototype=Object.assign(Object.create(tb.prototype),{constructor:id,isSpotLightShadow:!0,update:function(a){var b=2*T.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()}});jd.prototype=Object.assign(Object.create(pa.prototype),{constructor:jd,isSpotLight:!0,copy:function(a){pa.prototype.copy.call(this,a);this.distance=a.distance;this.angle=a.angle;this.penumbra=
12450 a.penumbra;this.decay=a.decay;this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});kd.prototype=Object.assign(Object.create(pa.prototype),{constructor:kd,isPointLight:!0,copy:function(a){pa.prototype.copy.call(this,a);this.distance=a.distance;this.decay=a.decay;this.shadow=a.shadow.clone();return this}});ld.prototype=Object.assign(Object.create(tb.prototype),{constructor:ld});md.prototype=Object.assign(Object.create(pa.prototype),{constructor:md,isDirectionalLight:!0,copy:function(a){pa.prototype.copy.call(this,
12451 a);this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});nd.prototype=Object.assign(Object.create(pa.prototype),{constructor:nd,isAmbientLight:!0});var ma={arraySlice:function(a,b,c){return ma.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=
12452 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],
12453 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&&
12454 (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||
12455 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_});od.prototype=Object.assign(Object.create(qa.prototype),{constructor:od,DefaultSettings_:{endingStart:2400,endingEnd:2400},
12456 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,
12457 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,n=this._weightNext,p=(c-b)/(d-b);c=p*p;d=c*p;b=-l*d+2*l*c-l*p;l=(1+l)*d+(-1.5-2*l)*c+(-.5+l)*p+1;p=(-1-n)*d+(1.5+n)*c+.5*p;n=n*d-n*c;for(c=0;c!==g;++c)e[c]=b*f[k+c]+l*f[h+c]+p*f[a+c]+n*f[m+c];return e}});Mc.prototype=Object.assign(Object.create(qa.prototype),{constructor:Mc,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;
12458 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}});pd.prototype=Object.assign(Object.create(qa.prototype),{constructor:pd,interpolate_:function(a,b,c,d){return this.copySampleValue_(a-1)}});var Wa;Wa={TimeBufferType:Float32Array,ValueBufferType:Float32Array,DefaultInterpolation:2301,InterpolantFactoryMethodDiscrete:function(a){return new pd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodLinear:function(a){return new Mc(this.times,this.values,
12459 this.getValueSize(),a)},InterpolantFactoryMethodSmooth:function(a){return new od(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);
12460 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=
12461 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=ma.arraySlice(c,e,f),this.values=ma.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",
12462 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&&ma.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,
12463 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,n=m+c,k=0;k!==c;++k){var p=b[m+k];if(p!==b[l+k]||p!==b[n+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=ma.arraySlice(a,0,e),this.values=ma.arraySlice(b,0,e*c));return this}};bc.prototype=Object.assign(Object.create(Wa),{constructor:bc,ValueTypeName:"vector"});
12464 qd.prototype=Object.assign(Object.create(qa.prototype),{constructor:qd,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)ba.slerpFlat(e,0,f,a-g,f,a,b);return e}});Nc.prototype=Object.assign(Object.create(Wa),{constructor:Nc,ValueTypeName:"quaternion",DefaultInterpolation:2301,InterpolantFactoryMethodLinear:function(a){return new qd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:void 0});
12465 cc.prototype=Object.assign(Object.create(Wa),{constructor:cc,ValueTypeName:"number"});rd.prototype=Object.assign(Object.create(Wa),{constructor:rd,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});sd.prototype=Object.assign(Object.create(Wa),{constructor:sd,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});
12466 td.prototype=Object.assign(Object.create(Wa),{constructor:td,ValueTypeName:"color"});vb.prototype=Wa;Wa.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=[];ma.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=
12467 b.toJSON(a);else{var b={name:a.name,times:ma.convertArray(a.times,Array),values:ma.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 cc;case "vector":case "vector2":case "vector3":case "vector4":return bc;case "color":return td;case "quaternion":return Nc;case "bool":case "boolean":return sd;
12468 case "string":return rd}throw Error("Unsupported typeName: "+a);}});Ha.prototype={constructor:Ha,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(Ha,{parse:function(a){for(var b=[],c=a.tracks,
12469 d=1/(a.fps||1),e=0,f=c.length;e!==f;++e)b.push(vb.parse(c[e]).scale(d));return new Ha(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=ma.getKeyframeOrder(h),h=ma.sortedArray(h,1,m),k=ma.sortedArray(k,1,m);d||0!==h[0]||(h.push(e),
12470 k.push(k[0]));f.push((new cc(".morphTargetInfluences["+b[g].name+"]",h,k)).scale(1/c))}return new Ha(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(Ha.CreateFromMorphTargetSequence(m,
12471 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=[];ma.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 n=0;n<m[l].morphTargets.length;n++)f[m[l].morphTargets[n]]=
12472 -1;for(var p in f){for(var q=[],x=[],n=0;n!==m[l].morphTargets.length;++n){var t=m[l];q.push(t.time);x.push(t.morphTarget===p?1:0)}d.push(new cc(".morphTargetInfluence["+p+"]",q,x))}f=f.length*(g||1)}else l=".bones["+b[k].name+"]",c(bc,l+".position",m,"pos",d),c(Nc,l+".quaternion",m,"rot",d),c(bc,l+".scale",m,"scl",d)}return 0===d.length?null:new Ha(e,f,d)}});Object.assign(ud.prototype,{load:function(a,b,c,d){var e=this;(new Ja(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},setTextures:function(a){this.textures=
12473 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 Df[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);
12474 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!==a.opacity&&(d.opacity=a.opacity);void 0!==a.transparent&&(d.transparent=a.transparent);void 0!==a.alphaTest&&(d.alphaTest=
12475 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&&(d.wireframeLinejoin=a.wireframeLinejoin);void 0!==a.skinning&&(d.skinning=a.skinning);void 0!==a.morphTargets&&(d.morphTargets=
12476 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=a.normalScale;!1===Array.isArray(e)&&(e=[e,e]);d.normalScale=(new B).fromArray(e)}void 0!==a.displacementMap&&(d.displacementMap=
12477 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=a.emissiveIntensity);void 0!==a.specularMap&&(d.specularMap=b(a.specularMap));void 0!==a.envMap&&(d.envMap=b(a.envMap));
12478 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);if(void 0!==a.materials)for(var e=0,f=a.materials.length;e<f;e++)d.materials.push(this.parse(a.materials[e]));return d}});Object.assign(Id.prototype,{load:function(a,b,c,d){var e=this;(new Ja(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},
12479 c,d)},parse:function(a){var b=new G,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),b.setIndex(new C(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 C(c,g.itemSize,g.normalized))}d=a.data.groups||a.data.drawcalls||a.data.offsets;
12480 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 Ca(d,a.radius));return b}});wb.prototype={constructor:wb,crossOrigin:void 0,extractUrlBase:function(a){a=a.split("/");if(1===a.length)return"./";a.pop();return a.join("/")+"/"},initMaterials:function(a,b,c){for(var d=[],e=0;e<a.length;++e)d[e]=this.createMaterial(a[e],b,c);return d},createMaterial:function(){var a,
12481 b,c;return function(d,e,f){function g(a,c,d,g,k){a=e+a;var l=wb.Handlers.get(a);null!==l?a=l.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=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=T.generateUUID();h[c]=a;return c}void 0===a&&(a=new O);void 0===b&&(b=new gd);
12482 void 0===c&&(c=new ud);var h={},k={uuid:T.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=Fe[l];break;case "colorAmbient":case "mapAmbient":console.warn("THREE.Loader.createMaterial:",m,"is no longer supported.");break;case "colorDiffuse":k.color=a.fromArray(l).getHex();break;case "colorSpecular":k.specular=a.fromArray(l).getHex();break;
12483 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,d.mapDiffuseWrap,d.mapDiffuseAnisotropy);break;case "mapDiffuseRepeat":case "mapDiffuseOffset":case "mapDiffuseWrap":case "mapDiffuseAnisotropy":break;
12484 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;case "mapAO":k.aoMap=g(l,d.mapAORepeat,d.mapAOOffset,d.mapAOWrap,
12485 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);break;case "mapNormalFactor":k.normalScale=[l,l];break;
12486 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);break;case "mapMetalnessRepeat":case "mapMetalnessOffset":case "mapMetalnessWrap":case "mapMetalnessAnisotropy":break;
12487 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;case "flipSided":k.side=1;break;case "doubleSided":k.side=
12488 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"===k.type&&delete k.emissive;"MeshPhongMaterial"!==
12489 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(Jd.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 Ja(this.manager);g.setWithCredentials(this.withCredentials);
12490 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,b){var c=new Q,d=void 0!==a.scale?1/a.scale:
12491 1;(function(b){var d,g,h,k,l,w,n,p,r,x,t,D,u,v=a.faces;w=a.vertices;var z=a.normals,y=a.colors,E=0;if(void 0!==a.uvs){for(d=0;d<a.uvs.length;d++)a.uvs[d].length&&E++;for(d=0;d<E;d++)c.faceVertexUvs[d]=[]}k=0;for(l=w.length;k<l;)d=new q,d.x=w[k++]*b,d.y=w[k++]*b,d.z=w[k++]*b,c.vertices.push(d);k=0;for(l=v.length;k<l;)if(b=v[k++],r=b&1,h=b&2,d=b&8,n=b&16,x=b&32,w=b&64,b&=128,r){r=new ea;r.a=v[k];r.b=v[k+1];r.c=v[k+3];t=new ea;t.a=v[k+1];t.b=v[k+2];t.c=v[k+3];k+=4;h&&(h=v[k++],r.materialIndex=h,t.materialIndex=
12492 h);h=c.faces.length;if(d)for(d=0;d<E;d++)for(D=a.uvs[d],c.faceVertexUvs[d][h]=[],c.faceVertexUvs[d][h+1]=[],g=0;4>g;g++)p=v[k++],u=D[2*p],p=D[2*p+1],u=new B(u,p),2!==g&&c.faceVertexUvs[d][h].push(u),0!==g&&c.faceVertexUvs[d][h+1].push(u);n&&(n=3*v[k++],r.normal.set(z[n++],z[n++],z[n]),t.normal.copy(r.normal));if(x)for(d=0;4>d;d++)n=3*v[k++],x=new q(z[n++],z[n++],z[n]),2!==d&&r.vertexNormals.push(x),0!==d&&t.vertexNormals.push(x);w&&(w=v[k++],w=y[w],r.color.setHex(w),t.color.setHex(w));if(b)for(d=
12493 0;4>d;d++)w=v[k++],w=y[w],2!==d&&r.vertexColors.push(new O(w)),0!==d&&t.vertexColors.push(new O(w));c.faces.push(r);c.faces.push(t)}else{r=new ea;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<E;d++)for(D=a.uvs[d],c.faceVertexUvs[d][h]=[],g=0;3>g;g++)p=v[k++],u=D[2*p],p=D[2*p+1],u=new B(u,p),c.faceVertexUvs[d][h].push(u);n&&(n=3*v[k++],r.normal.set(z[n++],z[n++],z[n]));if(x)for(d=0;3>d;d++)n=3*v[k++],x=new q(z[n++],z[n++],z[n]),r.vertexNormals.push(x);
12494 w&&(w=v[k++],r.color.setHex(y[w]));if(b)for(d=0;3>d;d++)w=v[k++],r.vertexColors.push(new O(y[w]));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],1<b?a.skinIndices[d+1]:0,2<
12495 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=a.morphTargets[d].name;
12496 c.morphTargets[d].vertices=[];for(var h=c.morphTargets[d].vertices,k=a.morphTargets[d].vertices,l=0,w=k.length;l<w;l+=3){var n=new q;n.x=k[l]*b;n.y=k[l+1]*b;n.z=k[l+2]*b;h.push(n)}}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);void 0!==a.animations&&
12497 (a.animations.length?d=d.concat(a.animations):d.push(a.animations));for(var g=0;g<d.length;g++){var h=Ha.parseAnimation(d[g],c.bones);h&&b.push(h)}c.morphTargets&&(d=Ha.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}}});Object.assign(xe.prototype,
12498 {load:function(a,b,c,d){""===this.texturePath&&(this.texturePath=a.substring(0,a.lastIndexOf("/")+1));var e=this;(new Ja(e.manager)).load(a,function(a){e.parse(JSON.parse(a),b)},c,d)},setTexturePath:function(a){this.texturePath=a},setCrossOrigin:function(a){this.crossOrigin=a},parse:function(a,b){var c=this.parseGeometries(a.geometries),d=this.parseImages(a.images,function(){void 0!==b&&b(e)}),d=this.parseTextures(a.textures,d),d=this.parseMaterials(a.materials,d),e=this.parseObject(a.object,c,d);
12499 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 Jd,d=new Id,e=0,f=a.length;e<f;e++){var g,h=a[e];switch(h.type){case "PlaneGeometry":case "PlaneBufferGeometry":g=new Na[h.type](h.width,h.height,h.widthSegments,h.heightSegments);break;case "BoxGeometry":case "BoxBufferGeometry":case "CubeGeometry":g=new Na[h.type](h.width,h.height,h.depth,h.widthSegments,
12500 h.heightSegments,h.depthSegments);break;case "CircleGeometry":case "CircleBufferGeometry":g=new Na[h.type](h.radius,h.segments,h.thetaStart,h.thetaLength);break;case "CylinderGeometry":case "CylinderBufferGeometry":g=new Na[h.type](h.radiusTop,h.radiusBottom,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "ConeGeometry":case "ConeBufferGeometry":g=new Na[h.type](h.radius,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);
12501 break;case "SphereGeometry":case "SphereBufferGeometry":g=new Na[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=new Na[h.type](h.radius,h.detail);break;case "RingGeometry":case "RingBufferGeometry":g=new Na[h.type](h.innerRadius,h.outerRadius,h.thetaSegments,h.phiSegments,h.thetaStart,h.thetaLength);break;case "TorusGeometry":case "TorusBufferGeometry":g=
12502 new Na[h.type](h.radius,h.tube,h.radialSegments,h.tubularSegments,h.arc);break;case "TorusKnotGeometry":case "TorusKnotBufferGeometry":g=new Na[h.type](h.radius,h.tube,h.tubularSegments,h.radialSegments,h.p,h.q);break;case "LatheGeometry":case "LatheBufferGeometry":g=new Na[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 "'+
12503 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 ud;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=[],c=0;c<a.length;c++){var d=Ha.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)})}
12504 var d=this,e={};if(void 0!==a&&0<a.length){var f=new Fd(b),g=new Lc(f);g.setCrossOrigin(this.crossOrigin);for(var f=0,h=a.length;f<h;f++){var k=a[f],l=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(k.url)?k.url:d.texturePath+k.url;e[k.uuid]=c(l)}}return e},parseTextures:function(a,b){function c(a,b){if("number"===typeof a)return a;console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",a);return b[a]}var d={};if(void 0!==a)for(var e=0,f=a.length;e<f;e++){var g=a[e];void 0===g.image&&
12505 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 da(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,Ge));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],ae),h.wrapT=c(g.wrap[1],ae));void 0!==g.minFilter&&(h.minFilter=c(g.minFilter,be));
12506 void 0!==g.magFilter&&(h.magFilter=c(g.magFilter,be));void 0!==g.anisotropy&&(h.anisotropy=g.anisotropy);void 0!==g.flipY&&(h.flipY=g.flipY);d[g.uuid]=h}return d},parseObject:function(){var a=new J;return function(b,c,d){function e(a){void 0===c[a]&&console.warn("THREE.ObjectLoader: Undefined geometry",a);return c[a]}function f(a){if(void 0!==a)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)&&
12507 (g.background=new O(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 Ea(b.fov,b.aspect,b.near,b.far);void 0!==b.focus&&(g.focus=b.focus);void 0!==b.zoom&&(g.zoom=b.zoom);void 0!==b.filmGauge&&(g.filmGauge=b.filmGauge);void 0!==b.filmOffset&&(g.filmOffset=b.filmOffset);void 0!==b.view&&(g.view=Object.assign({},b.view));break;case "OrthographicCamera":g=
12508 new Hb(b.left,b.right,b.top,b.bottom,b.near,b.far);break;case "AmbientLight":g=new nd(b.color,b.intensity);break;case "DirectionalLight":g=new md(b.color,b.intensity);break;case "PointLight":g=new kd(b.color,b.intensity,b.distance,b.decay);break;case "SpotLight":g=new jd(b.color,b.intensity,b.distance,b.angle,b.penumbra,b.decay);break;case "HemisphereLight":g=new hd(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 dd(g,h):new ya(g,
12509 h);break;case "LOD":g=new rc;break;case "Line":g=new Ta(e(b.geometry),f(b.material),b.mode);break;case "LineSegments":g=new la(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 qc(f(b.material));break;case "Group":g=new sc;break;default:g=new z}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),
12510 void 0!==b.rotation&&g.rotation.fromArray(b.rotation),void 0!==b.quaternion&&g.quaternion.fromArray(b.quaternion),void 0!==b.scale&&g.scale.fromArray(b.scale));void 0!==b.castShadow&&(g.castShadow=b.castShadow);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=
12511 this.parseObject(b.shadow.camera)));void 0!==b.visible&&(g.visible=b.visible);void 0!==b.userData&&(g.userData=b.userData);if(void 0!==b.children)for(var k in b.children)g.add(this.parseObject(b.children[k],c,d));if("LOD"===b.type)for(b=b.levels,h=0;h<b.length;h++){var l=b[h];k=g.getObjectByProperty("uuid",l.object);void 0!==k&&g.addLevel(k,l.distance)}return g}}()});ia.prototype={constructor:ia,getPoint:function(a){console.warn("THREE.Curve: Warning, getPoint() not implemented!");return null},getPointAt:function(a){a=
12512 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/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;
12513 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),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=
12514 a-1E-4;a+=1E-4;0>b&&(b=0);1<a&&(a=1);b=this.getPoint(b);return this.getPoint(a).clone().sub(b).normalize()},getTangentAt:function(a){a=this.getUtoTmapping(a);return this.getTangent(a)},computeFrenetFrames:function(a,b){var c=new q,d=[],e=[],f=[],g=new q,h=new J,k,l;for(k=0;k<=a;k++)l=k/a,d[k]=this.getTangentAt(l),d[k].normalize();e[0]=new q;f[0]=new q;k=Number.MAX_VALUE;l=Math.abs(d[0].x);var w=Math.abs(d[0].y),n=Math.abs(d[0].z);l<=k&&(k=l,c.set(1,0,0));w<=k&&(k=w,c.set(0,1,0));n<=k&&c.set(0,0,1);
12515 g.crossVectors(d[0],c).normalize();e[0].crossVectors(d[0],g);f[0].crossVectors(d[0],e[0]);for(k=1;k<=a;k++)e[k]=e[k-1].clone(),f[k]=f[k-1].clone(),g.crossVectors(d[k-1],d[k]),g.length()>Number.EPSILON&&(g.normalize(),c=Math.acos(T.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(T.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)),
12516 f[k].crossVectors(d[k],e[k]);return{tangents:d,normals:e,binormals:f}}};ia.create=function(a,b){a.prototype=Object.create(ia.prototype);a.prototype.constructor=a;a.prototype.getPoint=b;return a};Sa.prototype=Object.create(ia.prototype);Sa.prototype.constructor=Sa;Sa.prototype.isLineCurve=!0;Sa.prototype.getPoint=function(a){if(1===a)return this.v2.clone();var b=this.v2.clone().sub(this.v1);b.multiplyScalar(a).add(this.v1);return b};Sa.prototype.getPointAt=function(a){return this.getPoint(a)};Sa.prototype.getTangent=
12517 function(a){return this.v2.clone().sub(this.v1).normalize()};Oc.prototype=Object.assign(Object.create(ia.prototype),{constructor:Oc,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 Sa(b,a))},getPoint:function(a){var b=a*this.getLength(),c=this.getCurveLengths();for(a=0;a<c.length;){if(c[a]>=b)return b=c[a]-b,a=this.curves[a],c=a.getLength(),a.getPointAt(0===c?0:1-b/c);a++}return null},
12518 getLength:function(){var a=this.getCurveLengths();return a[a.length-1]},updateArcLengths:function(){this.needsUpdate=!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&&
12519 b.push(b[0]);return b},getPoints:function(a){a=a||12;for(var b=[],c,d=0,e=this.curves;d<e.length;d++)for(var f=e[d],f=f.getPoints(f&&f.isEllipseCurve?2*a:f&&f.isLineCurve?1:f&&f.isSplineCurve?a*f.points.length: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);
12520 return this.createGeometry(a)},createGeometry:function(a){for(var b=new Q,c=0,d=a.length;c<d;c++){var e=a[c];b.vertices.push(new q(e.x,e.y,e.z||0))}return b}});Va.prototype=Object.create(ia.prototype);Va.prototype.constructor=Va;Va.prototype.isEllipseCurve=!0;Va.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+
12521 this.xRadius*Math.cos(b);var e=this.aY+this.yRadius*Math.sin(b);0!==this.aRotation&&(b=Math.cos(this.aRotation),c=Math.sin(this.aRotation),d=a-this.aX,e-=this.aY,a=d*b-e*c+this.aX,e=d*c+e*b+this.aY);return new B(a,e)};var Xc={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*
12522 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)*f+a*e+b}};xb.prototype=Object.create(ia.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=Xc.interpolate;return new B(c(d.x,e.x,f.x,b.x,a),c(d.y,e.y,f.y,b.y,a))};yb.prototype=Object.create(ia.prototype);
12523 yb.prototype.constructor=yb;yb.prototype.getPoint=function(a){var b=ra.b3;return new B(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))};yb.prototype.getTangent=function(a){var b=Xc.tangentCubicBezier;return(new B(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(ia.prototype);zb.prototype.constructor=zb;zb.prototype.getPoint=function(a){var b=ra.b2;return new B(b(a,this.v0.x,
12524 this.v1.x,this.v2.x),b(a,this.v0.y,this.v1.y,this.v2.y))};zb.prototype.getTangent=function(a){var b=Xc.tangentQuadraticBezier;return(new B(b(a,this.v0.x,this.v1.x,this.v2.x),b(a,this.v0.y,this.v1.y,this.v2.y))).normalize()};var de=Object.assign(Object.create(Oc.prototype),{fromPoints:function(a){this.moveTo(a[0].x,a[0].y);for(var b=1,c=a.length;b<c;b++)this.lineTo(a[b].x,a[b].y)},moveTo:function(a,b){this.currentPoint.set(a,b)},lineTo:function(a,b){var c=new Sa(this.currentPoint.clone(),new B(a,b));
12525 this.curves.push(c);this.currentPoint.set(a,b)},quadraticCurveTo:function(a,b,c,d){a=new zb(this.currentPoint.clone(),new B(a,b),new B(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 B(a,b),new B(c,d),new B(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,
12526 e,f){this.absarc(a+this.currentPoint.x,b+this.currentPoint.y,c,d,e,f)},absarc:function(a,b,c,d,e,f){this.absellipse(a,b,c,c,d,e,f)},ellipse:function(a,b,c,d,e,f,g,h){this.absellipse(a+this.currentPoint.x,b+this.currentPoint.y,c,d,e,f,g,h)},absellipse:function(a,b,c,d,e,f,g,h){a=new Va(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(de),
12527 {constructor:Ab,getPointsHoles:function(a){for(var b=[],c=0,d=this.holes.length;c<d;c++)b[c]=this.holes[c].getPoints(a);return b},extractAllPoints:function(a){return{shape:this.getPoints(a),holes:this.getPointsHoles(a)}},extractPoints:function(a){return this.extractAllPoints(a)}});Pc.prototype=de;de.constructor=Pc;Kd.prototype={moveTo:function(a,b){this.currentPath=new Pc;this.subPaths.push(this.currentPath);this.currentPath.moveTo(a,b)},lineTo:function(a,b){this.currentPath.lineTo(a,b)},quadraticCurveTo:function(a,
12528 b,c,d){this.currentPath.quadraticCurveTo(a,b,c,d)},bezierCurveTo:function(a,b,c,d,e,f){this.currentPath.bezierCurveTo(a,b,c,d,e,f)},splineThru:function(a){this.currentPath.splineThru(a)},toShapes:function(a,b){function c(a){for(var b=[],c=0,d=a.length;c<d;c++){var e=a[c],f=new Ab;f.curves=e.curves;b.push(f)}return b}function d(a,b){for(var c=b.length,d=!1,e=c-1,f=0;f<c;e=f++){var g=b[e],h=b[f],k=h.x-g.x,l=h.y-g.y;if(Math.abs(l)>Number.EPSILON){if(0>l&&(g=b[f],k=-k,h=b[e],l=-l),!(a.y<g.y||a.y>h.y))if(a.y===
12529 g.y){if(a.x===g.x)return!0}else{e=l*(a.x-g.x)-k*(a.y-g.y);if(0===e)return!0;0>e||(d=!d)}}else if(a.y===g.y&&(h.x<=a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=ra.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);var g,h,k,l=[];if(1===f.length)return h=f[0],k=new Ab,k.curves=h.curves,l.push(k),l;var q=!e(f[0].getPoints()),q=a?!q:q;k=[];var n=[],p=[],r=0,x;n[r]=void 0;p[r]=[];for(var t=0,D=f.length;t<D;t++)h=f[t],x=h.getPoints(),g=e(x),(g=a?!g:g)?(!q&&n[r]&&r++,
12530 n[r]={s:new Ab,p:x},n[r].s.curves=h.curves,q&&r++,p[r]=[]):p[r].push({h:h,p:x[0]});if(!n[0])return c(f);if(1<n.length){t=!1;h=[];e=0;for(f=n.length;e<f;e++)k[e]=[];e=0;for(f=n.length;e<f;e++)for(g=p[e],q=0;q<g.length;q++){r=g[q];x=!0;for(D=0;D<n.length;D++)d(r.p,n[D].p)&&(e!==D&&h.push({froms:e,tos:D,hole:q}),x?(x=!1,k[D].push(r)):t=!0);x&&k[e].push(r)}0<h.length&&(t||(p=k))}t=0;for(e=n.length;t<e;t++)for(k=n[t].s,l.push(k),h=p[t],f=0,g=h.length;f<g;f++)k.holes.push(h[f].h);return l}};Object.assign(Ld.prototype,
12531 {isFont:!0,generateShapes:function(a,b,c){void 0===b&&(b=100);void 0===c&&(c=4);var d=this.data;a=String(a).split("");var e=b/d.resolution,f=0;b=[];for(var g=0;g<a.length;g++){var h;h=e;var k=f,l=d.glyphs[a[g]]||d.glyphs["?"];if(l){var q=new Kd,n=[],p=ra.b2,r=ra.b3,x,t,D,u,v,z,y,E;if(l.o)for(var B=l._cachedOutline||(l._cachedOutline=l.o.split(" ")),C=0,G=B.length;C<G;)switch(B[C++]){case "m":x=B[C++]*h+k;t=B[C++]*h;q.moveTo(x,t);break;case "l":x=B[C++]*h+k;t=B[C++]*h;q.lineTo(x,t);break;case "q":x=
12532 B[C++]*h+k;t=B[C++]*h;v=B[C++]*h+k;z=B[C++]*h;q.quadraticCurveTo(v,z,x,t);if(u=n[n.length-1]){D=u.x;u=u.y;for(var J=1;J<=c;J++){var K=J/c;p(K,D,v,x);p(K,u,z,t)}}break;case "b":if(x=B[C++]*h+k,t=B[C++]*h,v=B[C++]*h+k,z=B[C++]*h,y=B[C++]*h+k,E=B[C++]*h,q.bezierCurveTo(v,z,y,E,x,t),u=n[n.length-1])for(D=u.x,u=u.y,J=1;J<=c;J++)K=J/c,r(K,D,v,y,x),r(K,u,z,E,t)}h={offset:l.ha*h,path:q}}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());
12533 return c}});Object.assign(ye.prototype,{load:function(a,b,c,d){var e=this;(new Ja(this.manager)).load(a,function(a){var c;try{c=JSON.parse(a)}catch(d){console.warn("THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead."),c=JSON.parse(a.substring(65,a.length-2))}a=e.parse(c);b&&b(a)},c,d)},parse:function(a){return new Ld(a)}});var Nd;Object.assign(Od.prototype,{load:function(a,b,c,d){var e=new Ja(this.manager);e.setResponseType("arraybuffer");e.load(a,function(a){Md().decodeAudioData(a,
12534 function(a){b(a)})},c,d)}});Object.assign(ze.prototype,{update:function(){var a,b,c,d,e,f,g,h=new J,k=new J;return function(l){if(a!==this||b!==l.focus||c!==l.fov||d!==l.aspect*this.aspect||e!==l.near||f!==l.far||g!==l.zoom){a=this;b=l.focus;c=l.fov;d=l.aspect*this.aspect;e=l.near;f=l.far;g=l.zoom;var q=l.projectionMatrix.clone(),n=this.eyeSep/2,p=n*e/b,r=e*Math.tan(T.DEG2RAD*c*.5)/g,x;k.elements[12]=-n;h.elements[12]=n;n=-r*d+p;x=r*d+p;q.elements[0]=2*e/(x-n);q.elements[8]=(x+n)/(x-n);this.cameraL.projectionMatrix.copy(q);
12535 n=-r*d-p;x=r*d-p;q.elements[0]=2*e/(x-n);q.elements[8]=(x+n)/(x-n);this.cameraR.projectionMatrix.copy(q)}this.cameraL.matrixWorld.copy(l.matrixWorld).multiply(k);this.cameraR.matrixWorld.copy(l.matrixWorld).multiply(h)}}()});vd.prototype=Object.create(z.prototype);vd.prototype.constructor=vd;Pd.prototype=Object.assign(Object.create(z.prototype),{constructor:Pd,getInput:function(){return this.gain},removeFilter:function(){null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),
12536 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);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=
12537 new q,b=new ba,c=new q,d=new q;return function(e){z.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.setPosition(a.x,a.y,a.z);e.setOrientation(d.x,d.y,d.z,f.x,f.y,f.z)}}()});dc.prototype=Object.assign(Object.create(z.prototype),{constructor:dc,getOutput:function(){return this.gain},setNodeSource:function(a){this.hasPlaybackControl=!1;this.sourceType="audioNode";this.source=a;this.connect();return this},
12538 setBuffer:function(a){this.source.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.");else{var a=this.context.createBufferSource();a.buffer=this.source.buffer;a.loop=this.source.loop;a.onended=this.source.onended;a.start(0,this.startTime);a.playbackRate.value=this.playbackRate;this.isPlaying=
12539 !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.");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]);
12540 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-1].disconnect(this.filters[a]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this},
12541 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.");else return this.playbackRate=a,!0===this.isPlaying&&(this.source.playbackRate.value=this.playbackRate),
12542 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.source.loop},setLoop:function(a){!1===this.hasPlaybackControl?console.warn("THREE.Audio: this Audio has no playback control."):this.source.loop=a},getVolume:function(){return this.gain.gain.value},setVolume:function(a){this.gain.gain.value=a;return this}});Qd.prototype=Object.assign(Object.create(dc.prototype),
12543 {constructor:Qd,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=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=
12544 a},updateMatrixWorld:function(){var a=new q;return function(b){z.prototype.updateMatrixWorld.call(this,b);a.setFromMatrixPosition(this.matrixWorld);this.panner.setPosition(a.x,a.y,a.z)}}()});Object.assign(Rd.prototype,{getFrequencyData:function(){this.analyser.getByteFrequencyData(this.data);return this.data},getAverageFrequency:function(){for(var a=0,b=this.getFrequencyData(),c=0;c<b.length;c++)a+=b[c];return a/b.length}});wd.prototype={constructor:wd,accumulate:function(a,b){var c=this.buffer,d=
12545 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&&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=
12546 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){ba.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f=1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}};fa.prototype={constructor:fa,getValue:function(a,b){this.bind();this.getValue(a,b)},setValue:function(a,b){this.bind();this.setValue(a,b)},bind:function(){var a=
12547 this.node,b=this.parsedPath,c=b.objectName,d=b.propertyName,e=b.propertyIndex;a||(this.node=a=fa.findNode(this.rootNode,b.nodeName)||this.rootNode);this.getValue=this._getValue_unavailable;this.setValue=this._setValue_unavailable;if(a){if(c){var f=b.objectIndex;switch(c){case "materials":if(!a.material){console.error("  can not bind to material as node does not have a material",this);return}if(!a.material.materials){console.error("  can not bind to material.materials as node.material does not have a materials array",
12548 this);return}a=a.material.materials;break;case "bones":if(!a.skeleton){console.error("  can not bind to bones as node does not have a skeleton",this);return}a=a.skeleton.bones;for(c=0;c<a.length;c++)if(a[c].name===f){f=c;break}break;default:if(void 0===a[c]){console.error("  can not bind to objectName of node, undefined",this);return}a=a[c]}if(void 0!==f){if(void 0===a[f]){console.error("  trying to bind to objectIndex of objectName, but is undefined:",this,a);return}a=a[f]}}f=a[d];if(void 0===f)console.error("  trying to update property for track: "+
12549 b.nodeName+"."+d+" but it wasn't found.",a);else{b=this.Versioning.None;void 0!==a.needsUpdate?(b=this.Versioning.NeedsUpdate,this.targetObject=a):void 0!==a.matrixWorldNeedsUpdate&&(b=this.Versioning.MatrixWorldNeedsUpdate,this.targetObject=a);c=this.BindingType.Direct;if(void 0!==e){if("morphTargetInfluences"===d){if(!a.geometry){console.error("  can not bind to morphTargetInfluences becasuse node does not have a geometry",this);return}if(!a.geometry.morphTargets){console.error("  can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets",
12550 this);return}for(c=0;c<this.node.geometry.morphTargets.length;c++)if(a.geometry.morphTargets[c].name===e){e=c;break}}c=this.BindingType.ArrayElement;this.resolvedProperty=f;this.propertyIndex=e}else void 0!==f.fromArray&&void 0!==f.toArray?(c=this.BindingType.HasFromToArray,this.resolvedProperty=f):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: "+
12551 this.path+" but it wasn't found.")},unbind:function(){this.node=null;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}};Object.assign(fa.prototype,{_getValue_unavailable:function(){},_setValue_unavailable:function(){},_getValue_unbound:fa.prototype.getValue,_setValue_unbound:fa.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]},
12552 function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)a[b++]=c[d]},function(a,b){a[b]=this.resolvedProperty[this.propertyIndex]},function(a,b){this.resolvedProperty.toArray(a,b)}],SetterByBindingTypeAndVersioning:[[function(a,b){this.node[this.propertyName]=a[b]},function(a,b){this.node[this.propertyName]=a[b];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,
12553 d=0,e=c.length;d!==e;++d)c[d]=a[b++]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.needsUpdate=!0},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty[this.propertyIndex]=a[b]},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];
12554 this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty.fromArray(a,b)},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.matrixWorldNeedsUpdate=!0}]]});fa.Composite=function(a,b,c){c=c||fa.parseTrackName(b);this._targetGroup=a;this._bindings=a.subscribe_(b,c)};fa.Composite.prototype={constructor:fa.Composite,getValue:function(a,b){this.bind();var c=this._bindings[this._targetGroup.nCachedObjects_];
12555 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_,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()}};fa.create=function(a,b,c){return a&&a.isAnimationObjectGroup?new fa.Composite(a,b,c):new fa(a,b,c)};fa.parseTrackName=function(a){var b=
12556 /^((?:\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]};if(null===b.propertyName||0===b.propertyName.length)throw Error("can not parse propertyName from trackName: "+a);return b};fa.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=
12557 a.bones[c];if(d.name===b)return d}return null}(a.skeleton);if(c)return c}if(a.children){var d=function(a){for(var c=0;c<a.length;c++){var g=a[c];if(g.name===b||g.uuid===b||(g=d(g.children)))return g}return null};if(c=d(a.children))return c}return null};Sd.prototype={constructor:Sd,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 n=
12558 arguments[l],p=n.uuid,r=e[p];if(void 0===r){r=c++;e[p]=r;b.push(n);for(var p=0,x=k;p!==x;++p)h[p].push(new fa(n,f[p],g[p]))}else if(r<d){var t=b[r],D=--d,x=b[D];e[x.uuid]=r;b[r]=x;e[p]=D;b[D]=n;p=0;for(x=k;p!==x;++p){var u=h[p],v=u[r];u[r]=u[D];void 0===v&&(v=new fa(n,f[p],g[p]));u[D]=v}}else b[r]!==t&&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,
12559 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 n=c++,p=b[n];d[p.uuid]=q;b[q]=p;d[l]=n;b[n]=k;k=0;for(l=f;k!==l;++k){var p=e[k],r=p[q];p[q]=p[n];p[n]=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!==
12560 q)if(delete e[l],q<d){var l=--d,n=b[l],p=--c,r=b[p];e[n.uuid]=q;b[q]=n;e[r.uuid]=l;b[l]=r;b.pop();n=0;for(r=g;n!==r;++n){var x=f[n],t=x[p];x[q]=x[l];x[l]=t;x.pop()}}else for(p=--c,r=b[p],e[r.uuid]=q,b[q]=r,b.pop(),n=0,r=g;n!==r;++n)x=f[n],x[q]=x[p],x.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]=
12561 d;f.push(a);g.push(b);e.push(l);c=k;for(d=h.length;c!==d;++c)l[c]=new fa(h[c],a,b);return l},unsubscribe_:function(a){var b=this._bindingsIndicesByPath,c=b[a];if(void 0!==c){var d=this._paths,e=this._parsedPaths,f=this._bindings,g=f.length-1,h=f[g];b[a[g]]=c;f[c]=h;f.pop();e[c]=e[g];e.pop();d[c]=d[g];d.pop()}}};Td.prototype={constructor:Td,play:function(){this._mixer._activateAction(this);return this},stop:function(){this._mixer._deactivateAction(this);return this.reset()},reset:function(){this.paused=
12562 !1;this.enabled=!0;this.time=0;this._loopCount=-1;this._startTime=null;return this.stopFading().stopWarping()},isRunning:function(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)},isScheduled:function(){return this._mixer._isActiveAction(this)},startAt:function(a){this._startTime=a;return this},setLoop:function(a,b){this.loop=a;this.repetitions=b;return this},setEffectiveWeight:function(a){this.weight=a;this._effectiveWeight=this.enabled?
12563 a:0;return this.stopFading()},getEffectiveWeight:function(){return this._effectiveWeight},fadeIn:function(a){return this._scheduleFading(a,0,1)},fadeOut:function(a){return this._scheduleFading(a,1,0)},crossFadeFrom:function(a,b,c){a.fadeOut(b);this.fadeIn(b);if(c){c=this._clip.duration;var d=a._clip.duration,e=c/d;a.warp(1,d/c,b);this.warp(e,1,b)}return this},crossFadeTo:function(a,b,c){return a.crossFadeFrom(this,b,c)},stopFading:function(){var a=this._weightInterpolant;null!==a&&(this._weightInterpolant=
12564 null,this._mixer._takeBackControlInterpolant(a));return this},setEffectiveTimeScale:function(a){this.timeScale=a;this._effectiveTimeScale=this.paused?0:a;return this.stopWarping()},getEffectiveTimeScale:function(){return this._effectiveTimeScale},setDuration:function(a){this.timeScale=this._clip.duration/a;return this.stopWarping()},syncWith:function(a){this.time=a.time;this.timeScale=a.timeScale;return this.stopWarping()},halt:function(a){return this.warp(this._effectiveTimeScale,0,a)},warp:function(a,
12565 b,c){var d=this._mixer,e=d.time,f=this._timeScaleInterpolant,g=this.timeScale;null===f&&(this._timeScaleInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;d[1]=e+c;f[0]=a/g;f[1]=b/g;return this},stopWarping:function(){var a=this._timeScaleInterpolant;null!==a&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(a));return this},getMixer:function(){return this._mixer},getClip:function(){return this._clip},getRoot:function(){return this._localRoot||
12566 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,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]&&
12567 (this.stopFading(),0===d&&(this.enabled=!1))}}return this._effectiveWeight=b},_updateTimeScale:function(a){var b=0;if(!this.paused){var b=this.timeScale,c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.parameterPositions[1]&&(this.stopWarping(),0===b?this.paused=!0:this.timeScale=b)}}return this._effectiveTimeScale=b},_updateTime:function(a){var b=this.time+a;if(0===a)return b;var c=this._clip.duration,d=this.loop,e=this._loopCount;if(2200===d)a:{if(-1===e&&(this.loopCount=
12568 0,this._setEndings(!0,!0,!1)),b>=c)b=c;else if(0>b)b=0;else break a;this.clampWhenFinished?this.paused=!0:this.enabled=!1;this._mixer.dispatchEvent({type:"finished",action:this,direction:0>a?-1:1})}else{d=2202===d;-1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions,d)):this._setEndings(0===this.repetitions,!0,d));if(b>=c||0>b){var f=Math.floor(b/c),b=b-c*f,e=e+Math.abs(f),g=this.repetitions-e;0>g?(this.clampWhenFinished?this.paused=!0:this.enabled=!1,b=0<a?c:0,this._mixer.dispatchEvent({type:"finished",
12569 action:this,direction:0<a?1:-1})):(0===g?(a=0>a,this._setEndings(a,!a,d)):this._setEndings(!1,!1,d),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:f}))}if(d&&1===(e&1))return this.time=b,c-b}return this.time=b},_setEndings:function(a,b,c){var d=this._interpolantSettings;c?(d.endingStart=2401,d.endingEnd=2401):(d.endingStart=a?this.zeroSlopeAtStart?2401:2400:2402,d.endingEnd=b?this.zeroSlopeAtEnd?2401:2400:2402)},_scheduleFading:function(a,b,c){var d=this._mixer,e=d.time,
12570 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(Ud.prototype,sa.prototype,{clipAction:function(a,b){var c=b||this._root,d=c.uuid,e="string"===typeof a?Ha.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 Td(this,
12571 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?Ha.findByName(c,a):a,c=this._actionsByClip[c?c.uuid:a];return void 0!==c?c.actionByRoot[d]||null:null},stopAllAction:function(){for(var a=this._actions,b=this._nActiveActions,c=this._bindings,d=this._nActiveBindings,e=this._nActiveBindings=this._nActiveActions=0;e!==b;++e)a[e].reset();for(e=0;e!==d;++e)c[e].useCount=0;return this},update:function(a){a*=
12572 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},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,
12573 k=b[b.length-1];g._cacheIndex=null;g._byClipCacheIndex=null;k._cacheIndex=h;b[h]=k;b.pop();this._removeInactiveBindingsForAction(g)}delete c[a]}},uncacheRoot:function(a){a=a.uuid;var b=this._actionsByClip,c;for(c in b){var d=b[c].actionByRoot[a];void 0!==d&&(this._deactivateAction(d),this._removeInactiveAction(d))}c=this._bindingsByRootAndName[a];if(void 0!==c)for(var e in c)a=c[e],a.restoreOriginalState(),this._removeInactiveBinding(a)},uncacheAction:function(a,b){var c=this.existingAction(a,b);
12574 null!==c&&(this._deactivateAction(c),this._removeInactiveAction(c))}});Object.assign(Ud.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=d[k],n=q.name,p=l[n];if(void 0===p){p=f[k];if(void 0!==p){null===p._cacheIndex&&(++p.referenceCount,this._addInactiveBinding(p,h,n));continue}p=new wd(fa.create(c,n,b&&b._propertyBindings[k].binding.parsedPath),
12575 q.ValueTypeName,q.getValueSize());++p.referenceCount;this._addInactiveBinding(p,h,n)}f[k]=p;g[k].resultBuffer=p.buffer}},_activateAction:function(a){if(!this._isActiveAction(a)){if(null===a._cacheIndex){var b=(a._localRoot||this._root).uuid,c=a._clip.uuid,d=this._actionsByClip[c];this._bindAction(a,d&&d.knownActions[0]);this._addInactiveAction(a,c,b)}b=a._propertyBindings;c=0;for(d=b.length;c!==d;++c){var e=b[c];0===e.useCount++&&(this._lendBinding(e),e.saveOriginalState())}this._lendAction(a)}},
12576 _deactivateAction:function(a){if(this._isActiveAction(a)){for(var b=a._propertyBindings,c=0,d=b.length;c!==d;++c){var e=b[c];0===--e.useCount&&(e.restoreOriginalState(),this._takeBackBinding(e))}this._takeBackAction(a)}},_initMemoryManager:function(){this._actions=[];this._nActiveActions=0;this._actionsByClip={};this._bindings=[];this._nActiveBindings=0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var a=this;this.stats={actions:{get total(){return a._actions.length},
12577 get inUse(){return a._nActiveActions}},bindings:{get total(){return a._bindings.length},get inUse(){return a._nActiveBindings}},controlInterpolants:{get total(){return a._controlInterpolants.length},get inUse(){return a._nActiveControlInterpolants}}}},_isActiveAction:function(a){a=a._cacheIndex;return null!==a&&a<this._nActiveActions},_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=
12578 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=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)},
12579 _removeInactiveBindingsForAction:function(a){a=a._propertyBindings;for(var b=0,c=a.length;b!==c;++b){var d=a[b];0===--d.referenceCount&&this._removeInactiveBinding(d)}},_lendAction:function(a){var b=this._actions,c=a._cacheIndex,d=this._nActiveActions++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackAction:function(a){var b=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,
12580 e=d[b],f=this._bindings;void 0===e&&(e={},d[b]=e);e[c]=a;a._cacheIndex=f.length;f.push(a)},_removeInactiveBinding:function(a){var b=this._bindings,c=a.binding,d=c.rootNode.uuid,c=c.path,e=this._bindingsByRootAndName,f=e[d],g=b[b.length-1];a=a._cacheIndex;g._cacheIndex=a;b[a]=g;b.pop();delete f[c];a:{for(var h in f)break a;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=
12581 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 Mc(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer),c.__cacheIndex=b,a[b]=c);return c},_takeBackControlInterpolant:function(a){var b=this._controlInterpolants,c=a.__cacheIndex,d=--this._nActiveControlInterpolants,e=b[d];a.__cacheIndex=
12582 d;b[d]=a;e.__cacheIndex=c;b[c]=e},_controlInterpolantsResultBuffer:new Float32Array(1)});Bb.prototype=Object.create(G.prototype);Bb.prototype.constructor=Bb;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,
12583 d.count,d.materialIndex)}return this};Vd.prototype={constructor:Vd,isInterleavedBufferAttribute:!0,get count(){return this.data.count},get array(){return this.data.array},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},
12584 getX:function(a){return this.data.array[a*this.data.stride+this.offset]},getY:function(a){return this.data.array[a*this.data.stride+this.offset+1]},getZ:function(a){return this.data.array[a*this.data.stride+this.offset+2]},getW:function(a){return this.data.array[a*this.data.stride+this.offset+3]},setXY:function(a,b,c){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+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+
12585 1]=c;this.data.array[a+2]=d;return this},setXYZW:function(a,b,c,d,e){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;this.data.array[a+3]=e;return this}};ec.prototype={constructor:ec,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=
12586 a;return this},copy:function(a){this.array=new a.array.constructor(a.array);this.count=a.count;this.stride=a.stride;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.stride;c*=b.stride;for(var d=0,e=this.stride;d<e;d++)this.array[a+d]=b.array[c+d];return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},clone:function(){return(new this.constructor).copy(this)}};fc.prototype=Object.create(ec.prototype);fc.prototype.constructor=fc;fc.prototype.isInstancedInterleavedBuffer=
12587 !0;fc.prototype.copy=function(a){ec.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this};gc.prototype=Object.create(C.prototype);gc.prototype.constructor=gc;gc.prototype.isInstancedBufferAttribute=!0;gc.prototype.copy=function(a){C.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this};Wd.prototype={constructor:Wd,linePrecision:1,set:function(a,b){this.ray.set(a,b)},setFromCamera:function(a,b){b&&b.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(b.matrixWorld),
12588 this.ray.direction.set(a.x,a.y,.5).unproject(b).sub(this.ray.origin).normalize()):b&&b.isOrthographicCamera?(this.ray.origin.set(a.x,a.y,(b.near+b.far)/(b.near-b.far)).unproject(b),this.ray.direction.set(0,0,-1).transformDirection(b.matrixWorld)):console.error("THREE.Raycaster: Unsupported camera type.")},intersectObject:function(a,b){var c=[];Xd(a,this,c,b);c.sort(Be);return c},intersectObjects:function(a,b){var c=[];if(!1===Array.isArray(a))return console.warn("THREE.Raycaster.intersectObjects: objects is not an Array."),
12589 c;for(var d=0,e=a.length;d<e;d++)Xd(a[d],this,c,b);c.sort(Be);return c}};Yd.prototype={constructor:Yd,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+=
12590 a}return a}};Zd.prototype={constructor:Zd,set:function(a,b,c){this.radius=a;this.phi=b;this.theta=c;return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.radius=a.radius;this.phi=a.phi;this.theta=a.theta;return this},makeSafe:function(){this.phi=Math.max(1E-6,Math.min(Math.PI-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(T.clamp(a.y/this.radius,
12591 -1,1)));return this}};na.prototype=Object.create(ya.prototype);na.prototype.constructor=na;na.prototype.createAnimation=function(a,b,c,d){b={start:b,end:c,length:c-b+1,fps:d,duration:(c-b)/d,lastFrame:0,currentFrame:0,active:!1,time:0,direction:1,weight:1,directionBackwards:!1,mirroredLoop:!1};this.animationsMap[a]=b;this.animationsList.push(b)};na.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);
12592 if(h&&1<h.length){var k=h[1];d[k]||(d[k]={start:Infinity,end:-Infinity});h=d[k];f<h.start&&(h.start=f);f>h.end&&(h.end=f);c||(c=k)}}for(k in d)h=d[k],this.createAnimation(k,h.start,h.end,a);this.firstAnimation=c};na.prototype.setAnimationDirectionForward=function(a){if(a=this.animationsMap[a])a.direction=1,a.directionBackwards=!1};na.prototype.setAnimationDirectionBackward=function(a){if(a=this.animationsMap[a])a.direction=-1,a.directionBackwards=!0};na.prototype.setAnimationFPS=function(a,b){var c=
12593 this.animationsMap[a];c&&(c.fps=b,c.duration=(c.end-c.start)/c.fps)};na.prototype.setAnimationDuration=function(a,b){var c=this.animationsMap[a];c&&(c.duration=b,c.fps=(c.end-c.start)/c.duration)};na.prototype.setAnimationWeight=function(a,b){var c=this.animationsMap[a];c&&(c.weight=b)};na.prototype.setAnimationTime=function(a,b){var c=this.animationsMap[a];c&&(c.time=b)};na.prototype.getAnimationTime=function(a){var b=0;if(a=this.animationsMap[a])b=a.time;return b};na.prototype.getAnimationDuration=
12594 function(a){var b=-1;if(a=this.animationsMap[a])b=a.duration;return b};na.prototype.playAnimation=function(a){var b=this.animationsMap[a];b?(b.time=0,b.active=!0):console.warn("THREE.MorphBlendMesh: animation["+a+"] undefined in .playAnimation()")};na.prototype.stopAnimation=function(a){if(a=this.animationsMap[a])a.active=!1};na.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>
12595 d.duration||0>d.time)d.direction*=-1,d.time>d.duration&&(d.time=d.duration,d.directionBackwards=!0),0>d.time&&(d.time=0,d.directionBackwards=!1)}else d.time%=d.duration,0>d.time&&(d.time+=d.duration);var f=d.start+T.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!==
12596 d.lastFrame?(this.morphTargetInfluences[d.currentFrame]=e*g,this.morphTargetInfluences[d.lastFrame]=(1-e)*g):this.morphTargetInfluences[d.currentFrame]=g}}};Qc.prototype=Object.create(z.prototype);Qc.prototype.constructor=Qc;Qc.prototype.isImmediateRenderObject=!0;Rc.prototype=Object.create(la.prototype);Rc.prototype.constructor=Rc;Rc.prototype.update=function(){var a=new q,b=new q,c=new Ia;return function(){var d=["a","b","c"];this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);
12597 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 n=k[l],p=0,r=n.vertexNormals.length;p<r;p++){var x=n.vertexNormals[p];a.copy(h[n[d[p]]]).applyMatrix4(e);b.copy(x).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,p=g=0,r=d.count;p<
12598 r;p++)a.set(d.getX(p),d.getY(p),d.getZ(p)).applyMatrix4(e),b.set(h.getX(p),h.getY(p),h.getZ(p)),b.applyMatrix3(c).normalize().multiplyScalar(this.size).add(a),f.setXYZ(g,a.x,a.y,a.z),g+=1,f.setXYZ(g,b.x,b.y,b.z),g+=1;f.needsUpdate=!0;return this}}();hc.prototype=Object.create(z.prototype);hc.prototype.constructor=hc;hc.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()};hc.prototype.update=function(){var a=new q,b=new q;return function(){var c=this.light.distance?
12599 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));this.cone.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)}}();ic.prototype=Object.create(la.prototype);ic.prototype.constructor=ic;ic.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]));
12600 return b};ic.prototype.update=function(){for(var a=this.geometry,b=(new J).getInverse(this.root.matrixWorld),c=new J,d=0,e=0;e<this.bones.length;e++){var f=this.bones[e];f.parent&&f.parent.isBone&&(c.multiplyMatrices(b,f.matrixWorld),a.vertices[d].setFromMatrixPosition(c),c.multiplyMatrices(b,f.parent.matrixWorld),a.vertices[d+1].setFromMatrixPosition(c),d+=2)}a.verticesNeedUpdate=!0;a.computeBoundingSphere()};jc.prototype=Object.create(ya.prototype);jc.prototype.constructor=jc;jc.prototype.dispose=
12601 function(){this.geometry.dispose();this.material.dispose()};jc.prototype.update=function(){this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)};kc.prototype=Object.create(z.prototype);kc.prototype.constructor=kc;kc.prototype.dispose=function(){this.lightSphere.geometry.dispose();this.lightSphere.material.dispose()};kc.prototype.update=function(){var a=new q;return function(){this.colors[0].copy(this.light.color).multiplyScalar(this.light.intensity);this.colors[1].copy(this.light.groundColor).multiplyScalar(this.light.intensity);
12602 this.lightSphere.lookAt(a.setFromMatrixPosition(this.light.matrixWorld).negate());this.lightSphere.geometry.colorsNeedUpdate=!0}}();Sc.prototype=Object.create(la.prototype);Sc.prototype.constructor=Sc;Sc.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")};Tc.prototype=Object.create(la.prototype);Tc.prototype.constructor=Tc;Tc.prototype.update=function(){var a=new q,b=new q,c=new Ia;return function(){this.object.updateMatrixWorld(!0);
12603 c.getNormalMatrix(this.object.matrixWorld);for(var d=this.object.matrixWorld,e=this.geometry.attributes.position,f=this.object.geometry,g=f.vertices,f=f.faces,h=0,k=0,l=f.length;k<l;k++){var q=f[k],n=q.normal;a.copy(g[q.a]).add(g[q.b]).add(g[q.c]).divideScalar(3).applyMatrix4(d);b.copy(n).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}}();lc.prototype=Object.create(z.prototype);lc.prototype.constructor=
12604 lc;lc.prototype.dispose=function(){var a=this.children[0],b=this.children[1];a.geometry.dispose();a.material.dispose();b.geometry.dispose();b.material.dispose()};lc.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);
12605 e.scale.z=c.length()}}();Uc.prototype=Object.create(la.prototype);Uc.prototype.constructor=Uc;Uc.prototype.update=function(){function a(a,g,h,k){d.set(g,h,k).unproject(e);a=c[a];if(void 0!==a)for(g=0,h=a.length;g<h;g++)b.vertices[a[g]].copy(d)}var b,c,d=new q,e=new Z;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",
12606 -1,1,1);a("f4",1,1,1);a("u1",.7,1.1,-1);a("u2",-.7,1.1,-1);a("u3",0,2,-1);a("cf1",-1,0,1);a("cf2",1,0,1);a("cf3",0,-1,1);a("cf4",0,1,1);a("cn1",-1,0,-1);a("cn2",1,0,-1);a("cn3",0,-1,-1);a("cn4",0,1,-1);b.verticesNeedUpdate=!0}}();Vc.prototype=Object.create(ya.prototype);Vc.prototype.constructor=Vc;Vc.prototype.update=function(){this.box.setFromObject(this.object);this.box.getSize(this.scale);this.box.getCenter(this.position)};Wc.prototype=Object.create(la.prototype);Wc.prototype.constructor=Wc;Wc.prototype.update=
12607 function(){var a=new Ba;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]=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 Ce=new G;Ce.addAttribute("position",new ha([0,
12608 0,0,0,1,0],3));var De=new Ua(0,.5,1,5,1);De.translate(0,-.5,0);Cb.prototype=Object.create(z.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(),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();
12609 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)};xd.prototype=Object.create(la.prototype);xd.prototype.constructor=xd;var $d=function(){function a(){}var b=new q,c=new a,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,n){this.init(b,c,((b-a)/e-(c-a)/
12610 (e+l)+(c-b)/l)*l,((c-b)/l-(d-b)/(l+n)+(d-c)/n)*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 ia.create(function(a){this.points=a||[];this.closed=!1},function(a){var g=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-
12611 1&&(h=k-2,a=1);var l,w,n;this.closed||0<h?l=g[(h-1)%k]:(b.subVectors(g[0],g[1]).add(g[0]),l=b);w=g[h%k];n=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 p="chordal"===this.type?.5:.25;k=Math.pow(l.distanceToSquared(w),p);h=Math.pow(w.distanceToSquared(n),p);p=Math.pow(n.distanceToSquared(g),p);1E-4>h&&(h=1);1E-4>k&&(k=h);1E-4>p&&(p=h);c.initNonuniformCatmullRom(l.x,w.x,n.x,g.x,k,
12612 h,p);d.initNonuniformCatmullRom(l.y,w.y,n.y,g.y,k,h,p);e.initNonuniformCatmullRom(l.z,w.z,n.z,g.z,k,h,p)}else"catmullrom"===this.type&&(k=void 0!==this.tension?this.tension:.5,c.initCatmullRom(l.x,w.x,n.x,g.x,k),d.initCatmullRom(l.y,w.y,n.y,g.y,k),e.initCatmullRom(l.z,w.z,n.z,g.z,k));return new q(c.calc(a),d.calc(a),e.calc(a))})}();Ee.prototype=Object.create($d.prototype);var Ef=ia.create(function(a){console.warn("THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3");this.points=
12613 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=Xc.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))}),Ff=ia.create(function(a,b,c,d){this.v0=a;this.v1=b;this.v2=c;this.v3=d},function(a){var b=ra.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,
12614 this.v3.z))}),Gf=ia.create(function(a,b,c){this.v0=a;this.v1=b;this.v2=c},function(a){var b=ra.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))}),Hf=ia.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);b.add(this.v1);return b});yd.prototype=Object.create(Va.prototype);yd.prototype.constructor=yd;Object.assign(mc.prototype,{center:function(a){console.warn("THREE.Box2: .center() has been renamed to .getCenter().");
12615 return this.getCenter(a)},empty:function(){console.warn("THREE.Box2: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},size:function(a){console.warn("THREE.Box2: .size() has been renamed to .getSize().");return this.getSize(a)}});Object.assign(Ba.prototype,{center:function(a){console.warn("THREE.Box3: .center() has been renamed to .getCenter().");
12616 return this.getCenter(a)},empty:function(){console.warn("THREE.Box3: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().");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().");
12617 return this.getSize(a)}});Object.assign(gb.prototype,{center:function(a){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");return this.getCenter(a)}});Object.assign(Ia.prototype,{multiplyVector3:function(a){console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.");return a.applyMatrix3(this)},multiplyVector3Array:function(a){console.warn("THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.");
12618 return this.applyToVector3Array(a)}});Object.assign(J.prototype,{extractPosition:function(a){console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().");return this.copyPosition(a)},setRotationFromQuaternion:function(a){console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().");return this.makeRotationFromQuaternion(a)},multiplyVector3:function(a){console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.");
12619 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.");return this.applyToVector3Array(a)},rotateAxis:function(a){console.warn("THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.");
12620 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(a){console.error("THREE.Matrix4: .translate() has been removed.")},rotateX:function(a){console.error("THREE.Matrix4: .rotateX() has been removed.")},rotateY:function(a){console.error("THREE.Matrix4: .rotateY() has been removed.")},rotateZ:function(a){console.error("THREE.Matrix4: .rotateZ() has been removed.")},
12621 rotateByAxis:function(a,b){console.error("THREE.Matrix4: .rotateByAxis() has been removed.")}});Object.assign(va.prototype,{isIntersectionLine:function(a){console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().");return this.intersectsLine(a)}});Object.assign(ba.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(ab.prototype,
12622 {isIntersectionBox:function(a){console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionPlane:function(a){console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().");return this.intersectsPlane(a)},isIntersectionSphere:function(a){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)}});Object.assign(Ab.prototype,{extrude:function(a){console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.");
12623 return new za(this,a)},makeGeometry:function(a){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");return new cb(this,a)}});Object.assign(q.prototype,{setEulerFromRotationMatrix:function(){console.error("THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.")},setEulerFromQuaternion:function(){console.error("THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.")},
12624 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().");return this.setFromMatrixScale(a)},getColumnFromMatrix:function(a,b){console.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().");return this.setFromMatrixColumn(b,
12625 a)}});Object.assign(z.prototype,{getChildByName:function(a){console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().");return this.getObjectByName(a)},renderDepth:function(a){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.")},translate:function(a,b){console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.");return this.translateOnAxis(b,a)}});Object.defineProperties(z.prototype,
12626 {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.")},set:function(a){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}});
12627 Object.defineProperties(rc.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Ea.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(pa.prototype,{onlyShadow:{set:function(a){console.warn("THREE.Light: .onlyShadow has been removed.")}},shadowCameraFov:{set:function(a){console.warn("THREE.Light: .shadowCameraFov is now .shadow.camera.fov.");
12628 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.");this.shadow.camera.top=a}},shadowCameraBottom:{set:function(a){console.warn("THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.");
12629 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(a){console.warn("THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.")}},shadowBias:{set:function(a){console.warn("THREE.Light: .shadowBias is now .shadow.bias.");
12630 this.shadow.bias=a}},shadowDarkness:{set:function(a){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(C.prototype,{length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Please use .count.");
12631 return this.array.length}}});Object.assign(G.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,b)},clearDrawCalls:function(){console.warn("THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().");
12632 this.clearGroups()},computeTangents:function(){console.warn("THREE.BufferGeometry: .computeTangents() has been removed.")},computeOffsets:function(){console.warn("THREE.BufferGeometry: .computeOffsets() has been removed.")}});Object.defineProperties(G.prototype,{drawcalls:{get:function(){console.error("THREE.BufferGeometry: .drawcalls has been renamed to .groups.");return this.groups}},offsets:{get:function(){console.warn("THREE.BufferGeometry: .offsets has been renamed to .groups.");return this.groups}}});
12633 Object.defineProperties(U.prototype,{wrapAround:{get:function(){console.warn("THREE."+this.type+": .wrapAround has been removed.")},set:function(a){console.warn("THREE."+this.type+": .wrapAround has been removed.")}},wrapRGB:{get:function(){console.warn("THREE."+this.type+": .wrapRGB has been removed.");return new O}}});Object.defineProperties(db.prototype,{metal:{get:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.");return!1},set:function(a){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead")}}});
12634 Object.defineProperties(Fa.prototype,{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");return this.extensions.derivatives},set:function(a){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=a}}});sa.prototype=Object.assign(Object.create({constructor:sa,apply:function(a){console.warn("THREE.EventDispatcher: .apply is deprecated, just inherit or Object.assign the prototype to mix-in.");
12635 Object.assign(a,this)}}),sa.prototype);Object.defineProperties(Ae.prototype,{dynamic:{set:function(a){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.assign(Dd.prototype,{supportsFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' ).");
12636 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' ).");
12637 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(){return this.capabilities.vertexTextures},
12638 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.")},
12639 addPostPlugin:function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},updateShadowMap:function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")}});Object.defineProperties(Dd.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.");
12640 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(pe.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,
12641 {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.");
12642 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.");
12643 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},
12644 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.");
12645 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}}});Object.assign(dc.prototype,{load:function(a){console.warn("THREE.Audio: .load has been deprecated. Please use THREE.AudioLoader.");var b=this;(new Od).load(a,function(a){b.setBuffer(a)});
12646 return this}});Object.assign(Rd.prototype,{getData:function(a){console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData().");return this.getFrequencyData()}});l.WebGLRenderTargetCube=Eb;l.WebGLRenderTarget=Db;l.WebGLRenderer=Dd;l.ShaderLib=Gb;l.UniformsLib=W;l.UniformsUtils=La;l.ShaderChunk=X;l.FogExp2=Ib;l.Fog=Jb;l.Scene=jb;l.LensFlare=Ed;l.Sprite=qc;l.LOD=rc;l.SkinnedMesh=dd;l.Skeleton=bd;l.Bone=cd;l.Mesh=ya;l.LineSegments=la;l.Line=Ta;l.Points=Kb;l.Group=sc;l.VideoTexture=ed;l.DataTexture=
12647 lb;l.CompressedTexture=Lb;l.CubeTexture=Xa;l.CanvasTexture=fd;l.DepthTexture=tc;l.TextureIdCount=function(){return ee++};l.Texture=da;l.MaterialIdCount=function(){return oe++};l.CompressedTextureLoader=we;l.BinaryTextureLoader=Gd;l.DataTextureLoader=Gd;l.CubeTextureLoader=Hd;l.TextureLoader=gd;l.ObjectLoader=xe;l.MaterialLoader=ud;l.BufferGeometryLoader=Id;l.DefaultLoadingManager=Ga;l.LoadingManager=Fd;l.JSONLoader=Jd;l.ImageLoader=Lc;l.FontLoader=ye;l.XHRLoader=Ja;l.Loader=wb;l.Cache=ce;l.AudioLoader=
12648 Od;l.SpotLightShadow=id;l.SpotLight=jd;l.PointLight=kd;l.HemisphereLight=hd;l.DirectionalLightShadow=ld;l.DirectionalLight=md;l.AmbientLight=nd;l.LightShadow=tb;l.Light=pa;l.StereoCamera=ze;l.PerspectiveCamera=Ea;l.OrthographicCamera=Hb;l.CubeCamera=vd;l.Camera=Z;l.AudioListener=Pd;l.PositionalAudio=Qd;l.getAudioContext=Md;l.AudioAnalyser=Rd;l.Audio=dc;l.VectorKeyframeTrack=bc;l.StringKeyframeTrack=rd;l.QuaternionKeyframeTrack=Nc;l.NumberKeyframeTrack=cc;l.ColorKeyframeTrack=td;l.BooleanKeyframeTrack=
12649 sd;l.PropertyMixer=wd;l.PropertyBinding=fa;l.KeyframeTrack=vb;l.AnimationUtils=ma;l.AnimationObjectGroup=Sd;l.AnimationMixer=Ud;l.AnimationClip=Ha;l.Uniform=Ae;l.InstancedBufferGeometry=Bb;l.BufferGeometry=G;l.GeometryIdCount=function(){return ad++};l.Geometry=Q;l.InterleavedBufferAttribute=Vd;l.InstancedInterleavedBuffer=fc;l.InterleavedBuffer=ec;l.InstancedBufferAttribute=gc;l.DynamicBufferAttribute=function(a,b){console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.");
12650 return(new C(a,b)).setDynamic(!0)};l.Float64Attribute=function(a,b){return new C(new Float64Array(a),b)};l.Float32Attribute=ha;l.Uint32Attribute=$c;l.Int32Attribute=function(a,b){return new C(new Int32Array(a),b)};l.Uint16Attribute=Zc;l.Int16Attribute=function(a,b){return new C(new Int16Array(a),b)};l.Uint8ClampedAttribute=function(a,b){return new C(new Uint8ClampedArray(a),b)};l.Uint8Attribute=function(a,b){return new C(new Uint8Array(a),b)};l.Int8Attribute=function(a,b){return new C(new Int8Array(a),
12651 b)};l.BufferAttribute=C;l.Face3=ea;l.Object3DIdCount=function(){return qe++};l.Object3D=z;l.Raycaster=Wd;l.Layers=Yc;l.EventDispatcher=sa;l.Clock=Yd;l.QuaternionLinearInterpolant=qd;l.LinearInterpolant=Mc;l.DiscreteInterpolant=pd;l.CubicInterpolant=od;l.Interpolant=qa;l.Triangle=wa;l.Spline=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,w,n,p;this.initFromArray=function(a){this.points=[];
12652 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]];w=this.points[c[1]];n=this.points[c[2]];p=this.points[c[3]];h=g*g;k=g*h;d.x=b(l.x,w.x,n.x,p.x,g,h,k);d.y=b(l.y,w.y,n.y,p.y,g,h,k);d.z=b(l.z,w.z,n.z,p.z,g,h,k);return d};this.getControlPointsArray=function(){var a,
12653 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),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());
12654 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=h}};l.Math=T;l.Spherical=Zd;l.Plane=va;l.Frustum=nc;l.Sphere=Ca;l.Ray=ab;l.Matrix4=J;l.Matrix3=Ia;l.Box3=Ba;l.Box2=mc;l.Line3=gb;l.Euler=bb;l.Vector4=ga;l.Vector3=q;l.Vector2=B;l.Quaternion=ba;l.ColorKeywords=He;l.Color=O;l.MorphBlendMesh=
12655 na;l.ImmediateRenderObject=Qc;l.VertexNormalsHelper=Rc;l.SpotLightHelper=hc;l.SkeletonHelper=ic;l.PointLightHelper=jc;l.HemisphereLightHelper=kc;l.GridHelper=Sc;l.FaceNormalsHelper=Tc;l.DirectionalLightHelper=lc;l.CameraHelper=Uc;l.BoundingBoxHelper=Vc;l.BoxHelper=Wc;l.ArrowHelper=Cb;l.AxisHelper=xd;l.ClosedSplineCurve3=Ee;l.CatmullRomCurve3=$d;l.SplineCurve3=Ef;l.CubicBezierCurve3=Ff;l.QuadraticBezierCurve3=Gf;l.LineCurve3=Hf;l.ArcCurve=yd;l.EllipseCurve=Va;l.SplineCurve=xb;l.CubicBezierCurve=yb;
12656 l.QuadraticBezierCurve=zb;l.LineCurve=Sa;l.Shape=Ab;l.ShapePath=Kd;l.Path=Pc;l.Font=Ld;l.CurvePath=Oc;l.Curve=ia;l.ShapeUtils=ra;l.SceneUtils={createMultiMaterialObject:function(a,b){for(var c=new sc,d=0,e=b.length;d<e;d++)c.add(new ya(a,b[d]));return c},detach:function(a,b,c){a.applyMatrix(b.matrixWorld);b.remove(a);c.add(a)},attach:function(a,b,c){var d=new J;d.getInverse(c.matrixWorld);a.applyMatrix(d);b.remove(a);c.add(a)}};l.CurveUtils=Xc;l.WireframeGeometry=Mb;l.ParametricGeometry=uc;l.ParametricBufferGeometry=
12657 Nb;l.TetrahedronGeometry=vc;l.TetrahedronBufferGeometry=Ob;l.OctahedronGeometry=wc;l.OctahedronBufferGeometry=Pb;l.IcosahedronGeometry=xc;l.IcosahedronBufferGeometry=Qb;l.DodecahedronGeometry=yc;l.DodecahedronBufferGeometry=Rb;l.PolyhedronGeometry=zc;l.PolyhedronBufferGeometry=ua;l.TubeGeometry=Ac;l.TubeBufferGeometry=Sb;l.TorusKnotGeometry=Bc;l.TorusKnotBufferGeometry=Tb;l.TorusGeometry=Cc;l.TorusBufferGeometry=Ub;l.TextGeometry=Dc;l.SphereBufferGeometry=mb;l.SphereGeometry=Vb;l.RingGeometry=Ec;
12658 l.RingBufferGeometry=Wb;l.PlaneBufferGeometry=ib;l.PlaneGeometry=Fc;l.LatheGeometry=Gc;l.LatheBufferGeometry=Xb;l.ShapeGeometry=cb;l.ExtrudeGeometry=za;l.EdgesGeometry=Yb;l.ConeGeometry=Hc;l.ConeBufferGeometry=Ic;l.CylinderGeometry=nb;l.CylinderBufferGeometry=Ua;l.CircleBufferGeometry=Zb;l.CircleGeometry=Jc;l.BoxBufferGeometry=hb;l.BoxGeometry=ob;l.ShadowMaterial=$b;l.SpriteMaterial=kb;l.RawShaderMaterial=ac;l.ShaderMaterial=Fa;l.PointsMaterial=xa;l.MultiMaterial=Kc;l.MeshPhysicalMaterial=pb;l.MeshStandardMaterial=
12659 Oa;l.MeshPhongMaterial=db;l.MeshNormalMaterial=qb;l.MeshLambertMaterial=rb;l.MeshDepthMaterial=Za;l.MeshBasicMaterial=Ma;l.LineDashedMaterial=sb;l.LineBasicMaterial=oa;l.Material=U;l.REVISION="82";l.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2};l.CullFaceNone=0;l.CullFaceBack=1;l.CullFaceFront=2;l.CullFaceFrontBack=3;l.FrontFaceDirectionCW=0;l.FrontFaceDirectionCCW=1;l.BasicShadowMap=0;l.PCFShadowMap=1;l.PCFSoftShadowMap=2;l.FrontSide=0;l.BackSide=1;l.DoubleSide=2;l.FlatShading=1;l.SmoothShading=2;l.NoColors=0;
12660 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=Fe;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=208;l.OneMinusDstColorFactor=
12661 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=304;l.SphericalReflectionMapping=
12662 305;l.CubeUVReflectionMapping=306;l.CubeUVRefractionMapping=307;l.TextureMapping=Ge;l.RepeatWrapping=1E3;l.ClampToEdgeWrapping=1001;l.MirroredRepeatWrapping=1002;l.TextureWrapping=ae;l.NearestFilter=1003;l.NearestMipMapNearestFilter=1004;l.NearestMipMapLinearFilter=1005;l.LinearFilter=1006;l.LinearMipMapNearestFilter=1007;l.LinearMipMapLinearFilter=1008;l.TextureFilter=be;l.UnsignedByteType=1009;l.ByteType=1010;l.ShortType=1011;l.UnsignedShortType=1012;l.IntType=1013;l.UnsignedIntType=1014;l.FloatType=
12663 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=2101;l.RGBA_PVRTC_4BPPV1_Format=
12664 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=3005;l.RGBDEncoding=3006;
12665 l.BasicDepthPacking=3200;l.RGBADepthPacking=3201;l.CubeGeometry=ob;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 ea(a,b,c,e,f,g)};l.LineStrip=0;l.LinePieces=1;l.MeshFaceMaterial=Kc;l.PointCloud=function(a,b){console.warn("THREE.PointCloud has been renamed to THREE.Points.");return new Kb(a,b)};l.Particle=qc;l.ParticleSystem=function(a,b){console.warn("THREE.ParticleSystem has been renamed to THREE.Points.");return new Kb(a,
12666 b)};l.PointCloudMaterial=function(a){console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.");return new xa(a)};l.ParticleBasicMaterial=function(a){console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.");return new xa(a)};l.ParticleSystemMaterial=function(a){console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.");return new xa(a)};l.Vertex=function(a,b,c){console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead.");
12667 return new q(a,b,c)};l.EdgesHelper=function(a,b){console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.");return new la(new Yb(a.geometry),new oa({color:void 0!==b?b:16777215}))};l.WireframeHelper=function(a,b){console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.");return new la(new Mb(a.geometry),new oa({color:void 0!==b?b:16777215}))};l.GeometryUtils={merge:function(a,b,c){console.warn("THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.");
12668 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 gd;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a},
12669 loadTextureCube:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");var e=new Hd;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.")}};
12670 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(a,b){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");
12671 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});Object.defineProperty(l,"AudioContext",{get:function(){return l.getAudioContext()}})});
12672
12673 },{}],161:[function(require,module,exports){
12674 //     Underscore.js 1.8.3
12675 //     http://underscorejs.org
12676 //     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
12677 //     Underscore may be freely distributed under the MIT license.
12678
12679 (function() {
12680
12681   // Baseline setup
12682   // --------------
12683
12684   // Establish the root object, `window` in the browser, or `exports` on the server.
12685   var root = this;
12686
12687   // Save the previous value of the `_` variable.
12688   var previousUnderscore = root._;
12689
12690   // Save bytes in the minified (but not gzipped) version:
12691   var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
12692
12693   // Create quick reference variables for speed access to core prototypes.
12694   var
12695     push             = ArrayProto.push,
12696     slice            = ArrayProto.slice,
12697     toString         = ObjProto.toString,
12698     hasOwnProperty   = ObjProto.hasOwnProperty;
12699
12700   // All **ECMAScript 5** native function implementations that we hope to use
12701   // are declared here.
12702   var
12703     nativeIsArray      = Array.isArray,
12704     nativeKeys         = Object.keys,
12705     nativeBind         = FuncProto.bind,
12706     nativeCreate       = Object.create;
12707
12708   // Naked function reference for surrogate-prototype-swapping.
12709   var Ctor = function(){};
12710
12711   // Create a safe reference to the Underscore object for use below.
12712   var _ = function(obj) {
12713     if (obj instanceof _) return obj;
12714     if (!(this instanceof _)) return new _(obj);
12715     this._wrapped = obj;
12716   };
12717
12718   // Export the Underscore object for **Node.js**, with
12719   // backwards-compatibility for the old `require()` API. If we're in
12720   // the browser, add `_` as a global object.
12721   if (typeof exports !== 'undefined') {
12722     if (typeof module !== 'undefined' && module.exports) {
12723       exports = module.exports = _;
12724     }
12725     exports._ = _;
12726   } else {
12727     root._ = _;
12728   }
12729
12730   // Current version.
12731   _.VERSION = '1.8.3';
12732
12733   // Internal function that returns an efficient (for current engines) version
12734   // of the passed-in callback, to be repeatedly applied in other Underscore
12735   // functions.
12736   var optimizeCb = function(func, context, argCount) {
12737     if (context === void 0) return func;
12738     switch (argCount == null ? 3 : argCount) {
12739       case 1: return function(value) {
12740         return func.call(context, value);
12741       };
12742       case 2: return function(value, other) {
12743         return func.call(context, value, other);
12744       };
12745       case 3: return function(value, index, collection) {
12746         return func.call(context, value, index, collection);
12747       };
12748       case 4: return function(accumulator, value, index, collection) {
12749         return func.call(context, accumulator, value, index, collection);
12750       };
12751     }
12752     return function() {
12753       return func.apply(context, arguments);
12754     };
12755   };
12756
12757   // A mostly-internal function to generate callbacks that can be applied
12758   // to each element in a collection, returning the desired result — either
12759   // identity, an arbitrary callback, a property matcher, or a property accessor.
12760   var cb = function(value, context, argCount) {
12761     if (value == null) return _.identity;
12762     if (_.isFunction(value)) return optimizeCb(value, context, argCount);
12763     if (_.isObject(value)) return _.matcher(value);
12764     return _.property(value);
12765   };
12766   _.iteratee = function(value, context) {
12767     return cb(value, context, Infinity);
12768   };
12769
12770   // An internal function for creating assigner functions.
12771   var createAssigner = function(keysFunc, undefinedOnly) {
12772     return function(obj) {
12773       var length = arguments.length;
12774       if (length < 2 || obj == null) return obj;
12775       for (var index = 1; index < length; index++) {
12776         var source = arguments[index],
12777             keys = keysFunc(source),
12778             l = keys.length;
12779         for (var i = 0; i < l; i++) {
12780           var key = keys[i];
12781           if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
12782         }
12783       }
12784       return obj;
12785     };
12786   };
12787
12788   // An internal function for creating a new object that inherits from another.
12789   var baseCreate = function(prototype) {
12790     if (!_.isObject(prototype)) return {};
12791     if (nativeCreate) return nativeCreate(prototype);
12792     Ctor.prototype = prototype;
12793     var result = new Ctor;
12794     Ctor.prototype = null;
12795     return result;
12796   };
12797
12798   var property = function(key) {
12799     return function(obj) {
12800       return obj == null ? void 0 : obj[key];
12801     };
12802   };
12803
12804   // Helper for collection methods to determine whether a collection
12805   // should be iterated as an array or as an object
12806   // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
12807   // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
12808   var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
12809   var getLength = property('length');
12810   var isArrayLike = function(collection) {
12811     var length = getLength(collection);
12812     return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
12813   };
12814
12815   // Collection Functions
12816   // --------------------
12817
12818   // The cornerstone, an `each` implementation, aka `forEach`.
12819   // Handles raw objects in addition to array-likes. Treats all
12820   // sparse array-likes as if they were dense.
12821   _.each = _.forEach = function(obj, iteratee, context) {
12822     iteratee = optimizeCb(iteratee, context);
12823     var i, length;
12824     if (isArrayLike(obj)) {
12825       for (i = 0, length = obj.length; i < length; i++) {
12826         iteratee(obj[i], i, obj);
12827       }
12828     } else {
12829       var keys = _.keys(obj);
12830       for (i = 0, length = keys.length; i < length; i++) {
12831         iteratee(obj[keys[i]], keys[i], obj);
12832       }
12833     }
12834     return obj;
12835   };
12836
12837   // Return the results of applying the iteratee to each element.
12838   _.map = _.collect = function(obj, iteratee, context) {
12839     iteratee = cb(iteratee, context);
12840     var keys = !isArrayLike(obj) && _.keys(obj),
12841         length = (keys || obj).length,
12842         results = Array(length);
12843     for (var index = 0; index < length; index++) {
12844       var currentKey = keys ? keys[index] : index;
12845       results[index] = iteratee(obj[currentKey], currentKey, obj);
12846     }
12847     return results;
12848   };
12849
12850   // Create a reducing function iterating left or right.
12851   function createReduce(dir) {
12852     // Optimized iterator function as using arguments.length
12853     // in the main function will deoptimize the, see #1991.
12854     function iterator(obj, iteratee, memo, keys, index, length) {
12855       for (; index >= 0 && index < length; index += dir) {
12856         var currentKey = keys ? keys[index] : index;
12857         memo = iteratee(memo, obj[currentKey], currentKey, obj);
12858       }
12859       return memo;
12860     }
12861
12862     return function(obj, iteratee, memo, context) {
12863       iteratee = optimizeCb(iteratee, context, 4);
12864       var keys = !isArrayLike(obj) && _.keys(obj),
12865           length = (keys || obj).length,
12866           index = dir > 0 ? 0 : length - 1;
12867       // Determine the initial value if none is provided.
12868       if (arguments.length < 3) {
12869         memo = obj[keys ? keys[index] : index];
12870         index += dir;
12871       }
12872       return iterator(obj, iteratee, memo, keys, index, length);
12873     };
12874   }
12875
12876   // **Reduce** builds up a single result from a list of values, aka `inject`,
12877   // or `foldl`.
12878   _.reduce = _.foldl = _.inject = createReduce(1);
12879
12880   // The right-associative version of reduce, also known as `foldr`.
12881   _.reduceRight = _.foldr = createReduce(-1);
12882
12883   // Return the first value which passes a truth test. Aliased as `detect`.
12884   _.find = _.detect = function(obj, predicate, context) {
12885     var key;
12886     if (isArrayLike(obj)) {
12887       key = _.findIndex(obj, predicate, context);
12888     } else {
12889       key = _.findKey(obj, predicate, context);
12890     }
12891     if (key !== void 0 && key !== -1) return obj[key];
12892   };
12893
12894   // Return all the elements that pass a truth test.
12895   // Aliased as `select`.
12896   _.filter = _.select = function(obj, predicate, context) {
12897     var results = [];
12898     predicate = cb(predicate, context);
12899     _.each(obj, function(value, index, list) {
12900       if (predicate(value, index, list)) results.push(value);
12901     });
12902     return results;
12903   };
12904
12905   // Return all the elements for which a truth test fails.
12906   _.reject = function(obj, predicate, context) {
12907     return _.filter(obj, _.negate(cb(predicate)), context);
12908   };
12909
12910   // Determine whether all of the elements match a truth test.
12911   // Aliased as `all`.
12912   _.every = _.all = function(obj, predicate, context) {
12913     predicate = cb(predicate, context);
12914     var keys = !isArrayLike(obj) && _.keys(obj),
12915         length = (keys || obj).length;
12916     for (var index = 0; index < length; index++) {
12917       var currentKey = keys ? keys[index] : index;
12918       if (!predicate(obj[currentKey], currentKey, obj)) return false;
12919     }
12920     return true;
12921   };
12922
12923   // Determine if at least one element in the object matches a truth test.
12924   // Aliased as `any`.
12925   _.some = _.any = function(obj, predicate, context) {
12926     predicate = cb(predicate, context);
12927     var keys = !isArrayLike(obj) && _.keys(obj),
12928         length = (keys || obj).length;
12929     for (var index = 0; index < length; index++) {
12930       var currentKey = keys ? keys[index] : index;
12931       if (predicate(obj[currentKey], currentKey, obj)) return true;
12932     }
12933     return false;
12934   };
12935
12936   // Determine if the array or object contains a given item (using `===`).
12937   // Aliased as `includes` and `include`.
12938   _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
12939     if (!isArrayLike(obj)) obj = _.values(obj);
12940     if (typeof fromIndex != 'number' || guard) fromIndex = 0;
12941     return _.indexOf(obj, item, fromIndex) >= 0;
12942   };
12943
12944   // Invoke a method (with arguments) on every item in a collection.
12945   _.invoke = function(obj, method) {
12946     var args = slice.call(arguments, 2);
12947     var isFunc = _.isFunction(method);
12948     return _.map(obj, function(value) {
12949       var func = isFunc ? method : value[method];
12950       return func == null ? func : func.apply(value, args);
12951     });
12952   };
12953
12954   // Convenience version of a common use case of `map`: fetching a property.
12955   _.pluck = function(obj, key) {
12956     return _.map(obj, _.property(key));
12957   };
12958
12959   // Convenience version of a common use case of `filter`: selecting only objects
12960   // containing specific `key:value` pairs.
12961   _.where = function(obj, attrs) {
12962     return _.filter(obj, _.matcher(attrs));
12963   };
12964
12965   // Convenience version of a common use case of `find`: getting the first object
12966   // containing specific `key:value` pairs.
12967   _.findWhere = function(obj, attrs) {
12968     return _.find(obj, _.matcher(attrs));
12969   };
12970
12971   // Return the maximum element (or element-based computation).
12972   _.max = function(obj, iteratee, context) {
12973     var result = -Infinity, lastComputed = -Infinity,
12974         value, computed;
12975     if (iteratee == null && obj != null) {
12976       obj = isArrayLike(obj) ? obj : _.values(obj);
12977       for (var i = 0, length = obj.length; i < length; i++) {
12978         value = obj[i];
12979         if (value > result) {
12980           result = value;
12981         }
12982       }
12983     } else {
12984       iteratee = cb(iteratee, context);
12985       _.each(obj, function(value, index, list) {
12986         computed = iteratee(value, index, list);
12987         if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
12988           result = value;
12989           lastComputed = computed;
12990         }
12991       });
12992     }
12993     return result;
12994   };
12995
12996   // Return the minimum element (or element-based computation).
12997   _.min = function(obj, iteratee, context) {
12998     var result = Infinity, lastComputed = Infinity,
12999         value, computed;
13000     if (iteratee == null && obj != null) {
13001       obj = isArrayLike(obj) ? obj : _.values(obj);
13002       for (var i = 0, length = obj.length; i < length; i++) {
13003         value = obj[i];
13004         if (value < result) {
13005           result = value;
13006         }
13007       }
13008     } else {
13009       iteratee = cb(iteratee, context);
13010       _.each(obj, function(value, index, list) {
13011         computed = iteratee(value, index, list);
13012         if (computed < lastComputed || computed === Infinity && result === Infinity) {
13013           result = value;
13014           lastComputed = computed;
13015         }
13016       });
13017     }
13018     return result;
13019   };
13020
13021   // Shuffle a collection, using the modern version of the
13022   // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
13023   _.shuffle = function(obj) {
13024     var set = isArrayLike(obj) ? obj : _.values(obj);
13025     var length = set.length;
13026     var shuffled = Array(length);
13027     for (var index = 0, rand; index < length; index++) {
13028       rand = _.random(0, index);
13029       if (rand !== index) shuffled[index] = shuffled[rand];
13030       shuffled[rand] = set[index];
13031     }
13032     return shuffled;
13033   };
13034
13035   // Sample **n** random values from a collection.
13036   // If **n** is not specified, returns a single random element.
13037   // The internal `guard` argument allows it to work with `map`.
13038   _.sample = function(obj, n, guard) {
13039     if (n == null || guard) {
13040       if (!isArrayLike(obj)) obj = _.values(obj);
13041       return obj[_.random(obj.length - 1)];
13042     }
13043     return _.shuffle(obj).slice(0, Math.max(0, n));
13044   };
13045
13046   // Sort the object's values by a criterion produced by an iteratee.
13047   _.sortBy = function(obj, iteratee, context) {
13048     iteratee = cb(iteratee, context);
13049     return _.pluck(_.map(obj, function(value, index, list) {
13050       return {
13051         value: value,
13052         index: index,
13053         criteria: iteratee(value, index, list)
13054       };
13055     }).sort(function(left, right) {
13056       var a = left.criteria;
13057       var b = right.criteria;
13058       if (a !== b) {
13059         if (a > b || a === void 0) return 1;
13060         if (a < b || b === void 0) return -1;
13061       }
13062       return left.index - right.index;
13063     }), 'value');
13064   };
13065
13066   // An internal function used for aggregate "group by" operations.
13067   var group = function(behavior) {
13068     return function(obj, iteratee, context) {
13069       var result = {};
13070       iteratee = cb(iteratee, context);
13071       _.each(obj, function(value, index) {
13072         var key = iteratee(value, index, obj);
13073         behavior(result, value, key);
13074       });
13075       return result;
13076     };
13077   };
13078
13079   // Groups the object's values by a criterion. Pass either a string attribute
13080   // to group by, or a function that returns the criterion.
13081   _.groupBy = group(function(result, value, key) {
13082     if (_.has(result, key)) result[key].push(value); else result[key] = [value];
13083   });
13084
13085   // Indexes the object's values by a criterion, similar to `groupBy`, but for
13086   // when you know that your index values will be unique.
13087   _.indexBy = group(function(result, value, key) {
13088     result[key] = value;
13089   });
13090
13091   // Counts instances of an object that group by a certain criterion. Pass
13092   // either a string attribute to count by, or a function that returns the
13093   // criterion.
13094   _.countBy = group(function(result, value, key) {
13095     if (_.has(result, key)) result[key]++; else result[key] = 1;
13096   });
13097
13098   // Safely create a real, live array from anything iterable.
13099   _.toArray = function(obj) {
13100     if (!obj) return [];
13101     if (_.isArray(obj)) return slice.call(obj);
13102     if (isArrayLike(obj)) return _.map(obj, _.identity);
13103     return _.values(obj);
13104   };
13105
13106   // Return the number of elements in an object.
13107   _.size = function(obj) {
13108     if (obj == null) return 0;
13109     return isArrayLike(obj) ? obj.length : _.keys(obj).length;
13110   };
13111
13112   // Split a collection into two arrays: one whose elements all satisfy the given
13113   // predicate, and one whose elements all do not satisfy the predicate.
13114   _.partition = function(obj, predicate, context) {
13115     predicate = cb(predicate, context);
13116     var pass = [], fail = [];
13117     _.each(obj, function(value, key, obj) {
13118       (predicate(value, key, obj) ? pass : fail).push(value);
13119     });
13120     return [pass, fail];
13121   };
13122
13123   // Array Functions
13124   // ---------------
13125
13126   // Get the first element of an array. Passing **n** will return the first N
13127   // values in the array. Aliased as `head` and `take`. The **guard** check
13128   // allows it to work with `_.map`.
13129   _.first = _.head = _.take = function(array, n, guard) {
13130     if (array == null) return void 0;
13131     if (n == null || guard) return array[0];
13132     return _.initial(array, array.length - n);
13133   };
13134
13135   // Returns everything but the last entry of the array. Especially useful on
13136   // the arguments object. Passing **n** will return all the values in
13137   // the array, excluding the last N.
13138   _.initial = function(array, n, guard) {
13139     return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
13140   };
13141
13142   // Get the last element of an array. Passing **n** will return the last N
13143   // values in the array.
13144   _.last = function(array, n, guard) {
13145     if (array == null) return void 0;
13146     if (n == null || guard) return array[array.length - 1];
13147     return _.rest(array, Math.max(0, array.length - n));
13148   };
13149
13150   // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
13151   // Especially useful on the arguments object. Passing an **n** will return
13152   // the rest N values in the array.
13153   _.rest = _.tail = _.drop = function(array, n, guard) {
13154     return slice.call(array, n == null || guard ? 1 : n);
13155   };
13156
13157   // Trim out all falsy values from an array.
13158   _.compact = function(array) {
13159     return _.filter(array, _.identity);
13160   };
13161
13162   // Internal implementation of a recursive `flatten` function.
13163   var flatten = function(input, shallow, strict, startIndex) {
13164     var output = [], idx = 0;
13165     for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
13166       var value = input[i];
13167       if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
13168         //flatten current level of array or arguments object
13169         if (!shallow) value = flatten(value, shallow, strict);
13170         var j = 0, len = value.length;
13171         output.length += len;
13172         while (j < len) {
13173           output[idx++] = value[j++];
13174         }
13175       } else if (!strict) {
13176         output[idx++] = value;
13177       }
13178     }
13179     return output;
13180   };
13181
13182   // Flatten out an array, either recursively (by default), or just one level.
13183   _.flatten = function(array, shallow) {
13184     return flatten(array, shallow, false);
13185   };
13186
13187   // Return a version of the array that does not contain the specified value(s).
13188   _.without = function(array) {
13189     return _.difference(array, slice.call(arguments, 1));
13190   };
13191
13192   // Produce a duplicate-free version of the array. If the array has already
13193   // been sorted, you have the option of using a faster algorithm.
13194   // Aliased as `unique`.
13195   _.uniq = _.unique = function(array, isSorted, iteratee, context) {
13196     if (!_.isBoolean(isSorted)) {
13197       context = iteratee;
13198       iteratee = isSorted;
13199       isSorted = false;
13200     }
13201     if (iteratee != null) iteratee = cb(iteratee, context);
13202     var result = [];
13203     var seen = [];
13204     for (var i = 0, length = getLength(array); i < length; i++) {
13205       var value = array[i],
13206           computed = iteratee ? iteratee(value, i, array) : value;
13207       if (isSorted) {
13208         if (!i || seen !== computed) result.push(value);
13209         seen = computed;
13210       } else if (iteratee) {
13211         if (!_.contains(seen, computed)) {
13212           seen.push(computed);
13213           result.push(value);
13214         }
13215       } else if (!_.contains(result, value)) {
13216         result.push(value);
13217       }
13218     }
13219     return result;
13220   };
13221
13222   // Produce an array that contains the union: each distinct element from all of
13223   // the passed-in arrays.
13224   _.union = function() {
13225     return _.uniq(flatten(arguments, true, true));
13226   };
13227
13228   // Produce an array that contains every item shared between all the
13229   // passed-in arrays.
13230   _.intersection = function(array) {
13231     var result = [];
13232     var argsLength = arguments.length;
13233     for (var i = 0, length = getLength(array); i < length; i++) {
13234       var item = array[i];
13235       if (_.contains(result, item)) continue;
13236       for (var j = 1; j < argsLength; j++) {
13237         if (!_.contains(arguments[j], item)) break;
13238       }
13239       if (j === argsLength) result.push(item);
13240     }
13241     return result;
13242   };
13243
13244   // Take the difference between one array and a number of other arrays.
13245   // Only the elements present in just the first array will remain.
13246   _.difference = function(array) {
13247     var rest = flatten(arguments, true, true, 1);
13248     return _.filter(array, function(value){
13249       return !_.contains(rest, value);
13250     });
13251   };
13252
13253   // Zip together multiple lists into a single array -- elements that share
13254   // an index go together.
13255   _.zip = function() {
13256     return _.unzip(arguments);
13257   };
13258
13259   // Complement of _.zip. Unzip accepts an array of arrays and groups
13260   // each array's elements on shared indices
13261   _.unzip = function(array) {
13262     var length = array && _.max(array, getLength).length || 0;
13263     var result = Array(length);
13264
13265     for (var index = 0; index < length; index++) {
13266       result[index] = _.pluck(array, index);
13267     }
13268     return result;
13269   };
13270
13271   // Converts lists into objects. Pass either a single array of `[key, value]`
13272   // pairs, or two parallel arrays of the same length -- one of keys, and one of
13273   // the corresponding values.
13274   _.object = function(list, values) {
13275     var result = {};
13276     for (var i = 0, length = getLength(list); i < length; i++) {
13277       if (values) {
13278         result[list[i]] = values[i];
13279       } else {
13280         result[list[i][0]] = list[i][1];
13281       }
13282     }
13283     return result;
13284   };
13285
13286   // Generator function to create the findIndex and findLastIndex functions
13287   function createPredicateIndexFinder(dir) {
13288     return function(array, predicate, context) {
13289       predicate = cb(predicate, context);
13290       var length = getLength(array);
13291       var index = dir > 0 ? 0 : length - 1;
13292       for (; index >= 0 && index < length; index += dir) {
13293         if (predicate(array[index], index, array)) return index;
13294       }
13295       return -1;
13296     };
13297   }
13298
13299   // Returns the first index on an array-like that passes a predicate test
13300   _.findIndex = createPredicateIndexFinder(1);
13301   _.findLastIndex = createPredicateIndexFinder(-1);
13302
13303   // Use a comparator function to figure out the smallest index at which
13304   // an object should be inserted so as to maintain order. Uses binary search.
13305   _.sortedIndex = function(array, obj, iteratee, context) {
13306     iteratee = cb(iteratee, context, 1);
13307     var value = iteratee(obj);
13308     var low = 0, high = getLength(array);
13309     while (low < high) {
13310       var mid = Math.floor((low + high) / 2);
13311       if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
13312     }
13313     return low;
13314   };
13315
13316   // Generator function to create the indexOf and lastIndexOf functions
13317   function createIndexFinder(dir, predicateFind, sortedIndex) {
13318     return function(array, item, idx) {
13319       var i = 0, length = getLength(array);
13320       if (typeof idx == 'number') {
13321         if (dir > 0) {
13322             i = idx >= 0 ? idx : Math.max(idx + length, i);
13323         } else {
13324             length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
13325         }
13326       } else if (sortedIndex && idx && length) {
13327         idx = sortedIndex(array, item);
13328         return array[idx] === item ? idx : -1;
13329       }
13330       if (item !== item) {
13331         idx = predicateFind(slice.call(array, i, length), _.isNaN);
13332         return idx >= 0 ? idx + i : -1;
13333       }
13334       for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
13335         if (array[idx] === item) return idx;
13336       }
13337       return -1;
13338     };
13339   }
13340
13341   // Return the position of the first occurrence of an item in an array,
13342   // or -1 if the item is not included in the array.
13343   // If the array is large and already in sort order, pass `true`
13344   // for **isSorted** to use binary search.
13345   _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
13346   _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
13347
13348   // Generate an integer Array containing an arithmetic progression. A port of
13349   // the native Python `range()` function. See
13350   // [the Python documentation](http://docs.python.org/library/functions.html#range).
13351   _.range = function(start, stop, step) {
13352     if (stop == null) {
13353       stop = start || 0;
13354       start = 0;
13355     }
13356     step = step || 1;
13357
13358     var length = Math.max(Math.ceil((stop - start) / step), 0);
13359     var range = Array(length);
13360
13361     for (var idx = 0; idx < length; idx++, start += step) {
13362       range[idx] = start;
13363     }
13364
13365     return range;
13366   };
13367
13368   // Function (ahem) Functions
13369   // ------------------
13370
13371   // Determines whether to execute a function as a constructor
13372   // or a normal function with the provided arguments
13373   var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
13374     if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
13375     var self = baseCreate(sourceFunc.prototype);
13376     var result = sourceFunc.apply(self, args);
13377     if (_.isObject(result)) return result;
13378     return self;
13379   };
13380
13381   // Create a function bound to a given object (assigning `this`, and arguments,
13382   // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
13383   // available.
13384   _.bind = function(func, context) {
13385     if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
13386     if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
13387     var args = slice.call(arguments, 2);
13388     var bound = function() {
13389       return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
13390     };
13391     return bound;
13392   };
13393
13394   // Partially apply a function by creating a version that has had some of its
13395   // arguments pre-filled, without changing its dynamic `this` context. _ acts
13396   // as a placeholder, allowing any combination of arguments to be pre-filled.
13397   _.partial = function(func) {
13398     var boundArgs = slice.call(arguments, 1);
13399     var bound = function() {
13400       var position = 0, length = boundArgs.length;
13401       var args = Array(length);
13402       for (var i = 0; i < length; i++) {
13403         args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
13404       }
13405       while (position < arguments.length) args.push(arguments[position++]);
13406       return executeBound(func, bound, this, this, args);
13407     };
13408     return bound;
13409   };
13410
13411   // Bind a number of an object's methods to that object. Remaining arguments
13412   // are the method names to be bound. Useful for ensuring that all callbacks
13413   // defined on an object belong to it.
13414   _.bindAll = function(obj) {
13415     var i, length = arguments.length, key;
13416     if (length <= 1) throw new Error('bindAll must be passed function names');
13417     for (i = 1; i < length; i++) {
13418       key = arguments[i];
13419       obj[key] = _.bind(obj[key], obj);
13420     }
13421     return obj;
13422   };
13423
13424   // Memoize an expensive function by storing its results.
13425   _.memoize = function(func, hasher) {
13426     var memoize = function(key) {
13427       var cache = memoize.cache;
13428       var address = '' + (hasher ? hasher.apply(this, arguments) : key);
13429       if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
13430       return cache[address];
13431     };
13432     memoize.cache = {};
13433     return memoize;
13434   };
13435
13436   // Delays a function for the given number of milliseconds, and then calls
13437   // it with the arguments supplied.
13438   _.delay = function(func, wait) {
13439     var args = slice.call(arguments, 2);
13440     return setTimeout(function(){
13441       return func.apply(null, args);
13442     }, wait);
13443   };
13444
13445   // Defers a function, scheduling it to run after the current call stack has
13446   // cleared.
13447   _.defer = _.partial(_.delay, _, 1);
13448
13449   // Returns a function, that, when invoked, will only be triggered at most once
13450   // during a given window of time. Normally, the throttled function will run
13451   // as much as it can, without ever going more than once per `wait` duration;
13452   // but if you'd like to disable the execution on the leading edge, pass
13453   // `{leading: false}`. To disable execution on the trailing edge, ditto.
13454   _.throttle = function(func, wait, options) {
13455     var context, args, result;
13456     var timeout = null;
13457     var previous = 0;
13458     if (!options) options = {};
13459     var later = function() {
13460       previous = options.leading === false ? 0 : _.now();
13461       timeout = null;
13462       result = func.apply(context, args);
13463       if (!timeout) context = args = null;
13464     };
13465     return function() {
13466       var now = _.now();
13467       if (!previous && options.leading === false) previous = now;
13468       var remaining = wait - (now - previous);
13469       context = this;
13470       args = arguments;
13471       if (remaining <= 0 || remaining > wait) {
13472         if (timeout) {
13473           clearTimeout(timeout);
13474           timeout = null;
13475         }
13476         previous = now;
13477         result = func.apply(context, args);
13478         if (!timeout) context = args = null;
13479       } else if (!timeout && options.trailing !== false) {
13480         timeout = setTimeout(later, remaining);
13481       }
13482       return result;
13483     };
13484   };
13485
13486   // Returns a function, that, as long as it continues to be invoked, will not
13487   // be triggered. The function will be called after it stops being called for
13488   // N milliseconds. If `immediate` is passed, trigger the function on the
13489   // leading edge, instead of the trailing.
13490   _.debounce = function(func, wait, immediate) {
13491     var timeout, args, context, timestamp, result;
13492
13493     var later = function() {
13494       var last = _.now() - timestamp;
13495
13496       if (last < wait && last >= 0) {
13497         timeout = setTimeout(later, wait - last);
13498       } else {
13499         timeout = null;
13500         if (!immediate) {
13501           result = func.apply(context, args);
13502           if (!timeout) context = args = null;
13503         }
13504       }
13505     };
13506
13507     return function() {
13508       context = this;
13509       args = arguments;
13510       timestamp = _.now();
13511       var callNow = immediate && !timeout;
13512       if (!timeout) timeout = setTimeout(later, wait);
13513       if (callNow) {
13514         result = func.apply(context, args);
13515         context = args = null;
13516       }
13517
13518       return result;
13519     };
13520   };
13521
13522   // Returns the first function passed as an argument to the second,
13523   // allowing you to adjust arguments, run code before and after, and
13524   // conditionally execute the original function.
13525   _.wrap = function(func, wrapper) {
13526     return _.partial(wrapper, func);
13527   };
13528
13529   // Returns a negated version of the passed-in predicate.
13530   _.negate = function(predicate) {
13531     return function() {
13532       return !predicate.apply(this, arguments);
13533     };
13534   };
13535
13536   // Returns a function that is the composition of a list of functions, each
13537   // consuming the return value of the function that follows.
13538   _.compose = function() {
13539     var args = arguments;
13540     var start = args.length - 1;
13541     return function() {
13542       var i = start;
13543       var result = args[start].apply(this, arguments);
13544       while (i--) result = args[i].call(this, result);
13545       return result;
13546     };
13547   };
13548
13549   // Returns a function that will only be executed on and after the Nth call.
13550   _.after = function(times, func) {
13551     return function() {
13552       if (--times < 1) {
13553         return func.apply(this, arguments);
13554       }
13555     };
13556   };
13557
13558   // Returns a function that will only be executed up to (but not including) the Nth call.
13559   _.before = function(times, func) {
13560     var memo;
13561     return function() {
13562       if (--times > 0) {
13563         memo = func.apply(this, arguments);
13564       }
13565       if (times <= 1) func = null;
13566       return memo;
13567     };
13568   };
13569
13570   // Returns a function that will be executed at most one time, no matter how
13571   // often you call it. Useful for lazy initialization.
13572   _.once = _.partial(_.before, 2);
13573
13574   // Object Functions
13575   // ----------------
13576
13577   // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
13578   var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
13579   var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
13580                       'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
13581
13582   function collectNonEnumProps(obj, keys) {
13583     var nonEnumIdx = nonEnumerableProps.length;
13584     var constructor = obj.constructor;
13585     var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
13586
13587     // Constructor is a special case.
13588     var prop = 'constructor';
13589     if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
13590
13591     while (nonEnumIdx--) {
13592       prop = nonEnumerableProps[nonEnumIdx];
13593       if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
13594         keys.push(prop);
13595       }
13596     }
13597   }
13598
13599   // Retrieve the names of an object's own properties.
13600   // Delegates to **ECMAScript 5**'s native `Object.keys`
13601   _.keys = function(obj) {
13602     if (!_.isObject(obj)) return [];
13603     if (nativeKeys) return nativeKeys(obj);
13604     var keys = [];
13605     for (var key in obj) if (_.has(obj, key)) keys.push(key);
13606     // Ahem, IE < 9.
13607     if (hasEnumBug) collectNonEnumProps(obj, keys);
13608     return keys;
13609   };
13610
13611   // Retrieve all the property names of an object.
13612   _.allKeys = function(obj) {
13613     if (!_.isObject(obj)) return [];
13614     var keys = [];
13615     for (var key in obj) keys.push(key);
13616     // Ahem, IE < 9.
13617     if (hasEnumBug) collectNonEnumProps(obj, keys);
13618     return keys;
13619   };
13620
13621   // Retrieve the values of an object's properties.
13622   _.values = function(obj) {
13623     var keys = _.keys(obj);
13624     var length = keys.length;
13625     var values = Array(length);
13626     for (var i = 0; i < length; i++) {
13627       values[i] = obj[keys[i]];
13628     }
13629     return values;
13630   };
13631
13632   // Returns the results of applying the iteratee to each element of the object
13633   // In contrast to _.map it returns an object
13634   _.mapObject = function(obj, iteratee, context) {
13635     iteratee = cb(iteratee, context);
13636     var keys =  _.keys(obj),
13637           length = keys.length,
13638           results = {},
13639           currentKey;
13640       for (var index = 0; index < length; index++) {
13641         currentKey = keys[index];
13642         results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
13643       }
13644       return results;
13645   };
13646
13647   // Convert an object into a list of `[key, value]` pairs.
13648   _.pairs = function(obj) {
13649     var keys = _.keys(obj);
13650     var length = keys.length;
13651     var pairs = Array(length);
13652     for (var i = 0; i < length; i++) {
13653       pairs[i] = [keys[i], obj[keys[i]]];
13654     }
13655     return pairs;
13656   };
13657
13658   // Invert the keys and values of an object. The values must be serializable.
13659   _.invert = function(obj) {
13660     var result = {};
13661     var keys = _.keys(obj);
13662     for (var i = 0, length = keys.length; i < length; i++) {
13663       result[obj[keys[i]]] = keys[i];
13664     }
13665     return result;
13666   };
13667
13668   // Return a sorted list of the function names available on the object.
13669   // Aliased as `methods`
13670   _.functions = _.methods = function(obj) {
13671     var names = [];
13672     for (var key in obj) {
13673       if (_.isFunction(obj[key])) names.push(key);
13674     }
13675     return names.sort();
13676   };
13677
13678   // Extend a given object with all the properties in passed-in object(s).
13679   _.extend = createAssigner(_.allKeys);
13680
13681   // Assigns a given object with all the own properties in the passed-in object(s)
13682   // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
13683   _.extendOwn = _.assign = createAssigner(_.keys);
13684
13685   // Returns the first key on an object that passes a predicate test
13686   _.findKey = function(obj, predicate, context) {
13687     predicate = cb(predicate, context);
13688     var keys = _.keys(obj), key;
13689     for (var i = 0, length = keys.length; i < length; i++) {
13690       key = keys[i];
13691       if (predicate(obj[key], key, obj)) return key;
13692     }
13693   };
13694
13695   // Return a copy of the object only containing the whitelisted properties.
13696   _.pick = function(object, oiteratee, context) {
13697     var result = {}, obj = object, iteratee, keys;
13698     if (obj == null) return result;
13699     if (_.isFunction(oiteratee)) {
13700       keys = _.allKeys(obj);
13701       iteratee = optimizeCb(oiteratee, context);
13702     } else {
13703       keys = flatten(arguments, false, false, 1);
13704       iteratee = function(value, key, obj) { return key in obj; };
13705       obj = Object(obj);
13706     }
13707     for (var i = 0, length = keys.length; i < length; i++) {
13708       var key = keys[i];
13709       var value = obj[key];
13710       if (iteratee(value, key, obj)) result[key] = value;
13711     }
13712     return result;
13713   };
13714
13715    // Return a copy of the object without the blacklisted properties.
13716   _.omit = function(obj, iteratee, context) {
13717     if (_.isFunction(iteratee)) {
13718       iteratee = _.negate(iteratee);
13719     } else {
13720       var keys = _.map(flatten(arguments, false, false, 1), String);
13721       iteratee = function(value, key) {
13722         return !_.contains(keys, key);
13723       };
13724     }
13725     return _.pick(obj, iteratee, context);
13726   };
13727
13728   // Fill in a given object with default properties.
13729   _.defaults = createAssigner(_.allKeys, true);
13730
13731   // Creates an object that inherits from the given prototype object.
13732   // If additional properties are provided then they will be added to the
13733   // created object.
13734   _.create = function(prototype, props) {
13735     var result = baseCreate(prototype);
13736     if (props) _.extendOwn(result, props);
13737     return result;
13738   };
13739
13740   // Create a (shallow-cloned) duplicate of an object.
13741   _.clone = function(obj) {
13742     if (!_.isObject(obj)) return obj;
13743     return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
13744   };
13745
13746   // Invokes interceptor with the obj, and then returns obj.
13747   // The primary purpose of this method is to "tap into" a method chain, in
13748   // order to perform operations on intermediate results within the chain.
13749   _.tap = function(obj, interceptor) {
13750     interceptor(obj);
13751     return obj;
13752   };
13753
13754   // Returns whether an object has a given set of `key:value` pairs.
13755   _.isMatch = function(object, attrs) {
13756     var keys = _.keys(attrs), length = keys.length;
13757     if (object == null) return !length;
13758     var obj = Object(object);
13759     for (var i = 0; i < length; i++) {
13760       var key = keys[i];
13761       if (attrs[key] !== obj[key] || !(key in obj)) return false;
13762     }
13763     return true;
13764   };
13765
13766
13767   // Internal recursive comparison function for `isEqual`.
13768   var eq = function(a, b, aStack, bStack) {
13769     // Identical objects are equal. `0 === -0`, but they aren't identical.
13770     // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
13771     if (a === b) return a !== 0 || 1 / a === 1 / b;
13772     // A strict comparison is necessary because `null == undefined`.
13773     if (a == null || b == null) return a === b;
13774     // Unwrap any wrapped objects.
13775     if (a instanceof _) a = a._wrapped;
13776     if (b instanceof _) b = b._wrapped;
13777     // Compare `[[Class]]` names.
13778     var className = toString.call(a);
13779     if (className !== toString.call(b)) return false;
13780     switch (className) {
13781       // Strings, numbers, regular expressions, dates, and booleans are compared by value.
13782       case '[object RegExp]':
13783       // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
13784       case '[object String]':
13785         // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
13786         // equivalent to `new String("5")`.
13787         return '' + a === '' + b;
13788       case '[object Number]':
13789         // `NaN`s are equivalent, but non-reflexive.
13790         // Object(NaN) is equivalent to NaN
13791         if (+a !== +a) return +b !== +b;
13792         // An `egal` comparison is performed for other numeric values.
13793         return +a === 0 ? 1 / +a === 1 / b : +a === +b;
13794       case '[object Date]':
13795       case '[object Boolean]':
13796         // Coerce dates and booleans to numeric primitive values. Dates are compared by their
13797         // millisecond representations. Note that invalid dates with millisecond representations
13798         // of `NaN` are not equivalent.
13799         return +a === +b;
13800     }
13801
13802     var areArrays = className === '[object Array]';
13803     if (!areArrays) {
13804       if (typeof a != 'object' || typeof b != 'object') return false;
13805
13806       // Objects with different constructors are not equivalent, but `Object`s or `Array`s
13807       // from different frames are.
13808       var aCtor = a.constructor, bCtor = b.constructor;
13809       if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
13810                                _.isFunction(bCtor) && bCtor instanceof bCtor)
13811                           && ('constructor' in a && 'constructor' in b)) {
13812         return false;
13813       }
13814     }
13815     // Assume equality for cyclic structures. The algorithm for detecting cyclic
13816     // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
13817
13818     // Initializing stack of traversed objects.
13819     // It's done here since we only need them for objects and arrays comparison.
13820     aStack = aStack || [];
13821     bStack = bStack || [];
13822     var length = aStack.length;
13823     while (length--) {
13824       // Linear search. Performance is inversely proportional to the number of
13825       // unique nested structures.
13826       if (aStack[length] === a) return bStack[length] === b;
13827     }
13828
13829     // Add the first object to the stack of traversed objects.
13830     aStack.push(a);
13831     bStack.push(b);
13832
13833     // Recursively compare objects and arrays.
13834     if (areArrays) {
13835       // Compare array lengths to determine if a deep comparison is necessary.
13836       length = a.length;
13837       if (length !== b.length) return false;
13838       // Deep compare the contents, ignoring non-numeric properties.
13839       while (length--) {
13840         if (!eq(a[length], b[length], aStack, bStack)) return false;
13841       }
13842     } else {
13843       // Deep compare objects.
13844       var keys = _.keys(a), key;
13845       length = keys.length;
13846       // Ensure that both objects contain the same number of properties before comparing deep equality.
13847       if (_.keys(b).length !== length) return false;
13848       while (length--) {
13849         // Deep compare each member
13850         key = keys[length];
13851         if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
13852       }
13853     }
13854     // Remove the first object from the stack of traversed objects.
13855     aStack.pop();
13856     bStack.pop();
13857     return true;
13858   };
13859
13860   // Perform a deep comparison to check if two objects are equal.
13861   _.isEqual = function(a, b) {
13862     return eq(a, b);
13863   };
13864
13865   // Is a given array, string, or object empty?
13866   // An "empty" object has no enumerable own-properties.
13867   _.isEmpty = function(obj) {
13868     if (obj == null) return true;
13869     if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
13870     return _.keys(obj).length === 0;
13871   };
13872
13873   // Is a given value a DOM element?
13874   _.isElement = function(obj) {
13875     return !!(obj && obj.nodeType === 1);
13876   };
13877
13878   // Is a given value an array?
13879   // Delegates to ECMA5's native Array.isArray
13880   _.isArray = nativeIsArray || function(obj) {
13881     return toString.call(obj) === '[object Array]';
13882   };
13883
13884   // Is a given variable an object?
13885   _.isObject = function(obj) {
13886     var type = typeof obj;
13887     return type === 'function' || type === 'object' && !!obj;
13888   };
13889
13890   // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
13891   _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
13892     _['is' + name] = function(obj) {
13893       return toString.call(obj) === '[object ' + name + ']';
13894     };
13895   });
13896
13897   // Define a fallback version of the method in browsers (ahem, IE < 9), where
13898   // there isn't any inspectable "Arguments" type.
13899   if (!_.isArguments(arguments)) {
13900     _.isArguments = function(obj) {
13901       return _.has(obj, 'callee');
13902     };
13903   }
13904
13905   // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
13906   // IE 11 (#1621), and in Safari 8 (#1929).
13907   if (typeof /./ != 'function' && typeof Int8Array != 'object') {
13908     _.isFunction = function(obj) {
13909       return typeof obj == 'function' || false;
13910     };
13911   }
13912
13913   // Is a given object a finite number?
13914   _.isFinite = function(obj) {
13915     return isFinite(obj) && !isNaN(parseFloat(obj));
13916   };
13917
13918   // Is the given value `NaN`? (NaN is the only number which does not equal itself).
13919   _.isNaN = function(obj) {
13920     return _.isNumber(obj) && obj !== +obj;
13921   };
13922
13923   // Is a given value a boolean?
13924   _.isBoolean = function(obj) {
13925     return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
13926   };
13927
13928   // Is a given value equal to null?
13929   _.isNull = function(obj) {
13930     return obj === null;
13931   };
13932
13933   // Is a given variable undefined?
13934   _.isUndefined = function(obj) {
13935     return obj === void 0;
13936   };
13937
13938   // Shortcut function for checking if an object has a given property directly
13939   // on itself (in other words, not on a prototype).
13940   _.has = function(obj, key) {
13941     return obj != null && hasOwnProperty.call(obj, key);
13942   };
13943
13944   // Utility Functions
13945   // -----------------
13946
13947   // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
13948   // previous owner. Returns a reference to the Underscore object.
13949   _.noConflict = function() {
13950     root._ = previousUnderscore;
13951     return this;
13952   };
13953
13954   // Keep the identity function around for default iteratees.
13955   _.identity = function(value) {
13956     return value;
13957   };
13958
13959   // Predicate-generating functions. Often useful outside of Underscore.
13960   _.constant = function(value) {
13961     return function() {
13962       return value;
13963     };
13964   };
13965
13966   _.noop = function(){};
13967
13968   _.property = property;
13969
13970   // Generates a function for a given object that returns a given property.
13971   _.propertyOf = function(obj) {
13972     return obj == null ? function(){} : function(key) {
13973       return obj[key];
13974     };
13975   };
13976
13977   // Returns a predicate for checking whether an object has a given set of
13978   // `key:value` pairs.
13979   _.matcher = _.matches = function(attrs) {
13980     attrs = _.extendOwn({}, attrs);
13981     return function(obj) {
13982       return _.isMatch(obj, attrs);
13983     };
13984   };
13985
13986   // Run a function **n** times.
13987   _.times = function(n, iteratee, context) {
13988     var accum = Array(Math.max(0, n));
13989     iteratee = optimizeCb(iteratee, context, 1);
13990     for (var i = 0; i < n; i++) accum[i] = iteratee(i);
13991     return accum;
13992   };
13993
13994   // Return a random integer between min and max (inclusive).
13995   _.random = function(min, max) {
13996     if (max == null) {
13997       max = min;
13998       min = 0;
13999     }
14000     return min + Math.floor(Math.random() * (max - min + 1));
14001   };
14002
14003   // A (possibly faster) way to get the current timestamp as an integer.
14004   _.now = Date.now || function() {
14005     return new Date().getTime();
14006   };
14007
14008    // List of HTML entities for escaping.
14009   var escapeMap = {
14010     '&': '&amp;',
14011     '<': '&lt;',
14012     '>': '&gt;',
14013     '"': '&quot;',
14014     "'": '&#x27;',
14015     '`': '&#x60;'
14016   };
14017   var unescapeMap = _.invert(escapeMap);
14018
14019   // Functions for escaping and unescaping strings to/from HTML interpolation.
14020   var createEscaper = function(map) {
14021     var escaper = function(match) {
14022       return map[match];
14023     };
14024     // Regexes for identifying a key that needs to be escaped
14025     var source = '(?:' + _.keys(map).join('|') + ')';
14026     var testRegexp = RegExp(source);
14027     var replaceRegexp = RegExp(source, 'g');
14028     return function(string) {
14029       string = string == null ? '' : '' + string;
14030       return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
14031     };
14032   };
14033   _.escape = createEscaper(escapeMap);
14034   _.unescape = createEscaper(unescapeMap);
14035
14036   // If the value of the named `property` is a function then invoke it with the
14037   // `object` as context; otherwise, return it.
14038   _.result = function(object, property, fallback) {
14039     var value = object == null ? void 0 : object[property];
14040     if (value === void 0) {
14041       value = fallback;
14042     }
14043     return _.isFunction(value) ? value.call(object) : value;
14044   };
14045
14046   // Generate a unique integer id (unique within the entire client session).
14047   // Useful for temporary DOM ids.
14048   var idCounter = 0;
14049   _.uniqueId = function(prefix) {
14050     var id = ++idCounter + '';
14051     return prefix ? prefix + id : id;
14052   };
14053
14054   // By default, Underscore uses ERB-style template delimiters, change the
14055   // following template settings to use alternative delimiters.
14056   _.templateSettings = {
14057     evaluate    : /<%([\s\S]+?)%>/g,
14058     interpolate : /<%=([\s\S]+?)%>/g,
14059     escape      : /<%-([\s\S]+?)%>/g
14060   };
14061
14062   // When customizing `templateSettings`, if you don't want to define an
14063   // interpolation, evaluation or escaping regex, we need one that is
14064   // guaranteed not to match.
14065   var noMatch = /(.)^/;
14066
14067   // Certain characters need to be escaped so that they can be put into a
14068   // string literal.
14069   var escapes = {
14070     "'":      "'",
14071     '\\':     '\\',
14072     '\r':     'r',
14073     '\n':     'n',
14074     '\u2028': 'u2028',
14075     '\u2029': 'u2029'
14076   };
14077
14078   var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
14079
14080   var escapeChar = function(match) {
14081     return '\\' + escapes[match];
14082   };
14083
14084   // JavaScript micro-templating, similar to John Resig's implementation.
14085   // Underscore templating handles arbitrary delimiters, preserves whitespace,
14086   // and correctly escapes quotes within interpolated code.
14087   // NB: `oldSettings` only exists for backwards compatibility.
14088   _.template = function(text, settings, oldSettings) {
14089     if (!settings && oldSettings) settings = oldSettings;
14090     settings = _.defaults({}, settings, _.templateSettings);
14091
14092     // Combine delimiters into one regular expression via alternation.
14093     var matcher = RegExp([
14094       (settings.escape || noMatch).source,
14095       (settings.interpolate || noMatch).source,
14096       (settings.evaluate || noMatch).source
14097     ].join('|') + '|$', 'g');
14098
14099     // Compile the template source, escaping string literals appropriately.
14100     var index = 0;
14101     var source = "__p+='";
14102     text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
14103       source += text.slice(index, offset).replace(escaper, escapeChar);
14104       index = offset + match.length;
14105
14106       if (escape) {
14107         source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
14108       } else if (interpolate) {
14109         source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
14110       } else if (evaluate) {
14111         source += "';\n" + evaluate + "\n__p+='";
14112       }
14113
14114       // Adobe VMs need the match returned to produce the correct offest.
14115       return match;
14116     });
14117     source += "';\n";
14118
14119     // If a variable is not specified, place data values in local scope.
14120     if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
14121
14122     source = "var __t,__p='',__j=Array.prototype.join," +
14123       "print=function(){__p+=__j.call(arguments,'');};\n" +
14124       source + 'return __p;\n';
14125
14126     try {
14127       var render = new Function(settings.variable || 'obj', '_', source);
14128     } catch (e) {
14129       e.source = source;
14130       throw e;
14131     }
14132
14133     var template = function(data) {
14134       return render.call(this, data, _);
14135     };
14136
14137     // Provide the compiled source as a convenience for precompilation.
14138     var argument = settings.variable || 'obj';
14139     template.source = 'function(' + argument + '){\n' + source + '}';
14140
14141     return template;
14142   };
14143
14144   // Add a "chain" function. Start chaining a wrapped Underscore object.
14145   _.chain = function(obj) {
14146     var instance = _(obj);
14147     instance._chain = true;
14148     return instance;
14149   };
14150
14151   // OOP
14152   // ---------------
14153   // If Underscore is called as a function, it returns a wrapped object that
14154   // can be used OO-style. This wrapper holds altered versions of all the
14155   // underscore functions. Wrapped objects may be chained.
14156
14157   // Helper function to continue chaining intermediate results.
14158   var result = function(instance, obj) {
14159     return instance._chain ? _(obj).chain() : obj;
14160   };
14161
14162   // Add your own custom functions to the Underscore object.
14163   _.mixin = function(obj) {
14164     _.each(_.functions(obj), function(name) {
14165       var func = _[name] = obj[name];
14166       _.prototype[name] = function() {
14167         var args = [this._wrapped];
14168         push.apply(args, arguments);
14169         return result(this, func.apply(_, args));
14170       };
14171     });
14172   };
14173
14174   // Add all of the Underscore functions to the wrapper object.
14175   _.mixin(_);
14176
14177   // Add all mutator Array functions to the wrapper.
14178   _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
14179     var method = ArrayProto[name];
14180     _.prototype[name] = function() {
14181       var obj = this._wrapped;
14182       method.apply(obj, arguments);
14183       if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
14184       return result(this, obj);
14185     };
14186   });
14187
14188   // Add all accessor Array functions to the wrapper.
14189   _.each(['concat', 'join', 'slice'], function(name) {
14190     var method = ArrayProto[name];
14191     _.prototype[name] = function() {
14192       return result(this, method.apply(this._wrapped, arguments));
14193     };
14194   });
14195
14196   // Extracts the result from a wrapped and chained object.
14197   _.prototype.value = function() {
14198     return this._wrapped;
14199   };
14200
14201   // Provide unwrapping proxy for some methods used in engine operations
14202   // such as arithmetic and JSON stringification.
14203   _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
14204
14205   _.prototype.toString = function() {
14206     return '' + this._wrapped;
14207   };
14208
14209   // AMD registration happens at the end for compatibility with AMD loaders
14210   // that may not enforce next-turn semantics on modules. Even though general
14211   // practice for AMD registration is to be anonymous, underscore registers
14212   // as a named module because, like jQuery, it is a base library that is
14213   // popular enough to be bundled in a third party lib, but not be part of
14214   // an AMD load request. Those cases could generate an error when an
14215   // anonymous define() is called outside of a loader request.
14216   if (typeof define === 'function' && define.amd) {
14217     define('underscore', [], function() {
14218       return _;
14219     });
14220   }
14221 }.call(this));
14222
14223 },{}],162:[function(require,module,exports){
14224 /*
14225  * Copyright (C) 2008 Apple Inc. All Rights Reserved.
14226  *
14227  * Redistribution and use in source and binary forms, with or without
14228  * modification, are permitted provided that the following conditions
14229  * are met:
14230  * 1. Redistributions of source code must retain the above copyright
14231  *    notice, this list of conditions and the following disclaimer.
14232  * 2. Redistributions in binary form must reproduce the above copyright
14233  *    notice, this list of conditions and the following disclaimer in the
14234  *    documentation and/or other materials provided with the distribution.
14235  *
14236  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14237  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14238  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
14239  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
14240  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
14241  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
14242  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
14243  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
14244  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14245  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
14246  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14247  *
14248  * Ported from Webkit
14249  * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h
14250  */
14251
14252 module.exports = UnitBezier;
14253
14254 function UnitBezier(p1x, p1y, p2x, p2y) {
14255     // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
14256     this.cx = 3.0 * p1x;
14257     this.bx = 3.0 * (p2x - p1x) - this.cx;
14258     this.ax = 1.0 - this.cx - this.bx;
14259
14260     this.cy = 3.0 * p1y;
14261     this.by = 3.0 * (p2y - p1y) - this.cy;
14262     this.ay = 1.0 - this.cy - this.by;
14263
14264     this.p1x = p1x;
14265     this.p1y = p2y;
14266     this.p2x = p2x;
14267     this.p2y = p2y;
14268 }
14269
14270 UnitBezier.prototype.sampleCurveX = function(t) {
14271     // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
14272     return ((this.ax * t + this.bx) * t + this.cx) * t;
14273 };
14274
14275 UnitBezier.prototype.sampleCurveY = function(t) {
14276     return ((this.ay * t + this.by) * t + this.cy) * t;
14277 };
14278
14279 UnitBezier.prototype.sampleCurveDerivativeX = function(t) {
14280     return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
14281 };
14282
14283 UnitBezier.prototype.solveCurveX = function(x, epsilon) {
14284     if (typeof epsilon === 'undefined') epsilon = 1e-6;
14285
14286     var t0, t1, t2, x2, i;
14287
14288     // First try a few iterations of Newton's method -- normally very fast.
14289     for (t2 = x, i = 0; i < 8; i++) {
14290
14291         x2 = this.sampleCurveX(t2) - x;
14292         if (Math.abs(x2) < epsilon) return t2;
14293
14294         var d2 = this.sampleCurveDerivativeX(t2);
14295         if (Math.abs(d2) < 1e-6) break;
14296
14297         t2 = t2 - x2 / d2;
14298     }
14299
14300     // Fall back to the bisection method for reliability.
14301     t0 = 0.0;
14302     t1 = 1.0;
14303     t2 = x;
14304
14305     if (t2 < t0) return t0;
14306     if (t2 > t1) return t1;
14307
14308     while (t0 < t1) {
14309
14310         x2 = this.sampleCurveX(t2);
14311         if (Math.abs(x2 - x) < epsilon) return t2;
14312
14313         if (x > x2) {
14314             t0 = t2;
14315         } else {
14316             t1 = t2;
14317         }
14318
14319         t2 = (t1 - t0) * 0.5 + t0;
14320     }
14321
14322     // Failure.
14323     return t2;
14324 };
14325
14326 UnitBezier.prototype.solve = function(x, epsilon) {
14327     return this.sampleCurveY(this.solveCurveX(x, epsilon));
14328 };
14329
14330 },{}],163:[function(require,module,exports){
14331 var createElement = require("./vdom/create-element.js")
14332
14333 module.exports = createElement
14334
14335 },{"./vdom/create-element.js":169}],164:[function(require,module,exports){
14336 var diff = require("./vtree/diff.js")
14337
14338 module.exports = diff
14339
14340 },{"./vtree/diff.js":189}],165:[function(require,module,exports){
14341 var h = require("./virtual-hyperscript/index.js")
14342
14343 module.exports = h
14344
14345 },{"./virtual-hyperscript/index.js":176}],166:[function(require,module,exports){
14346 var diff = require("./diff.js")
14347 var patch = require("./patch.js")
14348 var h = require("./h.js")
14349 var create = require("./create-element.js")
14350 var VNode = require('./vnode/vnode.js')
14351 var VText = require('./vnode/vtext.js')
14352
14353 module.exports = {
14354     diff: diff,
14355     patch: patch,
14356     h: h,
14357     create: create,
14358     VNode: VNode,
14359     VText: VText
14360 }
14361
14362 },{"./create-element.js":163,"./diff.js":164,"./h.js":165,"./patch.js":167,"./vnode/vnode.js":185,"./vnode/vtext.js":187}],167:[function(require,module,exports){
14363 var patch = require("./vdom/patch.js")
14364
14365 module.exports = patch
14366
14367 },{"./vdom/patch.js":172}],168:[function(require,module,exports){
14368 var isObject = require("is-object")
14369 var isHook = require("../vnode/is-vhook.js")
14370
14371 module.exports = applyProperties
14372
14373 function applyProperties(node, props, previous) {
14374     for (var propName in props) {
14375         var propValue = props[propName]
14376
14377         if (propValue === undefined) {
14378             removeProperty(node, propName, propValue, previous);
14379         } else if (isHook(propValue)) {
14380             removeProperty(node, propName, propValue, previous)
14381             if (propValue.hook) {
14382                 propValue.hook(node,
14383                     propName,
14384                     previous ? previous[propName] : undefined)
14385             }
14386         } else {
14387             if (isObject(propValue)) {
14388                 patchObject(node, props, previous, propName, propValue);
14389             } else {
14390                 node[propName] = propValue
14391             }
14392         }
14393     }
14394 }
14395
14396 function removeProperty(node, propName, propValue, previous) {
14397     if (previous) {
14398         var previousValue = previous[propName]
14399
14400         if (!isHook(previousValue)) {
14401             if (propName === "attributes") {
14402                 for (var attrName in previousValue) {
14403                     node.removeAttribute(attrName)
14404                 }
14405             } else if (propName === "style") {
14406                 for (var i in previousValue) {
14407                     node.style[i] = ""
14408                 }
14409             } else if (typeof previousValue === "string") {
14410                 node[propName] = ""
14411             } else {
14412                 node[propName] = null
14413             }
14414         } else if (previousValue.unhook) {
14415             previousValue.unhook(node, propName, propValue)
14416         }
14417     }
14418 }
14419
14420 function patchObject(node, props, previous, propName, propValue) {
14421     var previousValue = previous ? previous[propName] : undefined
14422
14423     // Set attributes
14424     if (propName === "attributes") {
14425         for (var attrName in propValue) {
14426             var attrValue = propValue[attrName]
14427
14428             if (attrValue === undefined) {
14429                 node.removeAttribute(attrName)
14430             } else {
14431                 node.setAttribute(attrName, attrValue)
14432             }
14433         }
14434
14435         return
14436     }
14437
14438     if(previousValue && isObject(previousValue) &&
14439         getPrototype(previousValue) !== getPrototype(propValue)) {
14440         node[propName] = propValue
14441         return
14442     }
14443
14444     if (!isObject(node[propName])) {
14445         node[propName] = {}
14446     }
14447
14448     var replacer = propName === "style" ? "" : undefined
14449
14450     for (var k in propValue) {
14451         var value = propValue[k]
14452         node[propName][k] = (value === undefined) ? replacer : value
14453     }
14454 }
14455
14456 function getPrototype(value) {
14457     if (Object.getPrototypeOf) {
14458         return Object.getPrototypeOf(value)
14459     } else if (value.__proto__) {
14460         return value.__proto__
14461     } else if (value.constructor) {
14462         return value.constructor.prototype
14463     }
14464 }
14465
14466 },{"../vnode/is-vhook.js":180,"is-object":18}],169:[function(require,module,exports){
14467 var document = require("global/document")
14468
14469 var applyProperties = require("./apply-properties")
14470
14471 var isVNode = require("../vnode/is-vnode.js")
14472 var isVText = require("../vnode/is-vtext.js")
14473 var isWidget = require("../vnode/is-widget.js")
14474 var handleThunk = require("../vnode/handle-thunk.js")
14475
14476 module.exports = createElement
14477
14478 function createElement(vnode, opts) {
14479     var doc = opts ? opts.document || document : document
14480     var warn = opts ? opts.warn : null
14481
14482     vnode = handleThunk(vnode).a
14483
14484     if (isWidget(vnode)) {
14485         return vnode.init()
14486     } else if (isVText(vnode)) {
14487         return doc.createTextNode(vnode.text)
14488     } else if (!isVNode(vnode)) {
14489         if (warn) {
14490             warn("Item is not a valid virtual dom node", vnode)
14491         }
14492         return null
14493     }
14494
14495     var node = (vnode.namespace === null) ?
14496         doc.createElement(vnode.tagName) :
14497         doc.createElementNS(vnode.namespace, vnode.tagName)
14498
14499     var props = vnode.properties
14500     applyProperties(node, props)
14501
14502     var children = vnode.children
14503
14504     for (var i = 0; i < children.length; i++) {
14505         var childNode = createElement(children[i], opts)
14506         if (childNode) {
14507             node.appendChild(childNode)
14508         }
14509     }
14510
14511     return node
14512 }
14513
14514 },{"../vnode/handle-thunk.js":178,"../vnode/is-vnode.js":181,"../vnode/is-vtext.js":182,"../vnode/is-widget.js":183,"./apply-properties":168,"global/document":14}],170:[function(require,module,exports){
14515 // Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
14516 // We don't want to read all of the DOM nodes in the tree so we use
14517 // the in-order tree indexing to eliminate recursion down certain branches.
14518 // We only recurse into a DOM node if we know that it contains a child of
14519 // interest.
14520
14521 var noChild = {}
14522
14523 module.exports = domIndex
14524
14525 function domIndex(rootNode, tree, indices, nodes) {
14526     if (!indices || indices.length === 0) {
14527         return {}
14528     } else {
14529         indices.sort(ascending)
14530         return recurse(rootNode, tree, indices, nodes, 0)
14531     }
14532 }
14533
14534 function recurse(rootNode, tree, indices, nodes, rootIndex) {
14535     nodes = nodes || {}
14536
14537
14538     if (rootNode) {
14539         if (indexInRange(indices, rootIndex, rootIndex)) {
14540             nodes[rootIndex] = rootNode
14541         }
14542
14543         var vChildren = tree.children
14544
14545         if (vChildren) {
14546
14547             var childNodes = rootNode.childNodes
14548
14549             for (var i = 0; i < tree.children.length; i++) {
14550                 rootIndex += 1
14551
14552                 var vChild = vChildren[i] || noChild
14553                 var nextIndex = rootIndex + (vChild.count || 0)
14554
14555                 // skip recursion down the tree if there are no nodes down here
14556                 if (indexInRange(indices, rootIndex, nextIndex)) {
14557                     recurse(childNodes[i], vChild, indices, nodes, rootIndex)
14558                 }
14559
14560                 rootIndex = nextIndex
14561             }
14562         }
14563     }
14564
14565     return nodes
14566 }
14567
14568 // Binary search for an index in the interval [left, right]
14569 function indexInRange(indices, left, right) {
14570     if (indices.length === 0) {
14571         return false
14572     }
14573
14574     var minIndex = 0
14575     var maxIndex = indices.length - 1
14576     var currentIndex
14577     var currentItem
14578
14579     while (minIndex <= maxIndex) {
14580         currentIndex = ((maxIndex + minIndex) / 2) >> 0
14581         currentItem = indices[currentIndex]
14582
14583         if (minIndex === maxIndex) {
14584             return currentItem >= left && currentItem <= right
14585         } else if (currentItem < left) {
14586             minIndex = currentIndex + 1
14587         } else  if (currentItem > right) {
14588             maxIndex = currentIndex - 1
14589         } else {
14590             return true
14591         }
14592     }
14593
14594     return false;
14595 }
14596
14597 function ascending(a, b) {
14598     return a > b ? 1 : -1
14599 }
14600
14601 },{}],171:[function(require,module,exports){
14602 var applyProperties = require("./apply-properties")
14603
14604 var isWidget = require("../vnode/is-widget.js")
14605 var VPatch = require("../vnode/vpatch.js")
14606
14607 var updateWidget = require("./update-widget")
14608
14609 module.exports = applyPatch
14610
14611 function applyPatch(vpatch, domNode, renderOptions) {
14612     var type = vpatch.type
14613     var vNode = vpatch.vNode
14614     var patch = vpatch.patch
14615
14616     switch (type) {
14617         case VPatch.REMOVE:
14618             return removeNode(domNode, vNode)
14619         case VPatch.INSERT:
14620             return insertNode(domNode, patch, renderOptions)
14621         case VPatch.VTEXT:
14622             return stringPatch(domNode, vNode, patch, renderOptions)
14623         case VPatch.WIDGET:
14624             return widgetPatch(domNode, vNode, patch, renderOptions)
14625         case VPatch.VNODE:
14626             return vNodePatch(domNode, vNode, patch, renderOptions)
14627         case VPatch.ORDER:
14628             reorderChildren(domNode, patch)
14629             return domNode
14630         case VPatch.PROPS:
14631             applyProperties(domNode, patch, vNode.properties)
14632             return domNode
14633         case VPatch.THUNK:
14634             return replaceRoot(domNode,
14635                 renderOptions.patch(domNode, patch, renderOptions))
14636         default:
14637             return domNode
14638     }
14639 }
14640
14641 function removeNode(domNode, vNode) {
14642     var parentNode = domNode.parentNode
14643
14644     if (parentNode) {
14645         parentNode.removeChild(domNode)
14646     }
14647
14648     destroyWidget(domNode, vNode);
14649
14650     return null
14651 }
14652
14653 function insertNode(parentNode, vNode, renderOptions) {
14654     var newNode = renderOptions.render(vNode, renderOptions)
14655
14656     if (parentNode) {
14657         parentNode.appendChild(newNode)
14658     }
14659
14660     return parentNode
14661 }
14662
14663 function stringPatch(domNode, leftVNode, vText, renderOptions) {
14664     var newNode
14665
14666     if (domNode.nodeType === 3) {
14667         domNode.replaceData(0, domNode.length, vText.text)
14668         newNode = domNode
14669     } else {
14670         var parentNode = domNode.parentNode
14671         newNode = renderOptions.render(vText, renderOptions)
14672
14673         if (parentNode && newNode !== domNode) {
14674             parentNode.replaceChild(newNode, domNode)
14675         }
14676     }
14677
14678     return newNode
14679 }
14680
14681 function widgetPatch(domNode, leftVNode, widget, renderOptions) {
14682     var updating = updateWidget(leftVNode, widget)
14683     var newNode
14684
14685     if (updating) {
14686         newNode = widget.update(leftVNode, domNode) || domNode
14687     } else {
14688         newNode = renderOptions.render(widget, renderOptions)
14689     }
14690
14691     var parentNode = domNode.parentNode
14692
14693     if (parentNode && newNode !== domNode) {
14694         parentNode.replaceChild(newNode, domNode)
14695     }
14696
14697     if (!updating) {
14698         destroyWidget(domNode, leftVNode)
14699     }
14700
14701     return newNode
14702 }
14703
14704 function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
14705     var parentNode = domNode.parentNode
14706     var newNode = renderOptions.render(vNode, renderOptions)
14707
14708     if (parentNode && newNode !== domNode) {
14709         parentNode.replaceChild(newNode, domNode)
14710     }
14711
14712     return newNode
14713 }
14714
14715 function destroyWidget(domNode, w) {
14716     if (typeof w.destroy === "function" && isWidget(w)) {
14717         w.destroy(domNode)
14718     }
14719 }
14720
14721 function reorderChildren(domNode, moves) {
14722     var childNodes = domNode.childNodes
14723     var keyMap = {}
14724     var node
14725     var remove
14726     var insert
14727
14728     for (var i = 0; i < moves.removes.length; i++) {
14729         remove = moves.removes[i]
14730         node = childNodes[remove.from]
14731         if (remove.key) {
14732             keyMap[remove.key] = node
14733         }
14734         domNode.removeChild(node)
14735     }
14736
14737     var length = childNodes.length
14738     for (var j = 0; j < moves.inserts.length; j++) {
14739         insert = moves.inserts[j]
14740         node = keyMap[insert.key]
14741         // this is the weirdest bug i've ever seen in webkit
14742         domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to])
14743     }
14744 }
14745
14746 function replaceRoot(oldRoot, newRoot) {
14747     if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
14748         oldRoot.parentNode.replaceChild(newRoot, oldRoot)
14749     }
14750
14751     return newRoot;
14752 }
14753
14754 },{"../vnode/is-widget.js":183,"../vnode/vpatch.js":186,"./apply-properties":168,"./update-widget":173}],172:[function(require,module,exports){
14755 var document = require("global/document")
14756 var isArray = require("x-is-array")
14757
14758 var render = require("./create-element")
14759 var domIndex = require("./dom-index")
14760 var patchOp = require("./patch-op")
14761 module.exports = patch
14762
14763 function patch(rootNode, patches, renderOptions) {
14764     renderOptions = renderOptions || {}
14765     renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch
14766         ? renderOptions.patch
14767         : patchRecursive
14768     renderOptions.render = renderOptions.render || render
14769
14770     return renderOptions.patch(rootNode, patches, renderOptions)
14771 }
14772
14773 function patchRecursive(rootNode, patches, renderOptions) {
14774     var indices = patchIndices(patches)
14775
14776     if (indices.length === 0) {
14777         return rootNode
14778     }
14779
14780     var index = domIndex(rootNode, patches.a, indices)
14781     var ownerDocument = rootNode.ownerDocument
14782
14783     if (!renderOptions.document && ownerDocument !== document) {
14784         renderOptions.document = ownerDocument
14785     }
14786
14787     for (var i = 0; i < indices.length; i++) {
14788         var nodeIndex = indices[i]
14789         rootNode = applyPatch(rootNode,
14790             index[nodeIndex],
14791             patches[nodeIndex],
14792             renderOptions)
14793     }
14794
14795     return rootNode
14796 }
14797
14798 function applyPatch(rootNode, domNode, patchList, renderOptions) {
14799     if (!domNode) {
14800         return rootNode
14801     }
14802
14803     var newNode
14804
14805     if (isArray(patchList)) {
14806         for (var i = 0; i < patchList.length; i++) {
14807             newNode = patchOp(patchList[i], domNode, renderOptions)
14808
14809             if (domNode === rootNode) {
14810                 rootNode = newNode
14811             }
14812         }
14813     } else {
14814         newNode = patchOp(patchList, domNode, renderOptions)
14815
14816         if (domNode === rootNode) {
14817             rootNode = newNode
14818         }
14819     }
14820
14821     return rootNode
14822 }
14823
14824 function patchIndices(patches) {
14825     var indices = []
14826
14827     for (var key in patches) {
14828         if (key !== "a") {
14829             indices.push(Number(key))
14830         }
14831     }
14832
14833     return indices
14834 }
14835
14836 },{"./create-element":169,"./dom-index":170,"./patch-op":171,"global/document":14,"x-is-array":208}],173:[function(require,module,exports){
14837 var isWidget = require("../vnode/is-widget.js")
14838
14839 module.exports = updateWidget
14840
14841 function updateWidget(a, b) {
14842     if (isWidget(a) && isWidget(b)) {
14843         if ("name" in a && "name" in b) {
14844             return a.id === b.id
14845         } else {
14846             return a.init === b.init
14847         }
14848     }
14849
14850     return false
14851 }
14852
14853 },{"../vnode/is-widget.js":183}],174:[function(require,module,exports){
14854 'use strict';
14855
14856 var EvStore = require('ev-store');
14857
14858 module.exports = EvHook;
14859
14860 function EvHook(value) {
14861     if (!(this instanceof EvHook)) {
14862         return new EvHook(value);
14863     }
14864
14865     this.value = value;
14866 }
14867
14868 EvHook.prototype.hook = function (node, propertyName) {
14869     var es = EvStore(node);
14870     var propName = propertyName.substr(3);
14871
14872     es[propName] = this.value;
14873 };
14874
14875 EvHook.prototype.unhook = function(node, propertyName) {
14876     var es = EvStore(node);
14877     var propName = propertyName.substr(3);
14878
14879     es[propName] = undefined;
14880 };
14881
14882 },{"ev-store":7}],175:[function(require,module,exports){
14883 'use strict';
14884
14885 module.exports = SoftSetHook;
14886
14887 function SoftSetHook(value) {
14888     if (!(this instanceof SoftSetHook)) {
14889         return new SoftSetHook(value);
14890     }
14891
14892     this.value = value;
14893 }
14894
14895 SoftSetHook.prototype.hook = function (node, propertyName) {
14896     if (node[propertyName] !== this.value) {
14897         node[propertyName] = this.value;
14898     }
14899 };
14900
14901 },{}],176:[function(require,module,exports){
14902 'use strict';
14903
14904 var isArray = require('x-is-array');
14905
14906 var VNode = require('../vnode/vnode.js');
14907 var VText = require('../vnode/vtext.js');
14908 var isVNode = require('../vnode/is-vnode');
14909 var isVText = require('../vnode/is-vtext');
14910 var isWidget = require('../vnode/is-widget');
14911 var isHook = require('../vnode/is-vhook');
14912 var isVThunk = require('../vnode/is-thunk');
14913
14914 var parseTag = require('./parse-tag.js');
14915 var softSetHook = require('./hooks/soft-set-hook.js');
14916 var evHook = require('./hooks/ev-hook.js');
14917
14918 module.exports = h;
14919
14920 function h(tagName, properties, children) {
14921     var childNodes = [];
14922     var tag, props, key, namespace;
14923
14924     if (!children && isChildren(properties)) {
14925         children = properties;
14926         props = {};
14927     }
14928
14929     props = props || properties || {};
14930     tag = parseTag(tagName, props);
14931
14932     // support keys
14933     if (props.hasOwnProperty('key')) {
14934         key = props.key;
14935         props.key = undefined;
14936     }
14937
14938     // support namespace
14939     if (props.hasOwnProperty('namespace')) {
14940         namespace = props.namespace;
14941         props.namespace = undefined;
14942     }
14943
14944     // fix cursor bug
14945     if (tag === 'INPUT' &&
14946         !namespace &&
14947         props.hasOwnProperty('value') &&
14948         props.value !== undefined &&
14949         !isHook(props.value)
14950     ) {
14951         props.value = softSetHook(props.value);
14952     }
14953
14954     transformProperties(props);
14955
14956     if (children !== undefined && children !== null) {
14957         addChild(children, childNodes, tag, props);
14958     }
14959
14960
14961     return new VNode(tag, props, childNodes, key, namespace);
14962 }
14963
14964 function addChild(c, childNodes, tag, props) {
14965     if (typeof c === 'string') {
14966         childNodes.push(new VText(c));
14967     } else if (typeof c === 'number') {
14968         childNodes.push(new VText(String(c)));
14969     } else if (isChild(c)) {
14970         childNodes.push(c);
14971     } else if (isArray(c)) {
14972         for (var i = 0; i < c.length; i++) {
14973             addChild(c[i], childNodes, tag, props);
14974         }
14975     } else if (c === null || c === undefined) {
14976         return;
14977     } else {
14978         throw UnexpectedVirtualElement({
14979             foreignObject: c,
14980             parentVnode: {
14981                 tagName: tag,
14982                 properties: props
14983             }
14984         });
14985     }
14986 }
14987
14988 function transformProperties(props) {
14989     for (var propName in props) {
14990         if (props.hasOwnProperty(propName)) {
14991             var value = props[propName];
14992
14993             if (isHook(value)) {
14994                 continue;
14995             }
14996
14997             if (propName.substr(0, 3) === 'ev-') {
14998                 // add ev-foo support
14999                 props[propName] = evHook(value);
15000             }
15001         }
15002     }
15003 }
15004
15005 function isChild(x) {
15006     return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x);
15007 }
15008
15009 function isChildren(x) {
15010     return typeof x === 'string' || isArray(x) || isChild(x);
15011 }
15012
15013 function UnexpectedVirtualElement(data) {
15014     var err = new Error();
15015
15016     err.type = 'virtual-hyperscript.unexpected.virtual-element';
15017     err.message = 'Unexpected virtual child passed to h().\n' +
15018         'Expected a VNode / Vthunk / VWidget / string but:\n' +
15019         'got:\n' +
15020         errorString(data.foreignObject) +
15021         '.\n' +
15022         'The parent vnode is:\n' +
15023         errorString(data.parentVnode)
15024         '\n' +
15025         'Suggested fix: change your `h(..., [ ... ])` callsite.';
15026     err.foreignObject = data.foreignObject;
15027     err.parentVnode = data.parentVnode;
15028
15029     return err;
15030 }
15031
15032 function errorString(obj) {
15033     try {
15034         return JSON.stringify(obj, null, '    ');
15035     } catch (e) {
15036         return String(obj);
15037     }
15038 }
15039
15040 },{"../vnode/is-thunk":179,"../vnode/is-vhook":180,"../vnode/is-vnode":181,"../vnode/is-vtext":182,"../vnode/is-widget":183,"../vnode/vnode.js":185,"../vnode/vtext.js":187,"./hooks/ev-hook.js":174,"./hooks/soft-set-hook.js":175,"./parse-tag.js":177,"x-is-array":208}],177:[function(require,module,exports){
15041 'use strict';
15042
15043 var split = require('browser-split');
15044
15045 var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
15046 var notClassId = /^\.|#/;
15047
15048 module.exports = parseTag;
15049
15050 function parseTag(tag, props) {
15051     if (!tag) {
15052         return 'DIV';
15053     }
15054
15055     var noId = !(props.hasOwnProperty('id'));
15056
15057     var tagParts = split(tag, classIdSplit);
15058     var tagName = null;
15059
15060     if (notClassId.test(tagParts[1])) {
15061         tagName = 'DIV';
15062     }
15063
15064     var classes, part, type, i;
15065
15066     for (i = 0; i < tagParts.length; i++) {
15067         part = tagParts[i];
15068
15069         if (!part) {
15070             continue;
15071         }
15072
15073         type = part.charAt(0);
15074
15075         if (!tagName) {
15076             tagName = part;
15077         } else if (type === '.') {
15078             classes = classes || [];
15079             classes.push(part.substring(1, part.length));
15080         } else if (type === '#' && noId) {
15081             props.id = part.substring(1, part.length);
15082         }
15083     }
15084
15085     if (classes) {
15086         if (props.className) {
15087             classes.push(props.className);
15088         }
15089
15090         props.className = classes.join(' ');
15091     }
15092
15093     return props.namespace ? tagName : tagName.toUpperCase();
15094 }
15095
15096 },{"browser-split":3}],178:[function(require,module,exports){
15097 var isVNode = require("./is-vnode")
15098 var isVText = require("./is-vtext")
15099 var isWidget = require("./is-widget")
15100 var isThunk = require("./is-thunk")
15101
15102 module.exports = handleThunk
15103
15104 function handleThunk(a, b) {
15105     var renderedA = a
15106     var renderedB = b
15107
15108     if (isThunk(b)) {
15109         renderedB = renderThunk(b, a)
15110     }
15111
15112     if (isThunk(a)) {
15113         renderedA = renderThunk(a, null)
15114     }
15115
15116     return {
15117         a: renderedA,
15118         b: renderedB
15119     }
15120 }
15121
15122 function renderThunk(thunk, previous) {
15123     var renderedThunk = thunk.vnode
15124
15125     if (!renderedThunk) {
15126         renderedThunk = thunk.vnode = thunk.render(previous)
15127     }
15128
15129     if (!(isVNode(renderedThunk) ||
15130             isVText(renderedThunk) ||
15131             isWidget(renderedThunk))) {
15132         throw new Error("thunk did not return a valid node");
15133     }
15134
15135     return renderedThunk
15136 }
15137
15138 },{"./is-thunk":179,"./is-vnode":181,"./is-vtext":182,"./is-widget":183}],179:[function(require,module,exports){
15139 module.exports = isThunk
15140
15141 function isThunk(t) {
15142     return t && t.type === "Thunk"
15143 }
15144
15145 },{}],180:[function(require,module,exports){
15146 module.exports = isHook
15147
15148 function isHook(hook) {
15149     return hook &&
15150       (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") ||
15151        typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook"))
15152 }
15153
15154 },{}],181:[function(require,module,exports){
15155 var version = require("./version")
15156
15157 module.exports = isVirtualNode
15158
15159 function isVirtualNode(x) {
15160     return x && x.type === "VirtualNode" && x.version === version
15161 }
15162
15163 },{"./version":184}],182:[function(require,module,exports){
15164 var version = require("./version")
15165
15166 module.exports = isVirtualText
15167
15168 function isVirtualText(x) {
15169     return x && x.type === "VirtualText" && x.version === version
15170 }
15171
15172 },{"./version":184}],183:[function(require,module,exports){
15173 module.exports = isWidget
15174
15175 function isWidget(w) {
15176     return w && w.type === "Widget"
15177 }
15178
15179 },{}],184:[function(require,module,exports){
15180 module.exports = "2"
15181
15182 },{}],185:[function(require,module,exports){
15183 var version = require("./version")
15184 var isVNode = require("./is-vnode")
15185 var isWidget = require("./is-widget")
15186 var isThunk = require("./is-thunk")
15187 var isVHook = require("./is-vhook")
15188
15189 module.exports = VirtualNode
15190
15191 var noProperties = {}
15192 var noChildren = []
15193
15194 function VirtualNode(tagName, properties, children, key, namespace) {
15195     this.tagName = tagName
15196     this.properties = properties || noProperties
15197     this.children = children || noChildren
15198     this.key = key != null ? String(key) : undefined
15199     this.namespace = (typeof namespace === "string") ? namespace : null
15200
15201     var count = (children && children.length) || 0
15202     var descendants = 0
15203     var hasWidgets = false
15204     var hasThunks = false
15205     var descendantHooks = false
15206     var hooks
15207
15208     for (var propName in properties) {
15209         if (properties.hasOwnProperty(propName)) {
15210             var property = properties[propName]
15211             if (isVHook(property) && property.unhook) {
15212                 if (!hooks) {
15213                     hooks = {}
15214                 }
15215
15216                 hooks[propName] = property
15217             }
15218         }
15219     }
15220
15221     for (var i = 0; i < count; i++) {
15222         var child = children[i]
15223         if (isVNode(child)) {
15224             descendants += child.count || 0
15225
15226             if (!hasWidgets && child.hasWidgets) {
15227                 hasWidgets = true
15228             }
15229
15230             if (!hasThunks && child.hasThunks) {
15231                 hasThunks = true
15232             }
15233
15234             if (!descendantHooks && (child.hooks || child.descendantHooks)) {
15235                 descendantHooks = true
15236             }
15237         } else if (!hasWidgets && isWidget(child)) {
15238             if (typeof child.destroy === "function") {
15239                 hasWidgets = true
15240             }
15241         } else if (!hasThunks && isThunk(child)) {
15242             hasThunks = true;
15243         }
15244     }
15245
15246     this.count = count + descendants
15247     this.hasWidgets = hasWidgets
15248     this.hasThunks = hasThunks
15249     this.hooks = hooks
15250     this.descendantHooks = descendantHooks
15251 }
15252
15253 VirtualNode.prototype.version = version
15254 VirtualNode.prototype.type = "VirtualNode"
15255
15256 },{"./is-thunk":179,"./is-vhook":180,"./is-vnode":181,"./is-widget":183,"./version":184}],186:[function(require,module,exports){
15257 var version = require("./version")
15258
15259 VirtualPatch.NONE = 0
15260 VirtualPatch.VTEXT = 1
15261 VirtualPatch.VNODE = 2
15262 VirtualPatch.WIDGET = 3
15263 VirtualPatch.PROPS = 4
15264 VirtualPatch.ORDER = 5
15265 VirtualPatch.INSERT = 6
15266 VirtualPatch.REMOVE = 7
15267 VirtualPatch.THUNK = 8
15268
15269 module.exports = VirtualPatch
15270
15271 function VirtualPatch(type, vNode, patch) {
15272     this.type = Number(type)
15273     this.vNode = vNode
15274     this.patch = patch
15275 }
15276
15277 VirtualPatch.prototype.version = version
15278 VirtualPatch.prototype.type = "VirtualPatch"
15279
15280 },{"./version":184}],187:[function(require,module,exports){
15281 var version = require("./version")
15282
15283 module.exports = VirtualText
15284
15285 function VirtualText(text) {
15286     this.text = String(text)
15287 }
15288
15289 VirtualText.prototype.version = version
15290 VirtualText.prototype.type = "VirtualText"
15291
15292 },{"./version":184}],188:[function(require,module,exports){
15293 var isObject = require("is-object")
15294 var isHook = require("../vnode/is-vhook")
15295
15296 module.exports = diffProps
15297
15298 function diffProps(a, b) {
15299     var diff
15300
15301     for (var aKey in a) {
15302         if (!(aKey in b)) {
15303             diff = diff || {}
15304             diff[aKey] = undefined
15305         }
15306
15307         var aValue = a[aKey]
15308         var bValue = b[aKey]
15309
15310         if (aValue === bValue) {
15311             continue
15312         } else if (isObject(aValue) && isObject(bValue)) {
15313             if (getPrototype(bValue) !== getPrototype(aValue)) {
15314                 diff = diff || {}
15315                 diff[aKey] = bValue
15316             } else if (isHook(bValue)) {
15317                  diff = diff || {}
15318                  diff[aKey] = bValue
15319             } else {
15320                 var objectDiff = diffProps(aValue, bValue)
15321                 if (objectDiff) {
15322                     diff = diff || {}
15323                     diff[aKey] = objectDiff
15324                 }
15325             }
15326         } else {
15327             diff = diff || {}
15328             diff[aKey] = bValue
15329         }
15330     }
15331
15332     for (var bKey in b) {
15333         if (!(bKey in a)) {
15334             diff = diff || {}
15335             diff[bKey] = b[bKey]
15336         }
15337     }
15338
15339     return diff
15340 }
15341
15342 function getPrototype(value) {
15343   if (Object.getPrototypeOf) {
15344     return Object.getPrototypeOf(value)
15345   } else if (value.__proto__) {
15346     return value.__proto__
15347   } else if (value.constructor) {
15348     return value.constructor.prototype
15349   }
15350 }
15351
15352 },{"../vnode/is-vhook":180,"is-object":18}],189:[function(require,module,exports){
15353 var isArray = require("x-is-array")
15354
15355 var VPatch = require("../vnode/vpatch")
15356 var isVNode = require("../vnode/is-vnode")
15357 var isVText = require("../vnode/is-vtext")
15358 var isWidget = require("../vnode/is-widget")
15359 var isThunk = require("../vnode/is-thunk")
15360 var handleThunk = require("../vnode/handle-thunk")
15361
15362 var diffProps = require("./diff-props")
15363
15364 module.exports = diff
15365
15366 function diff(a, b) {
15367     var patch = { a: a }
15368     walk(a, b, patch, 0)
15369     return patch
15370 }
15371
15372 function walk(a, b, patch, index) {
15373     if (a === b) {
15374         return
15375     }
15376
15377     var apply = patch[index]
15378     var applyClear = false
15379
15380     if (isThunk(a) || isThunk(b)) {
15381         thunks(a, b, patch, index)
15382     } else if (b == null) {
15383
15384         // If a is a widget we will add a remove patch for it
15385         // Otherwise any child widgets/hooks must be destroyed.
15386         // This prevents adding two remove patches for a widget.
15387         if (!isWidget(a)) {
15388             clearState(a, patch, index)
15389             apply = patch[index]
15390         }
15391
15392         apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
15393     } else if (isVNode(b)) {
15394         if (isVNode(a)) {
15395             if (a.tagName === b.tagName &&
15396                 a.namespace === b.namespace &&
15397                 a.key === b.key) {
15398                 var propsPatch = diffProps(a.properties, b.properties)
15399                 if (propsPatch) {
15400                     apply = appendPatch(apply,
15401                         new VPatch(VPatch.PROPS, a, propsPatch))
15402                 }
15403                 apply = diffChildren(a, b, patch, apply, index)
15404             } else {
15405                 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
15406                 applyClear = true
15407             }
15408         } else {
15409             apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
15410             applyClear = true
15411         }
15412     } else if (isVText(b)) {
15413         if (!isVText(a)) {
15414             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
15415             applyClear = true
15416         } else if (a.text !== b.text) {
15417             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
15418         }
15419     } else if (isWidget(b)) {
15420         if (!isWidget(a)) {
15421             applyClear = true
15422         }
15423
15424         apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
15425     }
15426
15427     if (apply) {
15428         patch[index] = apply
15429     }
15430
15431     if (applyClear) {
15432         clearState(a, patch, index)
15433     }
15434 }
15435
15436 function diffChildren(a, b, patch, apply, index) {
15437     var aChildren = a.children
15438     var orderedSet = reorder(aChildren, b.children)
15439     var bChildren = orderedSet.children
15440
15441     var aLen = aChildren.length
15442     var bLen = bChildren.length
15443     var len = aLen > bLen ? aLen : bLen
15444
15445     for (var i = 0; i < len; i++) {
15446         var leftNode = aChildren[i]
15447         var rightNode = bChildren[i]
15448         index += 1
15449
15450         if (!leftNode) {
15451             if (rightNode) {
15452                 // Excess nodes in b need to be added
15453                 apply = appendPatch(apply,
15454                     new VPatch(VPatch.INSERT, null, rightNode))
15455             }
15456         } else {
15457             walk(leftNode, rightNode, patch, index)
15458         }
15459
15460         if (isVNode(leftNode) && leftNode.count) {
15461             index += leftNode.count
15462         }
15463     }
15464
15465     if (orderedSet.moves) {
15466         // Reorder nodes last
15467         apply = appendPatch(apply, new VPatch(
15468             VPatch.ORDER,
15469             a,
15470             orderedSet.moves
15471         ))
15472     }
15473
15474     return apply
15475 }
15476
15477 function clearState(vNode, patch, index) {
15478     // TODO: Make this a single walk, not two
15479     unhook(vNode, patch, index)
15480     destroyWidgets(vNode, patch, index)
15481 }
15482
15483 // Patch records for all destroyed widgets must be added because we need
15484 // a DOM node reference for the destroy function
15485 function destroyWidgets(vNode, patch, index) {
15486     if (isWidget(vNode)) {
15487         if (typeof vNode.destroy === "function") {
15488             patch[index] = appendPatch(
15489                 patch[index],
15490                 new VPatch(VPatch.REMOVE, vNode, null)
15491             )
15492         }
15493     } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
15494         var children = vNode.children
15495         var len = children.length
15496         for (var i = 0; i < len; i++) {
15497             var child = children[i]
15498             index += 1
15499
15500             destroyWidgets(child, patch, index)
15501
15502             if (isVNode(child) && child.count) {
15503                 index += child.count
15504             }
15505         }
15506     } else if (isThunk(vNode)) {
15507         thunks(vNode, null, patch, index)
15508     }
15509 }
15510
15511 // Create a sub-patch for thunks
15512 function thunks(a, b, patch, index) {
15513     var nodes = handleThunk(a, b)
15514     var thunkPatch = diff(nodes.a, nodes.b)
15515     if (hasPatches(thunkPatch)) {
15516         patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
15517     }
15518 }
15519
15520 function hasPatches(patch) {
15521     for (var index in patch) {
15522         if (index !== "a") {
15523             return true
15524         }
15525     }
15526
15527     return false
15528 }
15529
15530 // Execute hooks when two nodes are identical
15531 function unhook(vNode, patch, index) {
15532     if (isVNode(vNode)) {
15533         if (vNode.hooks) {
15534             patch[index] = appendPatch(
15535                 patch[index],
15536                 new VPatch(
15537                     VPatch.PROPS,
15538                     vNode,
15539                     undefinedKeys(vNode.hooks)
15540                 )
15541             )
15542         }
15543
15544         if (vNode.descendantHooks || vNode.hasThunks) {
15545             var children = vNode.children
15546             var len = children.length
15547             for (var i = 0; i < len; i++) {
15548                 var child = children[i]
15549                 index += 1
15550
15551                 unhook(child, patch, index)
15552
15553                 if (isVNode(child) && child.count) {
15554                     index += child.count
15555                 }
15556             }
15557         }
15558     } else if (isThunk(vNode)) {
15559         thunks(vNode, null, patch, index)
15560     }
15561 }
15562
15563 function undefinedKeys(obj) {
15564     var result = {}
15565
15566     for (var key in obj) {
15567         result[key] = undefined
15568     }
15569
15570     return result
15571 }
15572
15573 // List diff, naive left to right reordering
15574 function reorder(aChildren, bChildren) {
15575     // O(M) time, O(M) memory
15576     var bChildIndex = keyIndex(bChildren)
15577     var bKeys = bChildIndex.keys
15578     var bFree = bChildIndex.free
15579
15580     if (bFree.length === bChildren.length) {
15581         return {
15582             children: bChildren,
15583             moves: null
15584         }
15585     }
15586
15587     // O(N) time, O(N) memory
15588     var aChildIndex = keyIndex(aChildren)
15589     var aKeys = aChildIndex.keys
15590     var aFree = aChildIndex.free
15591
15592     if (aFree.length === aChildren.length) {
15593         return {
15594             children: bChildren,
15595             moves: null
15596         }
15597     }
15598
15599     // O(MAX(N, M)) memory
15600     var newChildren = []
15601
15602     var freeIndex = 0
15603     var freeCount = bFree.length
15604     var deletedItems = 0
15605
15606     // Iterate through a and match a node in b
15607     // O(N) time,
15608     for (var i = 0 ; i < aChildren.length; i++) {
15609         var aItem = aChildren[i]
15610         var itemIndex
15611
15612         if (aItem.key) {
15613             if (bKeys.hasOwnProperty(aItem.key)) {
15614                 // Match up the old keys
15615                 itemIndex = bKeys[aItem.key]
15616                 newChildren.push(bChildren[itemIndex])
15617
15618             } else {
15619                 // Remove old keyed items
15620                 itemIndex = i - deletedItems++
15621                 newChildren.push(null)
15622             }
15623         } else {
15624             // Match the item in a with the next free item in b
15625             if (freeIndex < freeCount) {
15626                 itemIndex = bFree[freeIndex++]
15627                 newChildren.push(bChildren[itemIndex])
15628             } else {
15629                 // There are no free items in b to match with
15630                 // the free items in a, so the extra free nodes
15631                 // are deleted.
15632                 itemIndex = i - deletedItems++
15633                 newChildren.push(null)
15634             }
15635         }
15636     }
15637
15638     var lastFreeIndex = freeIndex >= bFree.length ?
15639         bChildren.length :
15640         bFree[freeIndex]
15641
15642     // Iterate through b and append any new keys
15643     // O(M) time
15644     for (var j = 0; j < bChildren.length; j++) {
15645         var newItem = bChildren[j]
15646
15647         if (newItem.key) {
15648             if (!aKeys.hasOwnProperty(newItem.key)) {
15649                 // Add any new keyed items
15650                 // We are adding new items to the end and then sorting them
15651                 // in place. In future we should insert new items in place.
15652                 newChildren.push(newItem)
15653             }
15654         } else if (j >= lastFreeIndex) {
15655             // Add any leftover non-keyed items
15656             newChildren.push(newItem)
15657         }
15658     }
15659
15660     var simulate = newChildren.slice()
15661     var simulateIndex = 0
15662     var removes = []
15663     var inserts = []
15664     var simulateItem
15665
15666     for (var k = 0; k < bChildren.length;) {
15667         var wantedItem = bChildren[k]
15668         simulateItem = simulate[simulateIndex]
15669
15670         // remove items
15671         while (simulateItem === null && simulate.length) {
15672             removes.push(remove(simulate, simulateIndex, null))
15673             simulateItem = simulate[simulateIndex]
15674         }
15675
15676         if (!simulateItem || simulateItem.key !== wantedItem.key) {
15677             // if we need a key in this position...
15678             if (wantedItem.key) {
15679                 if (simulateItem && simulateItem.key) {
15680                     // if an insert doesn't put this key in place, it needs to move
15681                     if (bKeys[simulateItem.key] !== k + 1) {
15682                         removes.push(remove(simulate, simulateIndex, simulateItem.key))
15683                         simulateItem = simulate[simulateIndex]
15684                         // if the remove didn't put the wanted item in place, we need to insert it
15685                         if (!simulateItem || simulateItem.key !== wantedItem.key) {
15686                             inserts.push({key: wantedItem.key, to: k})
15687                         }
15688                         // items are matching, so skip ahead
15689                         else {
15690                             simulateIndex++
15691                         }
15692                     }
15693                     else {
15694                         inserts.push({key: wantedItem.key, to: k})
15695                     }
15696                 }
15697                 else {
15698                     inserts.push({key: wantedItem.key, to: k})
15699                 }
15700                 k++
15701             }
15702             // a key in simulate has no matching wanted key, remove it
15703             else if (simulateItem && simulateItem.key) {
15704                 removes.push(remove(simulate, simulateIndex, simulateItem.key))
15705             }
15706         }
15707         else {
15708             simulateIndex++
15709             k++
15710         }
15711     }
15712
15713     // remove all the remaining nodes from simulate
15714     while(simulateIndex < simulate.length) {
15715         simulateItem = simulate[simulateIndex]
15716         removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key))
15717     }
15718
15719     // If the only moves we have are deletes then we can just
15720     // let the delete patch remove these items.
15721     if (removes.length === deletedItems && !inserts.length) {
15722         return {
15723             children: newChildren,
15724             moves: null
15725         }
15726     }
15727
15728     return {
15729         children: newChildren,
15730         moves: {
15731             removes: removes,
15732             inserts: inserts
15733         }
15734     }
15735 }
15736
15737 function remove(arr, index, key) {
15738     arr.splice(index, 1)
15739
15740     return {
15741         from: index,
15742         key: key
15743     }
15744 }
15745
15746 function keyIndex(children) {
15747     var keys = {}
15748     var free = []
15749     var length = children.length
15750
15751     for (var i = 0; i < length; i++) {
15752         var child = children[i]
15753
15754         if (child.key) {
15755             keys[child.key] = i
15756         } else {
15757             free.push(i)
15758         }
15759     }
15760
15761     return {
15762         keys: keys,     // A hash of key name to index
15763         free: free      // An array of unkeyed item indices
15764     }
15765 }
15766
15767 function appendPatch(apply, patch) {
15768     if (apply) {
15769         if (isArray(apply)) {
15770             apply.push(patch)
15771         } else {
15772             apply = [apply, patch]
15773         }
15774
15775         return apply
15776     } else {
15777         return patch
15778     }
15779 }
15780
15781 },{"../vnode/handle-thunk":178,"../vnode/is-thunk":179,"../vnode/is-vnode":181,"../vnode/is-vtext":182,"../vnode/is-widget":183,"../vnode/vpatch":186,"./diff-props":188,"x-is-array":208}],190:[function(require,module,exports){
15782 /** @license MIT License (c) copyright 2010-2014 original author or authors */
15783 /** @author Brian Cavalier */
15784 /** @author John Hann */
15785
15786 (function(define) { 'use strict';
15787 define(function (require) {
15788
15789         var makePromise = require('./makePromise');
15790         var Scheduler = require('./Scheduler');
15791         var async = require('./env').asap;
15792
15793         return makePromise({
15794                 scheduler: new Scheduler(async)
15795         });
15796
15797 });
15798 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
15799
15800 },{"./Scheduler":191,"./env":203,"./makePromise":205}],191:[function(require,module,exports){
15801 /** @license MIT License (c) copyright 2010-2014 original author or authors */
15802 /** @author Brian Cavalier */
15803 /** @author John Hann */
15804
15805 (function(define) { 'use strict';
15806 define(function() {
15807
15808         // Credit to Twisol (https://github.com/Twisol) for suggesting
15809         // this type of extensible queue + trampoline approach for next-tick conflation.
15810
15811         /**
15812          * Async task scheduler
15813          * @param {function} async function to schedule a single async function
15814          * @constructor
15815          */
15816         function Scheduler(async) {
15817                 this._async = async;
15818                 this._running = false;
15819
15820                 this._queue = this;
15821                 this._queueLen = 0;
15822                 this._afterQueue = {};
15823                 this._afterQueueLen = 0;
15824
15825                 var self = this;
15826                 this.drain = function() {
15827                         self._drain();
15828                 };
15829         }
15830
15831         /**
15832          * Enqueue a task
15833          * @param {{ run:function }} task
15834          */
15835         Scheduler.prototype.enqueue = function(task) {
15836                 this._queue[this._queueLen++] = task;
15837                 this.run();
15838         };
15839
15840         /**
15841          * Enqueue a task to run after the main task queue
15842          * @param {{ run:function }} task
15843          */
15844         Scheduler.prototype.afterQueue = function(task) {
15845                 this._afterQueue[this._afterQueueLen++] = task;
15846                 this.run();
15847         };
15848
15849         Scheduler.prototype.run = function() {
15850                 if (!this._running) {
15851                         this._running = true;
15852                         this._async(this.drain);
15853                 }
15854         };
15855
15856         /**
15857          * Drain the handler queue entirely, and then the after queue
15858          */
15859         Scheduler.prototype._drain = function() {
15860                 var i = 0;
15861                 for (; i < this._queueLen; ++i) {
15862                         this._queue[i].run();
15863                         this._queue[i] = void 0;
15864                 }
15865
15866                 this._queueLen = 0;
15867                 this._running = false;
15868
15869                 for (i = 0; i < this._afterQueueLen; ++i) {
15870                         this._afterQueue[i].run();
15871                         this._afterQueue[i] = void 0;
15872                 }
15873
15874                 this._afterQueueLen = 0;
15875         };
15876
15877         return Scheduler;
15878
15879 });
15880 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
15881
15882 },{}],192:[function(require,module,exports){
15883 /** @license MIT License (c) copyright 2010-2014 original author or authors */
15884 /** @author Brian Cavalier */
15885 /** @author John Hann */
15886
15887 (function(define) { 'use strict';
15888 define(function() {
15889
15890         /**
15891          * Custom error type for promises rejected by promise.timeout
15892          * @param {string} message
15893          * @constructor
15894          */
15895         function TimeoutError (message) {
15896                 Error.call(this);
15897                 this.message = message;
15898                 this.name = TimeoutError.name;
15899                 if (typeof Error.captureStackTrace === 'function') {
15900                         Error.captureStackTrace(this, TimeoutError);
15901                 }
15902         }
15903
15904         TimeoutError.prototype = Object.create(Error.prototype);
15905         TimeoutError.prototype.constructor = TimeoutError;
15906
15907         return TimeoutError;
15908 });
15909 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
15910 },{}],193:[function(require,module,exports){
15911 /** @license MIT License (c) copyright 2010-2014 original author or authors */
15912 /** @author Brian Cavalier */
15913 /** @author John Hann */
15914
15915 (function(define) { 'use strict';
15916 define(function() {
15917
15918         makeApply.tryCatchResolve = tryCatchResolve;
15919
15920         return makeApply;
15921
15922         function makeApply(Promise, call) {
15923                 if(arguments.length < 2) {
15924                         call = tryCatchResolve;
15925                 }
15926
15927                 return apply;
15928
15929                 function apply(f, thisArg, args) {
15930                         var p = Promise._defer();
15931                         var l = args.length;
15932                         var params = new Array(l);
15933                         callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
15934
15935                         return p;
15936                 }
15937
15938                 function callAndResolve(c, h) {
15939                         if(c.i < 0) {
15940                                 return call(c.f, c.thisArg, c.params, h);
15941                         }
15942
15943                         var handler = Promise._handler(c.args[c.i]);
15944                         handler.fold(callAndResolveNext, c, void 0, h);
15945                 }
15946
15947                 function callAndResolveNext(c, x, h) {
15948                         c.params[c.i] = x;
15949                         c.i -= 1;
15950                         callAndResolve(c, h);
15951                 }
15952         }
15953
15954         function tryCatchResolve(f, thisArg, args, resolver) {
15955                 try {
15956                         resolver.resolve(f.apply(thisArg, args));
15957                 } catch(e) {
15958                         resolver.reject(e);
15959                 }
15960         }
15961
15962 });
15963 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
15964
15965
15966
15967 },{}],194:[function(require,module,exports){
15968 /** @license MIT License (c) copyright 2010-2014 original author or authors */
15969 /** @author Brian Cavalier */
15970 /** @author John Hann */
15971
15972 (function(define) { 'use strict';
15973 define(function(require) {
15974
15975         var state = require('../state');
15976         var applier = require('../apply');
15977
15978         return function array(Promise) {
15979
15980                 var applyFold = applier(Promise);
15981                 var toPromise = Promise.resolve;
15982                 var all = Promise.all;
15983
15984                 var ar = Array.prototype.reduce;
15985                 var arr = Array.prototype.reduceRight;
15986                 var slice = Array.prototype.slice;
15987
15988                 // Additional array combinators
15989
15990                 Promise.any = any;
15991                 Promise.some = some;
15992                 Promise.settle = settle;
15993
15994                 Promise.map = map;
15995                 Promise.filter = filter;
15996                 Promise.reduce = reduce;
15997                 Promise.reduceRight = reduceRight;
15998
15999                 /**
16000                  * When this promise fulfills with an array, do
16001                  * onFulfilled.apply(void 0, array)
16002                  * @param {function} onFulfilled function to apply
16003                  * @returns {Promise} promise for the result of applying onFulfilled
16004                  */
16005                 Promise.prototype.spread = function(onFulfilled) {
16006                         return this.then(all).then(function(array) {
16007                                 return onFulfilled.apply(this, array);
16008                         });
16009                 };
16010
16011                 return Promise;
16012
16013                 /**
16014                  * One-winner competitive race.
16015                  * Return a promise that will fulfill when one of the promises
16016                  * in the input array fulfills, or will reject when all promises
16017                  * have rejected.
16018                  * @param {array} promises
16019                  * @returns {Promise} promise for the first fulfilled value
16020                  */
16021                 function any(promises) {
16022                         var p = Promise._defer();
16023                         var resolver = p._handler;
16024                         var l = promises.length>>>0;
16025
16026                         var pending = l;
16027                         var errors = [];
16028
16029                         for (var h, x, i = 0; i < l; ++i) {
16030                                 x = promises[i];
16031                                 if(x === void 0 && !(i in promises)) {
16032                                         --pending;
16033                                         continue;
16034                                 }
16035
16036                                 h = Promise._handler(x);
16037                                 if(h.state() > 0) {
16038                                         resolver.become(h);
16039                                         Promise._visitRemaining(promises, i, h);
16040                                         break;
16041                                 } else {
16042                                         h.visit(resolver, handleFulfill, handleReject);
16043                                 }
16044                         }
16045
16046                         if(pending === 0) {
16047                                 resolver.reject(new RangeError('any(): array must not be empty'));
16048                         }
16049
16050                         return p;
16051
16052                         function handleFulfill(x) {
16053                                 /*jshint validthis:true*/
16054                                 errors = null;
16055                                 this.resolve(x); // this === resolver
16056                         }
16057
16058                         function handleReject(e) {
16059                                 /*jshint validthis:true*/
16060                                 if(this.resolved) { // this === resolver
16061                                         return;
16062                                 }
16063
16064                                 errors.push(e);
16065                                 if(--pending === 0) {
16066                                         this.reject(errors);
16067                                 }
16068                         }
16069                 }
16070
16071                 /**
16072                  * N-winner competitive race
16073                  * Return a promise that will fulfill when n input promises have
16074                  * fulfilled, or will reject when it becomes impossible for n
16075                  * input promises to fulfill (ie when promises.length - n + 1
16076                  * have rejected)
16077                  * @param {array} promises
16078                  * @param {number} n
16079                  * @returns {Promise} promise for the earliest n fulfillment values
16080                  *
16081                  * @deprecated
16082                  */
16083                 function some(promises, n) {
16084                         /*jshint maxcomplexity:7*/
16085                         var p = Promise._defer();
16086                         var resolver = p._handler;
16087
16088                         var results = [];
16089                         var errors = [];
16090
16091                         var l = promises.length>>>0;
16092                         var nFulfill = 0;
16093                         var nReject;
16094                         var x, i; // reused in both for() loops
16095
16096                         // First pass: count actual array items
16097                         for(i=0; i<l; ++i) {
16098                                 x = promises[i];
16099                                 if(x === void 0 && !(i in promises)) {
16100                                         continue;
16101                                 }
16102                                 ++nFulfill;
16103                         }
16104
16105                         // Compute actual goals
16106                         n = Math.max(n, 0);
16107                         nReject = (nFulfill - n + 1);
16108                         nFulfill = Math.min(n, nFulfill);
16109
16110                         if(n > nFulfill) {
16111                                 resolver.reject(new RangeError('some(): array must contain at least '
16112                                 + n + ' item(s), but had ' + nFulfill));
16113                         } else if(nFulfill === 0) {
16114                                 resolver.resolve(results);
16115                         }
16116
16117                         // Second pass: observe each array item, make progress toward goals
16118                         for(i=0; i<l; ++i) {
16119                                 x = promises[i];
16120                                 if(x === void 0 && !(i in promises)) {
16121                                         continue;
16122                                 }
16123
16124                                 Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
16125                         }
16126
16127                         return p;
16128
16129                         function fulfill(x) {
16130                                 /*jshint validthis:true*/
16131                                 if(this.resolved) { // this === resolver
16132                                         return;
16133                                 }
16134
16135                                 results.push(x);
16136                                 if(--nFulfill === 0) {
16137                                         errors = null;
16138                                         this.resolve(results);
16139                                 }
16140                         }
16141
16142                         function reject(e) {
16143                                 /*jshint validthis:true*/
16144                                 if(this.resolved) { // this === resolver
16145                                         return;
16146                                 }
16147
16148                                 errors.push(e);
16149                                 if(--nReject === 0) {
16150                                         results = null;
16151                                         this.reject(errors);
16152                                 }
16153                         }
16154                 }
16155
16156                 /**
16157                  * Apply f to the value of each promise in a list of promises
16158                  * and return a new list containing the results.
16159                  * @param {array} promises
16160                  * @param {function(x:*, index:Number):*} f mapping function
16161                  * @returns {Promise}
16162                  */
16163                 function map(promises, f) {
16164                         return Promise._traverse(f, promises);
16165                 }
16166
16167                 /**
16168                  * Filter the provided array of promises using the provided predicate.  Input may
16169                  * contain promises and values
16170                  * @param {Array} promises array of promises and values
16171                  * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
16172                  *  Must return truthy (or promise for truthy) for items to retain.
16173                  * @returns {Promise} promise that will fulfill with an array containing all items
16174                  *  for which predicate returned truthy.
16175                  */
16176                 function filter(promises, predicate) {
16177                         var a = slice.call(promises);
16178                         return Promise._traverse(predicate, a).then(function(keep) {
16179                                 return filterSync(a, keep);
16180                         });
16181                 }
16182
16183                 function filterSync(promises, keep) {
16184                         // Safe because we know all promises have fulfilled if we've made it this far
16185                         var l = keep.length;
16186                         var filtered = new Array(l);
16187                         for(var i=0, j=0; i<l; ++i) {
16188                                 if(keep[i]) {
16189                                         filtered[j++] = Promise._handler(promises[i]).value;
16190                                 }
16191                         }
16192                         filtered.length = j;
16193                         return filtered;
16194
16195                 }
16196
16197                 /**
16198                  * Return a promise that will always fulfill with an array containing
16199                  * the outcome states of all input promises.  The returned promise
16200                  * will never reject.
16201                  * @param {Array} promises
16202                  * @returns {Promise} promise for array of settled state descriptors
16203                  */
16204                 function settle(promises) {
16205                         return all(promises.map(settleOne));
16206                 }
16207
16208                 function settleOne(p) {
16209                         var h = Promise._handler(p);
16210                         if(h.state() === 0) {
16211                                 return toPromise(p).then(state.fulfilled, state.rejected);
16212                         }
16213
16214                         h._unreport();
16215                         return state.inspect(h);
16216                 }
16217
16218                 /**
16219                  * Traditional reduce function, similar to `Array.prototype.reduce()`, but
16220                  * input may contain promises and/or values, and reduceFunc
16221                  * may return either a value or a promise, *and* initialValue may
16222                  * be a promise for the starting value.
16223                  * @param {Array|Promise} promises array or promise for an array of anything,
16224                  *      may contain a mix of promises and values.
16225                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
16226                  * @returns {Promise} that will resolve to the final reduced value
16227                  */
16228                 function reduce(promises, f /*, initialValue */) {
16229                         return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
16230                                         : ar.call(promises, liftCombine(f));
16231                 }
16232
16233                 /**
16234                  * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
16235                  * input may contain promises and/or values, and reduceFunc
16236                  * may return either a value or a promise, *and* initialValue may
16237                  * be a promise for the starting value.
16238                  * @param {Array|Promise} promises array or promise for an array of anything,
16239                  *      may contain a mix of promises and values.
16240                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
16241                  * @returns {Promise} that will resolve to the final reduced value
16242                  */
16243                 function reduceRight(promises, f /*, initialValue */) {
16244                         return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
16245                                         : arr.call(promises, liftCombine(f));
16246                 }
16247
16248                 function liftCombine(f) {
16249                         return function(z, x, i) {
16250                                 return applyFold(f, void 0, [z,x,i]);
16251                         };
16252                 }
16253         };
16254
16255 });
16256 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
16257
16258 },{"../apply":193,"../state":206}],195:[function(require,module,exports){
16259 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16260 /** @author Brian Cavalier */
16261 /** @author John Hann */
16262
16263 (function(define) { 'use strict';
16264 define(function() {
16265
16266         return function flow(Promise) {
16267
16268                 var resolve = Promise.resolve;
16269                 var reject = Promise.reject;
16270                 var origCatch = Promise.prototype['catch'];
16271
16272                 /**
16273                  * Handle the ultimate fulfillment value or rejection reason, and assume
16274                  * responsibility for all errors.  If an error propagates out of result
16275                  * or handleFatalError, it will be rethrown to the host, resulting in a
16276                  * loud stack track on most platforms and a crash on some.
16277                  * @param {function?} onResult
16278                  * @param {function?} onError
16279                  * @returns {undefined}
16280                  */
16281                 Promise.prototype.done = function(onResult, onError) {
16282                         this._handler.visit(this._handler.receiver, onResult, onError);
16283                 };
16284
16285                 /**
16286                  * Add Error-type and predicate matching to catch.  Examples:
16287                  * promise.catch(TypeError, handleTypeError)
16288                  *   .catch(predicate, handleMatchedErrors)
16289                  *   .catch(handleRemainingErrors)
16290                  * @param onRejected
16291                  * @returns {*}
16292                  */
16293                 Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
16294                         if (arguments.length < 2) {
16295                                 return origCatch.call(this, onRejected);
16296                         }
16297
16298                         if(typeof onRejected !== 'function') {
16299                                 return this.ensure(rejectInvalidPredicate);
16300                         }
16301
16302                         return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
16303                 };
16304
16305                 /**
16306                  * Wraps the provided catch handler, so that it will only be called
16307                  * if the predicate evaluates truthy
16308                  * @param {?function} handler
16309                  * @param {function} predicate
16310                  * @returns {function} conditional catch handler
16311                  */
16312                 function createCatchFilter(handler, predicate) {
16313                         return function(e) {
16314                                 return evaluatePredicate(e, predicate)
16315                                         ? handler.call(this, e)
16316                                         : reject(e);
16317                         };
16318                 }
16319
16320                 /**
16321                  * Ensures that onFulfilledOrRejected will be called regardless of whether
16322                  * this promise is fulfilled or rejected.  onFulfilledOrRejected WILL NOT
16323                  * receive the promises' value or reason.  Any returned value will be disregarded.
16324                  * onFulfilledOrRejected may throw or return a rejected promise to signal
16325                  * an additional error.
16326                  * @param {function} handler handler to be called regardless of
16327                  *  fulfillment or rejection
16328                  * @returns {Promise}
16329                  */
16330                 Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
16331                         if(typeof handler !== 'function') {
16332                                 return this;
16333                         }
16334
16335                         return this.then(function(x) {
16336                                 return runSideEffect(handler, this, identity, x);
16337                         }, function(e) {
16338                                 return runSideEffect(handler, this, reject, e);
16339                         });
16340                 };
16341
16342                 function runSideEffect (handler, thisArg, propagate, value) {
16343                         var result = handler.call(thisArg);
16344                         return maybeThenable(result)
16345                                 ? propagateValue(result, propagate, value)
16346                                 : propagate(value);
16347                 }
16348
16349                 function propagateValue (result, propagate, x) {
16350                         return resolve(result).then(function () {
16351                                 return propagate(x);
16352                         });
16353                 }
16354
16355                 /**
16356                  * Recover from a failure by returning a defaultValue.  If defaultValue
16357                  * is a promise, it's fulfillment value will be used.  If defaultValue is
16358                  * a promise that rejects, the returned promise will reject with the
16359                  * same reason.
16360                  * @param {*} defaultValue
16361                  * @returns {Promise} new promise
16362                  */
16363                 Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
16364                         return this.then(void 0, function() {
16365                                 return defaultValue;
16366                         });
16367                 };
16368
16369                 /**
16370                  * Shortcut for .then(function() { return value; })
16371                  * @param  {*} value
16372                  * @return {Promise} a promise that:
16373                  *  - is fulfilled if value is not a promise, or
16374                  *  - if value is a promise, will fulfill with its value, or reject
16375                  *    with its reason.
16376                  */
16377                 Promise.prototype['yield'] = function(value) {
16378                         return this.then(function() {
16379                                 return value;
16380                         });
16381                 };
16382
16383                 /**
16384                  * Runs a side effect when this promise fulfills, without changing the
16385                  * fulfillment value.
16386                  * @param {function} onFulfilledSideEffect
16387                  * @returns {Promise}
16388                  */
16389                 Promise.prototype.tap = function(onFulfilledSideEffect) {
16390                         return this.then(onFulfilledSideEffect)['yield'](this);
16391                 };
16392
16393                 return Promise;
16394         };
16395
16396         function rejectInvalidPredicate() {
16397                 throw new TypeError('catch predicate must be a function');
16398         }
16399
16400         function evaluatePredicate(e, predicate) {
16401                 return isError(predicate) ? e instanceof predicate : predicate(e);
16402         }
16403
16404         function isError(predicate) {
16405                 return predicate === Error
16406                         || (predicate != null && predicate.prototype instanceof Error);
16407         }
16408
16409         function maybeThenable(x) {
16410                 return (typeof x === 'object' || typeof x === 'function') && x !== null;
16411         }
16412
16413         function identity(x) {
16414                 return x;
16415         }
16416
16417 });
16418 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
16419
16420 },{}],196:[function(require,module,exports){
16421 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16422 /** @author Brian Cavalier */
16423 /** @author John Hann */
16424 /** @author Jeff Escalante */
16425
16426 (function(define) { 'use strict';
16427 define(function() {
16428
16429         return function fold(Promise) {
16430
16431                 Promise.prototype.fold = function(f, z) {
16432                         var promise = this._beget();
16433
16434                         this._handler.fold(function(z, x, to) {
16435                                 Promise._handler(z).fold(function(x, z, to) {
16436                                         to.resolve(f.call(this, z, x));
16437                                 }, x, this, to);
16438                         }, z, promise._handler.receiver, promise._handler);
16439
16440                         return promise;
16441                 };
16442
16443                 return Promise;
16444         };
16445
16446 });
16447 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
16448
16449 },{}],197:[function(require,module,exports){
16450 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16451 /** @author Brian Cavalier */
16452 /** @author John Hann */
16453
16454 (function(define) { 'use strict';
16455 define(function(require) {
16456
16457         var inspect = require('../state').inspect;
16458
16459         return function inspection(Promise) {
16460
16461                 Promise.prototype.inspect = function() {
16462                         return inspect(Promise._handler(this));
16463                 };
16464
16465                 return Promise;
16466         };
16467
16468 });
16469 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
16470
16471 },{"../state":206}],198:[function(require,module,exports){
16472 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16473 /** @author Brian Cavalier */
16474 /** @author John Hann */
16475
16476 (function(define) { 'use strict';
16477 define(function() {
16478
16479         return function generate(Promise) {
16480
16481                 var resolve = Promise.resolve;
16482
16483                 Promise.iterate = iterate;
16484                 Promise.unfold = unfold;
16485
16486                 return Promise;
16487
16488                 /**
16489                  * @deprecated Use github.com/cujojs/most streams and most.iterate
16490                  * Generate a (potentially infinite) stream of promised values:
16491                  * x, f(x), f(f(x)), etc. until condition(x) returns true
16492                  * @param {function} f function to generate a new x from the previous x
16493                  * @param {function} condition function that, given the current x, returns
16494                  *  truthy when the iterate should stop
16495                  * @param {function} handler function to handle the value produced by f
16496                  * @param {*|Promise} x starting value, may be a promise
16497                  * @return {Promise} the result of the last call to f before
16498                  *  condition returns true
16499                  */
16500                 function iterate(f, condition, handler, x) {
16501                         return unfold(function(x) {
16502                                 return [x, f(x)];
16503                         }, condition, handler, x);
16504                 }
16505
16506                 /**
16507                  * @deprecated Use github.com/cujojs/most streams and most.unfold
16508                  * Generate a (potentially infinite) stream of promised values
16509                  * by applying handler(generator(seed)) iteratively until
16510                  * condition(seed) returns true.
16511                  * @param {function} unspool function that generates a [value, newSeed]
16512                  *  given a seed.
16513                  * @param {function} condition function that, given the current seed, returns
16514                  *  truthy when the unfold should stop
16515                  * @param {function} handler function to handle the value produced by unspool
16516                  * @param x {*|Promise} starting value, may be a promise
16517                  * @return {Promise} the result of the last value produced by unspool before
16518                  *  condition returns true
16519                  */
16520                 function unfold(unspool, condition, handler, x) {
16521                         return resolve(x).then(function(seed) {
16522                                 return resolve(condition(seed)).then(function(done) {
16523                                         return done ? seed : resolve(unspool(seed)).spread(next);
16524                                 });
16525                         });
16526
16527                         function next(item, newSeed) {
16528                                 return resolve(handler(item)).then(function() {
16529                                         return unfold(unspool, condition, handler, newSeed);
16530                                 });
16531                         }
16532                 }
16533         };
16534
16535 });
16536 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
16537
16538 },{}],199:[function(require,module,exports){
16539 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16540 /** @author Brian Cavalier */
16541 /** @author John Hann */
16542
16543 (function(define) { 'use strict';
16544 define(function() {
16545
16546         return function progress(Promise) {
16547
16548                 /**
16549                  * @deprecated
16550                  * Register a progress handler for this promise
16551                  * @param {function} onProgress
16552                  * @returns {Promise}
16553                  */
16554                 Promise.prototype.progress = function(onProgress) {
16555                         return this.then(void 0, void 0, onProgress);
16556                 };
16557
16558                 return Promise;
16559         };
16560
16561 });
16562 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
16563
16564 },{}],200:[function(require,module,exports){
16565 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16566 /** @author Brian Cavalier */
16567 /** @author John Hann */
16568
16569 (function(define) { 'use strict';
16570 define(function(require) {
16571
16572         var env = require('../env');
16573         var TimeoutError = require('../TimeoutError');
16574
16575         function setTimeout(f, ms, x, y) {
16576                 return env.setTimer(function() {
16577                         f(x, y, ms);
16578                 }, ms);
16579         }
16580
16581         return function timed(Promise) {
16582                 /**
16583                  * Return a new promise whose fulfillment value is revealed only
16584                  * after ms milliseconds
16585                  * @param {number} ms milliseconds
16586                  * @returns {Promise}
16587                  */
16588                 Promise.prototype.delay = function(ms) {
16589                         var p = this._beget();
16590                         this._handler.fold(handleDelay, ms, void 0, p._handler);
16591                         return p;
16592                 };
16593
16594                 function handleDelay(ms, x, h) {
16595                         setTimeout(resolveDelay, ms, x, h);
16596                 }
16597
16598                 function resolveDelay(x, h) {
16599                         h.resolve(x);
16600                 }
16601
16602                 /**
16603                  * Return a new promise that rejects after ms milliseconds unless
16604                  * this promise fulfills earlier, in which case the returned promise
16605                  * fulfills with the same value.
16606                  * @param {number} ms milliseconds
16607                  * @param {Error|*=} reason optional rejection reason to use, defaults
16608                  *   to a TimeoutError if not provided
16609                  * @returns {Promise}
16610                  */
16611                 Promise.prototype.timeout = function(ms, reason) {
16612                         var p = this._beget();
16613                         var h = p._handler;
16614
16615                         var t = setTimeout(onTimeout, ms, reason, p._handler);
16616
16617                         this._handler.visit(h,
16618                                 function onFulfill(x) {
16619                                         env.clearTimer(t);
16620                                         this.resolve(x); // this = h
16621                                 },
16622                                 function onReject(x) {
16623                                         env.clearTimer(t);
16624                                         this.reject(x); // this = h
16625                                 },
16626                                 h.notify);
16627
16628                         return p;
16629                 };
16630
16631                 function onTimeout(reason, h, ms) {
16632                         var e = typeof reason === 'undefined'
16633                                 ? new TimeoutError('timed out after ' + ms + 'ms')
16634                                 : reason;
16635                         h.reject(e);
16636                 }
16637
16638                 return Promise;
16639         };
16640
16641 });
16642 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
16643
16644 },{"../TimeoutError":192,"../env":203}],201:[function(require,module,exports){
16645 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16646 /** @author Brian Cavalier */
16647 /** @author John Hann */
16648
16649 (function(define) { 'use strict';
16650 define(function(require) {
16651
16652         var setTimer = require('../env').setTimer;
16653         var format = require('../format');
16654
16655         return function unhandledRejection(Promise) {
16656
16657                 var logError = noop;
16658                 var logInfo = noop;
16659                 var localConsole;
16660
16661                 if(typeof console !== 'undefined') {
16662                         // Alias console to prevent things like uglify's drop_console option from
16663                         // removing console.log/error. Unhandled rejections fall into the same
16664                         // category as uncaught exceptions, and build tools shouldn't silence them.
16665                         localConsole = console;
16666                         logError = typeof localConsole.error !== 'undefined'
16667                                 ? function (e) { localConsole.error(e); }
16668                                 : function (e) { localConsole.log(e); };
16669
16670                         logInfo = typeof localConsole.info !== 'undefined'
16671                                 ? function (e) { localConsole.info(e); }
16672                                 : function (e) { localConsole.log(e); };
16673                 }
16674
16675                 Promise.onPotentiallyUnhandledRejection = function(rejection) {
16676                         enqueue(report, rejection);
16677                 };
16678
16679                 Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
16680                         enqueue(unreport, rejection);
16681                 };
16682
16683                 Promise.onFatalRejection = function(rejection) {
16684                         enqueue(throwit, rejection.value);
16685                 };
16686
16687                 var tasks = [];
16688                 var reported = [];
16689                 var running = null;
16690
16691                 function report(r) {
16692                         if(!r.handled) {
16693                                 reported.push(r);
16694                                 logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
16695                         }
16696                 }
16697
16698                 function unreport(r) {
16699                         var i = reported.indexOf(r);
16700                         if(i >= 0) {
16701                                 reported.splice(i, 1);
16702                                 logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
16703                         }
16704                 }
16705
16706                 function enqueue(f, x) {
16707                         tasks.push(f, x);
16708                         if(running === null) {
16709                                 running = setTimer(flush, 0);
16710                         }
16711                 }
16712
16713                 function flush() {
16714                         running = null;
16715                         while(tasks.length > 0) {
16716                                 tasks.shift()(tasks.shift());
16717                         }
16718                 }
16719
16720                 return Promise;
16721         };
16722
16723         function throwit(e) {
16724                 throw e;
16725         }
16726
16727         function noop() {}
16728
16729 });
16730 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
16731
16732 },{"../env":203,"../format":204}],202:[function(require,module,exports){
16733 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16734 /** @author Brian Cavalier */
16735 /** @author John Hann */
16736
16737 (function(define) { 'use strict';
16738 define(function() {
16739
16740         return function addWith(Promise) {
16741                 /**
16742                  * Returns a promise whose handlers will be called with `this` set to
16743                  * the supplied receiver.  Subsequent promises derived from the
16744                  * returned promise will also have their handlers called with receiver
16745                  * as `this`. Calling `with` with undefined or no arguments will return
16746                  * a promise whose handlers will again be called in the usual Promises/A+
16747                  * way (no `this`) thus safely undoing any previous `with` in the
16748                  * promise chain.
16749                  *
16750                  * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
16751                  * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
16752                  *
16753                  * @param {object} receiver `this` value for all handlers attached to
16754                  *  the returned promise.
16755                  * @returns {Promise}
16756                  */
16757                 Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
16758                         var p = this._beget();
16759                         var child = p._handler;
16760                         child.receiver = receiver;
16761                         this._handler.chain(child, receiver);
16762                         return p;
16763                 };
16764
16765                 return Promise;
16766         };
16767
16768 });
16769 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
16770
16771
16772 },{}],203:[function(require,module,exports){
16773 (function (process){
16774 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16775 /** @author Brian Cavalier */
16776 /** @author John Hann */
16777
16778 /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
16779 (function(define) { 'use strict';
16780 define(function(require) {
16781         /*jshint maxcomplexity:6*/
16782
16783         // Sniff "best" async scheduling option
16784         // Prefer process.nextTick or MutationObserver, then check for
16785         // setTimeout, and finally vertx, since its the only env that doesn't
16786         // have setTimeout
16787
16788         var MutationObs;
16789         var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
16790
16791         // Default env
16792         var setTimer = function(f, ms) { return setTimeout(f, ms); };
16793         var clearTimer = function(t) { return clearTimeout(t); };
16794         var asap = function (f) { return capturedSetTimeout(f, 0); };
16795
16796         // Detect specific env
16797         if (isNode()) { // Node
16798                 asap = function (f) { return process.nextTick(f); };
16799
16800         } else if (MutationObs = hasMutationObserver()) { // Modern browser
16801                 asap = initMutationObserver(MutationObs);
16802
16803         } else if (!capturedSetTimeout) { // vert.x
16804                 var vertxRequire = require;
16805                 var vertx = vertxRequire('vertx');
16806                 setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
16807                 clearTimer = vertx.cancelTimer;
16808                 asap = vertx.runOnLoop || vertx.runOnContext;
16809         }
16810
16811         return {
16812                 setTimer: setTimer,
16813                 clearTimer: clearTimer,
16814                 asap: asap
16815         };
16816
16817         function isNode () {
16818                 return typeof process !== 'undefined' &&
16819                         Object.prototype.toString.call(process) === '[object process]';
16820         }
16821
16822         function hasMutationObserver () {
16823                 return (typeof MutationObserver === 'function' && MutationObserver) ||
16824                         (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver);
16825         }
16826
16827         function initMutationObserver(MutationObserver) {
16828                 var scheduled;
16829                 var node = document.createTextNode('');
16830                 var o = new MutationObserver(run);
16831                 o.observe(node, { characterData: true });
16832
16833                 function run() {
16834                         var f = scheduled;
16835                         scheduled = void 0;
16836                         f();
16837                 }
16838
16839                 var i = 0;
16840                 return function (f) {
16841                         scheduled = f;
16842                         node.data = (i ^= 1);
16843                 };
16844         }
16845 });
16846 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
16847
16848 }).call(this,require('_process'))
16849
16850 },{"_process":4}],204:[function(require,module,exports){
16851 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16852 /** @author Brian Cavalier */
16853 /** @author John Hann */
16854
16855 (function(define) { 'use strict';
16856 define(function() {
16857
16858         return {
16859                 formatError: formatError,
16860                 formatObject: formatObject,
16861                 tryStringify: tryStringify
16862         };
16863
16864         /**
16865          * Format an error into a string.  If e is an Error and has a stack property,
16866          * it's returned.  Otherwise, e is formatted using formatObject, with a
16867          * warning added about e not being a proper Error.
16868          * @param {*} e
16869          * @returns {String} formatted string, suitable for output to developers
16870          */
16871         function formatError(e) {
16872                 var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
16873                 return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
16874         }
16875
16876         /**
16877          * Format an object, detecting "plain" objects and running them through
16878          * JSON.stringify if possible.
16879          * @param {Object} o
16880          * @returns {string}
16881          */
16882         function formatObject(o) {
16883                 var s = String(o);
16884                 if(s === '[object Object]' && typeof JSON !== 'undefined') {
16885                         s = tryStringify(o, s);
16886                 }
16887                 return s;
16888         }
16889
16890         /**
16891          * Try to return the result of JSON.stringify(x).  If that fails, return
16892          * defaultValue
16893          * @param {*} x
16894          * @param {*} defaultValue
16895          * @returns {String|*} JSON.stringify(x) or defaultValue
16896          */
16897         function tryStringify(x, defaultValue) {
16898                 try {
16899                         return JSON.stringify(x);
16900                 } catch(e) {
16901                         return defaultValue;
16902                 }
16903         }
16904
16905 });
16906 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
16907
16908 },{}],205:[function(require,module,exports){
16909 (function (process){
16910 /** @license MIT License (c) copyright 2010-2014 original author or authors */
16911 /** @author Brian Cavalier */
16912 /** @author John Hann */
16913
16914 (function(define) { 'use strict';
16915 define(function() {
16916
16917         return function makePromise(environment) {
16918
16919                 var tasks = environment.scheduler;
16920                 var emitRejection = initEmitRejection();
16921
16922                 var objectCreate = Object.create ||
16923                         function(proto) {
16924                                 function Child() {}
16925                                 Child.prototype = proto;
16926                                 return new Child();
16927                         };
16928
16929                 /**
16930                  * Create a promise whose fate is determined by resolver
16931                  * @constructor
16932                  * @returns {Promise} promise
16933                  * @name Promise
16934                  */
16935                 function Promise(resolver, handler) {
16936                         this._handler = resolver === Handler ? handler : init(resolver);
16937                 }
16938
16939                 /**
16940                  * Run the supplied resolver
16941                  * @param resolver
16942                  * @returns {Pending}
16943                  */
16944                 function init(resolver) {
16945                         var handler = new Pending();
16946
16947                         try {
16948                                 resolver(promiseResolve, promiseReject, promiseNotify);
16949                         } catch (e) {
16950                                 promiseReject(e);
16951                         }
16952
16953                         return handler;
16954
16955                         /**
16956                          * Transition from pre-resolution state to post-resolution state, notifying
16957                          * all listeners of the ultimate fulfillment or rejection
16958                          * @param {*} x resolution value
16959                          */
16960                         function promiseResolve (x) {
16961                                 handler.resolve(x);
16962                         }
16963                         /**
16964                          * Reject this promise with reason, which will be used verbatim
16965                          * @param {Error|*} reason rejection reason, strongly suggested
16966                          *   to be an Error type
16967                          */
16968                         function promiseReject (reason) {
16969                                 handler.reject(reason);
16970                         }
16971
16972                         /**
16973                          * @deprecated
16974                          * Issue a progress event, notifying all progress listeners
16975                          * @param {*} x progress event payload to pass to all listeners
16976                          */
16977                         function promiseNotify (x) {
16978                                 handler.notify(x);
16979                         }
16980                 }
16981
16982                 // Creation
16983
16984                 Promise.resolve = resolve;
16985                 Promise.reject = reject;
16986                 Promise.never = never;
16987
16988                 Promise._defer = defer;
16989                 Promise._handler = getHandler;
16990
16991                 /**
16992                  * Returns a trusted promise. If x is already a trusted promise, it is
16993                  * returned, otherwise returns a new trusted Promise which follows x.
16994                  * @param  {*} x
16995                  * @return {Promise} promise
16996                  */
16997                 function resolve(x) {
16998                         return isPromise(x) ? x
16999                                 : new Promise(Handler, new Async(getHandler(x)));
17000                 }
17001
17002                 /**
17003                  * Return a reject promise with x as its reason (x is used verbatim)
17004                  * @param {*} x
17005                  * @returns {Promise} rejected promise
17006                  */
17007                 function reject(x) {
17008                         return new Promise(Handler, new Async(new Rejected(x)));
17009                 }
17010
17011                 /**
17012                  * Return a promise that remains pending forever
17013                  * @returns {Promise} forever-pending promise.
17014                  */
17015                 function never() {
17016                         return foreverPendingPromise; // Should be frozen
17017                 }
17018
17019                 /**
17020                  * Creates an internal {promise, resolver} pair
17021                  * @private
17022                  * @returns {Promise}
17023                  */
17024                 function defer() {
17025                         return new Promise(Handler, new Pending());
17026                 }
17027
17028                 // Transformation and flow control
17029
17030                 /**
17031                  * Transform this promise's fulfillment value, returning a new Promise
17032                  * for the transformed result.  If the promise cannot be fulfilled, onRejected
17033                  * is called with the reason.  onProgress *may* be called with updates toward
17034                  * this promise's fulfillment.
17035                  * @param {function=} onFulfilled fulfillment handler
17036                  * @param {function=} onRejected rejection handler
17037                  * @param {function=} onProgress @deprecated progress handler
17038                  * @return {Promise} new promise
17039                  */
17040                 Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
17041                         var parent = this._handler;
17042                         var state = parent.join().state();
17043
17044                         if ((typeof onFulfilled !== 'function' && state > 0) ||
17045                                 (typeof onRejected !== 'function' && state < 0)) {
17046                                 // Short circuit: value will not change, simply share handler
17047                                 return new this.constructor(Handler, parent);
17048                         }
17049
17050                         var p = this._beget();
17051                         var child = p._handler;
17052
17053                         parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
17054
17055                         return p;
17056                 };
17057
17058                 /**
17059                  * If this promise cannot be fulfilled due to an error, call onRejected to
17060                  * handle the error. Shortcut for .then(undefined, onRejected)
17061                  * @param {function?} onRejected
17062                  * @return {Promise}
17063                  */
17064                 Promise.prototype['catch'] = function(onRejected) {
17065                         return this.then(void 0, onRejected);
17066                 };
17067
17068                 /**
17069                  * Creates a new, pending promise of the same type as this promise
17070                  * @private
17071                  * @returns {Promise}
17072                  */
17073                 Promise.prototype._beget = function() {
17074                         return begetFrom(this._handler, this.constructor);
17075                 };
17076
17077                 function begetFrom(parent, Promise) {
17078                         var child = new Pending(parent.receiver, parent.join().context);
17079                         return new Promise(Handler, child);
17080                 }
17081
17082                 // Array combinators
17083
17084                 Promise.all = all;
17085                 Promise.race = race;
17086                 Promise._traverse = traverse;
17087
17088                 /**
17089                  * Return a promise that will fulfill when all promises in the
17090                  * input array have fulfilled, or will reject when one of the
17091                  * promises rejects.
17092                  * @param {array} promises array of promises
17093                  * @returns {Promise} promise for array of fulfillment values
17094                  */
17095                 function all(promises) {
17096                         return traverseWith(snd, null, promises);
17097                 }
17098
17099                 /**
17100                  * Array<Promise<X>> -> Promise<Array<f(X)>>
17101                  * @private
17102                  * @param {function} f function to apply to each promise's value
17103                  * @param {Array} promises array of promises
17104                  * @returns {Promise} promise for transformed values
17105                  */
17106                 function traverse(f, promises) {
17107                         return traverseWith(tryCatch2, f, promises);
17108                 }
17109
17110                 function traverseWith(tryMap, f, promises) {
17111                         var handler = typeof f === 'function' ? mapAt : settleAt;
17112
17113                         var resolver = new Pending();
17114                         var pending = promises.length >>> 0;
17115                         var results = new Array(pending);
17116
17117                         for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
17118                                 x = promises[i];
17119
17120                                 if (x === void 0 && !(i in promises)) {
17121                                         --pending;
17122                                         continue;
17123                                 }
17124
17125                                 traverseAt(promises, handler, i, x, resolver);
17126                         }
17127
17128                         if(pending === 0) {
17129                                 resolver.become(new Fulfilled(results));
17130                         }
17131
17132                         return new Promise(Handler, resolver);
17133
17134                         function mapAt(i, x, resolver) {
17135                                 if(!resolver.resolved) {
17136                                         traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
17137                                 }
17138                         }
17139
17140                         function settleAt(i, x, resolver) {
17141                                 results[i] = x;
17142                                 if(--pending === 0) {
17143                                         resolver.become(new Fulfilled(results));
17144                                 }
17145                         }
17146                 }
17147
17148                 function traverseAt(promises, handler, i, x, resolver) {
17149                         if (maybeThenable(x)) {
17150                                 var h = getHandlerMaybeThenable(x);
17151                                 var s = h.state();
17152
17153                                 if (s === 0) {
17154                                         h.fold(handler, i, void 0, resolver);
17155                                 } else if (s > 0) {
17156                                         handler(i, h.value, resolver);
17157                                 } else {
17158                                         resolver.become(h);
17159                                         visitRemaining(promises, i+1, h);
17160                                 }
17161                         } else {
17162                                 handler(i, x, resolver);
17163                         }
17164                 }
17165
17166                 Promise._visitRemaining = visitRemaining;
17167                 function visitRemaining(promises, start, handler) {
17168                         for(var i=start; i<promises.length; ++i) {
17169                                 markAsHandled(getHandler(promises[i]), handler);
17170                         }
17171                 }
17172
17173                 function markAsHandled(h, handler) {
17174                         if(h === handler) {
17175                                 return;
17176                         }
17177
17178                         var s = h.state();
17179                         if(s === 0) {
17180                                 h.visit(h, void 0, h._unreport);
17181                         } else if(s < 0) {
17182                                 h._unreport();
17183                         }
17184                 }
17185
17186                 /**
17187                  * Fulfill-reject competitive race. Return a promise that will settle
17188                  * to the same state as the earliest input promise to settle.
17189                  *
17190                  * WARNING: The ES6 Promise spec requires that race()ing an empty array
17191                  * must return a promise that is pending forever.  This implementation
17192                  * returns a singleton forever-pending promise, the same singleton that is
17193                  * returned by Promise.never(), thus can be checked with ===
17194                  *
17195                  * @param {array} promises array of promises to race
17196                  * @returns {Promise} if input is non-empty, a promise that will settle
17197                  * to the same outcome as the earliest input promise to settle. if empty
17198                  * is empty, returns a promise that will never settle.
17199                  */
17200                 function race(promises) {
17201                         if(typeof promises !== 'object' || promises === null) {
17202                                 return reject(new TypeError('non-iterable passed to race()'));
17203                         }
17204
17205                         // Sigh, race([]) is untestable unless we return *something*
17206                         // that is recognizable without calling .then() on it.
17207                         return promises.length === 0 ? never()
17208                                  : promises.length === 1 ? resolve(promises[0])
17209                                  : runRace(promises);
17210                 }
17211
17212                 function runRace(promises) {
17213                         var resolver = new Pending();
17214                         var i, x, h;
17215                         for(i=0; i<promises.length; ++i) {
17216                                 x = promises[i];
17217                                 if (x === void 0 && !(i in promises)) {
17218                                         continue;
17219                                 }
17220
17221                                 h = getHandler(x);
17222                                 if(h.state() !== 0) {
17223                                         resolver.become(h);
17224                                         visitRemaining(promises, i+1, h);
17225                                         break;
17226                                 } else {
17227                                         h.visit(resolver, resolver.resolve, resolver.reject);
17228                                 }
17229                         }
17230                         return new Promise(Handler, resolver);
17231                 }
17232
17233                 // Promise internals
17234                 // Below this, everything is @private
17235
17236                 /**
17237                  * Get an appropriate handler for x, without checking for cycles
17238                  * @param {*} x
17239                  * @returns {object} handler
17240                  */
17241                 function getHandler(x) {
17242                         if(isPromise(x)) {
17243                                 return x._handler.join();
17244                         }
17245                         return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
17246                 }
17247
17248                 /**
17249                  * Get a handler for thenable x.
17250                  * NOTE: You must only call this if maybeThenable(x) == true
17251                  * @param {object|function|Promise} x
17252                  * @returns {object} handler
17253                  */
17254                 function getHandlerMaybeThenable(x) {
17255                         return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
17256                 }
17257
17258                 /**
17259                  * Get a handler for potentially untrusted thenable x
17260                  * @param {*} x
17261                  * @returns {object} handler
17262                  */
17263                 function getHandlerUntrusted(x) {
17264                         try {
17265                                 var untrustedThen = x.then;
17266                                 return typeof untrustedThen === 'function'
17267                                         ? new Thenable(untrustedThen, x)
17268                                         : new Fulfilled(x);
17269                         } catch(e) {
17270                                 return new Rejected(e);
17271                         }
17272                 }
17273
17274                 /**
17275                  * Handler for a promise that is pending forever
17276                  * @constructor
17277                  */
17278                 function Handler() {}
17279
17280                 Handler.prototype.when
17281                         = Handler.prototype.become
17282                         = Handler.prototype.notify // deprecated
17283                         = Handler.prototype.fail
17284                         = Handler.prototype._unreport
17285                         = Handler.prototype._report
17286                         = noop;
17287
17288                 Handler.prototype._state = 0;
17289
17290                 Handler.prototype.state = function() {
17291                         return this._state;
17292                 };
17293
17294                 /**
17295                  * Recursively collapse handler chain to find the handler
17296                  * nearest to the fully resolved value.
17297                  * @returns {object} handler nearest the fully resolved value
17298                  */
17299                 Handler.prototype.join = function() {
17300                         var h = this;
17301                         while(h.handler !== void 0) {
17302                                 h = h.handler;
17303                         }
17304                         return h;
17305                 };
17306
17307                 Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
17308                         this.when({
17309                                 resolver: to,
17310                                 receiver: receiver,
17311                                 fulfilled: fulfilled,
17312                                 rejected: rejected,
17313                                 progress: progress
17314                         });
17315                 };
17316
17317                 Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
17318                         this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
17319                 };
17320
17321                 Handler.prototype.fold = function(f, z, c, to) {
17322                         this.when(new Fold(f, z, c, to));
17323                 };
17324
17325                 /**
17326                  * Handler that invokes fail() on any handler it becomes
17327                  * @constructor
17328                  */
17329                 function FailIfRejected() {}
17330
17331                 inherit(Handler, FailIfRejected);
17332
17333                 FailIfRejected.prototype.become = function(h) {
17334                         h.fail();
17335                 };
17336
17337                 var failIfRejected = new FailIfRejected();
17338
17339                 /**
17340                  * Handler that manages a queue of consumers waiting on a pending promise
17341                  * @constructor
17342                  */
17343                 function Pending(receiver, inheritedContext) {
17344                         Promise.createContext(this, inheritedContext);
17345
17346                         this.consumers = void 0;
17347                         this.receiver = receiver;
17348                         this.handler = void 0;
17349                         this.resolved = false;
17350                 }
17351
17352                 inherit(Handler, Pending);
17353
17354                 Pending.prototype._state = 0;
17355
17356                 Pending.prototype.resolve = function(x) {
17357                         this.become(getHandler(x));
17358                 };
17359
17360                 Pending.prototype.reject = function(x) {
17361                         if(this.resolved) {
17362                                 return;
17363                         }
17364
17365                         this.become(new Rejected(x));
17366                 };
17367
17368                 Pending.prototype.join = function() {
17369                         if (!this.resolved) {
17370                                 return this;
17371                         }
17372
17373                         var h = this;
17374
17375                         while (h.handler !== void 0) {
17376                                 h = h.handler;
17377                                 if (h === this) {
17378                                         return this.handler = cycle();
17379                                 }
17380                         }
17381
17382                         return h;
17383                 };
17384
17385                 Pending.prototype.run = function() {
17386                         var q = this.consumers;
17387                         var handler = this.handler;
17388                         this.handler = this.handler.join();
17389                         this.consumers = void 0;
17390
17391                         for (var i = 0; i < q.length; ++i) {
17392                                 handler.when(q[i]);
17393                         }
17394                 };
17395
17396                 Pending.prototype.become = function(handler) {
17397                         if(this.resolved) {
17398                                 return;
17399                         }
17400
17401                         this.resolved = true;
17402                         this.handler = handler;
17403                         if(this.consumers !== void 0) {
17404                                 tasks.enqueue(this);
17405                         }
17406
17407                         if(this.context !== void 0) {
17408                                 handler._report(this.context);
17409                         }
17410                 };
17411
17412                 Pending.prototype.when = function(continuation) {
17413                         if(this.resolved) {
17414                                 tasks.enqueue(new ContinuationTask(continuation, this.handler));
17415                         } else {
17416                                 if(this.consumers === void 0) {
17417                                         this.consumers = [continuation];
17418                                 } else {
17419                                         this.consumers.push(continuation);
17420                                 }
17421                         }
17422                 };
17423
17424                 /**
17425                  * @deprecated
17426                  */
17427                 Pending.prototype.notify = function(x) {
17428                         if(!this.resolved) {
17429                                 tasks.enqueue(new ProgressTask(x, this));
17430                         }
17431                 };
17432
17433                 Pending.prototype.fail = function(context) {
17434                         var c = typeof context === 'undefined' ? this.context : context;
17435                         this.resolved && this.handler.join().fail(c);
17436                 };
17437
17438                 Pending.prototype._report = function(context) {
17439                         this.resolved && this.handler.join()._report(context);
17440                 };
17441
17442                 Pending.prototype._unreport = function() {
17443                         this.resolved && this.handler.join()._unreport();
17444                 };
17445
17446                 /**
17447                  * Wrap another handler and force it into a future stack
17448                  * @param {object} handler
17449                  * @constructor
17450                  */
17451                 function Async(handler) {
17452                         this.handler = handler;
17453                 }
17454
17455                 inherit(Handler, Async);
17456
17457                 Async.prototype.when = function(continuation) {
17458                         tasks.enqueue(new ContinuationTask(continuation, this));
17459                 };
17460
17461                 Async.prototype._report = function(context) {
17462                         this.join()._report(context);
17463                 };
17464
17465                 Async.prototype._unreport = function() {
17466                         this.join()._unreport();
17467                 };
17468
17469                 /**
17470                  * Handler that wraps an untrusted thenable and assimilates it in a future stack
17471                  * @param {function} then
17472                  * @param {{then: function}} thenable
17473                  * @constructor
17474                  */
17475                 function Thenable(then, thenable) {
17476                         Pending.call(this);
17477                         tasks.enqueue(new AssimilateTask(then, thenable, this));
17478                 }
17479
17480                 inherit(Pending, Thenable);
17481
17482                 /**
17483                  * Handler for a fulfilled promise
17484                  * @param {*} x fulfillment value
17485                  * @constructor
17486                  */
17487                 function Fulfilled(x) {
17488                         Promise.createContext(this);
17489                         this.value = x;
17490                 }
17491
17492                 inherit(Handler, Fulfilled);
17493
17494                 Fulfilled.prototype._state = 1;
17495
17496                 Fulfilled.prototype.fold = function(f, z, c, to) {
17497                         runContinuation3(f, z, this, c, to);
17498                 };
17499
17500                 Fulfilled.prototype.when = function(cont) {
17501                         runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
17502                 };
17503
17504                 var errorId = 0;
17505
17506                 /**
17507                  * Handler for a rejected promise
17508                  * @param {*} x rejection reason
17509                  * @constructor
17510                  */
17511                 function Rejected(x) {
17512                         Promise.createContext(this);
17513
17514                         this.id = ++errorId;
17515                         this.value = x;
17516                         this.handled = false;
17517                         this.reported = false;
17518
17519                         this._report();
17520                 }
17521
17522                 inherit(Handler, Rejected);
17523
17524                 Rejected.prototype._state = -1;
17525
17526                 Rejected.prototype.fold = function(f, z, c, to) {
17527                         to.become(this);
17528                 };
17529
17530                 Rejected.prototype.when = function(cont) {
17531                         if(typeof cont.rejected === 'function') {
17532                                 this._unreport();
17533                         }
17534                         runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
17535                 };
17536
17537                 Rejected.prototype._report = function(context) {
17538                         tasks.afterQueue(new ReportTask(this, context));
17539                 };
17540
17541                 Rejected.prototype._unreport = function() {
17542                         if(this.handled) {
17543                                 return;
17544                         }
17545                         this.handled = true;
17546                         tasks.afterQueue(new UnreportTask(this));
17547                 };
17548
17549                 Rejected.prototype.fail = function(context) {
17550                         this.reported = true;
17551                         emitRejection('unhandledRejection', this);
17552                         Promise.onFatalRejection(this, context === void 0 ? this.context : context);
17553                 };
17554
17555                 function ReportTask(rejection, context) {
17556                         this.rejection = rejection;
17557                         this.context = context;
17558                 }
17559
17560                 ReportTask.prototype.run = function() {
17561                         if(!this.rejection.handled && !this.rejection.reported) {
17562                                 this.rejection.reported = true;
17563                                 emitRejection('unhandledRejection', this.rejection) ||
17564                                         Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
17565                         }
17566                 };
17567
17568                 function UnreportTask(rejection) {
17569                         this.rejection = rejection;
17570                 }
17571
17572                 UnreportTask.prototype.run = function() {
17573                         if(this.rejection.reported) {
17574                                 emitRejection('rejectionHandled', this.rejection) ||
17575                                         Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
17576                         }
17577                 };
17578
17579                 // Unhandled rejection hooks
17580                 // By default, everything is a noop
17581
17582                 Promise.createContext
17583                         = Promise.enterContext
17584                         = Promise.exitContext
17585                         = Promise.onPotentiallyUnhandledRejection
17586                         = Promise.onPotentiallyUnhandledRejectionHandled
17587                         = Promise.onFatalRejection
17588                         = noop;
17589
17590                 // Errors and singletons
17591
17592                 var foreverPendingHandler = new Handler();
17593                 var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
17594
17595                 function cycle() {
17596                         return new Rejected(new TypeError('Promise cycle'));
17597                 }
17598
17599                 // Task runners
17600
17601                 /**
17602                  * Run a single consumer
17603                  * @constructor
17604                  */
17605                 function ContinuationTask(continuation, handler) {
17606                         this.continuation = continuation;
17607                         this.handler = handler;
17608                 }
17609
17610                 ContinuationTask.prototype.run = function() {
17611                         this.handler.join().when(this.continuation);
17612                 };
17613
17614                 /**
17615                  * Run a queue of progress handlers
17616                  * @constructor
17617                  */
17618                 function ProgressTask(value, handler) {
17619                         this.handler = handler;
17620                         this.value = value;
17621                 }
17622
17623                 ProgressTask.prototype.run = function() {
17624                         var q = this.handler.consumers;
17625                         if(q === void 0) {
17626                                 return;
17627                         }
17628
17629                         for (var c, i = 0; i < q.length; ++i) {
17630                                 c = q[i];
17631                                 runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
17632                         }
17633                 };
17634
17635                 /**
17636                  * Assimilate a thenable, sending it's value to resolver
17637                  * @param {function} then
17638                  * @param {object|function} thenable
17639                  * @param {object} resolver
17640                  * @constructor
17641                  */
17642                 function AssimilateTask(then, thenable, resolver) {
17643                         this._then = then;
17644                         this.thenable = thenable;
17645                         this.resolver = resolver;
17646                 }
17647
17648                 AssimilateTask.prototype.run = function() {
17649                         var h = this.resolver;
17650                         tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
17651
17652                         function _resolve(x) { h.resolve(x); }
17653                         function _reject(x)  { h.reject(x); }
17654                         function _notify(x)  { h.notify(x); }
17655                 };
17656
17657                 function tryAssimilate(then, thenable, resolve, reject, notify) {
17658                         try {
17659                                 then.call(thenable, resolve, reject, notify);
17660                         } catch (e) {
17661                                 reject(e);
17662                         }
17663                 }
17664
17665                 /**
17666                  * Fold a handler value with z
17667                  * @constructor
17668                  */
17669                 function Fold(f, z, c, to) {
17670                         this.f = f; this.z = z; this.c = c; this.to = to;
17671                         this.resolver = failIfRejected;
17672                         this.receiver = this;
17673                 }
17674
17675                 Fold.prototype.fulfilled = function(x) {
17676                         this.f.call(this.c, this.z, x, this.to);
17677                 };
17678
17679                 Fold.prototype.rejected = function(x) {
17680                         this.to.reject(x);
17681                 };
17682
17683                 Fold.prototype.progress = function(x) {
17684                         this.to.notify(x);
17685                 };
17686
17687                 // Other helpers
17688
17689                 /**
17690                  * @param {*} x
17691                  * @returns {boolean} true iff x is a trusted Promise
17692                  */
17693                 function isPromise(x) {
17694                         return x instanceof Promise;
17695                 }
17696
17697                 /**
17698                  * Test just enough to rule out primitives, in order to take faster
17699                  * paths in some code
17700                  * @param {*} x
17701                  * @returns {boolean} false iff x is guaranteed *not* to be a thenable
17702                  */
17703                 function maybeThenable(x) {
17704                         return (typeof x === 'object' || typeof x === 'function') && x !== null;
17705                 }
17706
17707                 function runContinuation1(f, h, receiver, next) {
17708                         if(typeof f !== 'function') {
17709                                 return next.become(h);
17710                         }
17711
17712                         Promise.enterContext(h);
17713                         tryCatchReject(f, h.value, receiver, next);
17714                         Promise.exitContext();
17715                 }
17716
17717                 function runContinuation3(f, x, h, receiver, next) {
17718                         if(typeof f !== 'function') {
17719                                 return next.become(h);
17720                         }
17721
17722                         Promise.enterContext(h);
17723                         tryCatchReject3(f, x, h.value, receiver, next);
17724                         Promise.exitContext();
17725                 }
17726
17727                 /**
17728                  * @deprecated
17729                  */
17730                 function runNotify(f, x, h, receiver, next) {
17731                         if(typeof f !== 'function') {
17732                                 return next.notify(x);
17733                         }
17734
17735                         Promise.enterContext(h);
17736                         tryCatchReturn(f, x, receiver, next);
17737                         Promise.exitContext();
17738                 }
17739
17740                 function tryCatch2(f, a, b) {
17741                         try {
17742                                 return f(a, b);
17743                         } catch(e) {
17744                                 return reject(e);
17745                         }
17746                 }
17747
17748                 /**
17749                  * Return f.call(thisArg, x), or if it throws return a rejected promise for
17750                  * the thrown exception
17751                  */
17752                 function tryCatchReject(f, x, thisArg, next) {
17753                         try {
17754                                 next.become(getHandler(f.call(thisArg, x)));
17755                         } catch(e) {
17756                                 next.become(new Rejected(e));
17757                         }
17758                 }
17759
17760                 /**
17761                  * Same as above, but includes the extra argument parameter.
17762                  */
17763                 function tryCatchReject3(f, x, y, thisArg, next) {
17764                         try {
17765                                 f.call(thisArg, x, y, next);
17766                         } catch(e) {
17767                                 next.become(new Rejected(e));
17768                         }
17769                 }
17770
17771                 /**
17772                  * @deprecated
17773                  * Return f.call(thisArg, x), or if it throws, *return* the exception
17774                  */
17775                 function tryCatchReturn(f, x, thisArg, next) {
17776                         try {
17777                                 next.notify(f.call(thisArg, x));
17778                         } catch(e) {
17779                                 next.notify(e);
17780                         }
17781                 }
17782
17783                 function inherit(Parent, Child) {
17784                         Child.prototype = objectCreate(Parent.prototype);
17785                         Child.prototype.constructor = Child;
17786                 }
17787
17788                 function snd(x, y) {
17789                         return y;
17790                 }
17791
17792                 function noop() {}
17793
17794                 function initEmitRejection() {
17795                         /*global process, self, CustomEvent*/
17796                         if(typeof process !== 'undefined' && process !== null
17797                                 && typeof process.emit === 'function') {
17798                                 // Returning falsy here means to call the default
17799                                 // onPotentiallyUnhandledRejection API.  This is safe even in
17800                                 // browserify since process.emit always returns falsy in browserify:
17801                                 // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
17802                                 return function(type, rejection) {
17803                                         return type === 'unhandledRejection'
17804                                                 ? process.emit(type, rejection.value, rejection)
17805                                                 : process.emit(type, rejection);
17806                                 };
17807                         } else if(typeof self !== 'undefined' && typeof CustomEvent === 'function') {
17808                                 return (function(noop, self, CustomEvent) {
17809                                         var hasCustomEvent = false;
17810                                         try {
17811                                                 var ev = new CustomEvent('unhandledRejection');
17812                                                 hasCustomEvent = ev instanceof CustomEvent;
17813                                         } catch (e) {}
17814
17815                                         return !hasCustomEvent ? noop : function(type, rejection) {
17816                                                 var ev = new CustomEvent(type, {
17817                                                         detail: {
17818                                                                 reason: rejection.value,
17819                                                                 key: rejection
17820                                                         },
17821                                                         bubbles: false,
17822                                                         cancelable: true
17823                                                 });
17824
17825                                                 return !self.dispatchEvent(ev);
17826                                         };
17827                                 }(noop, self, CustomEvent));
17828                         }
17829
17830                         return noop;
17831                 }
17832
17833                 return Promise;
17834         };
17835 });
17836 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17837
17838 }).call(this,require('_process'))
17839
17840 },{"_process":4}],206:[function(require,module,exports){
17841 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17842 /** @author Brian Cavalier */
17843 /** @author John Hann */
17844
17845 (function(define) { 'use strict';
17846 define(function() {
17847
17848         return {
17849                 pending: toPendingState,
17850                 fulfilled: toFulfilledState,
17851                 rejected: toRejectedState,
17852                 inspect: inspect
17853         };
17854
17855         function toPendingState() {
17856                 return { state: 'pending' };
17857         }
17858
17859         function toRejectedState(e) {
17860                 return { state: 'rejected', reason: e };
17861         }
17862
17863         function toFulfilledState(x) {
17864                 return { state: 'fulfilled', value: x };
17865         }
17866
17867         function inspect(handler) {
17868                 var state = handler.state();
17869                 return state === 0 ? toPendingState()
17870                          : state > 0   ? toFulfilledState(handler.value)
17871                                        : toRejectedState(handler.value);
17872         }
17873
17874 });
17875 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17876
17877 },{}],207:[function(require,module,exports){
17878 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17879
17880 /**
17881  * Promises/A+ and when() implementation
17882  * when is part of the cujoJS family of libraries (http://cujojs.com/)
17883  * @author Brian Cavalier
17884  * @author John Hann
17885  */
17886 (function(define) { 'use strict';
17887 define(function (require) {
17888
17889         var timed = require('./lib/decorators/timed');
17890         var array = require('./lib/decorators/array');
17891         var flow = require('./lib/decorators/flow');
17892         var fold = require('./lib/decorators/fold');
17893         var inspect = require('./lib/decorators/inspect');
17894         var generate = require('./lib/decorators/iterate');
17895         var progress = require('./lib/decorators/progress');
17896         var withThis = require('./lib/decorators/with');
17897         var unhandledRejection = require('./lib/decorators/unhandledRejection');
17898         var TimeoutError = require('./lib/TimeoutError');
17899
17900         var Promise = [array, flow, fold, generate, progress,
17901                 inspect, withThis, timed, unhandledRejection]
17902                 .reduce(function(Promise, feature) {
17903                         return feature(Promise);
17904                 }, require('./lib/Promise'));
17905
17906         var apply = require('./lib/apply')(Promise);
17907
17908         // Public API
17909
17910         when.promise     = promise;              // Create a pending promise
17911         when.resolve     = Promise.resolve;      // Create a resolved promise
17912         when.reject      = Promise.reject;       // Create a rejected promise
17913
17914         when.lift        = lift;                 // lift a function to return promises
17915         when['try']      = attempt;              // call a function and return a promise
17916         when.attempt     = attempt;              // alias for when.try
17917
17918         when.iterate     = Promise.iterate;      // DEPRECATED (use cujojs/most streams) Generate a stream of promises
17919         when.unfold      = Promise.unfold;       // DEPRECATED (use cujojs/most streams) Generate a stream of promises
17920
17921         when.join        = join;                 // Join 2 or more promises
17922
17923         when.all         = all;                  // Resolve a list of promises
17924         when.settle      = settle;               // Settle a list of promises
17925
17926         when.any         = lift(Promise.any);    // One-winner race
17927         when.some        = lift(Promise.some);   // Multi-winner race
17928         when.race        = lift(Promise.race);   // First-to-settle race
17929
17930         when.map         = map;                  // Array.map() for promises
17931         when.filter      = filter;               // Array.filter() for promises
17932         when.reduce      = lift(Promise.reduce);       // Array.reduce() for promises
17933         when.reduceRight = lift(Promise.reduceRight);  // Array.reduceRight() for promises
17934
17935         when.isPromiseLike = isPromiseLike;      // Is something promise-like, aka thenable
17936
17937         when.Promise     = Promise;              // Promise constructor
17938         when.defer       = defer;                // Create a {promise, resolve, reject} tuple
17939
17940         // Error types
17941
17942         when.TimeoutError = TimeoutError;
17943
17944         /**
17945          * Get a trusted promise for x, or by transforming x with onFulfilled
17946          *
17947          * @param {*} x
17948          * @param {function?} onFulfilled callback to be called when x is
17949          *   successfully fulfilled.  If promiseOrValue is an immediate value, callback
17950          *   will be invoked immediately.
17951          * @param {function?} onRejected callback to be called when x is
17952          *   rejected.
17953          * @param {function?} onProgress callback to be called when progress updates
17954          *   are issued for x. @deprecated
17955          * @returns {Promise} a new promise that will fulfill with the return
17956          *   value of callback or errback or the completion value of promiseOrValue if
17957          *   callback and/or errback is not supplied.
17958          */
17959         function when(x, onFulfilled, onRejected, onProgress) {
17960                 var p = Promise.resolve(x);
17961                 if (arguments.length < 2) {
17962                         return p;
17963                 }
17964
17965                 return p.then(onFulfilled, onRejected, onProgress);
17966         }
17967
17968         /**
17969          * Creates a new promise whose fate is determined by resolver.
17970          * @param {function} resolver function(resolve, reject, notify)
17971          * @returns {Promise} promise whose fate is determine by resolver
17972          */
17973         function promise(resolver) {
17974                 return new Promise(resolver);
17975         }
17976
17977         /**
17978          * Lift the supplied function, creating a version of f that returns
17979          * promises, and accepts promises as arguments.
17980          * @param {function} f
17981          * @returns {Function} version of f that returns promises
17982          */
17983         function lift(f) {
17984                 return function() {
17985                         for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
17986                                 a[i] = arguments[i];
17987                         }
17988                         return apply(f, this, a);
17989                 };
17990         }
17991
17992         /**
17993          * Call f in a future turn, with the supplied args, and return a promise
17994          * for the result.
17995          * @param {function} f
17996          * @returns {Promise}
17997          */
17998         function attempt(f /*, args... */) {
17999                 /*jshint validthis:true */
18000                 for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
18001                         a[i] = arguments[i+1];
18002                 }
18003                 return apply(f, this, a);
18004         }
18005
18006         /**
18007          * Creates a {promise, resolver} pair, either or both of which
18008          * may be given out safely to consumers.
18009          * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
18010          */
18011         function defer() {
18012                 return new Deferred();
18013         }
18014
18015         function Deferred() {
18016                 var p = Promise._defer();
18017
18018                 function resolve(x) { p._handler.resolve(x); }
18019                 function reject(x) { p._handler.reject(x); }
18020                 function notify(x) { p._handler.notify(x); }
18021
18022                 this.promise = p;
18023                 this.resolve = resolve;
18024                 this.reject = reject;
18025                 this.notify = notify;
18026                 this.resolver = { resolve: resolve, reject: reject, notify: notify };
18027         }
18028
18029         /**
18030          * Determines if x is promise-like, i.e. a thenable object
18031          * NOTE: Will return true for *any thenable object*, and isn't truly
18032          * safe, since it may attempt to access the `then` property of x (i.e.
18033          *  clever/malicious getters may do weird things)
18034          * @param {*} x anything
18035          * @returns {boolean} true if x is promise-like
18036          */
18037         function isPromiseLike(x) {
18038                 return x && typeof x.then === 'function';
18039         }
18040
18041         /**
18042          * Return a promise that will resolve only once all the supplied arguments
18043          * have resolved. The resolution value of the returned promise will be an array
18044          * containing the resolution values of each of the arguments.
18045          * @param {...*} arguments may be a mix of promises and values
18046          * @returns {Promise}
18047          */
18048         function join(/* ...promises */) {
18049                 return Promise.all(arguments);
18050         }
18051
18052         /**
18053          * Return a promise that will fulfill once all input promises have
18054          * fulfilled, or reject when any one input promise rejects.
18055          * @param {array|Promise} promises array (or promise for an array) of promises
18056          * @returns {Promise}
18057          */
18058         function all(promises) {
18059                 return when(promises, Promise.all);
18060         }
18061
18062         /**
18063          * Return a promise that will always fulfill with an array containing
18064          * the outcome states of all input promises.  The returned promise
18065          * will only reject if `promises` itself is a rejected promise.
18066          * @param {array|Promise} promises array (or promise for an array) of promises
18067          * @returns {Promise} promise for array of settled state descriptors
18068          */
18069         function settle(promises) {
18070                 return when(promises, Promise.settle);
18071         }
18072
18073         /**
18074          * Promise-aware array map function, similar to `Array.prototype.map()`,
18075          * but input array may contain promises or values.
18076          * @param {Array|Promise} promises array of anything, may contain promises and values
18077          * @param {function(x:*, index:Number):*} mapFunc map function which may
18078          *  return a promise or value
18079          * @returns {Promise} promise that will fulfill with an array of mapped values
18080          *  or reject if any input promise rejects.
18081          */
18082         function map(promises, mapFunc) {
18083                 return when(promises, function(promises) {
18084                         return Promise.map(promises, mapFunc);
18085                 });
18086         }
18087
18088         /**
18089          * Filter the provided array of promises using the provided predicate.  Input may
18090          * contain promises and values
18091          * @param {Array|Promise} promises array of promises and values
18092          * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
18093          *  Must return truthy (or promise for truthy) for items to retain.
18094          * @returns {Promise} promise that will fulfill with an array containing all items
18095          *  for which predicate returned truthy.
18096          */
18097         function filter(promises, predicate) {
18098                 return when(promises, function(promises) {
18099                         return Promise.filter(promises, predicate);
18100                 });
18101         }
18102
18103         return when;
18104 });
18105 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
18106
18107 },{"./lib/Promise":190,"./lib/TimeoutError":192,"./lib/apply":193,"./lib/decorators/array":194,"./lib/decorators/flow":195,"./lib/decorators/fold":196,"./lib/decorators/inspect":197,"./lib/decorators/iterate":198,"./lib/decorators/progress":199,"./lib/decorators/timed":200,"./lib/decorators/unhandledRejection":201,"./lib/decorators/with":202}],208:[function(require,module,exports){
18108 var nativeIsArray = Array.isArray
18109 var toString = Object.prototype.toString
18110
18111 module.exports = nativeIsArray || isArray
18112
18113 function isArray(obj) {
18114     return toString.call(obj) === "[object Array]"
18115 }
18116
18117 },{}],209:[function(require,module,exports){
18118 "use strict";
18119 var APIv3_1 = require("./api/APIv3");
18120 exports.APIv3 = APIv3_1.APIv3;
18121 var ModelCreator_1 = require("./api/ModelCreator");
18122 exports.ModelCreator = ModelCreator_1.ModelCreator;
18123
18124 },{"./api/APIv3":220,"./api/ModelCreator":221}],210:[function(require,module,exports){
18125 "use strict";
18126 var Component_1 = require("./component/Component");
18127 exports.Component = Component_1.Component;
18128 var ComponentService_1 = require("./component/ComponentService");
18129 exports.ComponentService = ComponentService_1.ComponentService;
18130 var AttributionComponent_1 = require("./component/AttributionComponent");
18131 exports.AttributionComponent = AttributionComponent_1.AttributionComponent;
18132 var BackgroundComponent_1 = require("./component/BackgroundComponent");
18133 exports.BackgroundComponent = BackgroundComponent_1.BackgroundComponent;
18134 var BearingComponent_1 = require("./component/BearingComponent");
18135 exports.BearingComponent = BearingComponent_1.BearingComponent;
18136 var CacheComponent_1 = require("./component/CacheComponent");
18137 exports.CacheComponent = CacheComponent_1.CacheComponent;
18138 var CoverComponent_1 = require("./component/CoverComponent");
18139 exports.CoverComponent = CoverComponent_1.CoverComponent;
18140 var DebugComponent_1 = require("./component/DebugComponent");
18141 exports.DebugComponent = DebugComponent_1.DebugComponent;
18142 var DirectionComponent_1 = require("./component/direction/DirectionComponent");
18143 exports.DirectionComponent = DirectionComponent_1.DirectionComponent;
18144 var DirectionDOMCalculator_1 = require("./component/direction/DirectionDOMCalculator");
18145 exports.DirectionDOMCalculator = DirectionDOMCalculator_1.DirectionDOMCalculator;
18146 var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer");
18147 exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer;
18148 var ImageComponent_1 = require("./component/ImageComponent");
18149 exports.ImageComponent = ImageComponent_1.ImageComponent;
18150 var KeyboardComponent_1 = require("./component/KeyboardComponent");
18151 exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent;
18152 var LoadingComponent_1 = require("./component/LoadingComponent");
18153 exports.LoadingComponent = LoadingComponent_1.LoadingComponent;
18154 var Marker_1 = require("./component/marker/Marker");
18155 exports.Marker = Marker_1.Marker;
18156 var MarkerComponent_1 = require("./component/marker/MarkerComponent");
18157 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
18158 var MouseComponent_1 = require("./component/MouseComponent");
18159 exports.MouseComponent = MouseComponent_1.MouseComponent;
18160 var NavigationComponent_1 = require("./component/NavigationComponent");
18161 exports.NavigationComponent = NavigationComponent_1.NavigationComponent;
18162 var RouteComponent_1 = require("./component/RouteComponent");
18163 exports.RouteComponent = RouteComponent_1.RouteComponent;
18164 var SequenceComponent_1 = require("./component/sequence/SequenceComponent");
18165 exports.SequenceComponent = SequenceComponent_1.SequenceComponent;
18166 var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer");
18167 exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer;
18168 var SequenceDOMInteraction_1 = require("./component/sequence/SequenceDOMInteraction");
18169 exports.SequenceDOMInteraction = SequenceDOMInteraction_1.SequenceDOMInteraction;
18170 var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent");
18171 exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent;
18172 var ImagePlaneFactory_1 = require("./component/imageplane/ImagePlaneFactory");
18173 exports.ImagePlaneFactory = ImagePlaneFactory_1.ImagePlaneFactory;
18174 var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer");
18175 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer;
18176 var ImagePlaneScene_1 = require("./component/imageplane/ImagePlaneScene");
18177 exports.ImagePlaneScene = ImagePlaneScene_1.ImagePlaneScene;
18178 var ImagePlaneShaders_1 = require("./component/imageplane/ImagePlaneShaders");
18179 exports.ImagePlaneShaders = ImagePlaneShaders_1.ImagePlaneShaders;
18180 var SimpleMarker_1 = require("./component/marker/SimpleMarker");
18181 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
18182 var SliderComponent_1 = require("./component/imageplane/SliderComponent");
18183 exports.SliderComponent = SliderComponent_1.SliderComponent;
18184 var StatsComponent_1 = require("./component/StatsComponent");
18185 exports.StatsComponent = StatsComponent_1.StatsComponent;
18186 var Tag_1 = require("./component/tag/tag/Tag");
18187 exports.Tag = Tag_1.Tag;
18188 var Alignment_1 = require("./component/tag/tag/Alignment");
18189 exports.Alignment = Alignment_1.Alignment;
18190 var OutlineTag_1 = require("./component/tag/tag/OutlineTag");
18191 exports.OutlineTag = OutlineTag_1.OutlineTag;
18192 var RenderTag_1 = require("./component/tag/tag/RenderTag");
18193 exports.RenderTag = RenderTag_1.RenderTag;
18194 var OutlineRenderTag_1 = require("./component/tag/tag/OutlineRenderTag");
18195 exports.OutlineRenderTag = OutlineRenderTag_1.OutlineRenderTag;
18196 var OutlineCreateTag_1 = require("./component/tag/tag/OutlineCreateTag");
18197 exports.OutlineCreateTag = OutlineCreateTag_1.OutlineCreateTag;
18198 var SpotTag_1 = require("./component/tag/tag/SpotTag");
18199 exports.SpotTag = SpotTag_1.SpotTag;
18200 var SpotRenderTag_1 = require("./component/tag/tag/SpotRenderTag");
18201 exports.SpotRenderTag = SpotRenderTag_1.SpotRenderTag;
18202 var TagComponent_1 = require("./component/tag/TagComponent");
18203 exports.TagComponent = TagComponent_1.TagComponent;
18204 var TagCreator_1 = require("./component/tag/TagCreator");
18205 exports.TagCreator = TagCreator_1.TagCreator;
18206 var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer");
18207 exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer;
18208 var TagGLRenderer_1 = require("./component/tag/TagGLRenderer");
18209 exports.TagGLRenderer = TagGLRenderer_1.TagGLRenderer;
18210 var TagOperation_1 = require("./component/tag/TagOperation");
18211 exports.TagOperation = TagOperation_1.TagOperation;
18212 var TagSet_1 = require("./component/tag/TagSet");
18213 exports.TagSet = TagSet_1.TagSet;
18214 var Geometry_1 = require("./component/tag/geometry/Geometry");
18215 exports.Geometry = Geometry_1.Geometry;
18216 var VertexGeometry_1 = require("./component/tag/geometry/VertexGeometry");
18217 exports.VertexGeometry = VertexGeometry_1.VertexGeometry;
18218 var RectGeometry_1 = require("./component/tag/geometry/RectGeometry");
18219 exports.RectGeometry = RectGeometry_1.RectGeometry;
18220 var PointGeometry_1 = require("./component/tag/geometry/PointGeometry");
18221 exports.PointGeometry = PointGeometry_1.PointGeometry;
18222 var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry");
18223 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
18224 var GeometryTagError_1 = require("./component/tag/error/GeometryTagError");
18225 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
18226
18227 },{"./component/AttributionComponent":222,"./component/BackgroundComponent":223,"./component/BearingComponent":224,"./component/CacheComponent":225,"./component/Component":226,"./component/ComponentService":227,"./component/CoverComponent":228,"./component/DebugComponent":229,"./component/ImageComponent":230,"./component/KeyboardComponent":231,"./component/LoadingComponent":232,"./component/MouseComponent":233,"./component/NavigationComponent":234,"./component/RouteComponent":235,"./component/StatsComponent":236,"./component/direction/DirectionComponent":237,"./component/direction/DirectionDOMCalculator":238,"./component/direction/DirectionDOMRenderer":239,"./component/imageplane/ImagePlaneComponent":240,"./component/imageplane/ImagePlaneFactory":241,"./component/imageplane/ImagePlaneGLRenderer":242,"./component/imageplane/ImagePlaneScene":243,"./component/imageplane/ImagePlaneShaders":244,"./component/imageplane/SliderComponent":245,"./component/marker/Marker":246,"./component/marker/MarkerComponent":247,"./component/marker/SimpleMarker":248,"./component/sequence/SequenceComponent":249,"./component/sequence/SequenceDOMInteraction":250,"./component/sequence/SequenceDOMRenderer":251,"./component/tag/TagComponent":253,"./component/tag/TagCreator":254,"./component/tag/TagDOMRenderer":255,"./component/tag/TagGLRenderer":256,"./component/tag/TagOperation":257,"./component/tag/TagSet":258,"./component/tag/error/GeometryTagError":259,"./component/tag/geometry/Geometry":260,"./component/tag/geometry/PointGeometry":261,"./component/tag/geometry/PolygonGeometry":262,"./component/tag/geometry/RectGeometry":263,"./component/tag/geometry/VertexGeometry":264,"./component/tag/tag/Alignment":265,"./component/tag/tag/OutlineCreateTag":266,"./component/tag/tag/OutlineRenderTag":267,"./component/tag/tag/OutlineTag":268,"./component/tag/tag/RenderTag":269,"./component/tag/tag/SpotRenderTag":270,"./component/tag/tag/SpotTag":271,"./component/tag/tag/Tag":272}],211:[function(require,module,exports){
18228 "use strict";
18229 var EdgeDirection_1 = require("./graph/edge/EdgeDirection");
18230 exports.EdgeDirection = EdgeDirection_1.EdgeDirection;
18231 var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings");
18232 exports.EdgeCalculatorSettings = EdgeCalculatorSettings_1.EdgeCalculatorSettings;
18233 var EdgeCalculatorDirections_1 = require("./graph/edge/EdgeCalculatorDirections");
18234 exports.EdgeCalculatorDirections = EdgeCalculatorDirections_1.EdgeCalculatorDirections;
18235 var EdgeCalculatorCoefficients_1 = require("./graph/edge/EdgeCalculatorCoefficients");
18236 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculatorCoefficients;
18237 var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator");
18238 exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator;
18239
18240 },{"./graph/edge/EdgeCalculator":290,"./graph/edge/EdgeCalculatorCoefficients":291,"./graph/edge/EdgeCalculatorDirections":292,"./graph/edge/EdgeCalculatorSettings":293,"./graph/edge/EdgeDirection":294}],212:[function(require,module,exports){
18241 "use strict";
18242 var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError");
18243 exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError;
18244 var GraphMapillaryError_1 = require("./error/GraphMapillaryError");
18245 exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError;
18246 var MapillaryError_1 = require("./error/MapillaryError");
18247 exports.MapillaryError = MapillaryError_1.MapillaryError;
18248
18249 },{"./error/ArgumentMapillaryError":273,"./error/GraphMapillaryError":274,"./error/MapillaryError":275}],213:[function(require,module,exports){
18250 "use strict";
18251 var Camera_1 = require("./geo/Camera");
18252 exports.Camera = Camera_1.Camera;
18253 var GeoCoords_1 = require("./geo/GeoCoords");
18254 exports.GeoCoords = GeoCoords_1.GeoCoords;
18255 var Spatial_1 = require("./geo/Spatial");
18256 exports.Spatial = Spatial_1.Spatial;
18257 var Transform_1 = require("./geo/Transform");
18258 exports.Transform = Transform_1.Transform;
18259
18260 },{"./geo/Camera":276,"./geo/GeoCoords":277,"./geo/Spatial":278,"./geo/Transform":279}],214:[function(require,module,exports){
18261 "use strict";
18262 var FilterCreator_1 = require("./graph/FilterCreator");
18263 exports.FilterCreator = FilterCreator_1.FilterCreator;
18264 var Graph_1 = require("./graph/Graph");
18265 exports.Graph = Graph_1.Graph;
18266 var GraphCalculator_1 = require("./graph/GraphCalculator");
18267 exports.GraphCalculator = GraphCalculator_1.GraphCalculator;
18268 var GraphService_1 = require("./graph/GraphService");
18269 exports.GraphService = GraphService_1.GraphService;
18270 var ImageLoader_1 = require("./graph/ImageLoader");
18271 exports.ImageLoader = ImageLoader_1.ImageLoader;
18272 var ImageLoadingService_1 = require("./graph/ImageLoadingService");
18273 exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService;
18274 var MeshReader_1 = require("./graph/MeshReader");
18275 exports.MeshReader = MeshReader_1.MeshReader;
18276 var Node_1 = require("./graph/Node");
18277 exports.Node = Node_1.Node;
18278 var NodeCache_1 = require("./graph/NodeCache");
18279 exports.NodeCache = NodeCache_1.NodeCache;
18280 var Sequence_1 = require("./graph/Sequence");
18281 exports.Sequence = Sequence_1.Sequence;
18282
18283 },{"./graph/FilterCreator":280,"./graph/Graph":281,"./graph/GraphCalculator":282,"./graph/GraphService":283,"./graph/ImageLoader":284,"./graph/ImageLoadingService":285,"./graph/MeshReader":286,"./graph/Node":287,"./graph/NodeCache":288,"./graph/Sequence":289}],215:[function(require,module,exports){
18284 /**
18285  * MapillaryJS is a WebGL JavaScript library for exploring street level imagery
18286  * @name Mapillary
18287  */
18288 "use strict";
18289 var Edge_1 = require("./Edge");
18290 exports.EdgeDirection = Edge_1.EdgeDirection;
18291 var Render_1 = require("./Render");
18292 exports.RenderMode = Render_1.RenderMode;
18293 var Viewer_1 = require("./Viewer");
18294 exports.ImageSize = Viewer_1.ImageSize;
18295 exports.Viewer = Viewer_1.Viewer;
18296 var TagComponent = require("./component/tag/Tag");
18297 exports.TagComponent = TagComponent;
18298
18299 },{"./Edge":211,"./Render":216,"./Viewer":219,"./component/tag/Tag":252}],216:[function(require,module,exports){
18300 "use strict";
18301 var DOMRenderer_1 = require("./render/DOMRenderer");
18302 exports.DOMRenderer = DOMRenderer_1.DOMRenderer;
18303 var GLRenderer_1 = require("./render/GLRenderer");
18304 exports.GLRenderer = GLRenderer_1.GLRenderer;
18305 var GLRenderStage_1 = require("./render/GLRenderStage");
18306 exports.GLRenderStage = GLRenderStage_1.GLRenderStage;
18307 var RenderCamera_1 = require("./render/RenderCamera");
18308 exports.RenderCamera = RenderCamera_1.RenderCamera;
18309 var RenderMode_1 = require("./render/RenderMode");
18310 exports.RenderMode = RenderMode_1.RenderMode;
18311 var RenderService_1 = require("./render/RenderService");
18312 exports.RenderService = RenderService_1.RenderService;
18313
18314 },{"./render/DOMRenderer":295,"./render/GLRenderStage":296,"./render/GLRenderer":297,"./render/RenderCamera":298,"./render/RenderMode":299,"./render/RenderService":300}],217:[function(require,module,exports){
18315 "use strict";
18316 var State_1 = require("./state/State");
18317 exports.State = State_1.State;
18318 var StateBase_1 = require("./state/states/StateBase");
18319 exports.StateBase = StateBase_1.StateBase;
18320 var StateContext_1 = require("./state/StateContext");
18321 exports.StateContext = StateContext_1.StateContext;
18322 var StateService_1 = require("./state/StateService");
18323 exports.StateService = StateService_1.StateService;
18324 var TraversingState_1 = require("./state/states/TraversingState");
18325 exports.TraversingState = TraversingState_1.TraversingState;
18326 var WaitingState_1 = require("./state/states/WaitingState");
18327 exports.WaitingState = WaitingState_1.WaitingState;
18328
18329 },{"./state/State":301,"./state/StateContext":302,"./state/StateService":303,"./state/states/StateBase":304,"./state/states/TraversingState":305,"./state/states/WaitingState":306}],218:[function(require,module,exports){
18330 "use strict";
18331 var EventEmitter_1 = require("./utils/EventEmitter");
18332 exports.EventEmitter = EventEmitter_1.EventEmitter;
18333 var Settings_1 = require("./utils/Settings");
18334 exports.Settings = Settings_1.Settings;
18335 var Urls_1 = require("./utils/Urls");
18336 exports.Urls = Urls_1.Urls;
18337
18338 },{"./utils/EventEmitter":307,"./utils/Settings":308,"./utils/Urls":309}],219:[function(require,module,exports){
18339 "use strict";
18340 var Container_1 = require("./viewer/Container");
18341 exports.Container = Container_1.Container;
18342 var EventLauncher_1 = require("./viewer/EventLauncher");
18343 exports.EventLauncher = EventLauncher_1.EventLauncher;
18344 var ImageSize_1 = require("./viewer/ImageSize");
18345 exports.ImageSize = ImageSize_1.ImageSize;
18346 var LoadingService_1 = require("./viewer/LoadingService");
18347 exports.LoadingService = LoadingService_1.LoadingService;
18348 var MouseService_1 = require("./viewer/MouseService");
18349 exports.MouseService = MouseService_1.MouseService;
18350 var Navigator_1 = require("./viewer/Navigator");
18351 exports.Navigator = Navigator_1.Navigator;
18352 var ComponentController_1 = require("./viewer/ComponentController");
18353 exports.ComponentController = ComponentController_1.ComponentController;
18354 var SpriteAlignment_1 = require("./viewer/SpriteAlignment");
18355 exports.SpriteAlignment = SpriteAlignment_1.SpriteAlignment;
18356 var SpriteService_1 = require("./viewer/SpriteService");
18357 exports.SpriteService = SpriteService_1.SpriteService;
18358 var TouchService_1 = require("./viewer/TouchService");
18359 exports.TouchService = TouchService_1.TouchService;
18360 exports.TouchMove = TouchService_1.TouchMove;
18361 var Viewer_1 = require("./viewer/Viewer");
18362 exports.Viewer = Viewer_1.Viewer;
18363
18364 },{"./viewer/ComponentController":310,"./viewer/Container":311,"./viewer/EventLauncher":312,"./viewer/ImageSize":313,"./viewer/LoadingService":314,"./viewer/MouseService":315,"./viewer/Navigator":316,"./viewer/SpriteAlignment":317,"./viewer/SpriteService":318,"./viewer/TouchService":319,"./viewer/Viewer":320}],220:[function(require,module,exports){
18365 /// <reference path="../../typings/index.d.ts" />
18366 "use strict";
18367 var Observable_1 = require("rxjs/Observable");
18368 require("rxjs/add/observable/defer");
18369 require("rxjs/add/observable/fromPromise");
18370 require("rxjs/add/operator/catch");
18371 require("rxjs/add/operator/map");
18372 var API_1 = require("../API");
18373 var APIv3 = (function () {
18374     function APIv3(clientId, token, creator) {
18375         this._clientId = clientId;
18376         this._modelCreator = creator != null ? creator : new API_1.ModelCreator();
18377         this._model = this._modelCreator.createModel(clientId, token);
18378         this._pageCount = 999;
18379         this._pathImageByKey = "imageByKey";
18380         this._pathImageCloseTo = "imageCloseTo";
18381         this._pathImagesByH = "imagesByH";
18382         this._pathImageViewAdd = "imageViewAdd";
18383         this._pathSequenceByKey = "sequenceByKey";
18384         this._pathSequenceViewAdd = "sequenceViewAdd";
18385         this._propertiesCore = [
18386             "cl",
18387             "l",
18388             "sequence",
18389         ];
18390         this._propertiesFill = [
18391             "captured_at",
18392             "user",
18393             "project",
18394         ];
18395         this._propertiesKey = [
18396             "key",
18397         ];
18398         this._propertiesSequence = [
18399             "keys",
18400         ];
18401         this._propertiesSpatial = [
18402             "atomic_scale",
18403             "ca",
18404             "calt",
18405             "cca",
18406             "cfocal",
18407             "gpano",
18408             "height",
18409             "merge_cc",
18410             "merge_version",
18411             "c_rotation",
18412             "orientation",
18413             "width",
18414         ];
18415         this._propertiesUser = [
18416             "username",
18417         ];
18418     }
18419     ;
18420     APIv3.prototype.imageByKeyFill$ = function (keys) {
18421         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
18422             this._pathImageByKey,
18423             keys,
18424             this._propertiesKey
18425                 .concat(this._propertiesFill)
18426                 .concat(this._propertiesSpatial),
18427             this._propertiesKey
18428                 .concat(this._propertiesUser)]))
18429             .map(function (value) {
18430             return value.json.imageByKey;
18431         }), this._pathImageByKey, keys);
18432     };
18433     APIv3.prototype.imageByKeyFull$ = function (keys) {
18434         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
18435             this._pathImageByKey,
18436             keys,
18437             this._propertiesKey
18438                 .concat(this._propertiesCore)
18439                 .concat(this._propertiesFill)
18440                 .concat(this._propertiesSpatial),
18441             this._propertiesKey
18442                 .concat(this._propertiesUser)]))
18443             .map(function (value) {
18444             return value.json.imageByKey;
18445         }), this._pathImageByKey, keys);
18446     };
18447     APIv3.prototype.imageCloseTo$ = function (lat, lon) {
18448         var lonLat = lon + ":" + lat;
18449         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
18450             this._pathImageCloseTo,
18451             [lonLat],
18452             this._propertiesKey
18453                 .concat(this._propertiesCore)
18454                 .concat(this._propertiesFill)
18455                 .concat(this._propertiesSpatial),
18456             this._propertiesKey
18457                 .concat(this._propertiesUser)]))
18458             .map(function (value) {
18459             return value != null ? value.json.imageCloseTo[lonLat] : null;
18460         }), this._pathImageCloseTo, [lonLat]);
18461     };
18462     APIv3.prototype.imagesByH$ = function (hs) {
18463         var _this = this;
18464         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
18465             this._pathImagesByH,
18466             hs,
18467             { from: 0, to: this._pageCount },
18468             this._propertiesKey
18469                 .concat(this._propertiesCore),
18470             this._propertiesKey]))
18471             .map(function (value) {
18472             if (value == null) {
18473                 value = { json: { imagesByH: {} } };
18474                 for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) {
18475                     var h = hs_1[_i];
18476                     value.json.imagesByH[h] = {};
18477                     for (var i = 0; i <= _this._pageCount; i++) {
18478                         value.json.imagesByH[h][i] = null;
18479                     }
18480                 }
18481             }
18482             return value.json.imagesByH;
18483         }), this._pathImagesByH, hs);
18484     };
18485     APIv3.prototype.imageViewAdd$ = function (keys) {
18486         return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys);
18487     };
18488     APIv3.prototype.invalidateImageByKey = function (keys) {
18489         this._invalidateGet(this._pathImageByKey, keys);
18490     };
18491     APIv3.prototype.invalidateImagesByH = function (hs) {
18492         this._invalidateGet(this._pathImagesByH, hs);
18493     };
18494     APIv3.prototype.invalidateSequenceByKey = function (sKeys) {
18495         this._invalidateGet(this._pathSequenceByKey, sKeys);
18496     };
18497     APIv3.prototype.setToken = function (token) {
18498         this._model.invalidate([]);
18499         this._model = null;
18500         this._model = this._modelCreator.createModel(this._clientId, token);
18501     };
18502     APIv3.prototype.sequenceByKey$ = function (sequenceKeys) {
18503         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
18504             this._pathSequenceByKey,
18505             sequenceKeys,
18506             this._propertiesKey
18507                 .concat(this._propertiesSequence)]))
18508             .map(function (value) {
18509             return value.json.sequenceByKey;
18510         }), this._pathSequenceByKey, sequenceKeys);
18511     };
18512     APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) {
18513         return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys);
18514     };
18515     Object.defineProperty(APIv3.prototype, "clientId", {
18516         get: function () {
18517             return this._clientId;
18518         },
18519         enumerable: true,
18520         configurable: true
18521     });
18522     APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) {
18523         var _this = this;
18524         return observable
18525             .catch(function (error) {
18526             _this._invalidateGet(path, paths);
18527             throw error;
18528         });
18529     };
18530     APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) {
18531         var _this = this;
18532         return observable
18533             .catch(function (error) {
18534             _this._invalidateCall(path, paths);
18535             throw error;
18536         });
18537     };
18538     APIv3.prototype._invalidateGet = function (path, paths) {
18539         this._model.invalidate([path, paths]);
18540     };
18541     APIv3.prototype._invalidateCall = function (path, paths) {
18542         this._model.invalidate([path], [paths]);
18543     };
18544     APIv3.prototype._wrapPromise$ = function (promise) {
18545         return Observable_1.Observable.defer(function () { return Observable_1.Observable.fromPromise(promise); });
18546     };
18547     return APIv3;
18548 }());
18549 exports.APIv3 = APIv3;
18550 Object.defineProperty(exports, "__esModule", { value: true });
18551 exports.default = APIv3;
18552
18553 },{"../API":209,"rxjs/Observable":28,"rxjs/add/observable/defer":38,"rxjs/add/observable/fromPromise":42,"rxjs/add/operator/catch":49,"rxjs/add/operator/map":61}],221:[function(require,module,exports){
18554 /// <reference path="../../typings/index.d.ts" />
18555 "use strict";
18556 var falcor = require("falcor");
18557 var HttpDataSource = require("falcor-http-datasource");
18558 var Utils_1 = require("../Utils");
18559 var ModelCreator = (function () {
18560     function ModelCreator() {
18561     }
18562     ModelCreator.prototype.createModel = function (clientId, token) {
18563         var configuration = {
18564             crossDomain: true,
18565             withCredentials: false,
18566         };
18567         if (token != null) {
18568             configuration.headers = { "Authorization": "Bearer " + token };
18569         }
18570         return new falcor.Model({
18571             source: new HttpDataSource(Utils_1.Urls.falcorModel(clientId), configuration),
18572         });
18573     };
18574     return ModelCreator;
18575 }());
18576 exports.ModelCreator = ModelCreator;
18577 Object.defineProperty(exports, "__esModule", { value: true });
18578 exports.default = ModelCreator;
18579
18580 },{"../Utils":218,"falcor":13,"falcor-http-datasource":8}],222:[function(require,module,exports){
18581 /// <reference path="../../typings/index.d.ts" />
18582 "use strict";
18583 var __extends = (this && this.__extends) || function (d, b) {
18584     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
18585     function __() { this.constructor = d; }
18586     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18587 };
18588 var vd = require("virtual-dom");
18589 var Component_1 = require("../Component");
18590 var AttributionComponent = (function (_super) {
18591     __extends(AttributionComponent, _super);
18592     function AttributionComponent(name, container, navigator) {
18593         _super.call(this, name, container, navigator);
18594     }
18595     AttributionComponent.prototype._activate = function () {
18596         var _this = this;
18597         this._disposable = this._navigator.stateService.currentNode$
18598             .map(function (node) {
18599             return { name: _this._name, vnode: _this._getAttributionNode(node.username, node.key) };
18600         })
18601             .subscribe(this._container.domRenderer.render$);
18602     };
18603     AttributionComponent.prototype._deactivate = function () {
18604         this._disposable.unsubscribe();
18605     };
18606     AttributionComponent.prototype._getDefaultConfiguration = function () {
18607         return {};
18608     };
18609     AttributionComponent.prototype._getAttributionNode = function (username, photoId) {
18610         return vd.h("div.Attribution", {}, [
18611             vd.h("a", { href: "https://www.mapillary.com/app/user/" + username,
18612                 target: "_blank",
18613                 textContent: "@" + username,
18614             }, []),
18615             vd.h("span", { textContent: "|" }, []),
18616             vd.h("a", { href: "https://www.mapillary.com/app/?pKey=" + photoId + "&focus=photo",
18617                 target: "_blank",
18618                 textContent: "mapillary.com",
18619             }, []),
18620         ]);
18621     };
18622     AttributionComponent.componentName = "attribution";
18623     return AttributionComponent;
18624 }(Component_1.Component));
18625 exports.AttributionComponent = AttributionComponent;
18626 Component_1.ComponentService.register(AttributionComponent);
18627 Object.defineProperty(exports, "__esModule", { value: true });
18628 exports.default = AttributionComponent;
18629
18630 },{"../Component":210,"virtual-dom":166}],223:[function(require,module,exports){
18631 /// <reference path="../../typings/index.d.ts" />
18632 "use strict";
18633 var __extends = (this && this.__extends) || function (d, b) {
18634     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
18635     function __() { this.constructor = d; }
18636     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18637 };
18638 var vd = require("virtual-dom");
18639 var Component_1 = require("../Component");
18640 var BackgroundComponent = (function (_super) {
18641     __extends(BackgroundComponent, _super);
18642     function BackgroundComponent(name, container, navigator) {
18643         _super.call(this, name, container, navigator);
18644     }
18645     BackgroundComponent.prototype._activate = function () {
18646         this._container.domRenderer.render$
18647             .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given photo.") });
18648     };
18649     BackgroundComponent.prototype._deactivate = function () {
18650         return;
18651     };
18652     BackgroundComponent.prototype._getDefaultConfiguration = function () {
18653         return {};
18654     };
18655     BackgroundComponent.prototype._getBackgroundNode = function (notice) {
18656         // todo: add condition for when to display the DOM node
18657         return vd.h("div.BackgroundWrapper", {}, [
18658             vd.h("p", { textContent: notice }, []),
18659         ]);
18660     };
18661     BackgroundComponent.componentName = "background";
18662     return BackgroundComponent;
18663 }(Component_1.Component));
18664 exports.BackgroundComponent = BackgroundComponent;
18665 Component_1.ComponentService.register(BackgroundComponent);
18666 Object.defineProperty(exports, "__esModule", { value: true });
18667 exports.default = BackgroundComponent;
18668
18669 },{"../Component":210,"virtual-dom":166}],224:[function(require,module,exports){
18670 /// <reference path="../../typings/index.d.ts" />
18671 "use strict";
18672 var __extends = (this && this.__extends) || function (d, b) {
18673     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
18674     function __() { this.constructor = d; }
18675     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18676 };
18677 var vd = require("virtual-dom");
18678 var Component_1 = require("../Component");
18679 var BearingComponent = (function (_super) {
18680     __extends(BearingComponent, _super);
18681     function BearingComponent(name, container, navigator) {
18682         _super.call(this, name, container, navigator);
18683     }
18684     BearingComponent.prototype._activate = function () {
18685         var _this = this;
18686         this._renderSubscription = this._navigator.stateService.currentNode$
18687             .map(function (node) {
18688             return node.fullPano;
18689         })
18690             .map(function (pano) {
18691             return {
18692                 name: _this._name,
18693                 vnode: pano ? vd.h("div.BearingIndicator", {}, []) : vd.h("div", {}, []),
18694             };
18695         })
18696             .subscribe(this._container.domRenderer.render$);
18697     };
18698     BearingComponent.prototype._deactivate = function () {
18699         this._renderSubscription.unsubscribe();
18700     };
18701     BearingComponent.prototype._getDefaultConfiguration = function () {
18702         return {};
18703     };
18704     BearingComponent.componentName = "bearing";
18705     return BearingComponent;
18706 }(Component_1.Component));
18707 exports.BearingComponent = BearingComponent;
18708 Component_1.ComponentService.register(BearingComponent);
18709 Object.defineProperty(exports, "__esModule", { value: true });
18710 exports.default = BearingComponent;
18711
18712 },{"../Component":210,"virtual-dom":166}],225:[function(require,module,exports){
18713 "use strict";
18714 var __extends = (this && this.__extends) || function (d, b) {
18715     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
18716     function __() { this.constructor = d; }
18717     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18718 };
18719 var Observable_1 = require("rxjs/Observable");
18720 require("rxjs/add/observable/combineLatest");
18721 require("rxjs/add/observable/from");
18722 require("rxjs/add/observable/merge");
18723 require("rxjs/add/observable/of");
18724 require("rxjs/add/observable/zip");
18725 require("rxjs/add/operator/catch");
18726 require("rxjs/add/operator/combineLatest");
18727 require("rxjs/add/operator/distinct");
18728 require("rxjs/add/operator/expand");
18729 require("rxjs/add/operator/filter");
18730 require("rxjs/add/operator/map");
18731 require("rxjs/add/operator/merge");
18732 require("rxjs/add/operator/mergeMap");
18733 require("rxjs/add/operator/mergeAll");
18734 require("rxjs/add/operator/skip");
18735 require("rxjs/add/operator/switchMap");
18736 var Edge_1 = require("../Edge");
18737 var Component_1 = require("../Component");
18738 var CacheComponent = (function (_super) {
18739     __extends(CacheComponent, _super);
18740     function CacheComponent(name, container, navigator) {
18741         _super.call(this, name, container, navigator);
18742     }
18743     /**
18744      * Set the cache depth.
18745      *
18746      * Configures the cache depth. The cache depth can be different for
18747      * different edge direction types.
18748      *
18749      * @param {ICacheDepth} depth - Cache depth structure.
18750      */
18751     CacheComponent.prototype.setDepth = function (depth) {
18752         this.configure({ depth: depth });
18753     };
18754     CacheComponent.prototype._activate = function () {
18755         var _this = this;
18756         this._sequenceSubscription = Observable_1.Observable
18757             .combineLatest(this._navigator.stateService.currentNode$
18758             .switchMap(function (node) {
18759             return node.sequenceEdges$;
18760         })
18761             .filter(function (status) {
18762             return status.cached;
18763         }), this._configuration$)
18764             .switchMap(function (nc) {
18765             var status = nc[0];
18766             var configuration = nc[1];
18767             var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence));
18768             var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth);
18769             var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth);
18770             return Observable_1.Observable
18771                 .merge(next$, prev$)
18772                 .catch(function (error, caught) {
18773                 console.error("Failed to cache sequence edges.", error);
18774                 return Observable_1.Observable.empty();
18775             });
18776         })
18777             .subscribe();
18778         this._spatialSubscription = this._navigator.stateService.currentNode$
18779             .switchMap(function (node) {
18780             return Observable_1.Observable
18781                 .combineLatest(Observable_1.Observable.of(node), node.spatialEdges$
18782                 .filter(function (status) {
18783                 return status.cached;
18784             }));
18785         })
18786             .combineLatest(this._configuration$, function (ns, configuration) {
18787             return [ns[0], ns[1], configuration];
18788         })
18789             .switchMap(function (args) {
18790             var node = args[0];
18791             var edges = args[1].edges;
18792             var depth = args[2].depth;
18793             var panoDepth = Math.max(0, Math.min(2, depth.pano));
18794             var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step));
18795             var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn));
18796             var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth);
18797             var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth);
18798             var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth);
18799             var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth);
18800             var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth);
18801             var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth);
18802             var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth);
18803             var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth);
18804             return Observable_1.Observable
18805                 .merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$)
18806                 .catch(function (error, caught) {
18807                 console.error("Failed to cache spatial edges.", error);
18808                 return Observable_1.Observable.empty();
18809             });
18810         })
18811             .subscribe();
18812     };
18813     CacheComponent.prototype._deactivate = function () {
18814         this._sequenceSubscription.unsubscribe();
18815         this._spatialSubscription.unsubscribe();
18816     };
18817     CacheComponent.prototype._getDefaultConfiguration = function () {
18818         return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } };
18819     };
18820     CacheComponent.prototype._cache$ = function (edges, direction, depth) {
18821         var _this = this;
18822         return Observable_1.Observable
18823             .zip(Observable_1.Observable.of(edges), Observable_1.Observable.of(depth))
18824             .expand(function (ed) {
18825             var es = ed[0];
18826             var d = ed[1];
18827             var edgesDepths$ = [];
18828             if (d > 0) {
18829                 for (var _i = 0, es_1 = es; _i < es_1.length; _i++) {
18830                     var edge = es_1[_i];
18831                     if (edge.data.direction === direction) {
18832                         edgesDepths$.push(Observable_1.Observable
18833                             .zip(_this._navigator.graphService.cacheNode$(edge.to)
18834                             .mergeMap(function (n) {
18835                             return _this._nodeToEdges$(n, direction);
18836                         }), Observable_1.Observable.of(d - 1)));
18837                     }
18838                 }
18839             }
18840             return Observable_1.Observable
18841                 .from(edgesDepths$)
18842                 .mergeAll();
18843         })
18844             .skip(1);
18845     };
18846     CacheComponent.prototype._nodeToEdges$ = function (node, direction) {
18847         return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
18848             node.sequenceEdges$ :
18849             node.spatialEdges$)
18850             .first(function (status) {
18851             return status.cached;
18852         })
18853             .map(function (status) {
18854             return status.edges;
18855         });
18856     };
18857     CacheComponent.componentName = "cache";
18858     return CacheComponent;
18859 }(Component_1.Component));
18860 exports.CacheComponent = CacheComponent;
18861 Component_1.ComponentService.register(CacheComponent);
18862 Object.defineProperty(exports, "__esModule", { value: true });
18863 exports.default = CacheComponent;
18864
18865 },{"../Component":210,"../Edge":211,"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":46,"rxjs/add/operator/catch":49,"rxjs/add/operator/combineLatest":50,"rxjs/add/operator/distinct":53,"rxjs/add/operator/expand":56,"rxjs/add/operator/filter":57,"rxjs/add/operator/map":61,"rxjs/add/operator/merge":62,"rxjs/add/operator/mergeAll":63,"rxjs/add/operator/mergeMap":64,"rxjs/add/operator/skip":71,"rxjs/add/operator/switchMap":74}],226:[function(require,module,exports){
18866 "use strict";
18867 var __extends = (this && this.__extends) || function (d, b) {
18868     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
18869     function __() { this.constructor = d; }
18870     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18871 };
18872 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
18873 var Subject_1 = require("rxjs/Subject");
18874 require("rxjs/add/operator/publishReplay");
18875 require("rxjs/add/operator/scan");
18876 require("rxjs/add/operator/startWith");
18877 var Utils_1 = require("../Utils");
18878 var Component = (function (_super) {
18879     __extends(Component, _super);
18880     function Component(name, container, navigator) {
18881         _super.call(this);
18882         this._activated$ = new BehaviorSubject_1.BehaviorSubject(false);
18883         this._configurationSubject$ = new Subject_1.Subject();
18884         this._activated = false;
18885         this._container = container;
18886         this._name = name;
18887         this._navigator = navigator;
18888         this._configuration$ =
18889             this._configurationSubject$
18890                 .startWith(this.defaultConfiguration)
18891                 .scan(function (conf, newConf) {
18892                 for (var key in newConf) {
18893                     if (newConf.hasOwnProperty(key)) {
18894                         conf[key] = newConf[key];
18895                     }
18896                 }
18897                 return conf;
18898             })
18899                 .publishReplay(1)
18900                 .refCount();
18901         this._configuration$.subscribe();
18902     }
18903     Object.defineProperty(Component.prototype, "activated", {
18904         get: function () {
18905             return this._activated;
18906         },
18907         enumerable: true,
18908         configurable: true
18909     });
18910     Object.defineProperty(Component.prototype, "activated$", {
18911         get: function () {
18912             return this._activated$;
18913         },
18914         enumerable: true,
18915         configurable: true
18916     });
18917     Object.defineProperty(Component.prototype, "defaultConfiguration", {
18918         /**
18919          * Get default configuration.
18920          *
18921          * @returns {TConfiguration} Default configuration for component.
18922          */
18923         get: function () {
18924             return this._getDefaultConfiguration();
18925         },
18926         enumerable: true,
18927         configurable: true
18928     });
18929     Object.defineProperty(Component.prototype, "configuration$", {
18930         get: function () {
18931             return this._configuration$;
18932         },
18933         enumerable: true,
18934         configurable: true
18935     });
18936     Component.prototype.activate = function (conf) {
18937         if (this._activated) {
18938             return;
18939         }
18940         if (conf !== undefined) {
18941             this._configurationSubject$.next(conf);
18942         }
18943         this._activate();
18944         this._activated = true;
18945         this._activated$.next(true);
18946     };
18947     ;
18948     Component.prototype.configure = function (conf) {
18949         this._configurationSubject$.next(conf);
18950     };
18951     Component.prototype.deactivate = function () {
18952         if (!this._activated) {
18953             return;
18954         }
18955         this._deactivate();
18956         this._container.domRenderer.clear(this._name);
18957         this._container.glRenderer.clear(this._name);
18958         this._activated = false;
18959         this._activated$.next(false);
18960     };
18961     ;
18962     /**
18963      * Detect the viewer's new width and height and resize the component's
18964      * rendered elements accordingly if applicable.
18965      */
18966     Component.prototype.resize = function () { return; };
18967     /**
18968      * Component name. Used when interacting with component through the Viewer's API.
18969      */
18970     Component.componentName = "not_worthy";
18971     return Component;
18972 }(Utils_1.EventEmitter));
18973 exports.Component = Component;
18974 Object.defineProperty(exports, "__esModule", { value: true });
18975 exports.default = Component;
18976
18977 },{"../Utils":218,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/operator/publishReplay":68,"rxjs/add/operator/scan":69,"rxjs/add/operator/startWith":73}],227:[function(require,module,exports){
18978 /// <reference path="../../typings/index.d.ts" />
18979 "use strict";
18980 var _ = require("underscore");
18981 var Error_1 = require("../Error");
18982 var ComponentService = (function () {
18983     function ComponentService(container, navigator) {
18984         this._components = {};
18985         this._container = container;
18986         this._navigator = navigator;
18987         for (var _i = 0, _a = _.values(ComponentService.registeredComponents); _i < _a.length; _i++) {
18988             var component = _a[_i];
18989             this._components[component.componentName] = {
18990                 active: false,
18991                 component: new component(component.componentName, container, navigator),
18992             };
18993         }
18994         this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator);
18995         this._coverComponent.activate();
18996         this._coverActivated = true;
18997     }
18998     ComponentService.register = function (component) {
18999         if (ComponentService.registeredComponents[component.componentName] === undefined) {
19000             ComponentService.registeredComponents[component.componentName] = component;
19001         }
19002     };
19003     ComponentService.registerCover = function (coverComponent) {
19004         ComponentService.registeredCoverComponent = coverComponent;
19005     };
19006     ComponentService.prototype.activateCover = function () {
19007         if (this._coverActivated) {
19008             return;
19009         }
19010         this._coverActivated = true;
19011         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
19012             var component = _a[_i];
19013             if (component.active) {
19014                 component.component.deactivate();
19015             }
19016         }
19017         return;
19018     };
19019     ComponentService.prototype.deactivateCover = function () {
19020         if (!this._coverActivated) {
19021             return;
19022         }
19023         this._coverActivated = false;
19024         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
19025             var component = _a[_i];
19026             if (component.active) {
19027                 component.component.activate();
19028             }
19029         }
19030         return;
19031     };
19032     ComponentService.prototype.activate = function (name) {
19033         this._checkName(name);
19034         this._components[name].active = true;
19035         if (!this._coverActivated) {
19036             this.get(name).activate();
19037         }
19038     };
19039     ComponentService.prototype.configure = function (name, conf) {
19040         this._checkName(name);
19041         this.get(name).configure(conf);
19042     };
19043     ComponentService.prototype.deactivate = function (name) {
19044         this._checkName(name);
19045         this._components[name].active = false;
19046         if (!this._coverActivated) {
19047             this.get(name).deactivate();
19048         }
19049     };
19050     ComponentService.prototype.resize = function () {
19051         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
19052             var component = _a[_i];
19053             component.component.resize();
19054         }
19055     };
19056     ComponentService.prototype.get = function (name) {
19057         return this._components[name].component;
19058     };
19059     ComponentService.prototype.getCover = function () {
19060         return this._coverComponent;
19061     };
19062     ComponentService.prototype._checkName = function (name) {
19063         if (!(name in this._components)) {
19064             throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name);
19065         }
19066     };
19067     ComponentService.registeredComponents = {};
19068     return ComponentService;
19069 }());
19070 exports.ComponentService = ComponentService;
19071 Object.defineProperty(exports, "__esModule", { value: true });
19072 exports.default = ComponentService;
19073
19074 },{"../Error":212,"underscore":161}],228:[function(require,module,exports){
19075 /// <reference path="../../typings/index.d.ts" />
19076 "use strict";
19077 var __extends = (this && this.__extends) || function (d, b) {
19078     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19079     function __() { this.constructor = d; }
19080     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19081 };
19082 var vd = require("virtual-dom");
19083 require("rxjs/add/operator/filter");
19084 require("rxjs/add/operator/map");
19085 require("rxjs/add/operator/withLatestFrom");
19086 var Component_1 = require("../Component");
19087 var CoverComponent = (function (_super) {
19088     __extends(CoverComponent, _super);
19089     function CoverComponent(name, container, navigator) {
19090         _super.call(this, name, container, navigator);
19091     }
19092     CoverComponent.prototype._activate = function () {
19093         var _this = this;
19094         this._keyDisposable = this._navigator.stateService.currentNode$
19095             .withLatestFrom(this._configuration$, function (node, configuration) {
19096             return [node, configuration];
19097         })
19098             .filter(function (nc) {
19099             return nc[0].key !== nc[1].key;
19100         })
19101             .map(function (nc) { return nc[0]; })
19102             .map(function (node) {
19103             return { key: node.key, src: node.image.src };
19104         })
19105             .subscribe(this._configurationSubject$);
19106         this._disposable = this._configuration$
19107             .map(function (conf) {
19108             if (!conf.key) {
19109                 return { name: _this._name, vnode: vd.h("div", []) };
19110             }
19111             if (!conf.visible) {
19112                 return { name: _this._name, vnode: vd.h("div.Cover.CoverDone", [_this._getCoverBackgroundVNode(conf)]) };
19113             }
19114             return { name: _this._name, vnode: _this._getCoverButtonVNode(conf) };
19115         })
19116             .subscribe(this._container.domRenderer.render$);
19117     };
19118     CoverComponent.prototype._deactivate = function () {
19119         this._disposable.unsubscribe();
19120         this._keyDisposable.unsubscribe();
19121     };
19122     CoverComponent.prototype._getDefaultConfiguration = function () {
19123         return { "loading": false, "visible": true };
19124     };
19125     CoverComponent.prototype._getCoverButtonVNode = function (conf) {
19126         var _this = this;
19127         var cover = conf.loading ? "div.Cover.CoverLoading" : "div.Cover";
19128         return vd.h(cover, [
19129             this._getCoverBackgroundVNode(conf),
19130             vd.h("button.CoverButton", { onclick: function () { _this.configure({ loading: true }); } }, ["Explore"]),
19131             vd.h("a.CoverLogo", { href: "https://www.mapillary.com", target: "_blank" }, []),
19132         ]);
19133     };
19134     CoverComponent.prototype._getCoverBackgroundVNode = function (conf) {
19135         var url = conf.src != null ?
19136             "url(" + conf.src + ")" :
19137             "url(https://d1cuyjsrcm0gby.cloudfront.net/" + conf.key + "/thumb-640.jpg)";
19138         var properties = { style: { backgroundImage: url } };
19139         var children = [];
19140         if (conf.loading) {
19141             children.push(vd.h("div.Spinner", {}, []));
19142         }
19143         children.push(vd.h("div.CoverBackgroundGradient", {}, []));
19144         return vd.h("div.CoverBackground", properties, children);
19145     };
19146     CoverComponent.componentName = "cover";
19147     return CoverComponent;
19148 }(Component_1.Component));
19149 exports.CoverComponent = CoverComponent;
19150 Component_1.ComponentService.registerCover(CoverComponent);
19151 Object.defineProperty(exports, "__esModule", { value: true });
19152 exports.default = CoverComponent;
19153
19154 },{"../Component":210,"rxjs/add/operator/filter":57,"rxjs/add/operator/map":61,"rxjs/add/operator/withLatestFrom":77,"virtual-dom":166}],229:[function(require,module,exports){
19155 /// <reference path="../../typings/index.d.ts" />
19156 "use strict";
19157 var __extends = (this && this.__extends) || function (d, b) {
19158     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19159     function __() { this.constructor = d; }
19160     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19161 };
19162 var _ = require("underscore");
19163 var vd = require("virtual-dom");
19164 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
19165 require("rxjs/add/operator/combineLatest");
19166 var Component_1 = require("../Component");
19167 var DebugComponent = (function (_super) {
19168     __extends(DebugComponent, _super);
19169     function DebugComponent(name, container, navigator) {
19170         _super.call(this, name, container, navigator);
19171         this._open$ = new BehaviorSubject_1.BehaviorSubject(false);
19172         this._displaying = false;
19173     }
19174     DebugComponent.prototype._activate = function () {
19175         var _this = this;
19176         this._disposable = this._navigator.stateService.currentState$
19177             .combineLatest(this._open$, this._navigator.imageLoadingService.loadstatus$, function (frame, open, loadStatus) {
19178             return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) };
19179         })
19180             .subscribe(this._container.domRenderer.render$);
19181     };
19182     DebugComponent.prototype._deactivate = function () {
19183         this._disposable.unsubscribe();
19184     };
19185     DebugComponent.prototype._getDefaultConfiguration = function () {
19186         return {};
19187     };
19188     DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) {
19189         var ret = [];
19190         ret.push(vd.h("h2", "Node"));
19191         if (frame.state.currentNode) {
19192             ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key));
19193         }
19194         if (frame.state.previousNode) {
19195             ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key));
19196         }
19197         ret.push(vd.h("h2", "Loading"));
19198         var total = 0;
19199         var loaded = 0;
19200         var loading = 0;
19201         for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
19202             var loadStat = _a[_i];
19203             total += loadStat.loaded;
19204             if (loadStat.loaded !== loadStat.total) {
19205                 loading++;
19206             }
19207             else {
19208                 loaded++;
19209             }
19210         }
19211         ret.push(vd.h("p", "Loaded Images: " + loaded));
19212         ret.push(vd.h("p", "Loading Images: " + loading));
19213         ret.push(vd.h("p", "Total bytes loaded: " + total));
19214         ret.push(vd.h("h2", "Camera"));
19215         ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x));
19216         ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y));
19217         ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z));
19218         ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x));
19219         ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y));
19220         ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z));
19221         ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x));
19222         ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y));
19223         ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z));
19224         return ret;
19225     };
19226     DebugComponent.prototype._getDebugVNode = function (open, info) {
19227         if (open) {
19228             return vd.h("div.Debug", {}, [
19229                 vd.h("h2", {}, ["Debug"]),
19230                 this._getDebugVNodeButton(open),
19231                 vd.h("pre", {}, info),
19232             ]);
19233         }
19234         else {
19235             return this._getDebugVNodeButton(open);
19236         }
19237     };
19238     DebugComponent.prototype._getDebugVNodeButton = function (open) {
19239         var buttonText = open ? "Disable Debug" : "D";
19240         var buttonCssClass = open ? "" : ".DebugButtonFixed";
19241         if (open) {
19242             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]);
19243         }
19244         else {
19245             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]);
19246         }
19247     };
19248     DebugComponent.prototype._closeDebugElement = function (open) {
19249         this._open$.next(false);
19250     };
19251     DebugComponent.prototype._openDebugElement = function () {
19252         this._open$.next(true);
19253     };
19254     DebugComponent.componentName = "debug";
19255     return DebugComponent;
19256 }(Component_1.Component));
19257 exports.DebugComponent = DebugComponent;
19258 Component_1.ComponentService.register(DebugComponent);
19259 Object.defineProperty(exports, "__esModule", { value: true });
19260 exports.default = DebugComponent;
19261
19262 },{"../Component":210,"rxjs/BehaviorSubject":25,"rxjs/add/operator/combineLatest":50,"underscore":161,"virtual-dom":166}],230:[function(require,module,exports){
19263 /// <reference path="../../typings/index.d.ts" />
19264 "use strict";
19265 var __extends = (this && this.__extends) || function (d, b) {
19266     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19267     function __() { this.constructor = d; }
19268     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19269 };
19270 var vd = require("virtual-dom");
19271 require("rxjs/add/operator/combineLatest");
19272 var Component_1 = require("../Component");
19273 var ImageComponent = (function (_super) {
19274     __extends(ImageComponent, _super);
19275     function ImageComponent(name, container, navigator) {
19276         _super.call(this, name, container, navigator);
19277         this._canvasId = container.id + "-" + this._name;
19278     }
19279     ImageComponent.prototype._activate = function () {
19280         var _this = this;
19281         this.drawSubscription = this._container.domRenderer.element$
19282             .combineLatest(this._navigator.stateService.currentNode$, function (element, node) {
19283             var canvas = document.getElementById(_this._canvasId);
19284             return { canvas: canvas, node: node };
19285         })
19286             .subscribe(function (canvasNode) {
19287             var canvas = canvasNode.canvas;
19288             var node = canvasNode.node;
19289             if (!node || !canvas) {
19290                 return null;
19291             }
19292             var adaptableDomRenderer = canvas.parentElement;
19293             var width = adaptableDomRenderer.offsetWidth;
19294             var height = adaptableDomRenderer.offsetHeight;
19295             canvas.width = width;
19296             canvas.height = height;
19297             var ctx = canvas.getContext("2d");
19298             ctx.drawImage(node.image, 0, 0, width, height);
19299         });
19300         this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) });
19301     };
19302     ImageComponent.prototype._deactivate = function () {
19303         this.drawSubscription.unsubscribe();
19304     };
19305     ImageComponent.prototype._getDefaultConfiguration = function () {
19306         return {};
19307     };
19308     ImageComponent.componentName = "image";
19309     return ImageComponent;
19310 }(Component_1.Component));
19311 exports.ImageComponent = ImageComponent;
19312 Component_1.ComponentService.register(ImageComponent);
19313 Object.defineProperty(exports, "__esModule", { value: true });
19314 exports.default = ImageComponent;
19315
19316 },{"../Component":210,"rxjs/add/operator/combineLatest":50,"virtual-dom":166}],231:[function(require,module,exports){
19317 "use strict";
19318 var __extends = (this && this.__extends) || function (d, b) {
19319     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19320     function __() { this.constructor = d; }
19321     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19322 };
19323 var Observable_1 = require("rxjs/Observable");
19324 require("rxjs/add/observable/fromEvent");
19325 require("rxjs/add/operator/withLatestFrom");
19326 var Edge_1 = require("../Edge");
19327 var Component_1 = require("../Component");
19328 var Geo_1 = require("../Geo");
19329 var KeyboardComponent = (function (_super) {
19330     __extends(KeyboardComponent, _super);
19331     function KeyboardComponent(name, container, navigator) {
19332         _super.call(this, name, container, navigator);
19333         this._spatial = new Geo_1.Spatial();
19334         this._perspectiveDirections = [
19335             Edge_1.EdgeDirection.StepForward,
19336             Edge_1.EdgeDirection.StepBackward,
19337             Edge_1.EdgeDirection.StepLeft,
19338             Edge_1.EdgeDirection.StepRight,
19339             Edge_1.EdgeDirection.TurnLeft,
19340             Edge_1.EdgeDirection.TurnRight,
19341             Edge_1.EdgeDirection.TurnU,
19342         ];
19343     }
19344     KeyboardComponent.prototype._activate = function () {
19345         var _this = this;
19346         var sequenceEdges$ = this._navigator.stateService.currentNode$
19347             .switchMap(function (node) {
19348             return node.sequenceEdges$;
19349         });
19350         var spatialEdges$ = this._navigator.stateService.currentNode$
19351             .switchMap(function (node) {
19352             return node.spatialEdges$;
19353         });
19354         this._disposable = Observable_1.Observable
19355             .fromEvent(document, "keydown")
19356             .withLatestFrom(this._navigator.stateService.currentState$, sequenceEdges$, spatialEdges$, function (event, frame, sequenceEdges, spatialEdges) {
19357             return { event: event, frame: frame, sequenceEdges: sequenceEdges, spatialEdges: spatialEdges };
19358         })
19359             .subscribe(function (kf) {
19360             if (!kf.frame.state.currentNode.pano) {
19361                 _this._navigatePerspective(kf.event, kf.sequenceEdges, kf.spatialEdges);
19362             }
19363             else {
19364                 _this._navigatePanorama(kf.event, kf.sequenceEdges, kf.spatialEdges, kf.frame.state.camera);
19365             }
19366         });
19367     };
19368     KeyboardComponent.prototype._deactivate = function () {
19369         this._disposable.unsubscribe();
19370     };
19371     KeyboardComponent.prototype._getDefaultConfiguration = function () {
19372         return {};
19373     };
19374     KeyboardComponent.prototype._navigatePanorama = function (event, sequenceEdges, spatialEdges, camera) {
19375         var navigationAngle = 0;
19376         var stepDirection = null;
19377         var sequenceDirection = null;
19378         var phi = this._rotationFromCamera(camera).phi;
19379         switch (event.keyCode) {
19380             case 37:
19381                 if (event.shiftKey || event.altKey) {
19382                     break;
19383                 }
19384                 navigationAngle = Math.PI / 2 + phi;
19385                 stepDirection = Edge_1.EdgeDirection.StepLeft;
19386                 break;
19387             case 38:
19388                 if (event.shiftKey) {
19389                     break;
19390                 }
19391                 if (event.altKey) {
19392                     sequenceDirection = Edge_1.EdgeDirection.Next;
19393                     break;
19394                 }
19395                 navigationAngle = phi;
19396                 stepDirection = Edge_1.EdgeDirection.StepForward;
19397                 break;
19398             case 39:
19399                 if (event.shiftKey || event.altKey) {
19400                     break;
19401                 }
19402                 navigationAngle = -Math.PI / 2 + phi;
19403                 stepDirection = Edge_1.EdgeDirection.StepRight;
19404                 break;
19405             case 40:
19406                 if (event.shiftKey) {
19407                     break;
19408                 }
19409                 if (event.altKey) {
19410                     sequenceDirection = Edge_1.EdgeDirection.Prev;
19411                     break;
19412                 }
19413                 navigationAngle = Math.PI + phi;
19414                 stepDirection = Edge_1.EdgeDirection.StepBackward;
19415                 break;
19416             default:
19417                 return;
19418         }
19419         event.preventDefault();
19420         if (sequenceDirection != null) {
19421             this._moveInDir(sequenceDirection, sequenceEdges);
19422             return;
19423         }
19424         if (stepDirection == null || !spatialEdges.cached) {
19425             return;
19426         }
19427         navigationAngle = this._spatial.wrapAngle(navigationAngle);
19428         var threshold = Math.PI / 4;
19429         var edges = spatialEdges.edges.filter(function (e) {
19430             return e.data.direction === Edge_1.EdgeDirection.Pano ||
19431                 e.data.direction === stepDirection;
19432         });
19433         var smallestAngle = Number.MAX_VALUE;
19434         var toKey = null;
19435         for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
19436             var edge = edges_1[_i];
19437             var angle = Math.abs(this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle));
19438             if (angle < Math.min(smallestAngle, threshold)) {
19439                 smallestAngle = angle;
19440                 toKey = edge.to;
19441             }
19442         }
19443         if (toKey == null) {
19444             return;
19445         }
19446         this._navigator.moveToKey$(toKey)
19447             .subscribe(function (n) { return; }, function (e) { console.error(e); });
19448     };
19449     KeyboardComponent.prototype._rotationFromCamera = function (camera) {
19450         var direction = camera.lookat.clone().sub(camera.position);
19451         var upProjection = direction.clone().dot(camera.up);
19452         var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection));
19453         var phi = Math.atan2(planeProjection.y, planeProjection.x);
19454         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
19455         return { phi: phi, theta: theta };
19456     };
19457     KeyboardComponent.prototype._navigatePerspective = function (event, sequenceEdges, spatialEdges) {
19458         var direction = null;
19459         var sequenceDirection = null;
19460         switch (event.keyCode) {
19461             case 37:
19462                 if (event.altKey) {
19463                     break;
19464                 }
19465                 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft;
19466                 break;
19467             case 38:
19468                 if (event.altKey) {
19469                     sequenceDirection = Edge_1.EdgeDirection.Next;
19470                     break;
19471                 }
19472                 direction = event.shiftKey ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward;
19473                 break;
19474             case 39:
19475                 if (event.altKey) {
19476                     break;
19477                 }
19478                 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight;
19479                 break;
19480             case 40:
19481                 if (event.altKey) {
19482                     sequenceDirection = Edge_1.EdgeDirection.Prev;
19483                     break;
19484                 }
19485                 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward;
19486                 break;
19487             default:
19488                 return;
19489         }
19490         event.preventDefault();
19491         if (sequenceDirection != null) {
19492             this._moveInDir(sequenceDirection, sequenceEdges);
19493             return;
19494         }
19495         this._moveInDir(direction, spatialEdges);
19496     };
19497     KeyboardComponent.prototype._moveInDir = function (direction, edgeStatus) {
19498         if (!edgeStatus.cached) {
19499             return;
19500         }
19501         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
19502             var edge = _a[_i];
19503             if (edge.data.direction === direction) {
19504                 this._navigator.moveToKey$(edge.to)
19505                     .subscribe(function (n) { return; }, function (e) { console.error(e); });
19506                 return;
19507             }
19508         }
19509     };
19510     KeyboardComponent.componentName = "keyboard";
19511     return KeyboardComponent;
19512 }(Component_1.Component));
19513 exports.KeyboardComponent = KeyboardComponent;
19514 Component_1.ComponentService.register(KeyboardComponent);
19515 Object.defineProperty(exports, "__esModule", { value: true });
19516 exports.default = KeyboardComponent;
19517
19518 },{"../Component":210,"../Edge":211,"../Geo":213,"rxjs/Observable":28,"rxjs/add/observable/fromEvent":41,"rxjs/add/operator/withLatestFrom":77}],232:[function(require,module,exports){
19519 /// <reference path="../../typings/index.d.ts" />
19520 "use strict";
19521 var __extends = (this && this.__extends) || function (d, b) {
19522     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19523     function __() { this.constructor = d; }
19524     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19525 };
19526 var _ = require("underscore");
19527 var vd = require("virtual-dom");
19528 require("rxjs/add/operator/combineLatest");
19529 var Component_1 = require("../Component");
19530 var LoadingComponent = (function (_super) {
19531     __extends(LoadingComponent, _super);
19532     function LoadingComponent(name, container, navigator) {
19533         _super.call(this, name, container, navigator);
19534     }
19535     LoadingComponent.prototype._activate = function () {
19536         var _this = this;
19537         this._loadingSubscription = this._navigator.loadingService.loading$
19538             .combineLatest(this._navigator.imageLoadingService.loadstatus$, function (loading, loadStatus) {
19539             if (!loading) {
19540                 return { name: "loading", vnode: _this._getBarVNode(100) };
19541             }
19542             var total = 0;
19543             var loaded = 0;
19544             for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
19545                 var loadStat = _a[_i];
19546                 if (loadStat.loaded !== loadStat.total) {
19547                     loaded += loadStat.loaded;
19548                     total += loadStat.total;
19549                 }
19550             }
19551             var percentage = 100;
19552             if (total !== 0) {
19553                 percentage = (loaded / total) * 100;
19554             }
19555             return { name: _this._name, vnode: _this._getBarVNode(percentage) };
19556         })
19557             .subscribe(this._container.domRenderer.render$);
19558     };
19559     LoadingComponent.prototype._deactivate = function () {
19560         this._loadingSubscription.unsubscribe();
19561     };
19562     LoadingComponent.prototype._getDefaultConfiguration = function () {
19563         return {};
19564     };
19565     LoadingComponent.prototype._getBarVNode = function (percentage) {
19566         var loadingBarStyle = {};
19567         var loadingContainerStyle = {};
19568         if (percentage !== 100) {
19569             loadingBarStyle.width = percentage.toFixed(0) + "%";
19570             loadingBarStyle.opacity = "1";
19571         }
19572         else {
19573             loadingBarStyle.width = "100%";
19574             loadingBarStyle.opacity = "0";
19575         }
19576         return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]);
19577     };
19578     LoadingComponent.componentName = "loading";
19579     return LoadingComponent;
19580 }(Component_1.Component));
19581 exports.LoadingComponent = LoadingComponent;
19582 Component_1.ComponentService.register(LoadingComponent);
19583 Object.defineProperty(exports, "__esModule", { value: true });
19584 exports.default = LoadingComponent;
19585
19586 },{"../Component":210,"rxjs/add/operator/combineLatest":50,"underscore":161,"virtual-dom":166}],233:[function(require,module,exports){
19587 /// <reference path="../../typings/index.d.ts" />
19588 "use strict";
19589 var __extends = (this && this.__extends) || function (d, b) {
19590     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19591     function __() { this.constructor = d; }
19592     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19593 };
19594 var THREE = require("three");
19595 var vd = require("virtual-dom");
19596 var Observable_1 = require("rxjs/Observable");
19597 require("rxjs/add/observable/merge");
19598 require("rxjs/add/operator/filter");
19599 require("rxjs/add/operator/map");
19600 require("rxjs/add/operator/withLatestFrom");
19601 var Component_1 = require("../Component");
19602 var Geo_1 = require("../Geo");
19603 /**
19604  * @class MouseComponent
19605  * @classdesc Component handling mouse and touch events for camera movement.
19606  */
19607 var MouseComponent = (function (_super) {
19608     __extends(MouseComponent, _super);
19609     function MouseComponent(name, container, navigator) {
19610         _super.call(this, name, container, navigator);
19611         this._spatial = new Geo_1.Spatial();
19612     }
19613     MouseComponent.prototype._activate = function () {
19614         var _this = this;
19615         var draggingStarted$ = this._container.mouseService
19616             .filtered$(this._name, this._container.mouseService.mouseDragStart$)
19617             .map(function (event) {
19618             return true;
19619         });
19620         var draggingStopped$ = this._container.mouseService
19621             .filtered$(this._name, this._container.mouseService.mouseDragEnd$)
19622             .map(function (event) {
19623             return false;
19624         });
19625         var dragging$ = Observable_1.Observable
19626             .merge(draggingStarted$, draggingStopped$)
19627             .startWith(false)
19628             .share();
19629         this._activeSubscription = dragging$
19630             .subscribe(this._container.mouseService.activate$);
19631         this._cursorSubscription = dragging$
19632             .map(function (dragging) {
19633             var className = dragging ? "MouseContainerGrabbing" : "MouseContainerGrab";
19634             var vNode = vd.h("div." + className, {}, []);
19635             return { name: _this._name, vnode: vNode };
19636         })
19637             .subscribe(this._container.domRenderer.render$);
19638         var mouseMovement$ = this._container.mouseService
19639             .filtered$(this._name, this._container.mouseService.mouseDrag$)
19640             .map(function (e) {
19641             return {
19642                 clientX: e.clientX,
19643                 clientY: e.clientY,
19644                 movementX: e.movementX,
19645                 movementY: e.movementY,
19646             };
19647         });
19648         var touchMovement$ = this._container.touchService.singleTouchMove$
19649             .map(function (touch) {
19650             return {
19651                 clientX: touch.clientX,
19652                 clientY: touch.clientY,
19653                 movementX: touch.movementX,
19654                 movementY: touch.movementY,
19655             };
19656         });
19657         this._movementSubscription = Observable_1.Observable
19658             .merge(mouseMovement$, touchMovement$)
19659             .withLatestFrom(this._navigator.stateService.currentState$, function (m, f) {
19660             return [m, f];
19661         })
19662             .filter(function (args) {
19663             var state = args[1].state;
19664             return state.currentNode.fullPano || state.nodesAhead < 1;
19665         })
19666             .map(function (args) {
19667             return args[0];
19668         })
19669             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.stateService.currentCamera$, function (m, r, t, c) {
19670             return [m, r, t, c];
19671         })
19672             .map(function (args) {
19673             var movement = args[0];
19674             var render = args[1];
19675             var transform = args[2];
19676             var camera = args[3].clone();
19677             var element = _this._container.element;
19678             var offsetWidth = element.offsetWidth;
19679             var offsetHeight = element.offsetHeight;
19680             var clientRect = element.getBoundingClientRect();
19681             var canvasX = movement.clientX - clientRect.left;
19682             var canvasY = movement.clientY - clientRect.top;
19683             var currentDirection = _this._unproject(canvasX, canvasY, offsetWidth, offsetHeight, render.perspective)
19684                 .sub(render.perspective.position);
19685             var directionX = _this._unproject(canvasX - movement.movementX, canvasY, offsetWidth, offsetHeight, render.perspective)
19686                 .sub(render.perspective.position);
19687             var directionY = _this._unproject(canvasX, canvasY - movement.movementY, offsetWidth, offsetHeight, render.perspective)
19688                 .sub(render.perspective.position);
19689             var deltaPhi = (movement.movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection);
19690             var deltaTheta = (movement.movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection);
19691             var upQuaternion = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
19692             var upQuaternionInverse = upQuaternion.clone().inverse();
19693             var offset = new THREE.Vector3();
19694             offset.copy(camera.lookat).sub(camera.position);
19695             offset.applyQuaternion(upQuaternion);
19696             var length = offset.length();
19697             var phi = Math.atan2(offset.y, offset.x);
19698             phi += deltaPhi;
19699             var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
19700             theta += deltaTheta;
19701             theta = Math.max(0.01, Math.min(Math.PI - 0.01, theta));
19702             offset.x = Math.sin(theta) * Math.cos(phi);
19703             offset.y = Math.sin(theta) * Math.sin(phi);
19704             offset.z = Math.cos(theta);
19705             offset.applyQuaternion(upQuaternionInverse);
19706             var lookat = new THREE.Vector3().copy(camera.position).add(offset.multiplyScalar(length));
19707             var basic = transform.projectBasic(lookat.toArray());
19708             var original = transform.projectBasic(camera.lookat.toArray());
19709             var x = basic[0] - original[0];
19710             var y = basic[1] - original[1];
19711             if (Math.abs(x) > 1) {
19712                 x = 0;
19713             }
19714             else if (x > 0.5) {
19715                 x = x - 1;
19716             }
19717             else if (x < -0.5) {
19718                 x = x + 1;
19719             }
19720             return [x, y];
19721         })
19722             .subscribe(function (basicRotation) {
19723             _this._navigator.stateService.rotateBasic(basicRotation);
19724         });
19725         this._mouseWheelSubscription = this._container.mouseService
19726             .filtered$(this._name, this._container.mouseService.mouseWheel$)
19727             .withLatestFrom(this._navigator.stateService.currentState$, function (w, f) {
19728             return [w, f];
19729         })
19730             .filter(function (args) {
19731             var state = args[1].state;
19732             return state.currentNode.fullPano || state.nodesAhead < 1;
19733         })
19734             .map(function (args) {
19735             return args[0];
19736         })
19737             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) {
19738             return [w, r, t];
19739         })
19740             .subscribe(function (args) {
19741             var event = args[0];
19742             var render = args[1];
19743             var transform = args[2];
19744             var element = _this._container.element;
19745             var offsetWidth = element.offsetWidth;
19746             var offsetHeight = element.offsetHeight;
19747             var clientRect = element.getBoundingClientRect();
19748             var canvasX = event.clientX - clientRect.left;
19749             var canvasY = event.clientY - clientRect.top;
19750             var unprojected = _this._unproject(canvasX, canvasY, offsetWidth, offsetHeight, render.perspective);
19751             var reference = transform.projectBasic(unprojected.toArray());
19752             var deltaY = event.deltaY;
19753             if (event.deltaMode === 1) {
19754                 deltaY = 40 * deltaY;
19755             }
19756             else if (event.deltaMode === 2) {
19757                 deltaY = 800 * deltaY;
19758             }
19759             var zoom = -3 * deltaY / offsetHeight;
19760             _this._navigator.stateService.zoomIn(zoom, reference);
19761         });
19762         this._pinchSubscription = this._container.touchService.pinch$
19763             .withLatestFrom(this._navigator.stateService.currentState$, function (p, f) {
19764             return [p, f];
19765         })
19766             .filter(function (args) {
19767             var state = args[1].state;
19768             return state.currentNode.fullPano || state.nodesAhead < 1;
19769         })
19770             .map(function (args) {
19771             return args[0];
19772         })
19773             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (p, r, t) {
19774             return [p, r, t];
19775         })
19776             .subscribe(function (args) {
19777             var pinch = args[0];
19778             var render = args[1];
19779             var transform = args[2];
19780             var element = _this._container.element;
19781             var offsetWidth = element.offsetWidth;
19782             var offsetHeight = element.offsetHeight;
19783             var clientRect = element.getBoundingClientRect();
19784             var unprojected = _this._unproject(pinch.centerClientX - clientRect.left, pinch.centerClientY - clientRect.top, offsetWidth, offsetHeight, render.perspective);
19785             var reference = transform.projectBasic(unprojected.toArray());
19786             var zoom = 3 * pinch.distanceChange / Math.min(offsetHeight, offsetWidth);
19787             _this._navigator.stateService.zoomIn(zoom, reference);
19788         });
19789         this._container.mouseService.claimMouse(this._name, 0);
19790     };
19791     MouseComponent.prototype._deactivate = function () {
19792         this._container.mouseService.unclaimMouse(this._name);
19793         this._activeSubscription.unsubscribe();
19794         this._cursorSubscription.unsubscribe();
19795         this._movementSubscription.unsubscribe();
19796         this._mouseWheelSubscription.unsubscribe();
19797         this._pinchSubscription.unsubscribe();
19798     };
19799     MouseComponent.prototype._getDefaultConfiguration = function () {
19800         return {};
19801     };
19802     MouseComponent.prototype._unproject = function (canvasX, canvasY, offsetWidth, offsetHeight, perspectiveCamera) {
19803         var projectedX = 2 * canvasX / offsetWidth - 1;
19804         var projectedY = 1 - 2 * canvasY / offsetHeight;
19805         return new THREE.Vector3(projectedX, projectedY, 1).unproject(perspectiveCamera);
19806     };
19807     /** @inheritdoc */
19808     MouseComponent.componentName = "mouse";
19809     return MouseComponent;
19810 }(Component_1.Component));
19811 exports.MouseComponent = MouseComponent;
19812 Component_1.ComponentService.register(MouseComponent);
19813 Object.defineProperty(exports, "__esModule", { value: true });
19814 exports.default = MouseComponent;
19815
19816 },{"../Component":210,"../Geo":213,"rxjs/Observable":28,"rxjs/add/observable/merge":43,"rxjs/add/operator/filter":57,"rxjs/add/operator/map":61,"rxjs/add/operator/withLatestFrom":77,"three":160,"virtual-dom":166}],234:[function(require,module,exports){
19817 /// <reference path="../../typings/index.d.ts" />
19818 "use strict";
19819 var __extends = (this && this.__extends) || function (d, b) {
19820     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19821     function __() { this.constructor = d; }
19822     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19823 };
19824 var vd = require("virtual-dom");
19825 var Observable_1 = require("rxjs/Observable");
19826 require("rxjs/add/operator/map");
19827 require("rxjs/add/operator/first");
19828 var Edge_1 = require("../Edge");
19829 var Component_1 = require("../Component");
19830 var NavigationComponent = (function (_super) {
19831     __extends(NavigationComponent, _super);
19832     function NavigationComponent(name, container, navigator) {
19833         _super.call(this, name, container, navigator);
19834         this._dirNames = {};
19835         this._dirNames[Edge_1.EdgeDirection.StepForward] = "Forward";
19836         this._dirNames[Edge_1.EdgeDirection.StepBackward] = "Backward";
19837         this._dirNames[Edge_1.EdgeDirection.StepLeft] = "Left";
19838         this._dirNames[Edge_1.EdgeDirection.StepRight] = "Right";
19839         this._dirNames[Edge_1.EdgeDirection.TurnLeft] = "Turnleft";
19840         this._dirNames[Edge_1.EdgeDirection.TurnRight] = "Turnright";
19841         this._dirNames[Edge_1.EdgeDirection.TurnU] = "Turnaround";
19842     }
19843     NavigationComponent.prototype._activate = function () {
19844         var _this = this;
19845         this._renderSubscription = this._navigator.stateService.currentNode$
19846             .switchMap(function (node) {
19847             return node.pano ?
19848                 Observable_1.Observable.of([]) :
19849                 Observable_1.Observable.combineLatest(node.sequenceEdges$, node.spatialEdges$, function (seq, spa) {
19850                     return seq.edges.concat(spa.edges);
19851                 });
19852         })
19853             .map(function (edges) {
19854             var btns = [];
19855             for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
19856                 var edge = edges_1[_i];
19857                 var direction = edge.data.direction;
19858                 var name_1 = _this._dirNames[direction];
19859                 if (name_1 == null) {
19860                     continue;
19861                 }
19862                 btns.push(_this._createVNode(direction, name_1));
19863             }
19864             return { name: _this._name, vnode: vd.h("div.NavigationComponent", btns) };
19865         })
19866             .subscribe(this._container.domRenderer.render$);
19867     };
19868     NavigationComponent.prototype._deactivate = function () {
19869         this._renderSubscription.unsubscribe();
19870     };
19871     NavigationComponent.prototype._getDefaultConfiguration = function () {
19872         return {};
19873     };
19874     NavigationComponent.prototype._createVNode = function (direction, name) {
19875         var _this = this;
19876         return vd.h("span.Direction.Direction" + name, {
19877             onclick: function (ev) {
19878                 _this._navigator.moveDir$(direction)
19879                     .subscribe(function (node) { return; }, function (error) { console.error(error); });
19880             },
19881         }, []);
19882     };
19883     NavigationComponent.componentName = "navigation";
19884     return NavigationComponent;
19885 }(Component_1.Component));
19886 exports.NavigationComponent = NavigationComponent;
19887 Component_1.ComponentService.register(NavigationComponent);
19888 Object.defineProperty(exports, "__esModule", { value: true });
19889 exports.default = NavigationComponent;
19890
19891 },{"../Component":210,"../Edge":211,"rxjs/Observable":28,"rxjs/add/operator/first":59,"rxjs/add/operator/map":61,"virtual-dom":166}],235:[function(require,module,exports){
19892 /// <reference path="../../typings/index.d.ts" />
19893 "use strict";
19894 var __extends = (this && this.__extends) || function (d, b) {
19895     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
19896     function __() { this.constructor = d; }
19897     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19898 };
19899 var _ = require("underscore");
19900 var vd = require("virtual-dom");
19901 var Observable_1 = require("rxjs/Observable");
19902 require("rxjs/add/observable/fromPromise");
19903 require("rxjs/add/observable/of");
19904 require("rxjs/add/operator/combineLatest");
19905 require("rxjs/add/operator/distinct");
19906 require("rxjs/add/operator/distinctUntilChanged");
19907 require("rxjs/add/operator/filter");
19908 require("rxjs/add/operator/map");
19909 require("rxjs/add/operator/mergeMap");
19910 require("rxjs/add/operator/pluck");
19911 require("rxjs/add/operator/scan");
19912 var Component_1 = require("../Component");
19913 var DescriptionState = (function () {
19914     function DescriptionState() {
19915     }
19916     return DescriptionState;
19917 }());
19918 var RouteState = (function () {
19919     function RouteState() {
19920     }
19921     return RouteState;
19922 }());
19923 var RouteTrack = (function () {
19924     function RouteTrack() {
19925         this.nodeInstructions = [];
19926         this.nodeInstructionsOrdered = [];
19927     }
19928     return RouteTrack;
19929 }());
19930 var RouteComponent = (function (_super) {
19931     __extends(RouteComponent, _super);
19932     function RouteComponent(name, container, navigator) {
19933         _super.call(this, name, container, navigator);
19934     }
19935     RouteComponent.prototype._activate = function () {
19936         var _this = this;
19937         var _slowedStream$;
19938         _slowedStream$ = this._navigator.stateService.currentState$.filter(function (frame) {
19939             return (frame.id % 2) === 0;
19940         }).filter(function (frame) {
19941             return frame.state.nodesAhead < 15;
19942         }).distinctUntilChanged(undefined, function (frame) {
19943             return frame.state.lastNode.key;
19944         });
19945         var _routeTrack$;
19946         _routeTrack$ = this.configuration$.mergeMap(function (conf) {
19947             return Observable_1.Observable.from(conf.paths);
19948         }).distinct(function (p1, p2) {
19949             return p1.sequenceKey === p2.sequenceKey;
19950         }).mergeMap(function (path) {
19951             return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey])
19952                 .map(function (sequenceByKey) {
19953                 return sequenceByKey[path.sequenceKey];
19954             });
19955         }).combineLatest(this.configuration$, function (sequence, conf) {
19956             var i = 0;
19957             var instructionPlaces = [];
19958             for (var _i = 0, _a = conf.paths; _i < _a.length; _i++) {
19959                 var path = _a[_i];
19960                 if (path.sequenceKey === sequence.key) {
19961                     var nodeInstructions = [];
19962                     var saveKey = false;
19963                     for (var _b = 0, _c = sequence.keys; _b < _c.length; _b++) {
19964                         var key = _c[_b];
19965                         if (path.startKey === key) {
19966                             saveKey = true;
19967                         }
19968                         if (saveKey) {
19969                             var description = null;
19970                             for (var _d = 0, _e = path.infoKeys; _d < _e.length; _d++) {
19971                                 var infoKey = _e[_d];
19972                                 if (infoKey.key === key) {
19973                                     description = infoKey.description;
19974                                 }
19975                             }
19976                             nodeInstructions.push({ description: description, key: key });
19977                         }
19978                         if (path.stopKey === key) {
19979                             saveKey = false;
19980                         }
19981                     }
19982                     instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i });
19983                 }
19984                 i++;
19985             }
19986             return instructionPlaces;
19987         }).scan(function (routeTrack, instructionPlaces) {
19988             for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) {
19989                 var instructionPlace = instructionPlaces_1[_i];
19990                 routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions;
19991             }
19992             routeTrack.nodeInstructions = _.flatten(routeTrack.nodeInstructionsOrdered);
19993             return routeTrack;
19994         }, new RouteTrack());
19995         this._disposable = _slowedStream$
19996             .combineLatest(_routeTrack$, this.configuration$, function (frame, routeTrack, conf) {
19997             return { conf: conf, frame: frame, routeTrack: routeTrack };
19998         }).scan(function (routeState, rtAndFrame) {
19999             if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) {
20000                 routeState.routeTrack = rtAndFrame.routeTrack;
20001                 routeState.currentNode = rtAndFrame.frame.state.currentNode;
20002                 routeState.lastNode = rtAndFrame.frame.state.lastNode;
20003                 routeState.playing = true;
20004             }
20005             else {
20006                 _this._navigator.stateService.cutNodes();
20007                 routeState.playing = false;
20008             }
20009             return routeState;
20010         }, new RouteState())
20011             .filter(function (routeState) {
20012             return routeState.playing;
20013         }).filter(function (routeState) {
20014             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
20015                 var nodeInstruction = _a[_i];
20016                 if (!nodeInstruction) {
20017                     continue;
20018                 }
20019                 if (nodeInstruction.key === routeState.lastNode.key) {
20020                     return true;
20021                 }
20022             }
20023             return false;
20024         }).distinctUntilChanged(undefined, function (routeState) {
20025             return routeState.lastNode.key;
20026         }).mergeMap(function (routeState) {
20027             var i = 0;
20028             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
20029                 var nodeInstruction = _a[_i];
20030                 if (nodeInstruction.key === routeState.lastNode.key) {
20031                     break;
20032                 }
20033                 i++;
20034             }
20035             var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1];
20036             if (!nextInstruction) {
20037                 return Observable_1.Observable.of(null);
20038             }
20039             return _this._navigator.graphService.cacheNode$(nextInstruction.key);
20040         }).combineLatest(this.configuration$, function (node, conf) {
20041             return { conf: conf, node: node };
20042         }).filter(function (cAN) {
20043             return cAN.node !== null && cAN.conf.playing;
20044         }).pluck("node").subscribe(this._navigator.stateService.appendNode$);
20045         this._disposableDescription = this._navigator.stateService.currentNode$
20046             .combineLatest(_routeTrack$, this.configuration$, function (node, routeTrack, conf) {
20047             if (conf.playing !== undefined && !conf.playing) {
20048                 return "quit";
20049             }
20050             var description = null;
20051             for (var _i = 0, _a = routeTrack.nodeInstructions; _i < _a.length; _i++) {
20052                 var nodeInstruction = _a[_i];
20053                 if (nodeInstruction.key === node.key) {
20054                     description = nodeInstruction.description;
20055                     break;
20056                 }
20057             }
20058             return description;
20059         }).scan(function (descriptionState, description) {
20060             if (description !== descriptionState.description && description !== null) {
20061                 descriptionState.description = description;
20062                 descriptionState.showsLeft = 6;
20063             }
20064             else {
20065                 descriptionState.showsLeft--;
20066             }
20067             if (description === "quit") {
20068                 descriptionState.description = null;
20069             }
20070             return descriptionState;
20071         }, new DescriptionState()).map(function (descriptionState) {
20072             if (descriptionState.showsLeft > 0 && descriptionState.description) {
20073                 return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) };
20074             }
20075             else {
20076                 return { name: _this._name, vnode: vd.h("div", []) };
20077             }
20078         }).subscribe(this._container.domRenderer.render$);
20079     };
20080     RouteComponent.prototype._deactivate = function () {
20081         this._disposable.unsubscribe();
20082         this._disposableDescription.unsubscribe();
20083     };
20084     RouteComponent.prototype._getDefaultConfiguration = function () {
20085         return {};
20086     };
20087     RouteComponent.prototype.play = function () {
20088         this.configure({ playing: true });
20089     };
20090     RouteComponent.prototype.stop = function () {
20091         this.configure({ playing: false });
20092     };
20093     RouteComponent.prototype._getRouteAnnotationNode = function (description) {
20094         return vd.h("div.RouteFrame", {}, [
20095             vd.h("p", { textContent: description }, []),
20096         ]);
20097     };
20098     RouteComponent.componentName = "route";
20099     return RouteComponent;
20100 }(Component_1.Component));
20101 exports.RouteComponent = RouteComponent;
20102 Component_1.ComponentService.register(RouteComponent);
20103 Object.defineProperty(exports, "__esModule", { value: true });
20104 exports.default = RouteComponent;
20105
20106 },{"../Component":210,"rxjs/Observable":28,"rxjs/add/observable/fromPromise":42,"rxjs/add/observable/of":44,"rxjs/add/operator/combineLatest":50,"rxjs/add/operator/distinct":53,"rxjs/add/operator/distinctUntilChanged":54,"rxjs/add/operator/filter":57,"rxjs/add/operator/map":61,"rxjs/add/operator/mergeMap":64,"rxjs/add/operator/pluck":66,"rxjs/add/operator/scan":69,"underscore":161,"virtual-dom":166}],236:[function(require,module,exports){
20107 "use strict";
20108 var __extends = (this && this.__extends) || function (d, b) {
20109     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20110     function __() { this.constructor = d; }
20111     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20112 };
20113 var Observable_1 = require("rxjs/Observable");
20114 require("rxjs/add/operator/buffer");
20115 require("rxjs/add/operator/debounceTime");
20116 require("rxjs/add/operator/filter");
20117 require("rxjs/add/operator/map");
20118 require("rxjs/add/operator/scan");
20119 var Component_1 = require("../Component");
20120 var StatsComponent = (function (_super) {
20121     __extends(StatsComponent, _super);
20122     function StatsComponent(name, container, navigator) {
20123         _super.call(this, name, container, navigator);
20124     }
20125     StatsComponent.prototype._activate = function () {
20126         var _this = this;
20127         this._sequenceSubscription = this._navigator.stateService.currentNode$
20128             .scan(function (keys, node) {
20129             var sKey = node.sequenceKey;
20130             keys.report = [];
20131             if (!(sKey in keys.reported)) {
20132                 keys.report = [sKey];
20133                 keys.reported[sKey] = true;
20134             }
20135             return keys;
20136         }, { report: [], reported: {} })
20137             .filter(function (keys) {
20138             return keys.report.length > 0;
20139         })
20140             .mergeMap(function (keys) {
20141             return _this._navigator.apiV3.sequenceViewAdd$(keys.report)
20142                 .catch(function (error, caught) {
20143                 console.error("Failed to report sequence stats (" + keys.report + ")", error);
20144                 return Observable_1.Observable.empty();
20145             });
20146         })
20147             .subscribe();
20148         this._imageSubscription = this._navigator.stateService.currentNode$
20149             .map(function (node) {
20150             return node.key;
20151         })
20152             .buffer(this._navigator.stateService.currentNode$.debounceTime(5000))
20153             .scan(function (keys, newKeys) {
20154             keys.report = [];
20155             for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
20156                 var key = newKeys_1[_i];
20157                 if (!(key in keys.reported)) {
20158                     keys.report.push(key);
20159                     keys.reported[key] = true;
20160                 }
20161             }
20162             return keys;
20163         }, { report: [], reported: {} })
20164             .filter(function (keys) {
20165             return keys.report.length > 0;
20166         })
20167             .mergeMap(function (keys) {
20168             return _this._navigator.apiV3.imageViewAdd$(keys.report)
20169                 .catch(function (error, caught) {
20170                 console.error("Failed to report image stats (" + keys.report + ")", error);
20171                 return Observable_1.Observable.empty();
20172             });
20173         })
20174             .subscribe();
20175     };
20176     StatsComponent.prototype._deactivate = function () {
20177         this._sequenceSubscription.unsubscribe();
20178         this._imageSubscription.unsubscribe();
20179     };
20180     StatsComponent.prototype._getDefaultConfiguration = function () {
20181         return {};
20182     };
20183     StatsComponent.componentName = "stats";
20184     return StatsComponent;
20185 }(Component_1.Component));
20186 exports.StatsComponent = StatsComponent;
20187 Component_1.ComponentService.register(StatsComponent);
20188 Object.defineProperty(exports, "__esModule", { value: true });
20189 exports.default = StatsComponent;
20190
20191 },{"../Component":210,"rxjs/Observable":28,"rxjs/add/operator/buffer":47,"rxjs/add/operator/debounceTime":52,"rxjs/add/operator/filter":57,"rxjs/add/operator/map":61,"rxjs/add/operator/scan":69}],237:[function(require,module,exports){
20192 /// <reference path="../../../typings/index.d.ts" />
20193 "use strict";
20194 var __extends = (this && this.__extends) || function (d, b) {
20195     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20196     function __() { this.constructor = d; }
20197     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20198 };
20199 var vd = require("virtual-dom");
20200 var Observable_1 = require("rxjs/Observable");
20201 var Subject_1 = require("rxjs/Subject");
20202 require("rxjs/add/observable/combineLatest");
20203 require("rxjs/add/operator/do");
20204 require("rxjs/add/operator/distinctUntilChanged");
20205 require("rxjs/add/operator/filter");
20206 require("rxjs/add/operator/map");
20207 require("rxjs/add/operator/share");
20208 var Component_1 = require("../../Component");
20209 /**
20210  * @class DirectionComponent
20211  * @classdesc Component showing navigation arrows for steps and turns.
20212  */
20213 var DirectionComponent = (function (_super) {
20214     __extends(DirectionComponent, _super);
20215     function DirectionComponent(name, container, navigator) {
20216         _super.call(this, name, container, navigator);
20217         this._renderer = new Component_1.DirectionDOMRenderer(this.defaultConfiguration, container.element);
20218         this._hoveredKeySubject$ = new Subject_1.Subject();
20219         this._hoveredKey$ = this._hoveredKeySubject$.share();
20220     }
20221     Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", {
20222         /**
20223          * Get hovered key observable.
20224          *
20225          * @description An observable emitting the key of the node for the direction
20226          * arrow that is being hovered. When the mouse leaves a direction arrow null
20227          * is emitted.
20228          *
20229          * @returns {Observable<string>}
20230          */
20231         get: function () {
20232             return this._hoveredKey$;
20233         },
20234         enumerable: true,
20235         configurable: true
20236     });
20237     /**
20238      * Set highlight key.
20239      *
20240      * @description The arrow pointing towards the node corresponding to the
20241      * highlight key will be highlighted.
20242      *
20243      * @param {string} highlightKey Key of node to be highlighted if existing
20244      * among arrows.
20245      */
20246     DirectionComponent.prototype.setHighlightKey = function (highlightKey) {
20247         this.configure({ highlightKey: highlightKey });
20248     };
20249     /**
20250      * Set min width of container element.
20251      *
20252      * @description  Set min width of the non transformed container element holding
20253      * the navigation arrows. If the min width is larger than the max width the
20254      * min width value will be used.
20255      *
20256      * The container element is automatically resized when the resize
20257      * method on the Viewer class is called.
20258      *
20259      * @param {number} minWidth
20260      */
20261     DirectionComponent.prototype.setMinWidth = function (minWidth) {
20262         this.configure({ minWidth: minWidth });
20263     };
20264     /**
20265      * Set max width of container element.
20266      *
20267      * @description Set max width of the non transformed container element holding
20268      * the navigation arrows. If the min width is larger than the max width the
20269      * min width value will be used.
20270      *
20271      * The container element is automatically resized when the resize
20272      * method on the Viewer class is called.
20273      *
20274      * @param {number} minWidth
20275      */
20276     DirectionComponent.prototype.setMaxWidth = function (maxWidth) {
20277         this.configure({ maxWidth: maxWidth });
20278     };
20279     /** @inheritdoc */
20280     DirectionComponent.prototype.resize = function () {
20281         this._renderer.resize(this._container.element);
20282     };
20283     DirectionComponent.prototype._activate = function () {
20284         var _this = this;
20285         this._configurationSubscription = this._configuration$
20286             .subscribe(function (configuration) {
20287             _this._renderer.setConfiguration(configuration);
20288         });
20289         this._nodeSubscription = this._navigator.stateService.currentNode$
20290             .do(function (node) {
20291             _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) });
20292             _this._renderer.setNode(node);
20293         })
20294             .withLatestFrom(this._configuration$)
20295             .switchMap(function (nc) {
20296             var node = nc[0];
20297             var configuration = nc[1];
20298             return node.spatialEdges$
20299                 .withLatestFrom(configuration.distinguishSequence ?
20300                 _this._navigator.graphService
20301                     .cacheSequence$(node.sequenceKey)
20302                     .catch(function (error, caught) {
20303                     console.error("Failed to cache sequence (" + node.sequenceKey + ")", error);
20304                     return Observable_1.Observable.empty();
20305                 }) :
20306                 Observable_1.Observable.of(null));
20307         })
20308             .subscribe(function (es) {
20309             _this._renderer.setEdges(es[0], es[1]);
20310         });
20311         this._renderCameraSubscription = this._container.renderService.renderCameraFrame$
20312             .do(function (renderCamera) {
20313             _this._renderer.setRenderCamera(renderCamera);
20314         })
20315             .map(function (renderCamera) {
20316             return _this._renderer;
20317         })
20318             .filter(function (renderer) {
20319             return renderer.needsRender;
20320         })
20321             .map(function (renderer) {
20322             return { name: _this._name, vnode: renderer.render(_this._navigator) };
20323         })
20324             .subscribe(this._container.domRenderer.render$);
20325         this._hoveredKeySubscription = Observable_1.Observable
20326             .combineLatest([
20327             this._container.domRenderer.element$,
20328             this._container.renderService.renderCamera$,
20329             this._container.mouseService.mouseMove$.startWith(null),
20330             this._container.mouseService.mouseUp$.startWith(null),
20331         ], function (e, rc, mm, mu) {
20332             return e;
20333         })
20334             .map(function (element) {
20335             var elements = element.getElementsByClassName("DirectionsPerspective");
20336             for (var i = 0; i < elements.length; i++) {
20337                 var hovered = elements.item(i).querySelector(":hover");
20338                 if (hovered != null && hovered.hasAttribute("data-key")) {
20339                     return hovered.getAttribute("data-key");
20340                 }
20341             }
20342             return null;
20343         })
20344             .distinctUntilChanged()
20345             .subscribe(this._hoveredKeySubject$);
20346     };
20347     DirectionComponent.prototype._deactivate = function () {
20348         this._configurationSubscription.unsubscribe();
20349         this._nodeSubscription.unsubscribe();
20350         this._renderCameraSubscription.unsubscribe();
20351         this._hoveredKeySubscription.unsubscribe();
20352     };
20353     DirectionComponent.prototype._getDefaultConfiguration = function () {
20354         return {
20355             distinguishSequence: false,
20356             maxWidth: 460,
20357             minWidth: 260,
20358         };
20359     };
20360     /** @inheritdoc */
20361     DirectionComponent.componentName = "direction";
20362     return DirectionComponent;
20363 }(Component_1.Component));
20364 exports.DirectionComponent = DirectionComponent;
20365 Component_1.ComponentService.register(DirectionComponent);
20366 Object.defineProperty(exports, "__esModule", { value: true });
20367 exports.default = DirectionComponent;
20368
20369 },{"../../Component":210,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":54,"rxjs/add/operator/do":55,"rxjs/add/operator/filter":57,"rxjs/add/operator/map":61,"rxjs/add/operator/share":70,"virtual-dom":166}],238:[function(require,module,exports){
20370 "use strict";
20371 var Geo_1 = require("../../Geo");
20372 /**
20373  * @class DirectionDOMCalculator
20374  * @classdesc Helper class for calculating DOM CSS properties.
20375  */
20376 var DirectionDOMCalculator = (function () {
20377     function DirectionDOMCalculator(configuration, element) {
20378         this._spatial = new Geo_1.Spatial();
20379         this._minThresholdWidth = 320;
20380         this._maxThresholdWidth = 1480;
20381         this._minThresholdHeight = 240;
20382         this._maxThresholdHeight = 820;
20383         this._configure(configuration);
20384         this._resize(element);
20385         this._reset();
20386     }
20387     Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", {
20388         get: function () {
20389             return this._minWidth;
20390         },
20391         enumerable: true,
20392         configurable: true
20393     });
20394     Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", {
20395         get: function () {
20396             return this._maxWidth;
20397         },
20398         enumerable: true,
20399         configurable: true
20400     });
20401     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", {
20402         get: function () {
20403             return this._containerWidth;
20404         },
20405         enumerable: true,
20406         configurable: true
20407     });
20408     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", {
20409         get: function () {
20410             return this._containerWidthCss;
20411         },
20412         enumerable: true,
20413         configurable: true
20414     });
20415     Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", {
20416         get: function () {
20417             return this._containerMarginCss;
20418         },
20419         enumerable: true,
20420         configurable: true
20421     });
20422     Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", {
20423         get: function () {
20424             return this._containerLeftCss;
20425         },
20426         enumerable: true,
20427         configurable: true
20428     });
20429     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", {
20430         get: function () {
20431             return this._containerHeight;
20432         },
20433         enumerable: true,
20434         configurable: true
20435     });
20436     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", {
20437         get: function () {
20438             return this._containerHeightCss;
20439         },
20440         enumerable: true,
20441         configurable: true
20442     });
20443     Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", {
20444         get: function () {
20445             return this._containerBottomCss;
20446         },
20447         enumerable: true,
20448         configurable: true
20449     });
20450     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", {
20451         get: function () {
20452             return this._stepCircleSize;
20453         },
20454         enumerable: true,
20455         configurable: true
20456     });
20457     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", {
20458         get: function () {
20459             return this._stepCircleSizeCss;
20460         },
20461         enumerable: true,
20462         configurable: true
20463     });
20464     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", {
20465         get: function () {
20466             return this._stepCircleMarginCss;
20467         },
20468         enumerable: true,
20469         configurable: true
20470     });
20471     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", {
20472         get: function () {
20473             return this._turnCircleSize;
20474         },
20475         enumerable: true,
20476         configurable: true
20477     });
20478     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", {
20479         get: function () {
20480             return this._turnCircleSizeCss;
20481         },
20482         enumerable: true,
20483         configurable: true
20484     });
20485     Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", {
20486         get: function () {
20487             return this._outerRadius;
20488         },
20489         enumerable: true,
20490         configurable: true
20491     });
20492     Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", {
20493         get: function () {
20494             return this._innerRadius;
20495         },
20496         enumerable: true,
20497         configurable: true
20498     });
20499     Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", {
20500         get: function () {
20501             return this._shadowOffset;
20502         },
20503         enumerable: true,
20504         configurable: true
20505     });
20506     /**
20507      * Configures the min and max width values.
20508      *
20509      * @param {IDirectionConfiguration} configuration Configuration
20510      * with min and max width values.
20511      */
20512     DirectionDOMCalculator.prototype.configure = function (configuration) {
20513         this._configure(configuration);
20514         this._reset();
20515     };
20516     /**
20517      * Resizes all properties according to the width and height
20518      * of the element.
20519      *
20520      * @param {HTMLElement} element The container element from which to extract
20521      * the width and height.
20522      */
20523     DirectionDOMCalculator.prototype.resize = function (element) {
20524         this._resize(element);
20525         this._reset();
20526     };
20527     /**
20528      * Calculates the coordinates on the unit circle for an angle.
20529      *
20530      * @param {number} angle Angle in radians.
20531      * @returns {Array<number>} The x and y coordinates on the unit circle.
20532      */
20533     DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) {
20534         return [Math.cos(angle), Math.sin(angle)];
20535     };
20536     /**
20537      * Calculates the coordinates on the unit circle for the
20538      * relative angle between the first and second angle.
20539      *
20540      * @param {number} first Angle in radians.
20541      * @param {number} second Angle in radians.
20542      * @returns {Array<number>} The x and y coordinates on the unit circle
20543      * for the relative angle between the first and second angle.
20544      */
20545     DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) {
20546         var relativeAngle = this._spatial.wrapAngle(first - second);
20547         return this.angleToCoordinates(relativeAngle);
20548     };
20549     DirectionDOMCalculator.prototype._configure = function (configuration) {
20550         this._minWidth = configuration.minWidth;
20551         this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth);
20552     };
20553     DirectionDOMCalculator.prototype._resize = function (element) {
20554         this._elementWidth = element.offsetWidth;
20555         this._elementHeight = element.offsetHeight;
20556     };
20557     DirectionDOMCalculator.prototype._reset = function () {
20558         this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight);
20559         this._containerHeight = this._getContainerHeight(this.containerWidth);
20560         this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight);
20561         this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight);
20562         this._outerRadius = this._getOuterRadius(this._containerHeight);
20563         this._innerRadius = this._getInnerRadius(this._containerHeight);
20564         this._shadowOffset = 3;
20565         this._containerWidthCss = this._numberToCssPixels(this._containerWidth);
20566         this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth);
20567         this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth));
20568         this._containerHeightCss = this._numberToCssPixels(this._containerHeight);
20569         this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight));
20570         this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize);
20571         this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize);
20572         this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize);
20573     };
20574     DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) {
20575         var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
20576         var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
20577         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
20578         coeff = 0.04 * Math.round(25 * coeff);
20579         return this._minWidth + coeff * (this._maxWidth - this._minWidth);
20580     };
20581     DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) {
20582         return 0.77 * containerWidth;
20583     };
20584     DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) {
20585         return 0.34 * containerHeight;
20586     };
20587     DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) {
20588         return 0.3 * containerHeight;
20589     };
20590     DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) {
20591         return 0.31 * containerHeight;
20592     };
20593     DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) {
20594         return 0.125 * containerHeight;
20595     };
20596     DirectionDOMCalculator.prototype._numberToCssPixels = function (value) {
20597         return value + "px";
20598     };
20599     DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) {
20600         return value > minWidth ? value : minWidth;
20601     };
20602     return DirectionDOMCalculator;
20603 }());
20604 exports.DirectionDOMCalculator = DirectionDOMCalculator;
20605 Object.defineProperty(exports, "__esModule", { value: true });
20606 exports.default = DirectionDOMCalculator;
20607
20608 },{"../../Geo":213}],239:[function(require,module,exports){
20609 /// <reference path="../../../typings/index.d.ts" />
20610 "use strict";
20611 var vd = require("virtual-dom");
20612 var Component_1 = require("../../Component");
20613 var Edge_1 = require("../../Edge");
20614 var Geo_1 = require("../../Geo");
20615 /**
20616  * @class DirectionDOMRenderer
20617  * @classdesc DOM renderer for direction arrows.
20618  */
20619 var DirectionDOMRenderer = (function () {
20620     function DirectionDOMRenderer(configuration, element) {
20621         this._isEdge = false;
20622         this._spatial = new Geo_1.Spatial();
20623         this._calculator = new Component_1.DirectionDOMCalculator(configuration, element);
20624         this._node = null;
20625         this._rotation = { phi: 0, theta: 0 };
20626         this._epsilon = 0.5 * Math.PI / 180;
20627         this._highlightKey = null;
20628         this._distinguishSequence = false;
20629         this._needsRender = false;
20630         this._stepEdges = [];
20631         this._turnEdges = [];
20632         this._panoEdges = [];
20633         this._sequenceEdgeKeys = [];
20634         this._stepDirections = [
20635             Edge_1.EdgeDirection.StepForward,
20636             Edge_1.EdgeDirection.StepBackward,
20637             Edge_1.EdgeDirection.StepLeft,
20638             Edge_1.EdgeDirection.StepRight,
20639         ];
20640         this._turnDirections = [
20641             Edge_1.EdgeDirection.TurnLeft,
20642             Edge_1.EdgeDirection.TurnRight,
20643             Edge_1.EdgeDirection.TurnU,
20644         ];
20645         this._turnNames = {};
20646         this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft";
20647         this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight";
20648         this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround";
20649         // detects IE 8-11, then Edge 20+.
20650         var isIE = !!document.documentMode;
20651         this._isEdge = !isIE && !!window.StyleMedia;
20652     }
20653     Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", {
20654         /**
20655          * Get needs render.
20656          *
20657          * @returns {boolean} Value indicating whether render should be called.
20658          */
20659         get: function () {
20660             return this._needsRender;
20661         },
20662         enumerable: true,
20663         configurable: true
20664     });
20665     /**
20666      * Renders virtual DOM elements.
20667      *
20668      * @description Calling render resets the needs render property.
20669      */
20670     DirectionDOMRenderer.prototype.render = function (navigator) {
20671         this._needsRender = false;
20672         var rotation = this._rotation;
20673         var steps = [];
20674         var turns = [];
20675         if (this._node.pano) {
20676             steps = steps.concat(this._createPanoArrows(navigator, rotation));
20677         }
20678         else {
20679             steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation));
20680             steps = steps.concat(this._createStepArrows(navigator, rotation));
20681             turns = turns.concat(this._createTurnArrows(navigator));
20682         }
20683         return this._getContainer(steps, turns, rotation);
20684     };
20685     DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) {
20686         this._setEdges(edgeStatus, sequence);
20687         this._setNeedsRender();
20688     };
20689     /**
20690      * Set node for which to show edges.
20691      *
20692      * @param {Node} node
20693      */
20694     DirectionDOMRenderer.prototype.setNode = function (node) {
20695         this._node = node;
20696         this._clearEdges();
20697         this._setNeedsRender();
20698     };
20699     /**
20700      * Set the render camera to use for calculating rotations.
20701      *
20702      * @param {RenderCamera} renderCamera
20703      */
20704     DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) {
20705         var camera = renderCamera.camera;
20706         var direction = this._directionFromCamera(camera);
20707         var rotation = this._getRotation(direction, camera.up);
20708         if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) {
20709             return;
20710         }
20711         this._rotation = rotation;
20712         this._setNeedsRender();
20713     };
20714     /**
20715      * Set configuration values.
20716      *
20717      * @param {IDirectionConfiguration} configuration
20718      */
20719     DirectionDOMRenderer.prototype.setConfiguration = function (configuration) {
20720         var needsRender = false;
20721         if (this._highlightKey !== configuration.highlightKey ||
20722             this._distinguishSequence !== configuration.distinguishSequence) {
20723             this._highlightKey = configuration.highlightKey;
20724             this._distinguishSequence = configuration.distinguishSequence;
20725             needsRender = true;
20726         }
20727         if (this._calculator.minWidth !== configuration.minWidth ||
20728             this._calculator.maxWidth !== configuration.maxWidth) {
20729             this._calculator.configure(configuration);
20730             needsRender = true;
20731         }
20732         if (needsRender) {
20733             this._setNeedsRender();
20734         }
20735     };
20736     /**
20737      * Detect the element's width and height and resize
20738      * elements accordingly.
20739      *
20740      * @param {HTMLElement} element Viewer container element.
20741      */
20742     DirectionDOMRenderer.prototype.resize = function (element) {
20743         this._calculator.resize(element);
20744         this._setNeedsRender();
20745     };
20746     DirectionDOMRenderer.prototype._setNeedsRender = function () {
20747         if (this._node != null) {
20748             this._needsRender = true;
20749         }
20750     };
20751     DirectionDOMRenderer.prototype._clearEdges = function () {
20752         this._stepEdges = [];
20753         this._turnEdges = [];
20754         this._panoEdges = [];
20755         this._sequenceEdgeKeys = [];
20756     };
20757     DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) {
20758         this._stepEdges = [];
20759         this._turnEdges = [];
20760         this._panoEdges = [];
20761         this._sequenceEdgeKeys = [];
20762         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
20763             var edge = _a[_i];
20764             var direction = edge.data.direction;
20765             if (this._stepDirections.indexOf(direction) > -1) {
20766                 this._stepEdges.push(edge);
20767                 continue;
20768             }
20769             if (this._turnDirections.indexOf(direction) > -1) {
20770                 this._turnEdges.push(edge);
20771                 continue;
20772             }
20773             if (edge.data.direction === Edge_1.EdgeDirection.Pano) {
20774                 this._panoEdges.push(edge);
20775             }
20776         }
20777         if (this._distinguishSequence && sequence != null) {
20778             var edges = this._panoEdges
20779                 .concat(this._stepEdges)
20780                 .concat(this._turnEdges);
20781             for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) {
20782                 var edge = edges_1[_b];
20783                 var edgeKey = edge.to;
20784                 for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
20785                     var sequenceKey = _d[_c];
20786                     if (sequenceKey === edgeKey) {
20787                         this._sequenceEdgeKeys.push(edgeKey);
20788                         break;
20789                     }
20790                 }
20791             }
20792         }
20793     };
20794     DirectionDOMRenderer.prototype._directionFromCamera = function (camera) {
20795         return camera.lookat.clone().sub(camera.position);
20796     };
20797     DirectionDOMRenderer.prototype._getRotation = function (direction, up) {
20798         var upProjection = direction.clone().dot(up);
20799         var planeProjection = direction.clone().sub(up.clone().multiplyScalar(upProjection));
20800         var phi = Math.atan2(planeProjection.y, planeProjection.x);
20801         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
20802         return { phi: phi, theta: theta };
20803     };
20804     DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) {
20805         var arrows = [];
20806         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
20807             var panoEdge = _a[_i];
20808             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano"));
20809         }
20810         for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) {
20811             var stepEdge = _c[_b];
20812             arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
20813         }
20814         return arrows;
20815     };
20816     DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) {
20817         var threshold = Math.PI / 8;
20818         var relativePhi = rotation.phi;
20819         switch (direction) {
20820             case Edge_1.EdgeDirection.StepBackward:
20821                 relativePhi = rotation.phi - Math.PI;
20822                 break;
20823             case Edge_1.EdgeDirection.StepLeft:
20824                 relativePhi = rotation.phi + Math.PI / 2;
20825                 break;
20826             case Edge_1.EdgeDirection.StepRight:
20827                 relativePhi = rotation.phi - Math.PI / 2;
20828                 break;
20829             default:
20830                 break;
20831         }
20832         if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) {
20833             return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep");
20834         }
20835         return this._createVNodeDisabled(key, azimuth, rotation);
20836     };
20837     DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) {
20838         var arrows = [];
20839         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
20840             var panoEdge = _a[_i];
20841             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true));
20842         }
20843         return arrows;
20844     };
20845     DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) {
20846         var arrows = [];
20847         for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) {
20848             var stepEdge = _a[_i];
20849             arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
20850         }
20851         return arrows;
20852     };
20853     DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) {
20854         var turns = [];
20855         for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) {
20856             var turnEdge = _a[_i];
20857             var direction = turnEdge.data.direction;
20858             var name_1 = this._turnNames[direction];
20859             turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction));
20860         }
20861         return turns;
20862     };
20863     DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) {
20864         var onClick = function (e) {
20865             navigator.moveToKey$(key)
20866                 .subscribe(function (node) { return; }, function (error) { console.error(error); });
20867         };
20868         return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically);
20869     };
20870     DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) {
20871         var onClick = function (e) {
20872             navigator.moveDir$(direction)
20873                 .subscribe(function (node) { return; }, function (error) { console.error(error); });
20874         };
20875         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick);
20876     };
20877     DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) {
20878         var onClick = function (e) {
20879             navigator.moveDir$(direction)
20880                 .subscribe(function (node) { return; }, function (error) { console.error(error); });
20881         };
20882         var style = {
20883             height: this._calculator.turnCircleSizeCss,
20884             transform: "rotate(0)",
20885             width: this._calculator.turnCircleSizeCss,
20886         };
20887         switch (direction) {
20888             case Edge_1.EdgeDirection.TurnLeft:
20889                 style.left = "5px";
20890                 style.top = "5px";
20891                 break;
20892             case Edge_1.EdgeDirection.TurnRight:
20893                 style.right = "5px";
20894                 style.top = "5px";
20895                 break;
20896             case Edge_1.EdgeDirection.TurnU:
20897                 style.left = "5px";
20898                 style.bottom = "5px";
20899                 break;
20900             default:
20901                 break;
20902         }
20903         var circleProperties = {
20904             attributes: {
20905                 "data-key": key,
20906             },
20907             onclick: onClick,
20908             style: style,
20909         };
20910         var circleClassName = "TurnCircle";
20911         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
20912             circleClassName += "Sequence";
20913         }
20914         if (this._highlightKey === key) {
20915             circleClassName += "Highlight";
20916         }
20917         var turn = vd.h("div." + className, {}, []);
20918         return vd.h("div." + circleClassName, circleProperties, [turn]);
20919     };
20920     DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) {
20921         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled");
20922     };
20923     DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) {
20924         var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi);
20925         // rotate 90 degrees clockwise and flip over X-axis
20926         var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth);
20927         var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight);
20928         var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi);
20929         var shadowOffset = this._calculator.shadowOffset;
20930         var shadowTranslationX = -shadowOffset * shadowTranslation[1];
20931         var shadowTranslationY = shadowOffset * shadowTranslation[0];
20932         var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))";
20933         var properties = {
20934             style: {
20935                 "-webkit-filter": filter,
20936                 filter: filter,
20937             },
20938         };
20939         var chevron = vd.h("div." + className, properties, []);
20940         var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi);
20941         var circleTransform = shiftVertically ?
20942             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" :
20943             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)";
20944         var circleProperties = {
20945             attributes: { "data-key": key },
20946             onclick: onClick,
20947             style: {
20948                 height: this._calculator.stepCircleSizeCss,
20949                 marginLeft: this._calculator.stepCircleMarginCss,
20950                 marginTop: this._calculator.stepCircleMarginCss,
20951                 transform: circleTransform,
20952                 width: this._calculator.stepCircleSizeCss,
20953             },
20954         };
20955         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
20956             circleClassName += "Sequence";
20957         }
20958         if (this._highlightKey === key) {
20959             circleClassName += "Highlight";
20960         }
20961         return vd.h("div." + circleClassName, circleProperties, [chevron]);
20962     };
20963     DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) {
20964         // edge does not handle hover on perspective transforms.
20965         var transform = this._isEdge ?
20966             "rotateX(60deg)" :
20967             "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)";
20968         var perspectiveStyle = {
20969             bottom: this._calculator.containerBottomCss,
20970             height: this._calculator.containerHeightCss,
20971             left: this._calculator.containerLeftCss,
20972             marginLeft: this._calculator.containerMarginCss,
20973             transform: transform,
20974             width: this._calculator.containerWidthCss,
20975         };
20976         return vd.h("div.DirectionsPerspective", { style: perspectiveStyle }, turns.concat(steps));
20977     };
20978     return DirectionDOMRenderer;
20979 }());
20980 exports.DirectionDOMRenderer = DirectionDOMRenderer;
20981 Object.defineProperty(exports, "__esModule", { value: true });
20982 exports.default = DirectionDOMRenderer;
20983
20984 },{"../../Component":210,"../../Edge":211,"../../Geo":213,"virtual-dom":166}],240:[function(require,module,exports){
20985 "use strict";
20986 var __extends = (this && this.__extends) || function (d, b) {
20987     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
20988     function __() { this.constructor = d; }
20989     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20990 };
20991 var Observable_1 = require("rxjs/Observable");
20992 var Subject_1 = require("rxjs/Subject");
20993 require("rxjs/add/observable/combineLatest");
20994 require("rxjs/add/observable/of");
20995 require("rxjs/add/operator/debounceTime");
20996 require("rxjs/add/operator/distinctUntilChanged");
20997 require("rxjs/add/operator/filter");
20998 require("rxjs/add/operator/map");
20999 require("rxjs/add/operator/scan");
21000 require("rxjs/add/operator/switchMap");
21001 require("rxjs/add/operator/withLatestFrom");
21002 var Component_1 = require("../../Component");
21003 var Render_1 = require("../../Render");
21004 var Graph_1 = require("../../Graph");
21005 var Utils_1 = require("../../Utils");
21006 var ImagePlaneComponent = (function (_super) {
21007     __extends(ImagePlaneComponent, _super);
21008     function ImagePlaneComponent(name, container, navigator) {
21009         _super.call(this, name, container, navigator);
21010         this._rendererOperation$ = new Subject_1.Subject();
21011         this._rendererCreator$ = new Subject_1.Subject();
21012         this._rendererDisposer$ = new Subject_1.Subject();
21013         this._renderer$ = this._rendererOperation$
21014             .scan(function (renderer, operation) {
21015             return operation(renderer);
21016         }, null)
21017             .filter(function (renderer) {
21018             return renderer != null;
21019         })
21020             .distinctUntilChanged(undefined, function (renderer) {
21021             return renderer.frameId;
21022         });
21023         this._rendererCreator$
21024             .map(function () {
21025             return function (renderer) {
21026                 if (renderer != null) {
21027                     throw new Error("Multiple image plane states can not be created at the same time");
21028                 }
21029                 return new Component_1.ImagePlaneGLRenderer();
21030             };
21031         })
21032             .subscribe(this._rendererOperation$);
21033         this._rendererDisposer$
21034             .map(function () {
21035             return function (renderer) {
21036                 renderer.dispose();
21037                 return null;
21038             };
21039         })
21040             .subscribe(this._rendererOperation$);
21041     }
21042     ImagePlaneComponent.prototype._activate = function () {
21043         var _this = this;
21044         this._rendererSubscription = this._renderer$
21045             .map(function (renderer) {
21046             var renderHash = {
21047                 name: _this._name,
21048                 render: {
21049                     frameId: renderer.frameId,
21050                     needsRender: renderer.needsRender,
21051                     render: renderer.render.bind(renderer),
21052                     stage: Render_1.GLRenderStage.Background,
21053                 },
21054             };
21055             renderer.clearNeedsRender();
21056             return renderHash;
21057         })
21058             .subscribe(this._container.glRenderer.render$);
21059         this._rendererCreator$.next(null);
21060         this._stateSubscription = this._navigator.stateService.currentState$
21061             .map(function (frame) {
21062             return function (renderer) {
21063                 renderer.updateFrame(frame);
21064                 return renderer;
21065             };
21066         })
21067             .subscribe(this._rendererOperation$);
21068         this._nodeSubscription = Observable_1.Observable
21069             .combineLatest(this._navigator.stateService.currentNode$, this._configuration$)
21070             .debounceTime(1000)
21071             .withLatestFrom(this._navigator.stateService.currentTransform$, function (nc, t) {
21072             return [nc[0], nc[1], t];
21073         })
21074             .map(function (params) {
21075             var node = params[0];
21076             var configuration = params[1];
21077             var transform = params[2];
21078             var imageSize = Utils_1.Settings.maxImageSize;
21079             if (node.pano) {
21080                 if (configuration.maxPanoramaResolution === "high") {
21081                     imageSize = Math.max(imageSize, Math.min(4096, Math.max(transform.width, transform.height)));
21082                 }
21083                 else if (configuration.maxPanoramaResolution === "full") {
21084                     imageSize = Math.max(imageSize, transform.width, transform.height);
21085                 }
21086             }
21087             return [node, imageSize];
21088         })
21089             .filter(function (params) {
21090             var node = params[0];
21091             var imageSize = params[1];
21092             return node.pano ?
21093                 imageSize > Utils_1.Settings.basePanoramaSize :
21094                 imageSize > Utils_1.Settings.baseImageSize;
21095         })
21096             .switchMap(function (params) {
21097             var node = params[0];
21098             var imageSize = params[1];
21099             var baseImageSize = node.pano ?
21100                 Utils_1.Settings.basePanoramaSize :
21101                 Utils_1.Settings.baseImageSize;
21102             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
21103                 return Observable_1.Observable.empty();
21104             }
21105             var image$ = null;
21106             if (node.pano && imageSize > Utils_1.Settings.maxImageSize) {
21107                 image$ = Graph_1.ImageLoader.loadDynamic(node.key, imageSize)
21108                     .first(function (statusObject) {
21109                     return statusObject.object != null;
21110                 })
21111                     .zip(Observable_1.Observable.of(node), function (status, n) {
21112                     return [status.object, n];
21113                 });
21114             }
21115             else {
21116                 image$ = node.cacheImage$(imageSize)
21117                     .map(function (n) {
21118                     return [n.image, n];
21119                 });
21120             }
21121             return image$
21122                 .catch(function (error, caught) {
21123                 console.error("Failed to fetch high res image (" + node.key + ")", error);
21124                 return Observable_1.Observable.empty();
21125             });
21126         })
21127             .map(function (imn) {
21128             return function (renderer) {
21129                 renderer.updateTexture(imn[0], imn[1]);
21130                 return renderer;
21131             };
21132         })
21133             .subscribe(this._rendererOperation$);
21134     };
21135     ImagePlaneComponent.prototype._deactivate = function () {
21136         this._rendererDisposer$.next(null);
21137         this._rendererSubscription.unsubscribe();
21138         this._stateSubscription.unsubscribe();
21139         this._nodeSubscription.unsubscribe();
21140     };
21141     ImagePlaneComponent.prototype._getDefaultConfiguration = function () {
21142         return { maxPanoramaResolution: "auto" };
21143     };
21144     ImagePlaneComponent.componentName = "imagePlane";
21145     return ImagePlaneComponent;
21146 }(Component_1.Component));
21147 exports.ImagePlaneComponent = ImagePlaneComponent;
21148 Component_1.ComponentService.register(ImagePlaneComponent);
21149 Object.defineProperty(exports, "__esModule", { value: true });
21150 exports.default = ImagePlaneComponent;
21151
21152 },{"../../Component":210,"../../Graph":214,"../../Render":216,"../../Utils":218,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/of":44,"rxjs/add/operator/debounceTime":52,"rxjs/add/operator/distinctUntilChanged":54,"rxjs/add/operator/filter":57,"rxjs/add/operator/map":61,"rxjs/add/operator/scan":69,"rxjs/add/operator/switchMap":74,"rxjs/add/operator/withLatestFrom":77}],241:[function(require,module,exports){
21153 /// <reference path="../../../typings/index.d.ts" />
21154 "use strict";
21155 var THREE = require("three");
21156 var Component_1 = require("../../Component");
21157 var ImagePlaneFactory = (function () {
21158     function ImagePlaneFactory(imagePlaneDepth, imageSphereRadius) {
21159         this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200;
21160         this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200;
21161     }
21162     ImagePlaneFactory.prototype.createMesh = function (node, transform) {
21163         var mesh = node.pano ?
21164             this._createImageSphere(node, transform) :
21165             this._createImagePlane(node, transform);
21166         return mesh;
21167     };
21168     ImagePlaneFactory.prototype._createImageSphere = function (node, transform) {
21169         var texture = this._createTexture(node.image);
21170         var materialParameters = this._createSphereMaterialParameters(transform, texture);
21171         var material = new THREE.ShaderMaterial(materialParameters);
21172         var mesh = this._useMesh(transform, node) ?
21173             new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
21174             new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
21175         return mesh;
21176     };
21177     ImagePlaneFactory.prototype._createImagePlane = function (node, transform) {
21178         var texture = this._createTexture(node.image);
21179         var materialParameters = this._createPlaneMaterialParameters(transform, texture);
21180         var material = new THREE.ShaderMaterial(materialParameters);
21181         var geometry = this._useMesh(transform, node) ?
21182             this._getImagePlaneGeo(transform, node) :
21183             this._getFlatImagePlaneGeo(transform);
21184         return new THREE.Mesh(geometry, material);
21185     };
21186     ImagePlaneFactory.prototype._createSphereMaterialParameters = function (transform, texture) {
21187         var gpano = transform.gpano;
21188         var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
21189         var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
21190         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
21191         var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
21192         var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
21193         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
21194         var materialParameters = {
21195             depthWrite: false,
21196             fragmentShader: Component_1.ImagePlaneShaders.equirectangular.fragment,
21197             side: THREE.DoubleSide,
21198             transparent: true,
21199             uniforms: {
21200                 opacity: {
21201                     type: "f",
21202                     value: 1,
21203                 },
21204                 phiLength: {
21205                     type: "f",
21206                     value: phiLength,
21207                 },
21208                 phiShift: {
21209                     type: "f",
21210                     value: phiShift,
21211                 },
21212                 projectorMat: {
21213                     type: "m4",
21214                     value: transform.rt,
21215                 },
21216                 projectorTex: {
21217                     type: "t",
21218                     value: texture,
21219                 },
21220                 thetaLength: {
21221                     type: "f",
21222                     value: thetaLength,
21223                 },
21224                 thetaShift: {
21225                     type: "f",
21226                     value: thetaShift,
21227                 },
21228             },
21229             vertexShader: Component_1.ImagePlaneShaders.equirectangular.vertex,
21230         };
21231         return materialParameters;
21232     };
21233     ImagePlaneFactory.prototype._createPlaneMaterialParameters = function (transform, texture) {
21234         var materialParameters = {
21235             depthWrite: false,
21236             fragmentShader: Component_1.ImagePlaneShaders.perspective.fragment,
21237             side: THREE.DoubleSide,
21238             transparent: true,
21239             uniforms: {
21240                 bbox: {
21241                     type: "v4",
21242                     value: new THREE.Vector4(0, 0, 1, 1),
21243                 },
21244                 opacity: {
21245                     type: "f",
21246                     value: 1,
21247                 },
21248                 projectorMat: {
21249                     type: "m4",
21250                     value: transform.projectorMatrix(),
21251                 },
21252                 projectorTex: {
21253                     type: "t",
21254                     value: texture,
21255                 },
21256             },
21257             vertexShader: Component_1.ImagePlaneShaders.perspective.vertex,
21258         };
21259         return materialParameters;
21260     };
21261     ImagePlaneFactory.prototype._createTexture = function (image) {
21262         var texture = new THREE.Texture(image);
21263         texture.minFilter = THREE.LinearFilter;
21264         texture.needsUpdate = true;
21265         return texture;
21266     };
21267     ImagePlaneFactory.prototype._useMesh = function (transform, node) {
21268         return node.mesh.vertices.length &&
21269             transform.scale > 1e-2 &&
21270             transform.scale < 50;
21271     };
21272     ImagePlaneFactory.prototype._getImageSphereGeo = function (transform, node) {
21273         var t = new THREE.Matrix4().getInverse(transform.srt);
21274         // push everything at least 5 meters in front of the camera
21275         var minZ = 5.0 * transform.scale;
21276         var maxZ = this._imageSphereRadius * transform.scale;
21277         var vertices = node.mesh.vertices;
21278         var numVertices = vertices.length / 3;
21279         var positions = new Float32Array(vertices.length);
21280         for (var i = 0; i < numVertices; ++i) {
21281             var index = 3 * i;
21282             var x = vertices[index + 0];
21283             var y = vertices[index + 1];
21284             var z = vertices[index + 2];
21285             var l = Math.sqrt(x * x + y * y + z * z);
21286             var boundedL = Math.max(minZ, Math.min(l, maxZ));
21287             var factor = boundedL / l;
21288             var p = new THREE.Vector3(x * factor, y * factor, z * factor);
21289             p.applyMatrix4(t);
21290             positions[index + 0] = p.x;
21291             positions[index + 1] = p.y;
21292             positions[index + 2] = p.z;
21293         }
21294         var faces = node.mesh.faces;
21295         var indices = new Uint16Array(faces.length);
21296         for (var i = 0; i < faces.length; ++i) {
21297             indices[i] = faces[i];
21298         }
21299         var geometry = new THREE.BufferGeometry();
21300         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
21301         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
21302         return geometry;
21303     };
21304     ImagePlaneFactory.prototype._getImagePlaneGeo = function (transform, node) {
21305         var t = new THREE.Matrix4().getInverse(transform.srt);
21306         // push everything at least 5 meters in front of the camera
21307         var minZ = 5.0 * transform.scale;
21308         var maxZ = this._imagePlaneDepth * transform.scale;
21309         var vertices = node.mesh.vertices;
21310         var numVertices = vertices.length / 3;
21311         var positions = new Float32Array(vertices.length);
21312         for (var i = 0; i < numVertices; ++i) {
21313             var index = 3 * i;
21314             var x = vertices[index + 0];
21315             var y = vertices[index + 1];
21316             var z = vertices[index + 2];
21317             var boundedZ = Math.max(minZ, Math.min(z, maxZ));
21318             var factor = boundedZ / z;
21319             var p = new THREE.Vector3(x * factor, y * factor, boundedZ);
21320             p.applyMatrix4(t);
21321             positions[index + 0] = p.x;
21322             positions[index + 1] = p.y;
21323             positions[index + 2] = p.z;
21324         }
21325         var faces = node.mesh.faces;
21326         var indices = new Uint16Array(faces.length);
21327         for (var i = 0; i < faces.length; ++i) {
21328             indices[i] = faces[i];
21329         }
21330         var geometry = new THREE.BufferGeometry();
21331         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
21332         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
21333         return geometry;
21334     };
21335     ImagePlaneFactory.prototype._getFlatImageSphereGeo = function (transform) {
21336         var gpano = transform.gpano;
21337         var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels;
21338         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
21339         var thetaStart = Math.PI *
21340             (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) /
21341             gpano.FullPanoHeightPixels;
21342         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
21343         var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength);
21344         geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt));
21345         return geometry;
21346     };
21347     ImagePlaneFactory.prototype._getFlatImagePlaneGeo = function (transform) {
21348         var width = transform.width;
21349         var height = transform.height;
21350         var size = Math.max(width, height);
21351         var dx = width / 2.0 / size;
21352         var dy = height / 2.0 / size;
21353         var vertices = [];
21354         vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
21355         vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
21356         vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
21357         vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
21358         var positions = new Float32Array(12);
21359         for (var i = 0; i < vertices.length; i++) {
21360             var index = 3 * i;
21361             positions[index + 0] = vertices[i][0];
21362             positions[index + 1] = vertices[i][1];
21363             positions[index + 2] = vertices[i][2];
21364         }
21365         var indices = new Uint16Array(6);
21366         indices[0] = 0;
21367         indices[1] = 1;
21368         indices[2] = 3;
21369         indices[3] = 1;
21370         indices[4] = 2;
21371         indices[5] = 3;
21372         var geometry = new THREE.BufferGeometry();
21373         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
21374         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
21375         return geometry;
21376     };
21377     return ImagePlaneFactory;
21378 }());
21379 exports.ImagePlaneFactory = ImagePlaneFactory;
21380 Object.defineProperty(exports, "__esModule", { value: true });
21381 exports.default = ImagePlaneFactory;
21382
21383 },{"../../Component":210,"three":160}],242:[function(require,module,exports){
21384 /// <reference path="../../../typings/index.d.ts" />
21385 "use strict";
21386 var Component_1 = require("../../Component");
21387 var Geo_1 = require("../../Geo");
21388 var ImagePlaneGLRenderer = (function () {
21389     function ImagePlaneGLRenderer() {
21390         this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
21391         this._imagePlaneScene = new Component_1.ImagePlaneScene();
21392         this._alpha = 0;
21393         this._alphaOld = 0;
21394         this._fadeOutSpeed = 0.05;
21395         this._lastCamera = new Geo_1.Camera();
21396         this._epsilon = 0.000001;
21397         this._currentKey = null;
21398         this._previousKey = null;
21399         this._frameId = 0;
21400         this._needsRender = false;
21401     }
21402     Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", {
21403         get: function () {
21404             return this._frameId;
21405         },
21406         enumerable: true,
21407         configurable: true
21408     });
21409     Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", {
21410         get: function () {
21411             return this._needsRender;
21412         },
21413         enumerable: true,
21414         configurable: true
21415     });
21416     ImagePlaneGLRenderer.prototype.updateFrame = function (frame) {
21417         this._updateFrameId(frame.id);
21418         this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender;
21419         this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender;
21420         this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender;
21421     };
21422     ImagePlaneGLRenderer.prototype.updateTexture = function (image, node) {
21423         if (this._currentKey !== node.key) {
21424             return;
21425         }
21426         this._needsRender = true;
21427         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
21428             var plane = _a[_i];
21429             var material = plane.material;
21430             var texture = material.uniforms.projectorTex.value;
21431             texture.image = image;
21432             texture.needsUpdate = true;
21433         }
21434     };
21435     ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
21436         var planeAlpha = this._imagePlaneScene.imagePlanesOld.length ? 1 : this._alpha;
21437         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
21438             var plane = _a[_i];
21439             plane.material.uniforms.opacity.value = planeAlpha;
21440         }
21441         for (var _b = 0, _c = this._imagePlaneScene.imagePlanesOld; _b < _c.length; _b++) {
21442             var plane = _c[_b];
21443             plane.material.uniforms.opacity.value = this._alphaOld;
21444         }
21445         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
21446         renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
21447         for (var _d = 0, _e = this._imagePlaneScene.imagePlanes; _d < _e.length; _d++) {
21448             var plane = _e[_d];
21449             plane.material.uniforms.opacity.value = this._alpha;
21450         }
21451         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
21452     };
21453     ImagePlaneGLRenderer.prototype.clearNeedsRender = function () {
21454         this._needsRender = false;
21455     };
21456     ImagePlaneGLRenderer.prototype.dispose = function () {
21457         this._imagePlaneScene.clear();
21458     };
21459     ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) {
21460         this._frameId = frameId;
21461     };
21462     ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) {
21463         if (alpha === this._alpha) {
21464             return false;
21465         }
21466         this._alpha = alpha;
21467         return true;
21468     };
21469     ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) {
21470         if (alpha < 1 || this._alphaOld === 0) {
21471             return false;
21472         }
21473         this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed);
21474         return true;
21475     };
21476     ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) {
21477         if (state.currentNode == null || state.currentNode.key === this._currentKey) {
21478             return false;
21479         }
21480         this._previousKey = state.previousNode != null ? state.previousNode.key : null;
21481         if (this._previousKey != null) {
21482             if (this._previousKey !== this._currentKey) {
21483                 var previousMesh = this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform);
21484                 this._imagePlaneScene.updateImagePlanes([previousMesh]);
21485             }
21486         }
21487         this._currentKey = state.currentNode.key;
21488         var currentMesh = this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform);
21489         this._imagePlaneScene.updateImagePlanes([currentMesh]);
21490         this._alphaOld = 1;
21491         return true;
21492     };
21493     return ImagePlaneGLRenderer;
21494 }());
21495 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer;
21496 Object.defineProperty(exports, "__esModule", { value: true });
21497 exports.default = ImagePlaneGLRenderer;
21498
21499 },{"../../Component":210,"../../Geo":213}],243:[function(require,module,exports){
21500 /// <reference path="../../../typings/index.d.ts" />
21501 "use strict";
21502 var THREE = require("three");
21503 var ImagePlaneScene = (function () {
21504     function ImagePlaneScene() {
21505         this.scene = new THREE.Scene();
21506         this.sceneOld = new THREE.Scene();
21507         this.imagePlanes = [];
21508         this.imagePlanesOld = [];
21509     }
21510     ImagePlaneScene.prototype.updateImagePlanes = function (planes) {
21511         this._dispose(this.imagePlanesOld, this.sceneOld);
21512         for (var _i = 0, _a = this.imagePlanes; _i < _a.length; _i++) {
21513             var plane = _a[_i];
21514             this.scene.remove(plane);
21515             this.sceneOld.add(plane);
21516         }
21517         for (var _b = 0, planes_1 = planes; _b < planes_1.length; _b++) {
21518             var plane = planes_1[_b];
21519             this.scene.add(plane);
21520         }
21521         this.imagePlanesOld = this.imagePlanes;
21522         this.imagePlanes = planes;
21523     };
21524     ImagePlaneScene.prototype.addImagePlanes = function (planes) {
21525         for (var _i = 0, planes_2 = planes; _i < planes_2.length; _i++) {
21526             var plane = planes_2[_i];
21527             this.scene.add(plane);
21528             this.imagePlanes.push(plane);
21529         }
21530     };
21531     ImagePlaneScene.prototype.addImagePlanesOld = function (planes) {
21532         for (var _i = 0, planes_3 = planes; _i < planes_3.length; _i++) {
21533             var plane = planes_3[_i];
21534             this.sceneOld.add(plane);
21535             this.imagePlanesOld.push(plane);
21536         }
21537     };
21538     ImagePlaneScene.prototype.setImagePlanes = function (planes) {
21539         this._clear();
21540         this.addImagePlanes(planes);
21541     };
21542     ImagePlaneScene.prototype.setImagePlanesOld = function (planes) {
21543         this._clearOld();
21544         this.addImagePlanesOld(planes);
21545     };
21546     ImagePlaneScene.prototype.clear = function () {
21547         this._clear();
21548         this._clearOld();
21549     };
21550     ImagePlaneScene.prototype._clear = function () {
21551         this._dispose(this.imagePlanes, this.scene);
21552         this.imagePlanes.length = 0;
21553     };
21554     ImagePlaneScene.prototype._clearOld = function () {
21555         this._dispose(this.imagePlanesOld, this.sceneOld);
21556         this.imagePlanesOld.length = 0;
21557     };
21558     ImagePlaneScene.prototype._dispose = function (planes, scene) {
21559         for (var _i = 0, planes_4 = planes; _i < planes_4.length; _i++) {
21560             var plane = planes_4[_i];
21561             scene.remove(plane);
21562             plane.geometry.dispose();
21563             plane.material.dispose();
21564             var texture = plane.material.uniforms.projectorTex.value;
21565             if (texture != null) {
21566                 texture.dispose();
21567             }
21568         }
21569     };
21570     return ImagePlaneScene;
21571 }());
21572 exports.ImagePlaneScene = ImagePlaneScene;
21573 Object.defineProperty(exports, "__esModule", { value: true });
21574 exports.default = ImagePlaneScene;
21575
21576 },{"three":160}],244:[function(require,module,exports){
21577 /// <reference path="../../../typings/index.d.ts" />
21578 "use strict";
21579
21580 var path = require("path");
21581 var ImagePlaneShaders = (function () {
21582     function ImagePlaneShaders() {
21583     }
21584     ImagePlaneShaders.equirectangular = {
21585         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}",
21586         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}",
21587     };
21588     ImagePlaneShaders.perspective = {
21589         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}",
21590         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}",
21591     };
21592     return ImagePlaneShaders;
21593 }());
21594 exports.ImagePlaneShaders = ImagePlaneShaders;
21595
21596 },{"path":21}],245:[function(require,module,exports){
21597 /// <reference path="../../../typings/index.d.ts" />
21598 "use strict";
21599 var __extends = (this && this.__extends) || function (d, b) {
21600     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
21601     function __() { this.constructor = d; }
21602     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21603 };
21604 var vd = require("virtual-dom");
21605 var Observable_1 = require("rxjs/Observable");
21606 var Subject_1 = require("rxjs/Subject");
21607 require("rxjs/add/observable/combineLatest");
21608 require("rxjs/add/observable/fromEvent");
21609 require("rxjs/add/observable/of");
21610 require("rxjs/add/observable/zip");
21611 require("rxjs/add/operator/distinctUntilChanged");
21612 require("rxjs/add/operator/filter");
21613 require("rxjs/add/operator/first");
21614 require("rxjs/add/operator/map");
21615 require("rxjs/add/operator/merge");
21616 require("rxjs/add/operator/mergeMap");
21617 require("rxjs/add/operator/scan");
21618 require("rxjs/add/operator/switchMap");
21619 require("rxjs/add/operator/withLatestFrom");
21620 require("rxjs/add/operator/zip");
21621 var State_1 = require("../../State");
21622 var Render_1 = require("../../Render");
21623 var Utils_1 = require("../../Utils");
21624 var Component_1 = require("../../Component");
21625 var SliderState = (function () {
21626     function SliderState() {
21627         this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
21628         this._imagePlaneScene = new Component_1.ImagePlaneScene();
21629         this._currentKey = null;
21630         this._previousKey = null;
21631         this._currentPano = false;
21632         this._frameId = 0;
21633         this._glNeedsRender = false;
21634         this._domNeedsRender = true;
21635         this._curtain = 1;
21636     }
21637     Object.defineProperty(SliderState.prototype, "frameId", {
21638         get: function () {
21639             return this._frameId;
21640         },
21641         enumerable: true,
21642         configurable: true
21643     });
21644     Object.defineProperty(SliderState.prototype, "curtain", {
21645         get: function () {
21646             return this._curtain;
21647         },
21648         enumerable: true,
21649         configurable: true
21650     });
21651     Object.defineProperty(SliderState.prototype, "glNeedsRender", {
21652         get: function () {
21653             return this._glNeedsRender;
21654         },
21655         enumerable: true,
21656         configurable: true
21657     });
21658     Object.defineProperty(SliderState.prototype, "domNeedsRender", {
21659         get: function () {
21660             return this._domNeedsRender;
21661         },
21662         enumerable: true,
21663         configurable: true
21664     });
21665     Object.defineProperty(SliderState.prototype, "sliderVisible", {
21666         get: function () {
21667             return this._sliderVisible;
21668         },
21669         set: function (value) {
21670             this._sliderVisible = value;
21671             this._domNeedsRender = true;
21672         },
21673         enumerable: true,
21674         configurable: true
21675     });
21676     Object.defineProperty(SliderState.prototype, "disabled", {
21677         get: function () {
21678             return this._currentKey == null ||
21679                 this._previousKey == null ||
21680                 this._currentPano;
21681         },
21682         enumerable: true,
21683         configurable: true
21684     });
21685     SliderState.prototype.update = function (frame) {
21686         this._updateFrameId(frame.id);
21687         var needsRender = this._updateImagePlanes(frame.state);
21688         this._domNeedsRender = needsRender || this._domNeedsRender;
21689         needsRender = this._updateCurtain(frame.state.alpha) || needsRender;
21690         this._glNeedsRender = needsRender || this._glNeedsRender;
21691     };
21692     SliderState.prototype.updateTexture = function (image, node) {
21693         var imagePlanes = node.key === this._currentKey ?
21694             this._imagePlaneScene.imagePlanes :
21695             node.key === this._previousKey ?
21696                 this._imagePlaneScene.imagePlanesOld :
21697                 [];
21698         if (imagePlanes.length === 0) {
21699             return;
21700         }
21701         this._glNeedsRender = true;
21702         for (var _i = 0, imagePlanes_1 = imagePlanes; _i < imagePlanes_1.length; _i++) {
21703             var plane = imagePlanes_1[_i];
21704             var material = plane.material;
21705             var texture = material.uniforms.projectorTex.value;
21706             texture.image = image;
21707             texture.needsUpdate = true;
21708         }
21709     };
21710     SliderState.prototype.render = function (perspectiveCamera, renderer) {
21711         if (!this.disabled) {
21712             renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
21713         }
21714         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
21715     };
21716     SliderState.prototype.dispose = function () {
21717         this._imagePlaneScene.clear();
21718     };
21719     SliderState.prototype.clearGLNeedsRender = function () {
21720         this._glNeedsRender = false;
21721     };
21722     SliderState.prototype.clearDomNeedsRender = function () {
21723         this._domNeedsRender = false;
21724     };
21725     SliderState.prototype._updateFrameId = function (frameId) {
21726         this._frameId = frameId;
21727     };
21728     SliderState.prototype._updateImagePlanes = function (state) {
21729         if (state.currentNode == null) {
21730             return;
21731         }
21732         var needsRender = false;
21733         if (state.previousNode != null && this._previousKey !== state.previousNode.key) {
21734             needsRender = true;
21735             this._previousKey = state.previousNode.key;
21736             this._imagePlaneScene.setImagePlanesOld([
21737                 this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform),
21738             ]);
21739         }
21740         if (this._currentKey !== state.currentNode.key) {
21741             needsRender = true;
21742             this._currentKey = state.currentNode.key;
21743             this._currentPano = state.currentNode.pano;
21744             this._imagePlaneScene.setImagePlanes([
21745                 this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform),
21746             ]);
21747             if (!this.disabled) {
21748                 this._updateBbox();
21749             }
21750         }
21751         return needsRender;
21752     };
21753     SliderState.prototype._updateCurtain = function (alpha) {
21754         if (this.disabled ||
21755             Math.abs(this._curtain - alpha) < 0.001) {
21756             return false;
21757         }
21758         this._curtain = alpha;
21759         this._updateBbox();
21760         return true;
21761     };
21762     SliderState.prototype._updateBbox = function () {
21763         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
21764             var plane = _a[_i];
21765             var shaderMaterial = plane.material;
21766             var bbox = shaderMaterial.uniforms.bbox.value;
21767             bbox.z = this._curtain;
21768         }
21769     };
21770     return SliderState;
21771 }());
21772 var SliderComponent = (function (_super) {
21773     __extends(SliderComponent, _super);
21774     /**
21775      * Create a new slider component instance.
21776      * @class SliderComponent
21777      */
21778     function SliderComponent(name, container, navigator) {
21779         _super.call(this, name, container, navigator);
21780         this._sliderStateOperation$ = new Subject_1.Subject();
21781         this._sliderStateCreator$ = new Subject_1.Subject();
21782         this._sliderStateDisposer$ = new Subject_1.Subject();
21783         this._sliderState$ = this._sliderStateOperation$
21784             .scan(function (sliderState, operation) {
21785             return operation(sliderState);
21786         }, null)
21787             .filter(function (sliderState) {
21788             return sliderState != null;
21789         })
21790             .distinctUntilChanged(undefined, function (sliderState) {
21791             return sliderState.frameId;
21792         });
21793         this._sliderStateCreator$
21794             .map(function () {
21795             return function (sliderState) {
21796                 if (sliderState != null) {
21797                     throw new Error("Multiple slider states can not be created at the same time");
21798                 }
21799                 return new SliderState();
21800             };
21801         })
21802             .subscribe(this._sliderStateOperation$);
21803         this._sliderStateDisposer$
21804             .map(function () {
21805             return function (sliderState) {
21806                 sliderState.dispose();
21807                 return null;
21808             };
21809         })
21810             .subscribe(this._sliderStateOperation$);
21811     }
21812     /**
21813      * Set the image keys.
21814      *
21815      * Configures the component to show the image planes for the supplied image keys.
21816      *
21817      * @param {keys} ISliderKeys - Slider keys object specifying the images to be shown in the foreground and the background.
21818      */
21819     SliderComponent.prototype.setKeys = function (keys) {
21820         this.configure({ keys: keys });
21821     };
21822     /**
21823      * Set the initial position.
21824      *
21825      * Configures the intial position of the slider. The inital position value will be used when the component is activated.
21826      *
21827      * @param {number} initialPosition - Initial slider position.
21828      */
21829     SliderComponent.prototype.setInitialPosition = function (initialPosition) {
21830         this.configure({ initialPosition: initialPosition });
21831     };
21832     /**
21833      * Set the value controlling if the slider is visible.
21834      *
21835      * @param {boolean} sliderVisible - Value indicating if the slider should be visible or not.
21836      */
21837     SliderComponent.prototype.setSliderVisible = function (sliderVisible) {
21838         this.configure({ sliderVisible: sliderVisible });
21839     };
21840     SliderComponent.prototype._activate = function () {
21841         var _this = this;
21842         this._container.mouseService.preventDefaultMouseDown$.next(false);
21843         this._container.touchService.preventDefaultTouchMove$.next(false);
21844         Observable_1.Observable
21845             .combineLatest(this._navigator.stateService.state$, this._configuration$)
21846             .first()
21847             .subscribe(function (stateConfig) {
21848             if (stateConfig[0] === State_1.State.Traversing) {
21849                 _this._navigator.stateService.wait();
21850                 var position = stateConfig[1].initialPosition;
21851                 _this._navigator.stateService.moveTo(position != null ? position : 1);
21852             }
21853         });
21854         this._glRenderSubscription = this._sliderState$
21855             .map(function (sliderState) {
21856             var renderHash = {
21857                 name: _this._name,
21858                 render: {
21859                     frameId: sliderState.frameId,
21860                     needsRender: sliderState.glNeedsRender,
21861                     render: sliderState.render.bind(sliderState),
21862                     stage: Render_1.GLRenderStage.Background,
21863                 },
21864             };
21865             sliderState.clearGLNeedsRender();
21866             return renderHash;
21867         })
21868             .subscribe(this._container.glRenderer.render$);
21869         this._domRenderSubscription = this._sliderState$
21870             .filter(function (sliderState) {
21871             return sliderState.domNeedsRender;
21872         })
21873             .map(function (sliderState) {
21874             var sliderInput = vd.h("input.SliderControl", {
21875                 max: 1000,
21876                 min: 0,
21877                 type: "range",
21878                 value: 1000 * sliderState.curtain,
21879             }, []);
21880             var vNode = sliderState.disabled || !sliderState.sliderVisible ?
21881                 null :
21882                 vd.h("div.SliderWrapper", {}, [sliderInput]);
21883             var hash = {
21884                 name: _this._name,
21885                 vnode: vNode,
21886             };
21887             sliderState.clearDomNeedsRender();
21888             return hash;
21889         })
21890             .subscribe(this._container.domRenderer.render$);
21891         this._elementSubscription = this._container.domRenderer.element$
21892             .map(function (e) {
21893             var nodeList = e.getElementsByClassName("SliderControl");
21894             var slider = nodeList.length > 0 ? nodeList[0] : null;
21895             return slider;
21896         })
21897             .filter(function (input) {
21898             return input != null;
21899         })
21900             .switchMap(function (input) {
21901             return Observable_1.Observable.fromEvent(input, "input");
21902         })
21903             .map(function (e) {
21904             return Number(e.target.value) / 1000;
21905         })
21906             .subscribe(function (curtain) {
21907             _this._navigator.stateService.moveTo(curtain);
21908         });
21909         this._sliderStateCreator$.next(null);
21910         this._stateSubscription = this._navigator.stateService.currentState$
21911             .map(function (frame) {
21912             return function (sliderState) {
21913                 sliderState.update(frame);
21914                 return sliderState;
21915             };
21916         })
21917             .subscribe(this._sliderStateOperation$);
21918         this._setSliderVisibleSubscription = this._configuration$
21919             .map(function (configuration) {
21920             return configuration.sliderVisible == null || configuration.sliderVisible;
21921         })
21922             .distinctUntilChanged()
21923             .map(function (sliderVisible) {
21924             return function (sliderState) {
21925                 sliderState.sliderVisible = sliderVisible;
21926                 return sliderState;
21927             };
21928         })
21929             .subscribe(this._sliderStateOperation$);
21930         this._setKeysSubscription = this._configuration$
21931             .filter(function (configuration) {
21932             return configuration.keys != null;
21933         })
21934             .switchMap(function (configuration) {
21935             return Observable_1.Observable
21936                 .zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground))
21937                 .map(function (nodes) {
21938                 return { background: nodes[0], foreground: nodes[1] };
21939             })
21940                 .zip(_this._navigator.stateService.currentState$.first())
21941                 .map(function (nf) {
21942                 return { nodes: nf[0], state: nf[1].state };
21943             });
21944         })
21945             .subscribe(function (co) {
21946             if (co.state.currentNode != null &&
21947                 co.state.previousNode != null &&
21948                 co.state.currentNode.key === co.nodes.foreground.key &&
21949                 co.state.previousNode.key === co.nodes.background.key) {
21950                 return;
21951             }
21952             if (co.state.currentNode.key === co.nodes.background.key) {
21953                 _this._navigator.stateService.setNodes([co.nodes.foreground]);
21954                 return;
21955             }
21956             if (co.state.currentNode.key === co.nodes.foreground.key &&
21957                 co.state.trajectory.length === 1) {
21958                 _this._navigator.stateService.prependNodes([co.nodes.background]);
21959                 return;
21960             }
21961             _this._navigator.stateService.setNodes([co.nodes.background]);
21962             _this._navigator.stateService.setNodes([co.nodes.foreground]);
21963         }, function (e) {
21964             console.log(e);
21965         });
21966         var previousNode$ = this._navigator.stateService.currentState$
21967             .map(function (frame) {
21968             return frame.state.previousNode;
21969         })
21970             .filter(function (node) {
21971             return node != null;
21972         })
21973             .distinctUntilChanged(undefined, function (node) {
21974             return node.key;
21975         });
21976         this._nodeSubscription = Observable_1.Observable
21977             .merge(previousNode$, this._navigator.stateService.currentNode$)
21978             .filter(function (node) {
21979             return node.pano ?
21980                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
21981                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
21982         })
21983             .mergeMap(function (node) {
21984             var baseImageSize = node.pano ?
21985                 Utils_1.Settings.basePanoramaSize :
21986                 Utils_1.Settings.baseImageSize;
21987             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
21988                 return Observable_1.Observable.empty();
21989             }
21990             return node.cacheImage$(Utils_1.Settings.maxImageSize)
21991                 .map(function (n) {
21992                 return [n.image, n];
21993             })
21994                 .catch(function (error, caught) {
21995                 console.error("Failed to fetch high res slider image (" + node.key + ")", error);
21996                 return Observable_1.Observable.empty();
21997             });
21998         })
21999             .map(function (imn) {
22000             return function (sliderState) {
22001                 sliderState.updateTexture(imn[0], imn[1]);
22002                 return sliderState;
22003             };
22004         })
22005             .subscribe(this._sliderStateOperation$);
22006     };
22007     SliderComponent.prototype._deactivate = function () {
22008         var _this = this;
22009         this._container.mouseService.preventDefaultMouseDown$.next(true);
22010         this._container.touchService.preventDefaultTouchMove$.next(true);
22011         this._navigator.stateService.state$
22012             .first()
22013             .subscribe(function (state) {
22014             if (state === State_1.State.Waiting) {
22015                 _this._navigator.stateService.traverse();
22016             }
22017         });
22018         this._sliderStateDisposer$.next(null);
22019         this._setKeysSubscription.unsubscribe();
22020         this._setSliderVisibleSubscription.unsubscribe();
22021         this._elementSubscription.unsubscribe();
22022         this._stateSubscription.unsubscribe();
22023         this._glRenderSubscription.unsubscribe();
22024         this._domRenderSubscription.unsubscribe();
22025         this._nodeSubscription.unsubscribe();
22026         this.configure({ keys: null });
22027     };
22028     SliderComponent.prototype._getDefaultConfiguration = function () {
22029         return {};
22030     };
22031     SliderComponent.prototype._catchCacheNode$ = function (key) {
22032         return this._navigator.graphService.cacheNode$(key)
22033             .catch(function (error, caught) {
22034             console.log("Failed to cache slider node (" + key + ")", error);
22035             return Observable_1.Observable.empty();
22036         });
22037     };
22038     SliderComponent.componentName = "slider";
22039     return SliderComponent;
22040 }(Component_1.Component));
22041 exports.SliderComponent = SliderComponent;
22042 Component_1.ComponentService.register(SliderComponent);
22043 Object.defineProperty(exports, "__esModule", { value: true });
22044 exports.default = SliderComponent;
22045
22046 },{"../../Component":210,"../../Render":216,"../../State":217,"../../Utils":218,"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":46,"rxjs/add/operator/distinctUntilChanged":54,"rxjs/add/operator/filter":57,"rxjs/add/operator/first":59,"rxjs/add/operator/map":61,"rxjs/add/operator/merge":62,"rxjs/add/operator/mergeMap":64,"rxjs/add/operator/scan":69,"rxjs/add/operator/switchMap":74,"rxjs/add/operator/withLatestFrom":77,"rxjs/add/operator/zip":78,"virtual-dom":166}],246:[function(require,module,exports){
22047 "use strict";
22048 var Marker = (function () {
22049     function Marker(latLonAlt, markerOptions) {
22050         this.visibleInKeys = [];
22051         this._id = markerOptions.id;
22052         this._latLonAlt = latLonAlt;
22053         this._markerOptions = markerOptions;
22054         this._type = markerOptions.type;
22055     }
22056     Object.defineProperty(Marker.prototype, "id", {
22057         get: function () {
22058             return this._id;
22059         },
22060         enumerable: true,
22061         configurable: true
22062     });
22063     Object.defineProperty(Marker.prototype, "type", {
22064         get: function () {
22065             return this._type;
22066         },
22067         enumerable: true,
22068         configurable: true
22069     });
22070     Object.defineProperty(Marker.prototype, "latLonAlt", {
22071         get: function () {
22072             return this._latLonAlt;
22073         },
22074         enumerable: true,
22075         configurable: true
22076     });
22077     return Marker;
22078 }());
22079 exports.Marker = Marker;
22080 Object.defineProperty(exports, "__esModule", { value: true });
22081 exports.default = Marker;
22082
22083 },{}],247:[function(require,module,exports){
22084 /// <reference path="../../../typings/index.d.ts" />
22085 "use strict";
22086 var __extends = (this && this.__extends) || function (d, b) {
22087     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
22088     function __() { this.constructor = d; }
22089     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22090 };
22091 var _ = require("underscore");
22092 var THREE = require("three");
22093 var rbush = require("rbush");
22094 var Observable_1 = require("rxjs/Observable");
22095 var Subject_1 = require("rxjs/Subject");
22096 require("rxjs/add/observable/combineLatest");
22097 require("rxjs/add/operator/distinctUntilChanged");
22098 require("rxjs/add/operator/filter");
22099 require("rxjs/add/operator/map");
22100 require("rxjs/add/operator/publishReplay");
22101 require("rxjs/add/operator/scan");
22102 require("rxjs/add/operator/switchMap");
22103 var Component_1 = require("../../Component");
22104 var Render_1 = require("../../Render");
22105 var Geo_1 = require("../../Geo");
22106 var MarkerSet = (function () {
22107     function MarkerSet() {
22108         this._create$ = new Subject_1.Subject();
22109         this._remove$ = new Subject_1.Subject();
22110         this._update$ = new Subject_1.Subject();
22111         // markers list stream is the result of applying marker updates.
22112         this._markers$ = this._update$
22113             .scan(function (markers, operation) {
22114             return operation(markers);
22115         }, { hash: {}, spatial: rbush(16, [".lon", ".lat", ".lon", ".lat"]) })
22116             .map(function (markers) {
22117             return markers.spatial;
22118         })
22119             .publishReplay(1)
22120             .refCount();
22121         // creation stream generate creation updates from given markers.
22122         this._create$
22123             .map(function (marker) {
22124             return function (markers) {
22125                 if (markers.hash[marker.id]) {
22126                     markers.spatial.remove(markers.hash[marker.id]);
22127                 }
22128                 var rbushObj = {
22129                     id: marker.id,
22130                     lat: marker.latLonAlt.lat,
22131                     lon: marker.latLonAlt.lon,
22132                     marker: marker,
22133                 };
22134                 markers.spatial.insert(rbushObj);
22135                 markers.hash[marker.id] = rbushObj;
22136                 return markers;
22137             };
22138         })
22139             .subscribe(this._update$);
22140         // remove stream generates remove updates from given markers
22141         this._remove$
22142             .map(function (id) {
22143             return function (markers) {
22144                 var rbushObj = markers.hash[id];
22145                 markers.spatial.remove(rbushObj);
22146                 delete markers.hash[id];
22147                 return markers;
22148             };
22149         })
22150             .subscribe(this._update$);
22151     }
22152     MarkerSet.prototype.addMarker = function (marker) {
22153         this._create$.next(marker);
22154     };
22155     MarkerSet.prototype.removeMarker = function (id) {
22156         this._remove$.next(id);
22157     };
22158     Object.defineProperty(MarkerSet.prototype, "markers$", {
22159         get: function () {
22160             return this._markers$;
22161         },
22162         enumerable: true,
22163         configurable: true
22164     });
22165     return MarkerSet;
22166 }());
22167 exports.MarkerSet = MarkerSet;
22168 var MarkerComponent = (function (_super) {
22169     __extends(MarkerComponent, _super);
22170     function MarkerComponent(name, container, navigator) {
22171         _super.call(this, name, container, navigator);
22172     }
22173     MarkerComponent.prototype._activate = function () {
22174         var _this = this;
22175         this._scene = new THREE.Scene();
22176         this._markerSet = new MarkerSet();
22177         this._markerObjects = {};
22178         this._disposable = Observable_1.Observable
22179             .combineLatest([
22180             this._navigator.stateService.currentState$,
22181             this._markerSet.markers$,
22182         ], function (frame, markers) {
22183             return { frame: frame, markers: markers };
22184         })
22185             .distinctUntilChanged(undefined, function (args) {
22186             return args.frame.id;
22187         })
22188             .map(function (args) {
22189             return _this._renderHash(args);
22190         })
22191             .subscribe(this._container.glRenderer.render$);
22192     };
22193     MarkerComponent.prototype._deactivate = function () {
22194         // release memory
22195         this._disposeScene();
22196         this._disposable.unsubscribe();
22197     };
22198     MarkerComponent.prototype._getDefaultConfiguration = function () {
22199         return {};
22200     };
22201     MarkerComponent.prototype.createMarker = function (latLonAlt, markerOptions) {
22202         if (markerOptions.type === "marker") {
22203             return new Component_1.SimpleMarker(latLonAlt, markerOptions);
22204         }
22205         return null;
22206     };
22207     MarkerComponent.prototype.addMarker = function (marker) {
22208         this._markerSet.addMarker(marker);
22209     };
22210     Object.defineProperty(MarkerComponent.prototype, "markers$", {
22211         get: function () {
22212             return this._markerSet.markers$;
22213         },
22214         enumerable: true,
22215         configurable: true
22216     });
22217     MarkerComponent.prototype.removeMarker = function (id) {
22218         this._markerSet.removeMarker(id);
22219     };
22220     MarkerComponent.prototype._renderHash = function (args) {
22221         // determine if render is needed while updating scene
22222         // specific properies.
22223         var needsRender = this._updateScene(args);
22224         // return render hash with render function and
22225         // render in foreground.
22226         return {
22227             name: this._name,
22228             render: {
22229                 frameId: args.frame.id,
22230                 needsRender: needsRender,
22231                 render: this._render.bind(this),
22232                 stage: Render_1.GLRenderStage.Foreground,
22233             },
22234         };
22235     };
22236     MarkerComponent.prototype._updateScene = function (args) {
22237         if (!args.frame ||
22238             !args.markers ||
22239             !args.frame.state.currentNode) {
22240             return false;
22241         }
22242         var needRender = false;
22243         var oldObjects = this._markerObjects;
22244         var node = args.frame.state.currentNode;
22245         this._markerObjects = {};
22246         var boxWidth = 0.001;
22247         var minLon = node.latLon.lon - boxWidth / 2;
22248         var minLat = node.latLon.lat - boxWidth / 2;
22249         var maxLon = node.latLon.lon + boxWidth / 2;
22250         var maxLat = node.latLon.lat + boxWidth / 2;
22251         var markers = _.map(args.markers.search({ maxX: maxLon, maxY: maxLat, minX: minLon, minY: minLat }), function (item) {
22252             return item.marker;
22253         }).filter(function (marker) {
22254             return marker.visibleInKeys.length === 0 || _.contains(marker.visibleInKeys, node.key);
22255         });
22256         for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
22257             var marker = markers_1[_i];
22258             if (marker.id in oldObjects) {
22259                 this._markerObjects[marker.id] = oldObjects[marker.id];
22260                 delete oldObjects[marker.id];
22261             }
22262             else {
22263                 var reference = args.frame.state.reference;
22264                 var p = (new Geo_1.GeoCoords).geodeticToEnu(marker.latLonAlt.lat, marker.latLonAlt.lon, marker.latLonAlt.alt, reference.lat, reference.lon, reference.alt);
22265                 var o = marker.createGeometry();
22266                 o.position.set(p[0], p[1], p[2]);
22267                 this._scene.add(o);
22268                 this._markerObjects[marker.id] = o;
22269                 needRender = true;
22270             }
22271         }
22272         for (var i in oldObjects) {
22273             if (oldObjects.hasOwnProperty(i)) {
22274                 this._disposeObject(oldObjects[i]);
22275                 needRender = true;
22276             }
22277         }
22278         return needRender;
22279     };
22280     MarkerComponent.prototype._render = function (perspectiveCamera, renderer) {
22281         renderer.render(this._scene, perspectiveCamera);
22282     };
22283     MarkerComponent.prototype._disposeObject = function (object) {
22284         this._scene.remove(object);
22285         for (var i = 0; i < object.children.length; ++i) {
22286             var c = object.children[i];
22287             c.geometry.dispose();
22288             c.material.dispose();
22289         }
22290     };
22291     MarkerComponent.prototype._disposeScene = function () {
22292         for (var i in this._markerObjects) {
22293             if (this._markerObjects.hasOwnProperty(i)) {
22294                 this._disposeObject(this._markerObjects[i]);
22295             }
22296         }
22297         this._markerObjects = {};
22298     };
22299     MarkerComponent.componentName = "marker";
22300     return MarkerComponent;
22301 }(Component_1.Component));
22302 exports.MarkerComponent = MarkerComponent;
22303 Component_1.ComponentService.register(MarkerComponent);
22304 Object.defineProperty(exports, "__esModule", { value: true });
22305 exports.default = MarkerComponent;
22306
22307 },{"../../Component":210,"../../Geo":213,"../../Render":216,"rbush":24,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":54,"rxjs/add/operator/filter":57,"rxjs/add/operator/map":61,"rxjs/add/operator/publishReplay":68,"rxjs/add/operator/scan":69,"rxjs/add/operator/switchMap":74,"three":160,"underscore":161}],248:[function(require,module,exports){
22308 "use strict";
22309 var __extends = (this && this.__extends) || function (d, b) {
22310     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
22311     function __() { this.constructor = d; }
22312     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22313 };
22314 var THREE = require("three");
22315 var Component_1 = require("../../Component");
22316 var SimpleMarker = (function (_super) {
22317     __extends(SimpleMarker, _super);
22318     function SimpleMarker(latLonAlt, markerOptions) {
22319         _super.call(this, latLonAlt, markerOptions);
22320         this._circleToRayAngle = 2.0;
22321         this._simpleMarkerStyle = markerOptions.style;
22322     }
22323     SimpleMarker.prototype.createGeometry = function () {
22324         var radius = 2;
22325         var cone = new THREE.Mesh(this._markerGeometry(radius, 16, 8), new THREE.MeshBasicMaterial({
22326             color: this._stringToRBG(this._simpleMarkerStyle.color),
22327             depthWrite: false,
22328             opacity: this._simpleMarkerStyle.opacity,
22329             shading: THREE.SmoothShading,
22330             transparent: true,
22331         }));
22332         var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 16, 8), new THREE.MeshBasicMaterial({
22333             color: this._stringToRBG(this._simpleMarkerStyle.ballColor),
22334             depthWrite: false,
22335             opacity: this._simpleMarkerStyle.ballOpacity,
22336             shading: THREE.SmoothShading,
22337             transparent: true,
22338         }));
22339         ball.position.z = this._markerHeight(radius);
22340         var group = new THREE.Object3D();
22341         group.add(ball);
22342         group.add(cone);
22343         return group;
22344     };
22345     SimpleMarker.prototype._markerHeight = function (radius) {
22346         var t = Math.tan(Math.PI - this._circleToRayAngle);
22347         return radius * Math.sqrt(1 + t * t);
22348     };
22349     SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) {
22350         var geometry = new THREE.Geometry();
22351         widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
22352         heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
22353         var height = this._markerHeight(radius);
22354         var vertices = [];
22355         for (var y = 0; y <= heightSegments; ++y) {
22356             var verticesRow = [];
22357             for (var x = 0; x <= widthSegments; ++x) {
22358                 var u = x / widthSegments * Math.PI * 2;
22359                 var v = y / heightSegments * Math.PI;
22360                 var r = void 0;
22361                 if (v < this._circleToRayAngle) {
22362                     r = radius;
22363                 }
22364                 else {
22365                     var t = Math.tan(v - this._circleToRayAngle);
22366                     r = radius * Math.sqrt(1 + t * t);
22367                 }
22368                 var vertex = new THREE.Vector3();
22369                 vertex.x = r * Math.cos(u) * Math.sin(v);
22370                 vertex.y = r * Math.sin(u) * Math.sin(v);
22371                 vertex.z = r * Math.cos(v) + height;
22372                 geometry.vertices.push(vertex);
22373                 verticesRow.push(geometry.vertices.length - 1);
22374             }
22375             vertices.push(verticesRow);
22376         }
22377         for (var y = 0; y < heightSegments; ++y) {
22378             for (var x = 0; x < widthSegments; ++x) {
22379                 var v1 = vertices[y][x + 1];
22380                 var v2 = vertices[y][x];
22381                 var v3 = vertices[y + 1][x];
22382                 var v4 = vertices[y + 1][x + 1];
22383                 var n1 = geometry.vertices[v1].clone().normalize();
22384                 var n2 = geometry.vertices[v2].clone().normalize();
22385                 var n3 = geometry.vertices[v3].clone().normalize();
22386                 var n4 = geometry.vertices[v4].clone().normalize();
22387                 geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4]));
22388                 geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()]));
22389             }
22390         }
22391         geometry.computeFaceNormals();
22392         geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height);
22393         return geometry;
22394     };
22395     SimpleMarker.prototype._stringToRBG = function (str) {
22396         var ret = 0;
22397         for (var i = 0; i < str.length; i++) {
22398             ret = str.charCodeAt(i) + ((ret << 5) - ret);
22399         }
22400         return ret;
22401     };
22402     return SimpleMarker;
22403 }(Component_1.Marker));
22404 exports.SimpleMarker = SimpleMarker;
22405 Object.defineProperty(exports, "__esModule", { value: true });
22406 exports.default = SimpleMarker;
22407
22408 },{"../../Component":210,"three":160}],249:[function(require,module,exports){
22409 /// <reference path="../../../typings/index.d.ts" />
22410 "use strict";
22411 var __extends = (this && this.__extends) || function (d, b) {
22412     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
22413     function __() { this.constructor = d; }
22414     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22415 };
22416 var Observable_1 = require("rxjs/Observable");
22417 var Subject_1 = require("rxjs/Subject");
22418 require("rxjs/add/observable/combineLatest");
22419 require("rxjs/add/observable/of");
22420 require("rxjs/add/operator/concat");
22421 require("rxjs/add/operator/distinctUntilChanged");
22422 require("rxjs/add/operator/filter");
22423 require("rxjs/add/operator/finally");
22424 require("rxjs/add/operator/first");
22425 require("rxjs/add/operator/map");
22426 require("rxjs/add/operator/publishReplay");
22427 require("rxjs/add/operator/scan");
22428 require("rxjs/add/operator/share");
22429 require("rxjs/add/operator/switchMap");
22430 require("rxjs/add/operator/takeUntil");
22431 require("rxjs/add/operator/withLatestFrom");
22432 var Component_1 = require("../../Component");
22433 var Edge_1 = require("../../Edge");
22434 /**
22435  * @class SequenceComponent
22436  * @classdesc Component showing navigation arrows for sequence directions
22437  * as well as playing button. Exposes an API to start and stop play.
22438  */
22439 var SequenceComponent = (function (_super) {
22440     __extends(SequenceComponent, _super);
22441     function SequenceComponent(name, container, navigator) {
22442         _super.call(this, name, container, navigator);
22443         this._nodesAhead = 5;
22444         this._configurationOperation$ = new Subject_1.Subject();
22445         this._sequenceDOMRenderer = new Component_1.SequenceDOMRenderer(container.element);
22446         this._sequenceDOMInteraction = new Component_1.SequenceDOMInteraction();
22447         this._containerWidth$ = new Subject_1.Subject();
22448         this._hoveredKeySubject$ = new Subject_1.Subject();
22449         this._hoveredKey$ = this._hoveredKeySubject$.share();
22450         this._edgeStatus$ = this._navigator.stateService.currentNode$
22451             .switchMap(function (node) {
22452             return node.sequenceEdges$;
22453         })
22454             .publishReplay(1)
22455             .refCount();
22456     }
22457     Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", {
22458         /**
22459          * Get hovered key observable.
22460          *
22461          * @description An observable emitting the key of the node for the direction
22462          * arrow that is being hovered. When the mouse leaves a direction arrow null
22463          * is emitted.
22464          *
22465          * @returns {Observable<string>}
22466          */
22467         get: function () {
22468             return this._hoveredKey$;
22469         },
22470         enumerable: true,
22471         configurable: true
22472     });
22473     /**
22474      * Start playing.
22475      *
22476      * @fires PlayerComponent#playingchanged
22477      */
22478     SequenceComponent.prototype.play = function () {
22479         this.configure({ playing: true });
22480     };
22481     /**
22482      * Stop playing.
22483      *
22484      * @fires PlayerComponent#playingchanged
22485      */
22486     SequenceComponent.prototype.stop = function () {
22487         this.configure({ playing: false });
22488     };
22489     /**
22490      * Set the direction to follow when playing.
22491      *
22492      * @param {EdgeDirection} direction - The direction that will be followed when playing.
22493      */
22494     SequenceComponent.prototype.setDirection = function (direction) {
22495         this.configure({ direction: direction });
22496     };
22497     /**
22498      * Set highlight key.
22499      *
22500      * @description The arrow pointing towards the node corresponding to the
22501      * highlight key will be highlighted.
22502      *
22503      * @param {string} highlightKey Key of node to be highlighted if existing.
22504      */
22505     SequenceComponent.prototype.setHighlightKey = function (highlightKey) {
22506         this.configure({ highlightKey: highlightKey });
22507     };
22508     /**
22509      * Set max width of container element.
22510      *
22511      * @description Set max width of the container element holding
22512      * the sequence navigation elements. If the min width is larger than the
22513      * max width the min width value will be used.
22514      *
22515      * The container element is automatically resized when the resize
22516      * method on the Viewer class is called.
22517      *
22518      * @param {number} minWidth
22519      */
22520     SequenceComponent.prototype.setMaxWidth = function (maxWidth) {
22521         this.configure({ maxWidth: maxWidth });
22522     };
22523     /**
22524      * Set min width of container element.
22525      *
22526      * @description Set min width of the container element holding
22527      * the sequence navigation elements. If the min width is larger than the
22528      * max width the min width value will be used.
22529      *
22530      * The container element is automatically resized when the resize
22531      * method on the Viewer class is called.
22532      *
22533      * @param {number} minWidth
22534      */
22535     SequenceComponent.prototype.setMinWidth = function (minWidth) {
22536         this.configure({ minWidth: minWidth });
22537     };
22538     /**
22539      * Set the value indicating whether the sequence UI elements should be visible.
22540      *
22541      * @param {boolean} visible
22542      */
22543     SequenceComponent.prototype.setVisible = function (visible) {
22544         this.configure({ visible: visible });
22545     };
22546     /** @inheritdoc */
22547     SequenceComponent.prototype.resize = function () {
22548         var _this = this;
22549         this._configuration$
22550             .first()
22551             .map(function (configuration) {
22552             return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
22553         })
22554             .subscribe(function (containerWidth) {
22555             _this._containerWidth$.next(containerWidth);
22556         });
22557     };
22558     SequenceComponent.prototype._activate = function () {
22559         var _this = this;
22560         this._renderSubscription = Observable_1.Observable
22561             .combineLatest(this._edgeStatus$, this._configuration$, this._containerWidth$)
22562             .map(function (ec) {
22563             var edgeStatus = ec[0];
22564             var configuration = ec[1];
22565             var containerWidth = ec[2];
22566             var vNode = _this._sequenceDOMRenderer
22567                 .render(edgeStatus, configuration, containerWidth, _this, _this._sequenceDOMInteraction, _this._navigator);
22568             return { name: _this._name, vnode: vNode };
22569         })
22570             .subscribe(this._container.domRenderer.render$);
22571         this._containerWidthSubscription = this._configuration$
22572             .distinctUntilChanged(function (value1, value2) {
22573             return value1[0] === value2[0] && value1[1] === value2[1];
22574         }, function (configuration) {
22575             return [configuration.minWidth, configuration.maxWidth];
22576         })
22577             .map(function (configuration) {
22578             return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
22579         })
22580             .subscribe(this._containerWidth$);
22581         this._configurationSubscription = this._configurationOperation$
22582             .scan(function (configuration, operation) {
22583             return operation(configuration);
22584         }, { playing: false })
22585             .finally(function () {
22586             if (_this._playingSubscription != null) {
22587                 _this._navigator.stateService.cutNodes();
22588                 _this._stop();
22589             }
22590         })
22591             .subscribe();
22592         this._configuration$
22593             .map(function (newConfiguration) {
22594             return function (configuration) {
22595                 if (newConfiguration.playing !== configuration.playing) {
22596                     _this._navigator.stateService.cutNodes();
22597                     if (newConfiguration.playing) {
22598                         _this._play();
22599                     }
22600                     else {
22601                         _this._stop();
22602                     }
22603                 }
22604                 configuration.playing = newConfiguration.playing;
22605                 return configuration;
22606             };
22607         })
22608             .subscribe(this._configurationOperation$);
22609         this._stopSubscription = this._configuration$
22610             .switchMap(function (configuration) {
22611             var edgeStatus$ = configuration.playing ?
22612                 _this._edgeStatus$ :
22613                 Observable_1.Observable.empty();
22614             var edgeDirection$ = Observable_1.Observable
22615                 .of(configuration.direction);
22616             return Observable_1.Observable
22617                 .combineLatest(edgeStatus$, edgeDirection$);
22618         })
22619             .map(function (ne) {
22620             var edgeStatus = ne[0];
22621             var direction = ne[1];
22622             if (!edgeStatus.cached) {
22623                 return true;
22624             }
22625             for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
22626                 var edge = _a[_i];
22627                 if (edge.data.direction === direction) {
22628                     return true;
22629                 }
22630             }
22631             return false;
22632         })
22633             .filter(function (hasEdge) {
22634             return !hasEdge;
22635         })
22636             .map(function (hasEdge) {
22637             return { playing: false };
22638         })
22639             .subscribe(this._configurationSubject$);
22640         this._hoveredKeySubscription = this._sequenceDOMInteraction.mouseEnterDirection$
22641             .switchMap(function (direction) {
22642             return _this._edgeStatus$
22643                 .map(function (edgeStatus) {
22644                 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
22645                     var edge = _a[_i];
22646                     if (edge.data.direction === direction) {
22647                         return edge.to;
22648                     }
22649                 }
22650                 return null;
22651             })
22652                 .takeUntil(_this._sequenceDOMInteraction.mouseLeaveDirection$)
22653                 .concat(Observable_1.Observable.of(null));
22654         })
22655             .distinctUntilChanged()
22656             .subscribe(this._hoveredKeySubject$);
22657     };
22658     SequenceComponent.prototype._deactivate = function () {
22659         this._stopSubscription.unsubscribe();
22660         this._renderSubscription.unsubscribe();
22661         this._configurationSubscription.unsubscribe();
22662         this._containerWidthSubscription.unsubscribe();
22663         this._hoveredKeySubscription.unsubscribe();
22664         this.stop();
22665     };
22666     SequenceComponent.prototype._getDefaultConfiguration = function () {
22667         return {
22668             direction: Edge_1.EdgeDirection.Next,
22669             maxWidth: 117,
22670             minWidth: 70,
22671             playing: false,
22672             visible: true,
22673         };
22674     };
22675     SequenceComponent.prototype._play = function () {
22676         var _this = this;
22677         this._playingSubscription = this._navigator.stateService.currentState$
22678             .filter(function (frame) {
22679             return frame.state.nodesAhead < _this._nodesAhead;
22680         })
22681             .map(function (frame) {
22682             return frame.state.lastNode;
22683         })
22684             .distinctUntilChanged(undefined, function (lastNode) {
22685             return lastNode.key;
22686         })
22687             .withLatestFrom(this._configuration$, function (lastNode, configuration) {
22688             return [lastNode, configuration.direction];
22689         })
22690             .switchMap(function (nd) {
22691             return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(nd[1]) > -1 ?
22692                 nd[0].sequenceEdges$ :
22693                 nd[0].spatialEdges$)
22694                 .filter(function (status) {
22695                 return status.cached;
22696             })
22697                 .zip(Observable_1.Observable.of(nd[1]), function (status, direction) {
22698                 return [status, direction];
22699             });
22700         })
22701             .map(function (ed) {
22702             var direction = ed[1];
22703             for (var _i = 0, _a = ed[0].edges; _i < _a.length; _i++) {
22704                 var edge = _a[_i];
22705                 if (edge.data.direction === direction) {
22706                     return edge.to;
22707                 }
22708             }
22709             return null;
22710         })
22711             .filter(function (key) {
22712             return key != null;
22713         })
22714             .switchMap(function (key) {
22715             return _this._navigator.graphService.cacheNode$(key);
22716         })
22717             .subscribe(function (node) {
22718             _this._navigator.stateService.appendNodes([node]);
22719         }, function (error) {
22720             console.error(error);
22721             _this.stop();
22722         });
22723         this.fire(SequenceComponent.playingchanged, true);
22724     };
22725     SequenceComponent.prototype._stop = function () {
22726         this._playingSubscription.unsubscribe();
22727         this._playingSubscription = null;
22728         this.fire(SequenceComponent.playingchanged, false);
22729     };
22730     /** @inheritdoc */
22731     SequenceComponent.componentName = "sequence";
22732     /**
22733      * Event fired when playing starts or stops.
22734      *
22735      * @event PlayerComponent#playingchanged
22736      * @type {boolean} Indicates whether the player is playing.
22737      */
22738     SequenceComponent.playingchanged = "playingchanged";
22739     return SequenceComponent;
22740 }(Component_1.Component));
22741 exports.SequenceComponent = SequenceComponent;
22742 Component_1.ComponentService.register(SequenceComponent);
22743 Object.defineProperty(exports, "__esModule", { value: true });
22744 exports.default = SequenceComponent;
22745
22746 },{"../../Component":210,"../../Edge":211,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/observable/of":44,"rxjs/add/operator/concat":51,"rxjs/add/operator/distinctUntilChanged":54,"rxjs/add/operator/filter":57,"rxjs/add/operator/finally":58,"rxjs/add/operator/first":59,"rxjs/add/operator/map":61,"rxjs/add/operator/publishReplay":68,"rxjs/add/operator/scan":69,"rxjs/add/operator/share":70,"rxjs/add/operator/switchMap":74,"rxjs/add/operator/takeUntil":76,"rxjs/add/operator/withLatestFrom":77}],250:[function(require,module,exports){
22747 "use strict";
22748 var Subject_1 = require("rxjs/Subject");
22749 var SequenceDOMInteraction = (function () {
22750     function SequenceDOMInteraction() {
22751         this._mouseEnterDirection$ = new Subject_1.Subject();
22752         this._mouseLeaveDirection$ = new Subject_1.Subject();
22753     }
22754     Object.defineProperty(SequenceDOMInteraction.prototype, "mouseEnterDirection$", {
22755         get: function () {
22756             return this._mouseEnterDirection$;
22757         },
22758         enumerable: true,
22759         configurable: true
22760     });
22761     Object.defineProperty(SequenceDOMInteraction.prototype, "mouseLeaveDirection$", {
22762         get: function () {
22763             return this._mouseLeaveDirection$;
22764         },
22765         enumerable: true,
22766         configurable: true
22767     });
22768     return SequenceDOMInteraction;
22769 }());
22770 exports.SequenceDOMInteraction = SequenceDOMInteraction;
22771 Object.defineProperty(exports, "__esModule", { value: true });
22772 exports.default = SequenceDOMInteraction;
22773
22774 },{"rxjs/Subject":33}],251:[function(require,module,exports){
22775 /// <reference path="../../../typings/index.d.ts" />
22776 "use strict";
22777 var vd = require("virtual-dom");
22778 var Edge_1 = require("../../Edge");
22779 var SequenceDOMRenderer = (function () {
22780     function SequenceDOMRenderer(element) {
22781         this._minThresholdWidth = 320;
22782         this._maxThresholdWidth = 1480;
22783         this._minThresholdHeight = 240;
22784         this._maxThresholdHeight = 820;
22785     }
22786     SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, component, interaction, navigator) {
22787         if (configuration.visible === false) {
22788             return vd.h("div.SequenceContainer", {}, []);
22789         }
22790         var nextKey = null;
22791         var prevKey = null;
22792         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
22793             var edge = _a[_i];
22794             if (edge.data.direction === Edge_1.EdgeDirection.Next) {
22795                 nextKey = edge.to;
22796             }
22797             if (edge.data.direction === Edge_1.EdgeDirection.Prev) {
22798                 prevKey = edge.to;
22799             }
22800         }
22801         var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component);
22802         var arrows = this._createSequenceArrows(nextKey, prevKey, configuration, interaction, navigator);
22803         var containerProperties = {
22804             style: { height: (0.27 * containerWidth) + "px", width: containerWidth + "px" },
22805         };
22806         return vd.h("div.SequenceContainer", containerProperties, arrows.concat([playingButton]));
22807     };
22808     SequenceDOMRenderer.prototype.getContainerWidth = function (element, configuration) {
22809         var elementWidth = element.offsetWidth;
22810         var elementHeight = element.offsetHeight;
22811         var minWidth = configuration.minWidth;
22812         var maxWidth = configuration.maxWidth;
22813         if (maxWidth < minWidth) {
22814             maxWidth = minWidth;
22815         }
22816         var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
22817         var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
22818         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
22819         return minWidth + coeff * (maxWidth - minWidth);
22820     };
22821     SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) {
22822         var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null ||
22823             configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null;
22824         var onclick = configuration.playing ?
22825             function (e) { component.stop(); } :
22826             canPlay ? function (e) { component.play(); } : null;
22827         var buttonProperties = {
22828             onclick: onclick,
22829             style: {},
22830         };
22831         var iconClass = configuration.playing ?
22832             "Stop" :
22833             canPlay ? "Play" : "PlayDisabled";
22834         var icon = vd.h("div.SequenceComponentIcon", { className: iconClass }, []);
22835         var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled";
22836         return vd.h("div." + buttonClass, buttonProperties, [icon]);
22837     };
22838     SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, configuration, interaction, navigator) {
22839         var nextProperties = {
22840             onclick: nextKey != null ?
22841                 function (e) {
22842                     navigator.moveDir$(Edge_1.EdgeDirection.Next)
22843                         .subscribe(function (node) { return; }, function (error) { console.error(error); });
22844                 } :
22845                 null,
22846             onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); },
22847             onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); },
22848             style: {},
22849         };
22850         var prevProperties = {
22851             onclick: prevKey != null ?
22852                 function (e) {
22853                     navigator.moveDir$(Edge_1.EdgeDirection.Prev)
22854                         .subscribe(function (node) { return; }, function (error) { console.error(error); });
22855                 } :
22856                 null,
22857             onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); },
22858             onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); },
22859             style: {},
22860         };
22861         var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey);
22862         var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey);
22863         var nextIcon = vd.h("div.SequenceComponentIcon", []);
22864         var prevIcon = vd.h("div.SequenceComponentIcon", []);
22865         return [
22866             vd.h("div." + nextClass, nextProperties, [nextIcon]),
22867             vd.h("div." + prevClass, prevProperties, [prevIcon]),
22868         ];
22869     };
22870     SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) {
22871         var className = direction === Edge_1.EdgeDirection.Next ?
22872             "SequenceStepNext" :
22873             "SequenceStepPrev";
22874         if (key == null) {
22875             className += "Disabled";
22876         }
22877         else {
22878             if (highlightKey === key) {
22879                 className += "Highlight";
22880             }
22881         }
22882         return className;
22883     };
22884     return SequenceDOMRenderer;
22885 }());
22886 exports.SequenceDOMRenderer = SequenceDOMRenderer;
22887 Object.defineProperty(exports, "__esModule", { value: true });
22888 exports.default = SequenceDOMRenderer;
22889
22890 },{"../../Edge":211,"virtual-dom":166}],252:[function(require,module,exports){
22891 "use strict";
22892 var GeometryTagError_1 = require("./error/GeometryTagError");
22893 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
22894 var PointGeometry_1 = require("./geometry/PointGeometry");
22895 exports.PointGeometry = PointGeometry_1.PointGeometry;
22896 var RectGeometry_1 = require("./geometry/RectGeometry");
22897 exports.RectGeometry = RectGeometry_1.RectGeometry;
22898 var PolygonGeometry_1 = require("./geometry/PolygonGeometry");
22899 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
22900 var OutlineTag_1 = require("./tag/OutlineTag");
22901 exports.OutlineTag = OutlineTag_1.OutlineTag;
22902 var SpotTag_1 = require("./tag/SpotTag");
22903 exports.SpotTag = SpotTag_1.SpotTag;
22904 var Alignment_1 = require("./tag/Alignment");
22905 exports.Alignment = Alignment_1.Alignment;
22906 var TagComponent_1 = require("./TagComponent");
22907 exports.TagComponent = TagComponent_1.TagComponent;
22908
22909 },{"./TagComponent":253,"./error/GeometryTagError":259,"./geometry/PointGeometry":261,"./geometry/PolygonGeometry":262,"./geometry/RectGeometry":263,"./tag/Alignment":265,"./tag/OutlineTag":268,"./tag/SpotTag":271}],253:[function(require,module,exports){
22910 /// <reference path="../../../typings/index.d.ts" />
22911 "use strict";
22912 var __extends = (this && this.__extends) || function (d, b) {
22913     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
22914     function __() { this.constructor = d; }
22915     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22916 };
22917 var THREE = require("three");
22918 var Observable_1 = require("rxjs/Observable");
22919 var Subject_1 = require("rxjs/Subject");
22920 require("rxjs/add/observable/combineLatest");
22921 require("rxjs/add/observable/empty");
22922 require("rxjs/add/observable/from");
22923 require("rxjs/add/observable/merge");
22924 require("rxjs/add/observable/of");
22925 require("rxjs/add/operator/combineLatest");
22926 require("rxjs/add/operator/concat");
22927 require("rxjs/add/operator/distinctUntilChanged");
22928 require("rxjs/add/operator/do");
22929 require("rxjs/add/operator/filter");
22930 require("rxjs/add/operator/map");
22931 require("rxjs/add/operator/merge");
22932 require("rxjs/add/operator/mergeMap");
22933 require("rxjs/add/operator/publishReplay");
22934 require("rxjs/add/operator/scan");
22935 require("rxjs/add/operator/share");
22936 require("rxjs/add/operator/skip");
22937 require("rxjs/add/operator/skipUntil");
22938 require("rxjs/add/operator/startWith");
22939 require("rxjs/add/operator/switchMap");
22940 require("rxjs/add/operator/take");
22941 require("rxjs/add/operator/takeUntil");
22942 require("rxjs/add/operator/withLatestFrom");
22943 var Component_1 = require("../../Component");
22944 var Render_1 = require("../../Render");
22945 /**
22946  * @class TagComponent
22947  * @classdesc Component for showing and editing tags with different geometries.
22948  */
22949 var TagComponent = (function (_super) {
22950     __extends(TagComponent, _super);
22951     function TagComponent(name, container, navigator) {
22952         var _this = this;
22953         _super.call(this, name, container, navigator);
22954         this._tagDomRenderer = new Component_1.TagDOMRenderer();
22955         this._tagSet = new Component_1.TagSet();
22956         this._tagCreator = new Component_1.TagCreator();
22957         this._tagGlRendererOperation$ = new Subject_1.Subject();
22958         this._tagGlRenderer$ = this._tagGlRendererOperation$
22959             .startWith(function (renderer) {
22960             return renderer;
22961         })
22962             .scan(function (renderer, operation) {
22963             return operation(renderer);
22964         }, new Component_1.TagGLRenderer());
22965         this._tags$ = this._tagSet.tagData$
22966             .map(function (tagData) {
22967             var tags = [];
22968             // ensure that tags are always rendered in the same order
22969             // to avoid hover tracking problems on first resize.
22970             for (var _i = 0, _a = Object.keys(tagData).sort(); _i < _a.length; _i++) {
22971                 var key = _a[_i];
22972                 tags.push(tagData[key]);
22973             }
22974             return tags;
22975         })
22976             .share();
22977         this._renderTags$ = this.tags$
22978             .withLatestFrom(this._navigator.stateService.currentTransform$)
22979             .map(function (args) {
22980             var tags = args[0];
22981             var transform = args[1];
22982             var renderTags = tags
22983                 .map(function (tag) {
22984                 if (tag instanceof Component_1.OutlineTag) {
22985                     return new Component_1.OutlineRenderTag(tag, transform);
22986                 }
22987                 else if (tag instanceof Component_1.SpotTag) {
22988                     return new Component_1.SpotRenderTag(tag, transform);
22989                 }
22990                 throw new Error("Tag type not supported");
22991             });
22992             return renderTags;
22993         })
22994             .share();
22995         this._tagChanged$ = this._tags$
22996             .switchMap(function (tags) {
22997             return Observable_1.Observable
22998                 .from(tags)
22999                 .mergeMap(function (tag) {
23000                 return Observable_1.Observable
23001                     .merge(tag.changed$, tag.geometryChanged$);
23002             });
23003         })
23004             .share();
23005         this._renderTagGLChanged$ = this._renderTags$
23006             .switchMap(function (tags) {
23007             return Observable_1.Observable
23008                 .from(tags)
23009                 .mergeMap(function (tag) {
23010                 return tag.glObjectsChanged$;
23011             });
23012         })
23013             .share();
23014         this._tagInterationInitiated$ = this._renderTags$
23015             .switchMap(function (tags) {
23016             return Observable_1.Observable
23017                 .from(tags)
23018                 .mergeMap(function (tag) {
23019                 return tag.interact$
23020                     .map(function (interaction) {
23021                     return interaction.tag.id;
23022                 });
23023             });
23024         })
23025             .share();
23026         this._tagInteractionAbort$ = Observable_1.Observable
23027             .merge(this._container.mouseService.mouseUp$, this._container.mouseService.mouseLeave$)
23028             .map(function (e) {
23029             return;
23030         })
23031             .share();
23032         this._activeTag$ = this._renderTags$
23033             .switchMap(function (tags) {
23034             return Observable_1.Observable
23035                 .from(tags)
23036                 .mergeMap(function (tag) {
23037                 return tag.interact$;
23038             });
23039         })
23040             .merge(this._tagInteractionAbort$
23041             .map(function () {
23042             return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null };
23043         }))
23044             .share();
23045         this._createGeometryChanged$ = this._tagCreator.tag$
23046             .switchMap(function (tag) {
23047             return tag != null ?
23048                 tag.geometryChanged$ :
23049                 Observable_1.Observable.empty();
23050         })
23051             .share();
23052         this._tagCreated$ = this._tagCreator.tag$
23053             .switchMap(function (tag) {
23054             return tag != null ?
23055                 tag.created$ :
23056                 Observable_1.Observable.empty();
23057         })
23058             .share();
23059         this._vertexGeometryCreated$ = this._tagCreated$
23060             .map(function (tag) {
23061             return tag.geometry;
23062         })
23063             .share();
23064         this._pointGeometryCreated$ = new Subject_1.Subject();
23065         this._geometryCreated$ = Observable_1.Observable
23066             .merge(this._vertexGeometryCreated$, this._pointGeometryCreated$)
23067             .share();
23068         this._basicClick$ = this._container.mouseService.staticClick$
23069             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (event, renderCamera, transform) {
23070             return [event, renderCamera, transform];
23071         })
23072             .map(function (ert) {
23073             var event = ert[0];
23074             var camera = ert[1];
23075             var transform = ert[2];
23076             var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
23077             return basic;
23078         })
23079             .share();
23080         this._validBasicClick$ = this._basicClick$
23081             .filter(function (basic) {
23082             var x = basic[0];
23083             var y = basic[1];
23084             return 0 <= x && x <= 1 && 0 <= y && y <= 1;
23085         })
23086             .share();
23087         this._creatingConfiguration$ = this._configuration$
23088             .distinctUntilChanged(function (c1, c2) {
23089             return c1.creating === c2.creating && c1.createType === c2.createType;
23090         }, function (configuration) {
23091             return {
23092                 createColor: configuration.createColor,
23093                 createType: configuration.createType,
23094                 creating: configuration.creating,
23095             };
23096         })
23097             .publishReplay(1)
23098             .refCount();
23099         this._creating$ = this._creatingConfiguration$
23100             .map(function (configuration) {
23101             return configuration.creating;
23102         })
23103             .publishReplay(1)
23104             .refCount();
23105         this._creating$
23106             .subscribe(function (creating) {
23107             _this.fire(TagComponent.creatingchanged, creating);
23108         });
23109     }
23110     Object.defineProperty(TagComponent.prototype, "tags$", {
23111         /**
23112          * Get tags observable.
23113          *
23114          * @description An observable emitting every time the items in the
23115          * tag array changes.
23116          *
23117          * @returns {Observable<Tag[]>}
23118          */
23119         get: function () {
23120             return this._tags$;
23121         },
23122         enumerable: true,
23123         configurable: true
23124     });
23125     Object.defineProperty(TagComponent.prototype, "geometryCreated$", {
23126         /**
23127          * Get geometry created observable.
23128          *
23129          * @description An observable emitting every time a geometry
23130          * has been created.
23131          *
23132          * @returns {Observable<Geometry>}
23133          */
23134         get: function () {
23135             return this._geometryCreated$;
23136         },
23137         enumerable: true,
23138         configurable: true
23139     });
23140     /**
23141      * Set the tags to display.
23142      *
23143      * @param {Tag[]} tags - The tags.
23144      */
23145     TagComponent.prototype.setTags = function (tags) {
23146         this._tagSet.set$.next(tags);
23147     };
23148     /**
23149      * Configure the component to enter create mode for
23150      * creating a geometry of a certain type.
23151      *
23152      * @description Supported geometry types are: rect
23153      *
23154      * @param {string} geometryType - String specifying the geometry type.
23155      */
23156     TagComponent.prototype.startCreate = function (geometryType) {
23157         this.configure({ createType: geometryType, creating: true });
23158     };
23159     /**
23160      * Configure the component to leave create mode.
23161      *
23162      * @description A non completed geometry will be removed.
23163      */
23164     TagComponent.prototype.stopCreate = function () {
23165         this.configure({ createType: null, creating: false });
23166     };
23167     TagComponent.prototype._activate = function () {
23168         var _this = this;
23169         this._geometryCreatedEventSubscription = this._geometryCreated$
23170             .subscribe(function (geometry) {
23171             _this.fire(TagComponent.geometrycreated, geometry);
23172         });
23173         this._tagsChangedEventSubscription = this._tags$
23174             .subscribe(function (tags) {
23175             _this.fire(TagComponent.tagschanged, tags);
23176         });
23177         var nodeChanged$ = this.configuration$
23178             .switchMap(function (configuration) {
23179             return configuration.creating ?
23180                 _this._navigator.stateService.currentNode$
23181                     .skip(1)
23182                     .take(1)
23183                     .map(function (n) { return null; }) :
23184                 Observable_1.Observable.empty();
23185         });
23186         var tagAborted$ = this._tagCreator.tag$
23187             .switchMap(function (tag) {
23188             return tag != null ?
23189                 tag.aborted$
23190                     .map(function (t) { return null; }) :
23191                 Observable_1.Observable.empty();
23192         });
23193         var tagCreated$ = this._tagCreated$
23194             .map(function (t) { return null; });
23195         var pointGeometryCreated$ = this._pointGeometryCreated$
23196             .map(function (p) { return null; });
23197         this._stopCreateSubscription = Observable_1.Observable
23198             .merge(nodeChanged$, tagAborted$, tagCreated$, pointGeometryCreated$)
23199             .subscribe(function () { _this.stopCreate(); });
23200         this._creatorConfigurationSubscription = this._configuration$
23201             .subscribe(this._tagCreator.configuration$);
23202         this._createSubscription = this._creatingConfiguration$
23203             .switchMap(function (configuration) {
23204             return configuration.creating &&
23205                 configuration.createType === "rect" ||
23206                 configuration.createType === "polygon" ?
23207                 _this._validBasicClick$.take(1) :
23208                 Observable_1.Observable.empty();
23209         })
23210             .subscribe(this._tagCreator.create$);
23211         this._createPointSubscription = this._creatingConfiguration$
23212             .switchMap(function (configuration) {
23213             return configuration.creating &&
23214                 configuration.createType === "point" ?
23215                 _this._validBasicClick$.take(1) :
23216                 Observable_1.Observable.empty();
23217         })
23218             .map(function (basic) {
23219             return new Component_1.PointGeometry(basic);
23220         })
23221             .subscribe(this._pointGeometryCreated$);
23222         this._setCreateVertexSubscription = Observable_1.Observable
23223             .combineLatest(this._container.mouseService.mouseMove$, this._tagCreator.tag$, this._container.renderService.renderCamera$)
23224             .filter(function (etr) {
23225             return etr[1] != null;
23226         })
23227             .withLatestFrom(this._navigator.stateService.currentTransform$, function (etr, transform) {
23228             return [etr[0], etr[1], etr[2], transform];
23229         })
23230             .subscribe(function (etrt) {
23231             var event = etrt[0];
23232             var tag = etrt[1];
23233             var camera = etrt[2];
23234             var transform = etrt[3];
23235             var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
23236             if (tag.geometry instanceof Component_1.RectGeometry) {
23237                 tag.geometry.setVertex2d(3, basic, transform);
23238             }
23239             else if (tag.geometry instanceof Component_1.PolygonGeometry) {
23240                 tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basic, transform);
23241             }
23242         });
23243         this._addPointSubscription = this._creatingConfiguration$
23244             .switchMap(function (configuration) {
23245             var createType = configuration.createType;
23246             return configuration.creating &&
23247                 (createType === "rect" || createType === "polygon") ?
23248                 _this._basicClick$.skipUntil(_this._validBasicClick$).skip(1) :
23249                 Observable_1.Observable.empty();
23250         })
23251             .withLatestFrom(this._tagCreator.tag$, function (basic, tag) {
23252             return [basic, tag];
23253         })
23254             .subscribe(function (bt) {
23255             var basic = bt[0];
23256             var tag = bt[1];
23257             tag.addPoint(basic);
23258         });
23259         this._deleteCreatedSubscription = this._creating$
23260             .subscribe(function (creating) {
23261             _this._tagCreator.delete$.next(null);
23262         });
23263         this._setGLCreateTagSubscription = Observable_1.Observable
23264             .merge(this._tagCreator.tag$, this._createGeometryChanged$)
23265             .withLatestFrom(this._navigator.stateService.currentTransform$, function (tag, transform) {
23266             return [tag, transform];
23267         })
23268             .map(function (tt) {
23269             return function (renderer) {
23270                 var tag = tt[0];
23271                 var transform = tt[1];
23272                 if (tag == null) {
23273                     renderer.removeCreateTag();
23274                 }
23275                 else {
23276                     renderer.setCreateTag(tag, transform);
23277                 }
23278                 return renderer;
23279             };
23280         })
23281             .subscribe(this._tagGlRendererOperation$);
23282         this._claimMouseSubscription = this._tagInterationInitiated$
23283             .switchMap(function (id) {
23284             return _this._container.mouseService.mouseMove$
23285                 .takeUntil(_this._tagInteractionAbort$)
23286                 .take(1);
23287         })
23288             .subscribe(function (e) {
23289             _this._container.mouseService.claimMouse(_this._name, 1);
23290         });
23291         this._mouseDragSubscription = this._activeTag$
23292             .withLatestFrom(this._container.mouseService.mouseMove$, function (a, e) {
23293             return [a, e];
23294         })
23295             .switchMap(function (args) {
23296             var activeTag = args[0];
23297             var mouseMove = args[1];
23298             if (activeTag.operation === Component_1.TagOperation.None) {
23299                 return Observable_1.Observable.empty();
23300             }
23301             var mouseDrag$ = Observable_1.Observable
23302                 .of(mouseMove)
23303                 .concat(_this._container.mouseService.filtered$(_this._name, _this._container.mouseService.mouseDrag$));
23304             return Observable_1.Observable
23305                 .combineLatest(mouseDrag$, _this._container.renderService.renderCamera$)
23306                 .withLatestFrom(Observable_1.Observable.of(activeTag), _this._navigator.stateService.currentTransform$, function (ec, a, t) {
23307                 return [ec[0], ec[1], a, t];
23308             });
23309         })
23310             .subscribe(function (args) {
23311             var mouseEvent = args[0];
23312             var renderCamera = args[1];
23313             var activeTag = args[2];
23314             var transform = args[3];
23315             if (activeTag.operation === Component_1.TagOperation.None) {
23316                 return;
23317             }
23318             var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, activeTag.offsetX, activeTag.offsetY);
23319             if (activeTag.operation === Component_1.TagOperation.Centroid) {
23320                 activeTag.tag.geometry.setCentroid2d(basic, transform);
23321             }
23322             else if (activeTag.operation === Component_1.TagOperation.Vertex) {
23323                 var vertexGeometry = activeTag.tag.geometry;
23324                 vertexGeometry.setVertex2d(activeTag.vertexIndex, basic, transform);
23325             }
23326         });
23327         this._unclaimMouseSubscription = this._container.mouseService
23328             .filtered$(this._name, this._container.mouseService.mouseDragEnd$)
23329             .subscribe(function (e) {
23330             _this._container.mouseService.unclaimMouse(_this._name);
23331         });
23332         this._setTagsSubscription = this._renderTags$
23333             .map(function (tags) {
23334             return function (renderer) {
23335                 renderer.setTags(tags);
23336                 return renderer;
23337             };
23338         })
23339             .subscribe(this._tagGlRendererOperation$);
23340         this._updateGLTagSubscription = this._renderTagGLChanged$
23341             .map(function (tag) {
23342             return function (renderer) {
23343                 renderer.updateTag(tag);
23344                 return renderer;
23345             };
23346         })
23347             .subscribe(this._tagGlRendererOperation$);
23348         this._setNeedsRenderSubscription = this._tagChanged$
23349             .map(function (tag) {
23350             return function (renderer) {
23351                 renderer.setNeedsRender();
23352                 return renderer;
23353             };
23354         })
23355             .subscribe(this._tagGlRendererOperation$);
23356         this._domSubscription = this._renderTags$
23357             .startWith([])
23358             .do(function (tags) {
23359             _this._container.domRenderer.render$.next({
23360                 name: _this._name,
23361                 vnode: _this._tagDomRenderer.clear(),
23362             });
23363         })
23364             .combineLatest(this._container.renderService.renderCamera$, this._container.spriteService.spriteAtlas$, this._tagChanged$.startWith(null), this._tagCreator.tag$.merge(this._createGeometryChanged$).startWith(null), this._configuration$, function (renderTags, rc, atlas, tag, ct, c) {
23365             return [rc, atlas, renderTags, tag, ct, c];
23366         })
23367             .withLatestFrom(this._navigator.stateService.currentTransform$, function (args, transform) {
23368             return [args[0], args[1], args[2], args[3], args[4], args[5], transform];
23369         })
23370             .map(function (args) {
23371             return {
23372                 name: _this._name,
23373                 vnode: _this._tagDomRenderer.render(args[2], args[4], args[1], args[0].perspective, args[6], args[5]),
23374             };
23375         })
23376             .subscribe(this._container.domRenderer.render$);
23377         this._glSubscription = this._navigator.stateService.currentState$
23378             .withLatestFrom(this._tagGlRenderer$, function (frame, renderer) {
23379             return [frame, renderer];
23380         })
23381             .map(function (fr) {
23382             var frame = fr[0];
23383             var renderer = fr[1];
23384             return {
23385                 name: _this._name,
23386                 render: {
23387                     frameId: frame.id,
23388                     needsRender: renderer.needsRender,
23389                     render: renderer.render.bind(renderer),
23390                     stage: Render_1.GLRenderStage.Foreground,
23391                 },
23392             };
23393         })
23394             .subscribe(this._container.glRenderer.render$);
23395     };
23396     TagComponent.prototype._deactivate = function () {
23397         this._tagGlRendererOperation$
23398             .next(function (renderer) {
23399             renderer.dispose();
23400             return renderer;
23401         });
23402         this._tagSet.set$.next([]);
23403         this._tagCreator.delete$.next(null);
23404         this._claimMouseSubscription.unsubscribe();
23405         this._mouseDragSubscription.unsubscribe();
23406         this._unclaimMouseSubscription.unsubscribe();
23407         this._setTagsSubscription.unsubscribe();
23408         this._updateGLTagSubscription.unsubscribe();
23409         this._setNeedsRenderSubscription.unsubscribe();
23410         this._stopCreateSubscription.unsubscribe();
23411         this._creatorConfigurationSubscription.unsubscribe();
23412         this._createSubscription.unsubscribe();
23413         this._createPointSubscription.unsubscribe();
23414         this._setCreateVertexSubscription.unsubscribe();
23415         this._addPointSubscription.unsubscribe();
23416         this._deleteCreatedSubscription.unsubscribe();
23417         this._setGLCreateTagSubscription.unsubscribe();
23418         this._domSubscription.unsubscribe();
23419         this._glSubscription.unsubscribe();
23420         this._geometryCreatedEventSubscription.unsubscribe();
23421         this._tagsChangedEventSubscription.unsubscribe();
23422     };
23423     TagComponent.prototype._getDefaultConfiguration = function () {
23424         return {
23425             createColor: 0xFFFFFF,
23426             creating: false,
23427         };
23428     };
23429     TagComponent.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) {
23430         offsetX = offsetX != null ? offsetX : 0;
23431         offsetY = offsetY != null ? offsetY : 0;
23432         var clientRect = element.getBoundingClientRect();
23433         var canvasX = event.clientX - clientRect.left - offsetX;
23434         var canvasY = event.clientY - clientRect.top - offsetY;
23435         var projectedX = 2 * canvasX / element.offsetWidth - 1;
23436         var projectedY = 1 - 2 * canvasY / element.offsetHeight;
23437         var unprojected = new THREE.Vector3(projectedX, projectedY, 1).unproject(camera.perspective);
23438         var basic = transform.projectBasic(unprojected.toArray());
23439         return basic;
23440     };
23441     /** @inheritdoc */
23442     TagComponent.componentName = "tag";
23443     /**
23444      * Event fired when creation starts and stops.
23445      *
23446      * @event TagComponent#creatingchanged
23447      * @type {boolean} Indicates whether the component is creating a tag.
23448      */
23449     TagComponent.creatingchanged = "creatingchanged";
23450     /**
23451      * Event fired when a geometry has been created.
23452      *
23453      * @event TagComponent#geometrycreated
23454      * @type {Geometry} Created geometry.
23455      */
23456     TagComponent.geometrycreated = "geometrycreated";
23457     /**
23458      * Event fired when the tags collection has changed.
23459      *
23460      * @event TagComponent#tagschanged
23461      * @type {Array<Tag>} Current array of tags.
23462      */
23463     TagComponent.tagschanged = "tagschanged";
23464     return TagComponent;
23465 }(Component_1.Component));
23466 exports.TagComponent = TagComponent;
23467 Component_1.ComponentService.register(TagComponent);
23468 Object.defineProperty(exports, "__esModule", { value: true });
23469 exports.default = TagComponent;
23470
23471 },{"../../Component":210,"../../Render":216,"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":50,"rxjs/add/operator/concat":51,"rxjs/add/operator/distinctUntilChanged":54,"rxjs/add/operator/do":55,"rxjs/add/operator/filter":57,"rxjs/add/operator/map":61,"rxjs/add/operator/merge":62,"rxjs/add/operator/mergeMap":64,"rxjs/add/operator/publishReplay":68,"rxjs/add/operator/scan":69,"rxjs/add/operator/share":70,"rxjs/add/operator/skip":71,"rxjs/add/operator/skipUntil":72,"rxjs/add/operator/startWith":73,"rxjs/add/operator/switchMap":74,"rxjs/add/operator/take":75,"rxjs/add/operator/takeUntil":76,"rxjs/add/operator/withLatestFrom":77,"three":160}],254:[function(require,module,exports){
23472 "use strict";
23473 var Subject_1 = require("rxjs/Subject");
23474 require("rxjs/add/operator/map");
23475 require("rxjs/add/operator/scan");
23476 require("rxjs/add/operator/share");
23477 require("rxjs/add/operator/withLatestFrom");
23478 var Component_1 = require("../../Component");
23479 var TagCreator = (function () {
23480     function TagCreator() {
23481         this._tagOperation$ = new Subject_1.Subject();
23482         this._create$ = new Subject_1.Subject();
23483         this._delete$ = new Subject_1.Subject();
23484         this._configuration$ = new Subject_1.Subject();
23485         this._tag$ = this._tagOperation$
23486             .scan(function (tag, operation) {
23487             return operation(tag);
23488         }, null)
23489             .share();
23490         this._create$
23491             .withLatestFrom(this._configuration$, function (coordinate, type) {
23492             return [coordinate, type];
23493         })
23494             .map(function (ct) {
23495             return function (tag) {
23496                 var coordinate = ct[0];
23497                 var configuration = ct[1];
23498                 if (configuration.createType === "rect") {
23499                     var geometry = new Component_1.RectGeometry([
23500                         coordinate[0],
23501                         coordinate[1],
23502                         coordinate[0],
23503                         coordinate[1],
23504                     ]);
23505                     return new Component_1.OutlineCreateTag(geometry, { color: configuration.createColor });
23506                 }
23507                 else if (configuration.createType === "polygon") {
23508                     var geometry = new Component_1.PolygonGeometry([
23509                         [coordinate[0], coordinate[1]],
23510                         [coordinate[0], coordinate[1]],
23511                         [coordinate[0], coordinate[1]],
23512                     ]);
23513                     return new Component_1.OutlineCreateTag(geometry, { color: configuration.createColor });
23514                 }
23515                 return null;
23516             };
23517         })
23518             .subscribe(this._tagOperation$);
23519         this._delete$
23520             .map(function () {
23521             return function (tag) {
23522                 return null;
23523             };
23524         })
23525             .subscribe(this._tagOperation$);
23526     }
23527     Object.defineProperty(TagCreator.prototype, "create$", {
23528         get: function () {
23529             return this._create$;
23530         },
23531         enumerable: true,
23532         configurable: true
23533     });
23534     Object.defineProperty(TagCreator.prototype, "delete$", {
23535         get: function () {
23536             return this._delete$;
23537         },
23538         enumerable: true,
23539         configurable: true
23540     });
23541     Object.defineProperty(TagCreator.prototype, "configuration$", {
23542         get: function () {
23543             return this._configuration$;
23544         },
23545         enumerable: true,
23546         configurable: true
23547     });
23548     Object.defineProperty(TagCreator.prototype, "tag$", {
23549         get: function () {
23550             return this._tag$;
23551         },
23552         enumerable: true,
23553         configurable: true
23554     });
23555     return TagCreator;
23556 }());
23557 exports.TagCreator = TagCreator;
23558 Object.defineProperty(exports, "__esModule", { value: true });
23559 exports.default = TagCreator;
23560
23561 },{"../../Component":210,"rxjs/Subject":33,"rxjs/add/operator/map":61,"rxjs/add/operator/scan":69,"rxjs/add/operator/share":70,"rxjs/add/operator/withLatestFrom":77}],255:[function(require,module,exports){
23562 /// <reference path="../../../typings/index.d.ts" />
23563 "use strict";
23564 var THREE = require("three");
23565 var vd = require("virtual-dom");
23566 var TagDOMRenderer = (function () {
23567     function TagDOMRenderer() {
23568     }
23569     TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, transform, configuration) {
23570         var matrixWorldInverse = new THREE.Matrix4().getInverse(camera.matrixWorld);
23571         var projectionMatrix = camera.projectionMatrix;
23572         var vNodes = [];
23573         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
23574             var tag = tags_1[_i];
23575             vNodes = vNodes.concat(tag.getDOMObjects(atlas, matrixWorldInverse, projectionMatrix));
23576         }
23577         if (createTag != null) {
23578             vNodes = vNodes.concat(createTag.getDOMObjects(transform, matrixWorldInverse, projectionMatrix));
23579         }
23580         var properties = {
23581             style: {
23582                 "pointer-events": configuration.creating ? "all" : "none",
23583             },
23584         };
23585         return vd.h("div.TagContainer", properties, vNodes);
23586     };
23587     TagDOMRenderer.prototype.clear = function () {
23588         return vd.h("div", {}, []);
23589     };
23590     return TagDOMRenderer;
23591 }());
23592 exports.TagDOMRenderer = TagDOMRenderer;
23593
23594 },{"three":160,"virtual-dom":166}],256:[function(require,module,exports){
23595 /// <reference path="../../../typings/index.d.ts" />
23596 "use strict";
23597 var THREE = require("three");
23598 var TagGLRenderer = (function () {
23599     function TagGLRenderer() {
23600         this._scene = new THREE.Scene();
23601         this._tags = {};
23602         this._createTag = null;
23603         this._needsRender = false;
23604     }
23605     Object.defineProperty(TagGLRenderer.prototype, "needsRender", {
23606         get: function () {
23607             return this._needsRender;
23608         },
23609         enumerable: true,
23610         configurable: true
23611     });
23612     TagGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
23613         renderer.render(this._scene, perspectiveCamera);
23614         this._needsRender = false;
23615     };
23616     TagGLRenderer.prototype.setCreateTag = function (tag, transform) {
23617         this._disposeCreateTag();
23618         this._addCreateTag(tag, transform);
23619         this._needsRender = true;
23620     };
23621     TagGLRenderer.prototype.removeCreateTag = function () {
23622         this._disposeCreateTag();
23623         this._needsRender = true;
23624     };
23625     TagGLRenderer.prototype.setTags = function (tags) {
23626         this._disposeTags();
23627         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
23628             var tag = tags_1[_i];
23629             this._addTag(tag);
23630         }
23631         this._needsRender = true;
23632     };
23633     TagGLRenderer.prototype.updateTag = function (tag) {
23634         for (var _i = 0, _a = this._tags[tag.tag.id][1]; _i < _a.length; _i++) {
23635             var object3d = _a[_i];
23636             this._scene.remove(object3d);
23637         }
23638         this._addTag(tag);
23639     };
23640     TagGLRenderer.prototype.setNeedsRender = function () {
23641         this._needsRender = true;
23642     };
23643     TagGLRenderer.prototype.dispose = function () {
23644         this._disposeTags();
23645         this._disposeCreateTag();
23646         this._needsRender = false;
23647     };
23648     TagGLRenderer.prototype._addTag = function (tag) {
23649         var objects = tag.glObjects;
23650         this._tags[tag.tag.id] = [tag, []];
23651         for (var _i = 0, objects_1 = objects; _i < objects_1.length; _i++) {
23652             var object = objects_1[_i];
23653             this._tags[tag.tag.id][1].push(object);
23654             this._scene.add(object);
23655         }
23656     };
23657     TagGLRenderer.prototype._addCreateTag = function (tag, transform) {
23658         var object = tag.getGLObject(transform);
23659         this._createTag = object;
23660         this._scene.add(object);
23661     };
23662     TagGLRenderer.prototype._disposeTags = function () {
23663         for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
23664             var id = _a[_i];
23665             for (var _b = 0, _c = this._tags[id][1]; _b < _c.length; _b++) {
23666                 var object = _c[_b];
23667                 this._scene.remove(object);
23668             }
23669             this._tags[id][0].dispose();
23670             delete this._tags[id];
23671         }
23672     };
23673     TagGLRenderer.prototype._disposeCreateTag = function () {
23674         if (this._createTag == null) {
23675             return;
23676         }
23677         var mesh = this._createTag;
23678         this._scene.remove(mesh);
23679         mesh.geometry.dispose();
23680         mesh.material.dispose();
23681         this._createTag = null;
23682     };
23683     return TagGLRenderer;
23684 }());
23685 exports.TagGLRenderer = TagGLRenderer;
23686
23687 },{"three":160}],257:[function(require,module,exports){
23688 "use strict";
23689 (function (TagOperation) {
23690     TagOperation[TagOperation["None"] = 0] = "None";
23691     TagOperation[TagOperation["Centroid"] = 1] = "Centroid";
23692     TagOperation[TagOperation["Vertex"] = 2] = "Vertex";
23693 })(exports.TagOperation || (exports.TagOperation = {}));
23694 var TagOperation = exports.TagOperation;
23695 Object.defineProperty(exports, "__esModule", { value: true });
23696 exports.default = TagOperation;
23697
23698 },{}],258:[function(require,module,exports){
23699 "use strict";
23700 var Subject_1 = require("rxjs/Subject");
23701 require("rxjs/add/operator/map");
23702 require("rxjs/add/operator/scan");
23703 require("rxjs/add/operator/share");
23704 var TagSet = (function () {
23705     function TagSet() {
23706         this._tagDataOperation$ = new Subject_1.Subject();
23707         this._set$ = new Subject_1.Subject();
23708         this._tagData$ = this._tagDataOperation$
23709             .scan(function (tagData, operation) {
23710             return operation(tagData);
23711         }, {})
23712             .share();
23713         this._set$
23714             .map(function (tags) {
23715             return function (tagData) {
23716                 for (var _i = 0, _a = Object.keys(tagData); _i < _a.length; _i++) {
23717                     var key = _a[_i];
23718                     delete tagData[key];
23719                 }
23720                 for (var _b = 0, tags_1 = tags; _b < tags_1.length; _b++) {
23721                     var tag = tags_1[_b];
23722                     tagData[tag.id] = tag;
23723                 }
23724                 return tagData;
23725             };
23726         })
23727             .subscribe(this._tagDataOperation$);
23728     }
23729     Object.defineProperty(TagSet.prototype, "tagData$", {
23730         get: function () {
23731             return this._tagData$;
23732         },
23733         enumerable: true,
23734         configurable: true
23735     });
23736     Object.defineProperty(TagSet.prototype, "set$", {
23737         get: function () {
23738             return this._set$;
23739         },
23740         enumerable: true,
23741         configurable: true
23742     });
23743     return TagSet;
23744 }());
23745 exports.TagSet = TagSet;
23746 Object.defineProperty(exports, "__esModule", { value: true });
23747 exports.default = TagSet;
23748
23749 },{"rxjs/Subject":33,"rxjs/add/operator/map":61,"rxjs/add/operator/scan":69,"rxjs/add/operator/share":70}],259:[function(require,module,exports){
23750 "use strict";
23751 var __extends = (this && this.__extends) || function (d, b) {
23752     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
23753     function __() { this.constructor = d; }
23754     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23755 };
23756 var Error_1 = require("../../../Error");
23757 var GeometryTagError = (function (_super) {
23758     __extends(GeometryTagError, _super);
23759     function GeometryTagError(message) {
23760         _super.call(this);
23761         this.name = "GeometryTagError";
23762         this.message = message != null ? message : "The provided geometry value is incorrect";
23763     }
23764     return GeometryTagError;
23765 }(Error_1.MapillaryError));
23766 exports.GeometryTagError = GeometryTagError;
23767 Object.defineProperty(exports, "__esModule", { value: true });
23768 exports.default = Error_1.MapillaryError;
23769
23770 },{"../../../Error":212}],260:[function(require,module,exports){
23771 "use strict";
23772 var Subject_1 = require("rxjs/Subject");
23773 /**
23774  * @class Geometry
23775  * @abstract
23776  * @classdesc Represents a geometry.
23777  */
23778 var Geometry = (function () {
23779     /**
23780      * Create a geometry.
23781      *
23782      * @constructor
23783      */
23784     function Geometry() {
23785         this._notifyChanged$ = new Subject_1.Subject();
23786     }
23787     Object.defineProperty(Geometry.prototype, "changed$", {
23788         /**
23789          * Get changed observable.
23790          *
23791          * @description Emits the geometry itself every time the geometry
23792          * has changed.
23793          *
23794          * @returns {Observable<Geometry>} Observable emitting the geometry instance.
23795          */
23796         get: function () {
23797             return this._notifyChanged$;
23798         },
23799         enumerable: true,
23800         configurable: true
23801     });
23802     return Geometry;
23803 }());
23804 exports.Geometry = Geometry;
23805 Object.defineProperty(exports, "__esModule", { value: true });
23806 exports.default = Geometry;
23807
23808 },{"rxjs/Subject":33}],261:[function(require,module,exports){
23809 "use strict";
23810 var __extends = (this && this.__extends) || function (d, b) {
23811     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
23812     function __() { this.constructor = d; }
23813     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23814 };
23815 var Component_1 = require("../../../Component");
23816 /**
23817  * @class PointGeometry
23818  * @classdesc Represents a point geometry in the basic coordinate system.
23819  */
23820 var PointGeometry = (function (_super) {
23821     __extends(PointGeometry, _super);
23822     /**
23823      * Create a point geometry.
23824      *
23825      * @constructor
23826      * @param {Array<number>} point - An array representing the basic coordinates of
23827      * the point.
23828      *
23829      * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
23830      */
23831     function PointGeometry(point) {
23832         _super.call(this);
23833         var x = point[0];
23834         var y = point[1];
23835         if (x < 0 || x > 1 || y < 0 || y > 1) {
23836             throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
23837         }
23838         this._point = point.slice();
23839     }
23840     Object.defineProperty(PointGeometry.prototype, "point", {
23841         /**
23842          * Get point property.
23843          * @returns {Array<number>} Array representing the basic coordinates of the point.
23844          */
23845         get: function () {
23846             return this._point;
23847         },
23848         enumerable: true,
23849         configurable: true
23850     });
23851     /**
23852      * Get the 3D world coordinates for the centroid of the point, i.e. the 3D
23853      * world coordinates of the point itself.
23854      *
23855      * @param {Transform} transform - The transform of the node related to the point.
23856      * @returns {Array<number>} 3D world coordinates representing the centroid.
23857      */
23858     PointGeometry.prototype.getCentroid3d = function (transform) {
23859         return transform.unprojectBasic(this._point, 200);
23860     };
23861     /**
23862      * Set the centroid of the point, i.e. the point coordinates.
23863      *
23864      * @param {Array<number>} value - The new value of the centroid.
23865      * @param {Transform} transform - The transform of the node related to the point.
23866      */
23867     PointGeometry.prototype.setCentroid2d = function (value, transform) {
23868         var changed = [
23869             Math.max(0, Math.min(1, value[0])),
23870             Math.max(0, Math.min(1, value[1])),
23871         ];
23872         this._point[0] = changed[0];
23873         this._point[1] = changed[1];
23874         this._notifyChanged$.next(this);
23875     };
23876     return PointGeometry;
23877 }(Component_1.Geometry));
23878 exports.PointGeometry = PointGeometry;
23879
23880 },{"../../../Component":210}],262:[function(require,module,exports){
23881 "use strict";
23882 var __extends = (this && this.__extends) || function (d, b) {
23883     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
23884     function __() { this.constructor = d; }
23885     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23886 };
23887 var Component_1 = require("../../../Component");
23888 /**
23889  * @class PolygonGeometry
23890  * @classdesc Represents a polygon geometry in the basic coordinate system.
23891  */
23892 var PolygonGeometry = (function (_super) {
23893     __extends(PolygonGeometry, _super);
23894     /**
23895      * Create a polygon geometry.
23896      *
23897      * @constructor
23898      * @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
23899      * @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
23900      * Each array of holes vertices must be closed.
23901      *
23902      * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
23903      */
23904     function PolygonGeometry(polygon, holes) {
23905         _super.call(this);
23906         var polygonLength = polygon.length;
23907         if (polygonLength < 3) {
23908             throw new Component_1.GeometryTagError("A polygon must have three or more positions.");
23909         }
23910         if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
23911             polygon[0][1] !== polygon[polygonLength - 1][1]) {
23912             throw new Component_1.GeometryTagError("First and last positions must be equivalent.");
23913         }
23914         this._polygon = [];
23915         for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) {
23916             var vertex = polygon_1[_i];
23917             if (vertex[0] < 0 || vertex[0] > 1 ||
23918                 vertex[1] < 0 || vertex[1] > 1) {
23919                 throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
23920             }
23921             this._polygon.push(vertex.slice());
23922         }
23923         this._holes = [];
23924         if (holes == null) {
23925             return;
23926         }
23927         for (var i = 0; i < holes.length; i++) {
23928             var hole = holes[i];
23929             var holeLength = hole.length;
23930             if (holeLength < 3) {
23931                 throw new Component_1.GeometryTagError("A polygon hole must have three or more positions.");
23932             }
23933             if (hole[0][0] !== hole[holeLength - 1][0] ||
23934                 hole[0][1] !== hole[holeLength - 1][1]) {
23935                 throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent.");
23936             }
23937             this._holes.push([]);
23938             for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) {
23939                 var vertex = hole_1[_a];
23940                 if (vertex[0] < 0 || vertex[0] > 1 ||
23941                     vertex[1] < 0 || vertex[1] > 1) {
23942                     throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
23943                 }
23944                 this._holes[i].push(vertex.slice());
23945             }
23946         }
23947     }
23948     Object.defineProperty(PolygonGeometry.prototype, "polygon", {
23949         /**
23950          * Get polygon property.
23951          * @returns {Array<Array<number>>} Closed 2d polygon.
23952          */
23953         get: function () {
23954             return this._polygon;
23955         },
23956         enumerable: true,
23957         configurable: true
23958     });
23959     Object.defineProperty(PolygonGeometry.prototype, "holes", {
23960         /**
23961          * Get holes property.
23962          * @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
23963          */
23964         get: function () {
23965             return this._holes;
23966         },
23967         enumerable: true,
23968         configurable: true
23969     });
23970     /**
23971      * Add a vertex to the polygon by appending it after the last vertex.
23972      *
23973      * @param {Array<number>} vertex - Vertex to add.
23974      */
23975     PolygonGeometry.prototype.addVertex2d = function (vertex) {
23976         var clamped = [
23977             Math.max(0, Math.min(1, vertex[0])),
23978             Math.max(0, Math.min(1, vertex[1])),
23979         ];
23980         this._polygon.splice(this._polygon.length - 1, 0, clamped);
23981         this._notifyChanged$.next(this);
23982     };
23983     /**
23984      * Remove a vertex from the polygon.
23985      *
23986      * @param {number} index - The index of the vertex to remove.
23987      */
23988     PolygonGeometry.prototype.removeVertex2d = function (index) {
23989         if (index < 0 ||
23990             index >= this._polygon.length ||
23991             this._polygon.length < 4) {
23992             throw new Component_1.GeometryTagError("Index for removed vertex must be valid.");
23993         }
23994         if (index > 0 && index < this._polygon.length - 1) {
23995             this._polygon.splice(index, 1);
23996         }
23997         else {
23998             this._polygon.splice(0, 1);
23999             this._polygon.pop();
24000             var closing = this._polygon[0].slice();
24001             this._polygon.push(closing);
24002         }
24003         this._notifyChanged$.next(this);
24004     };
24005     /** @inheritdoc */
24006     PolygonGeometry.prototype.setVertex2d = function (index, value, transform) {
24007         var changed = [
24008             Math.max(0, Math.min(1, value[0])),
24009             Math.max(0, Math.min(1, value[1])),
24010         ];
24011         if (index === 0 || index === this._polygon.length - 1) {
24012             this._polygon[0] = changed.slice();
24013             this._polygon[this._polygon.length - 1] = changed.slice();
24014         }
24015         else {
24016             this._polygon[index] = changed.slice();
24017         }
24018         this._notifyChanged$.next(this);
24019     };
24020     /** @inheritdoc */
24021     PolygonGeometry.prototype.setCentroid2d = function (value, transform) {
24022         var xs = this._polygon.map(function (point) { return point[0]; });
24023         var ys = this._polygon.map(function (point) { return point[1]; });
24024         var minX = Math.min.apply(Math, xs);
24025         var maxX = Math.max.apply(Math, xs);
24026         var minY = Math.min.apply(Math, ys);
24027         var maxY = Math.max.apply(Math, ys);
24028         var centroid = this._getCentroid2d();
24029         var minTranslationX = -minX;
24030         var maxTranslationX = 1 - maxX;
24031         var minTranslationY = -minY;
24032         var maxTranslationY = 1 - maxY;
24033         var translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
24034         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
24035         for (var _i = 0, _a = this._polygon; _i < _a.length; _i++) {
24036             var point = _a[_i];
24037             point[0] += translationX;
24038             point[1] += translationY;
24039         }
24040         this._notifyChanged$.next(this);
24041     };
24042     /** @inheritdoc */
24043     PolygonGeometry.prototype.getPoints3d = function (transform) {
24044         return this.getVertices3d(transform);
24045     };
24046     /** @inheritdoc */
24047     PolygonGeometry.prototype.getVertex3d = function (index, transform) {
24048         return transform.unprojectBasic(this._polygon[index], 200);
24049     };
24050     /** @inheritdoc */
24051     PolygonGeometry.prototype.getVertices3d = function (transform) {
24052         return this._polygon
24053             .map(function (point) {
24054             return transform.unprojectBasic(point, 200);
24055         });
24056     };
24057     /**
24058      * Get a polygon representation of the 3D coordinates for the vertices of each hole
24059      * of the geometry.
24060      *
24061      * @param {Transform} transform - The transform of the node related to the geometry.
24062      * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
24063      * representing the vertices of each hole of the geometry.
24064      */
24065     PolygonGeometry.prototype.getHoleVertices3d = function (transform) {
24066         var holes3d = [];
24067         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
24068             var hole = _a[_i];
24069             var hole3d = hole
24070                 .map(function (point) {
24071                 return transform.unprojectBasic(point, 200);
24072             });
24073             holes3d.push(hole3d);
24074         }
24075         return holes3d;
24076     };
24077     /** @inheritdoc */
24078     PolygonGeometry.prototype.getCentroid3d = function (transform) {
24079         var centroid2d = this._getCentroid2d();
24080         return transform.unprojectBasic(centroid2d, 200);
24081     };
24082     /** @inheritdoc */
24083     PolygonGeometry.prototype.getTriangles3d = function (transform) {
24084         return this._triangulate(this._polygon, this.getPoints3d(transform), this._holes, this.getHoleVertices3d(transform));
24085     };
24086     PolygonGeometry.prototype._getCentroid2d = function () {
24087         var polygon = this._polygon;
24088         var area = 0;
24089         var centroidX = 0;
24090         var centroidY = 0;
24091         for (var i = 0; i < polygon.length - 1; i++) {
24092             var xi = polygon[i][0];
24093             var yi = polygon[i][1];
24094             var xi1 = polygon[i + 1][0];
24095             var yi1 = polygon[i + 1][1];
24096             var a = xi * yi1 - xi1 * yi;
24097             area += a;
24098             centroidX += (xi + xi1) * a;
24099             centroidY += (yi + yi1) * a;
24100         }
24101         area /= 2;
24102         centroidX /= 6 * area;
24103         centroidY /= 6 * area;
24104         return [centroidX, centroidY];
24105     };
24106     return PolygonGeometry;
24107 }(Component_1.VertexGeometry));
24108 exports.PolygonGeometry = PolygonGeometry;
24109 Object.defineProperty(exports, "__esModule", { value: true });
24110 exports.default = PolygonGeometry;
24111
24112 },{"../../../Component":210}],263:[function(require,module,exports){
24113 "use strict";
24114 var __extends = (this && this.__extends) || function (d, b) {
24115     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24116     function __() { this.constructor = d; }
24117     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24118 };
24119 var Component_1 = require("../../../Component");
24120 /**
24121  * @class RectGeometry
24122  * @classdesc Represents a rectangle geometry in the basic coordinate system.
24123  */
24124 var RectGeometry = (function (_super) {
24125     __extends(RectGeometry, _super);
24126     /**
24127      * Create a rectangle geometry.
24128      *
24129      * @constructor
24130      * @param {Array<number>} rect - An array representing the top-left and bottom-right
24131      * corners of the rectangle in basic coordinates. Ordered according to [x0, y0, x1, y1].
24132      *
24133      * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates.
24134      */
24135     function RectGeometry(rect) {
24136         _super.call(this);
24137         if (rect[1] > rect[3]) {
24138             throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted.");
24139         }
24140         for (var _i = 0, rect_1 = rect; _i < rect_1.length; _i++) {
24141             var coord = rect_1[_i];
24142             if (coord < 0 || coord > 1) {
24143                 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
24144             }
24145         }
24146         this._rect = rect.slice(0, 4);
24147         if (this._rect[0] > this._rect[2]) {
24148             this._inverted = true;
24149         }
24150     }
24151     Object.defineProperty(RectGeometry.prototype, "rect", {
24152         /**
24153          * Get rect property.
24154          * @returns {Array<number>} Array representing the top-left and bottom-right
24155          * corners of the rectangle in basic coordinates.
24156          */
24157         get: function () {
24158             return this._rect;
24159         },
24160         enumerable: true,
24161         configurable: true
24162     });
24163     /**
24164      * Set the value of a vertex in the polygon representation of the rectangle.
24165      *
24166      * @description The polygon is defined to have the first vertex at the
24167      * bottom-left corner with the rest of the vertices following in clockwise order.
24168      *
24169      * @param {number} index - The index of the vertex to be set.
24170      * @param {Array<number>} value - The new value of the vertex.
24171      * @param {Transform} transform - The transform of the node related to the rectangle.
24172      */
24173     RectGeometry.prototype.setVertex2d = function (index, value, transform) {
24174         var original = this._rect.slice();
24175         var changed = [
24176             Math.max(0, Math.min(1, value[0])),
24177             Math.max(0, Math.min(1, value[1])),
24178         ];
24179         var rect = [];
24180         if (index === 0) {
24181             rect[0] = changed[0];
24182             rect[1] = original[1];
24183             rect[2] = original[2];
24184             rect[3] = changed[1];
24185         }
24186         else if (index === 1) {
24187             rect[0] = changed[0];
24188             rect[1] = changed[1];
24189             rect[2] = original[2];
24190             rect[3] = original[3];
24191         }
24192         else if (index === 2) {
24193             rect[0] = original[0];
24194             rect[1] = changed[1];
24195             rect[2] = changed[0];
24196             rect[3] = original[3];
24197         }
24198         else if (index === 3) {
24199             rect[0] = original[0];
24200             rect[1] = original[1];
24201             rect[2] = changed[0];
24202             rect[3] = changed[1];
24203         }
24204         if (transform.gpano) {
24205             var passingBoundaryLeft = index < 2 && changed[0] > 0.75 && original[0] < 0.25 ||
24206                 index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25;
24207             var passingBoundaryRight = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 ||
24208                 index >= 2 && changed[0] < 0.25 && original[2] > 0.75;
24209             if (passingBoundaryLeft || passingBoundaryRight) {
24210                 this._inverted = !this._inverted;
24211             }
24212             else {
24213                 if (rect[0] - original[0] < -0.25) {
24214                     rect[0] = original[0];
24215                 }
24216                 if (rect[2] - original[2] > 0.25) {
24217                     rect[2] = original[2];
24218                 }
24219             }
24220             if (!this._inverted && rect[0] > rect[2] ||
24221                 this._inverted && rect[0] < rect[2]) {
24222                 rect[0] = original[0];
24223                 rect[2] = original[2];
24224             }
24225         }
24226         else {
24227             if (rect[0] > rect[2]) {
24228                 rect[0] = original[0];
24229                 rect[2] = original[2];
24230             }
24231         }
24232         if (rect[1] > rect[3]) {
24233             rect[1] = original[1];
24234             rect[3] = original[3];
24235         }
24236         this._rect[0] = rect[0];
24237         this._rect[1] = rect[1];
24238         this._rect[2] = rect[2];
24239         this._rect[3] = rect[3];
24240         this._notifyChanged$.next(this);
24241     };
24242     /** @inheritdoc */
24243     RectGeometry.prototype.setCentroid2d = function (value, transform) {
24244         var original = this._rect.slice();
24245         var x0 = original[0];
24246         var x1 = this._inverted ? original[2] + 1 : original[2];
24247         var y0 = original[1];
24248         var y1 = original[3];
24249         var centerX = x0 + (x1 - x0) / 2;
24250         var centerY = y0 + (y1 - y0) / 2;
24251         var translationX = 0;
24252         if (transform.gpano != null &&
24253             transform.gpano.CroppedAreaImageWidthPixels === transform.gpano.FullPanoWidthPixels) {
24254             translationX = this._inverted ? value[0] + 1 - centerX : value[0] - centerX;
24255         }
24256         else {
24257             var minTranslationX = -x0;
24258             var maxTranslationX = 1 - x1;
24259             translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centerX));
24260         }
24261         var minTranslationY = -y0;
24262         var maxTranslationY = 1 - y1;
24263         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centerY));
24264         this._rect[0] = original[0] + translationX;
24265         this._rect[1] = original[1] + translationY;
24266         this._rect[2] = original[2] + translationX;
24267         this._rect[3] = original[3] + translationY;
24268         if (this._rect[0] < 0) {
24269             this._rect[0] += 1;
24270             this._inverted = !this._inverted;
24271         }
24272         else if (this._rect[0] > 1) {
24273             this._rect[0] -= 1;
24274             this._inverted = !this._inverted;
24275         }
24276         if (this._rect[2] < 0) {
24277             this._rect[2] += 1;
24278             this._inverted = !this._inverted;
24279         }
24280         else if (this._rect[2] > 1) {
24281             this._rect[2] -= 1;
24282             this._inverted = !this._inverted;
24283         }
24284         this._notifyChanged$.next(this);
24285     };
24286     /**
24287      * Get the 3D coordinates for the vertices of the rectangle with
24288      * interpolated points along the lines.
24289      *
24290      * @param {Transform} transform - The transform of the node related to
24291      * the rectangle.
24292      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates
24293      * representing the rectangle.
24294      */
24295     RectGeometry.prototype.getPoints3d = function (transform) {
24296         return this._getPoints2d(transform)
24297             .map(function (point) {
24298             return transform.unprojectBasic(point, 200);
24299         });
24300     };
24301     /**
24302      * Get a vertex from the polygon representation of the 3D coordinates for the
24303      * vertices of the geometry.
24304      *
24305      * @description The first vertex represents the bottom-left corner with the rest of
24306      * the vertices following in clockwise order.
24307      *
24308      * @param {number} index - Vertex index.
24309      * @param {Transform} transform - The transform of the node related to the geometry.
24310      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
24311      * the vertices of the geometry.
24312      */
24313     RectGeometry.prototype.getVertex3d = function (index, transform) {
24314         return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200);
24315     };
24316     /**
24317      * Get a polygon representation of the 3D coordinates for the vertices of the rectangle.
24318      *
24319      * @description The first vertex represents the bottom-left corner with the rest of
24320      * the vertices following in clockwise order.
24321      *
24322      * @param {Transform} transform - The transform of the node related to the rectangle.
24323      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
24324      * the rectangle vertices.
24325      */
24326     RectGeometry.prototype.getVertices3d = function (transform) {
24327         return this._rectToVertices2d(this._rect)
24328             .map(function (vertex) {
24329             return transform.unprojectBasic(vertex, 200);
24330         });
24331     };
24332     /** @inheritdoc */
24333     RectGeometry.prototype.getCentroid3d = function (transform) {
24334         var rect = this._rect;
24335         var x0 = rect[0];
24336         var x1 = this._inverted ? rect[2] + 1 : rect[2];
24337         var y0 = rect[1];
24338         var y1 = rect[3];
24339         var centroidX = x0 + (x1 - x0) / 2;
24340         var centroidY = y0 + (y1 - y0) / 2;
24341         return transform.unprojectBasic([centroidX, centroidY], 200);
24342     };
24343     /** @inheritdoc */
24344     RectGeometry.prototype.getTriangles3d = function (transform) {
24345         return this._triangulate(this._rectToVertices2d(this._rect), this.getVertices3d(transform));
24346     };
24347     /**
24348      * Check if a particular bottom-right value is valid according to the current
24349      * rectangle coordinates.
24350      *
24351      * @param {Array<number>} bottomRight - The bottom-right coordinates to validate
24352      * @returns {boolean} Value indicating whether the provided bottom-right coordinates
24353      * are valid.
24354      */
24355     RectGeometry.prototype.validate = function (bottomRight) {
24356         var rect = this._rect;
24357         if (!this._inverted && bottomRight[0] < rect[0] ||
24358             bottomRight[0] - rect[2] > 0.25 ||
24359             bottomRight[1] < rect[1]) {
24360             return false;
24361         }
24362         return true;
24363     };
24364     /**
24365      * Get the 2D coordinates for the vertices of the rectangle with
24366      * interpolated points along the lines.
24367      *
24368      * @param {Transform} transform - The transform of the node related to
24369      * the rectangle.
24370      * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates
24371      * representing the rectangle.
24372      */
24373     RectGeometry.prototype._getPoints2d = function (transform) {
24374         var vertices2d = this._rectToVertices2d(this._rect);
24375         var sides = vertices2d.length - 1;
24376         var sections = 10;
24377         var points2d = [];
24378         for (var i = 0; i < sides; ++i) {
24379             var startX = vertices2d[i][0];
24380             var startY = vertices2d[i][1];
24381             var endX = vertices2d[i + 1][0];
24382             var endY = vertices2d[i + 1][1];
24383             var intervalX = (endX - startX) / (sections - 1);
24384             var intervalY = (endY - startY) / (sections - 1);
24385             for (var j = 0; j < sections; ++j) {
24386                 var point = [
24387                     startX + j * intervalX,
24388                     startY + j * intervalY,
24389                 ];
24390                 points2d.push(point);
24391             }
24392         }
24393         return points2d;
24394     };
24395     /**
24396      * Convert the top-left, bottom-right representation of a rectangle to a polygon
24397      * representation of the vertices starting at the bottom-right corner going
24398      * clockwise.
24399      *
24400      * @param {Array<number>} rect - Top-left, bottom-right representation of a
24401      * rectangle.
24402      * @returns {Array<Array<number>>} Polygon representation of the vertices of the
24403      * rectangle.
24404      */
24405     RectGeometry.prototype._rectToVertices2d = function (rect) {
24406         return [
24407             [rect[0], rect[3]],
24408             [rect[0], rect[1]],
24409             [this._inverted ? rect[2] + 1 : rect[2], rect[1]],
24410             [this._inverted ? rect[2] + 1 : rect[2], rect[3]],
24411             [rect[0], rect[3]],
24412         ];
24413     };
24414     return RectGeometry;
24415 }(Component_1.VertexGeometry));
24416 exports.RectGeometry = RectGeometry;
24417 Object.defineProperty(exports, "__esModule", { value: true });
24418 exports.default = RectGeometry;
24419
24420 },{"../../../Component":210}],264:[function(require,module,exports){
24421 /// <reference path="../../../../typings/index.d.ts" />
24422 "use strict";
24423 var __extends = (this && this.__extends) || function (d, b) {
24424     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24425     function __() { this.constructor = d; }
24426     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24427 };
24428 var earcut = require("earcut");
24429 var Component_1 = require("../../../Component");
24430 /**
24431  * @class VertexGeometry
24432  * @abstract
24433  * @classdesc Represents a vertex geometry.
24434  */
24435 var VertexGeometry = (function (_super) {
24436     __extends(VertexGeometry, _super);
24437     /**
24438      * Create a vertex geometry.
24439      *
24440      * @constructor
24441      */
24442     function VertexGeometry() {
24443         _super.call(this);
24444     }
24445     /**
24446      * Triangulates a 2d polygon and returns the triangle
24447      * representation as a flattened array of 3d points.
24448      *
24449      * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
24450      * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points.
24451      * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate.
24452      * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points.
24453      * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles.
24454      */
24455     VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) {
24456         var data = [points2d.slice(0, -1)];
24457         for (var _i = 0, _a = holes2d != null ? holes2d : []; _i < _a.length; _i++) {
24458             var hole2d = _a[_i];
24459             data.push(hole2d.slice(0, -1));
24460         }
24461         var points = points3d.slice(0, -1);
24462         for (var _b = 0, _c = holes3d != null ? holes3d : []; _b < _c.length; _b++) {
24463             var hole3d = _c[_b];
24464             points = points.concat(hole3d.slice(0, -1));
24465         }
24466         var flattened = earcut.flatten(data);
24467         var indices = earcut(flattened.vertices, flattened.holes, flattened.dimensions);
24468         var triangles = [];
24469         for (var i = 0; i < indices.length; ++i) {
24470             var point = points[indices[i]];
24471             triangles.push(point[0]);
24472             triangles.push(point[1]);
24473             triangles.push(point[2]);
24474         }
24475         return triangles;
24476     };
24477     return VertexGeometry;
24478 }(Component_1.Geometry));
24479 exports.VertexGeometry = VertexGeometry;
24480 Object.defineProperty(exports, "__esModule", { value: true });
24481 exports.default = VertexGeometry;
24482
24483 },{"../../../Component":210,"earcut":6}],265:[function(require,module,exports){
24484 "use strict";
24485 (function (Alignment) {
24486     Alignment[Alignment["Center"] = 0] = "Center";
24487     Alignment[Alignment["Outer"] = 1] = "Outer";
24488 })(exports.Alignment || (exports.Alignment = {}));
24489 var Alignment = exports.Alignment;
24490 Object.defineProperty(exports, "__esModule", { value: true });
24491 exports.default = Alignment;
24492
24493 },{}],266:[function(require,module,exports){
24494 /// <reference path="../../../../typings/index.d.ts" />
24495 "use strict";
24496 var THREE = require("three");
24497 var vd = require("virtual-dom");
24498 var Subject_1 = require("rxjs/Subject");
24499 var Component_1 = require("../../../Component");
24500 var OutlineCreateTag = (function () {
24501     function OutlineCreateTag(geometry, options) {
24502         this._geometry = geometry;
24503         this._options = { color: options.color == null ? 0xFFFFFF : options.color };
24504         this._created$ = new Subject_1.Subject();
24505         this._aborted$ = new Subject_1.Subject();
24506     }
24507     Object.defineProperty(OutlineCreateTag.prototype, "geometry", {
24508         get: function () {
24509             return this._geometry;
24510         },
24511         enumerable: true,
24512         configurable: true
24513     });
24514     Object.defineProperty(OutlineCreateTag.prototype, "created$", {
24515         get: function () {
24516             return this._created$;
24517         },
24518         enumerable: true,
24519         configurable: true
24520     });
24521     Object.defineProperty(OutlineCreateTag.prototype, "aborted$", {
24522         get: function () {
24523             return this._aborted$;
24524         },
24525         enumerable: true,
24526         configurable: true
24527     });
24528     Object.defineProperty(OutlineCreateTag.prototype, "geometryChanged$", {
24529         get: function () {
24530             var _this = this;
24531             return this._geometry.changed$
24532                 .map(function (geometry) {
24533                 return _this;
24534             });
24535         },
24536         enumerable: true,
24537         configurable: true
24538     });
24539     OutlineCreateTag.prototype.getGLObject = function (transform) {
24540         var polygon3d = this._geometry.getPoints3d(transform);
24541         var positions = this._getPositions(polygon3d);
24542         var geometry = new THREE.BufferGeometry();
24543         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
24544         var material = new THREE.LineBasicMaterial({
24545             color: this._options.color,
24546             linewidth: 1,
24547         });
24548         return new THREE.Line(geometry, material);
24549     };
24550     OutlineCreateTag.prototype.getDOMObjects = function (transform, matrixWorldInverse, projectionMatrix) {
24551         var _this = this;
24552         var vNodes = [];
24553         var abort = function (e) {
24554             e.stopPropagation();
24555             _this._aborted$.next(_this);
24556         };
24557         if (this._geometry instanceof Component_1.RectGeometry) {
24558             var topLeftPoint3d = this._geometry.getVertex3d(1, transform);
24559             var topLeftCameraSpace = this._convertToCameraSpace(topLeftPoint3d, matrixWorldInverse);
24560             if (topLeftCameraSpace.z < 0) {
24561                 var centerCanvas = this._projectToCanvas(topLeftCameraSpace, projectionMatrix);
24562                 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
24563                 var pointProperties = {
24564                     style: {
24565                         background: "#" + ("000000" + this._options.color.toString(16)).substr(-6),
24566                         left: centerCss[0],
24567                         position: "absolute",
24568                         top: centerCss[1],
24569                     },
24570                 };
24571                 var completerProperties = {
24572                     onclick: abort,
24573                     style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
24574                 };
24575                 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
24576                 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
24577             }
24578         }
24579         else if (this._geometry instanceof Component_1.PolygonGeometry) {
24580             var polygonGeometry_1 = this._geometry;
24581             var firstVertex3d = this._geometry.getVertex3d(0, transform);
24582             var firstCameraSpace = this._convertToCameraSpace(firstVertex3d, matrixWorldInverse);
24583             if (firstCameraSpace.z < 0) {
24584                 var centerCanvas = this._projectToCanvas(firstCameraSpace, projectionMatrix);
24585                 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
24586                 var firstOnclick = polygonGeometry_1.polygon.length > 4 ?
24587                     function (e) {
24588                         e.stopPropagation();
24589                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 2);
24590                         _this._created$.next(_this);
24591                     } :
24592                     abort;
24593                 var completerProperties = {
24594                     onclick: firstOnclick,
24595                     style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
24596                 };
24597                 var firstClass = polygonGeometry_1.polygon.length > 4 ?
24598                     "TagCompleter" :
24599                     "TagInteractor";
24600                 vNodes.push(vd.h("div." + firstClass, completerProperties, []));
24601             }
24602             if (polygonGeometry_1.polygon.length > 3) {
24603                 var lastVertex3d = this._geometry.getVertex3d(polygonGeometry_1.polygon.length - 3, transform);
24604                 var lastCameraSpace = this._convertToCameraSpace(lastVertex3d, matrixWorldInverse);
24605                 if (lastCameraSpace.z < 0) {
24606                     var centerCanvas = this._projectToCanvas(lastCameraSpace, projectionMatrix);
24607                     var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
24608                     var remove = function (e) {
24609                         e.stopPropagation();
24610                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3);
24611                     };
24612                     var completerProperties = {
24613                         onclick: remove,
24614                         style: { left: centerCss[0], position: "absolute", top: centerCss[1] },
24615                     };
24616                     vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
24617                 }
24618             }
24619             var vertices3d = this._geometry.getVertices3d(transform);
24620             vertices3d.splice(-2, 2);
24621             for (var _i = 0, vertices3d_1 = vertices3d; _i < vertices3d_1.length; _i++) {
24622                 var vertex = vertices3d_1[_i];
24623                 var vertexCameraSpace = this._convertToCameraSpace(vertex, matrixWorldInverse);
24624                 if (vertexCameraSpace.z < 0) {
24625                     var centerCanvas = this._projectToCanvas(vertexCameraSpace, projectionMatrix);
24626                     var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
24627                     var pointProperties = {
24628                         style: {
24629                             background: "#" + ("000000" + this._options.color.toString(16)).substr(-6),
24630                             left: centerCss[0],
24631                             position: "absolute",
24632                             top: centerCss[1],
24633                         },
24634                     };
24635                     vNodes.push(vd.h("div.TagVertex", pointProperties, []));
24636                 }
24637             }
24638         }
24639         return vNodes;
24640     };
24641     OutlineCreateTag.prototype.addPoint = function (point) {
24642         if (this._geometry instanceof Component_1.RectGeometry) {
24643             var rectGeometry = this._geometry;
24644             if (!rectGeometry.validate(point)) {
24645                 return;
24646             }
24647             this._created$.next(this);
24648         }
24649         else if (this._geometry instanceof Component_1.PolygonGeometry) {
24650             var polygonGeometry = this._geometry;
24651             polygonGeometry.addVertex2d(point);
24652         }
24653     };
24654     OutlineCreateTag.prototype._getPositions = function (polygon3d) {
24655         var length = polygon3d.length;
24656         var positions = new Float32Array(length * 3);
24657         for (var i = 0; i < length; ++i) {
24658             var index = 3 * i;
24659             var position = polygon3d[i];
24660             positions[index] = position[0];
24661             positions[index + 1] = position[1];
24662             positions[index + 2] = position[2];
24663         }
24664         return positions;
24665     };
24666     OutlineCreateTag.prototype._projectToCanvas = function (point, projectionMatrix) {
24667         var projected = new THREE.Vector3(point.x, point.y, point.z)
24668             .applyProjection(projectionMatrix);
24669         return [(projected.x + 1) / 2, (-projected.y + 1) / 2];
24670     };
24671     OutlineCreateTag.prototype._convertToCameraSpace = function (point, matrixWorldInverse) {
24672         return new THREE.Vector3(point[0], point[1], point[2]).applyMatrix4(matrixWorldInverse);
24673     };
24674     return OutlineCreateTag;
24675 }());
24676 exports.OutlineCreateTag = OutlineCreateTag;
24677 Object.defineProperty(exports, "__esModule", { value: true });
24678 exports.default = OutlineCreateTag;
24679
24680 },{"../../../Component":210,"rxjs/Subject":33,"three":160,"virtual-dom":166}],267:[function(require,module,exports){
24681 /// <reference path="../../../../typings/index.d.ts" />
24682 "use strict";
24683 var __extends = (this && this.__extends) || function (d, b) {
24684     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
24685     function __() { this.constructor = d; }
24686     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24687 };
24688 var THREE = require("three");
24689 var vd = require("virtual-dom");
24690 var Component_1 = require("../../../Component");
24691 var Viewer_1 = require("../../../Viewer");
24692 /**
24693  * @class OutlineRenderTag
24694  * @classdesc Tag visualizing the properties of an OutlineTag.
24695  */
24696 var OutlineRenderTag = (function (_super) {
24697     __extends(OutlineRenderTag, _super);
24698     function OutlineRenderTag(tag, transform) {
24699         var _this = this;
24700         _super.call(this, tag, transform);
24701         this._fill = this._tag.fillOpacity > 0 && !transform.gpano ?
24702             this._createFill() :
24703             null;
24704         this._holes = this._tag.lineWidth >= 1 ?
24705             this._createHoles() :
24706             [];
24707         this._outline = this._tag.lineWidth >= 1 ?
24708             this._createOutline() :
24709             null;
24710         this._glObjects = this._createGLObjects();
24711         this._tag.geometry.changed$
24712             .subscribe(function (geometry) {
24713             if (_this._fill != null) {
24714                 _this._updateFillGeometry();
24715             }
24716             if (_this._holes.length > 0) {
24717                 _this._updateHoleGeometries();
24718             }
24719             if (_this._outline != null) {
24720                 _this._updateOulineGeometry();
24721             }
24722         });
24723         this._tag.changed$
24724             .subscribe(function (changedTag) {
24725             var glObjectsChanged = false;
24726             if (_this._fill == null) {
24727                 if (_this._tag.fillOpacity > 0 && !_this._transform.gpano) {
24728                     _this._fill = _this._createFill();
24729                     glObjectsChanged = true;
24730                 }
24731             }
24732             else {
24733                 _this._updateFillMaterial();
24734             }
24735             if (_this._outline == null) {
24736                 if (_this._tag.lineWidth > 0) {
24737                     _this._holes = _this._createHoles();
24738                     _this._outline = _this._createOutline();
24739                     glObjectsChanged = true;
24740                 }
24741             }
24742             else {
24743                 _this._updateHoleMaterials();
24744                 _this._updateOutlineMaterial();
24745             }
24746             if (glObjectsChanged) {
24747                 _this._glObjects = _this._createGLObjects();
24748                 _this._glObjectsChanged$.next(_this);
24749             }
24750         });
24751     }
24752     OutlineRenderTag.prototype.dispose = function () {
24753         this._disposeFill();
24754         this._disposeHoles();
24755         this._disposeOutline();
24756     };
24757     OutlineRenderTag.prototype.getDOMObjects = function (atlas, matrixWorldInverse, projectionMatrix) {
24758         var _this = this;
24759         var vNodes = [];
24760         if (this._tag.geometry instanceof Component_1.RectGeometry) {
24761             if (this._tag.icon != null) {
24762                 var iconVertex = this._tag.geometry.getVertex3d(this._tag.iconIndex, this._transform);
24763                 var iconCameraSpace = this._convertToCameraSpace(iconVertex, matrixWorldInverse);
24764                 if (iconCameraSpace.z < 0) {
24765                     var interact = function (e) {
24766                         _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
24767                     };
24768                     if (atlas.loaded) {
24769                         var spriteAlignments = this._getSpriteAlignment(this._tag.iconIndex, this._tag.iconAlignment);
24770                         var sprite = atlas.getDOMSprite(this._tag.icon, spriteAlignments[0], spriteAlignments[1]);
24771                         var click = function (e) {
24772                             e.stopPropagation();
24773                             _this._tag.click$.next(_this._tag);
24774                         };
24775                         var iconCanvas = this._projectToCanvas(iconCameraSpace, projectionMatrix);
24776                         var iconCss = iconCanvas.map(function (coord) { return (100 * coord) + "%"; });
24777                         var properties = {
24778                             onclick: click,
24779                             onmousedown: interact,
24780                             style: {
24781                                 left: iconCss[0],
24782                                 pointerEvents: "all",
24783                                 position: "absolute",
24784                                 top: iconCss[1],
24785                             },
24786                         };
24787                         vNodes.push(vd.h("div.TagSymbol", properties, [sprite]));
24788                     }
24789                 }
24790             }
24791             else if (this._tag.text != null) {
24792                 var textVertex = this._tag.geometry.getVertex3d(3, this._transform);
24793                 var textCameraSpace = this._convertToCameraSpace(textVertex, matrixWorldInverse);
24794                 if (textCameraSpace.z < 0) {
24795                     var interact = function (e) {
24796                         _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
24797                     };
24798                     var labelCanvas = this._projectToCanvas(textCameraSpace, projectionMatrix);
24799                     var labelCss = labelCanvas.map(function (coord) { return (100 * coord) + "%"; });
24800                     var properties = {
24801                         onmousedown: interact,
24802                         style: {
24803                             color: "#" + ("000000" + this._tag.textColor.toString(16)).substr(-6),
24804                             left: labelCss[0],
24805                             pointerEvents: "all",
24806                             position: "absolute",
24807                             top: labelCss[1],
24808                         },
24809                         textContent: this._tag.text,
24810                     };
24811                     vNodes.push(vd.h("span.TagSymbol", properties, []));
24812                 }
24813             }
24814         }
24815         if (!this._tag.editable) {
24816             return vNodes;
24817         }
24818         var lineColor = "#" + ("000000" + this._tag.lineColor.toString(16)).substr(-6);
24819         if (this._tag.geometry instanceof Component_1.RectGeometry) {
24820             var centroid3d = this._tag.geometry.getCentroid3d(this._transform);
24821             var centroidCameraSpace = this._convertToCameraSpace(centroid3d, matrixWorldInverse);
24822             if (centroidCameraSpace.z < 0) {
24823                 var interact = this._interact(Component_1.TagOperation.Centroid);
24824                 var centerCanvas = this._projectToCanvas(centroidCameraSpace, projectionMatrix);
24825                 var centerCss = centerCanvas.map(function (coord) { return (100 * coord) + "%"; });
24826                 var properties = {
24827                     onmousedown: interact,
24828                     style: { background: lineColor, left: centerCss[0], position: "absolute", top: centerCss[1] },
24829                 };
24830                 vNodes.push(vd.h("div.TagMover", properties, []));
24831             }
24832         }
24833         var vertices3d = this._tag.geometry.getVertices3d(this._transform);
24834         for (var i = 0; i < vertices3d.length - 1; i++) {
24835             var isRectGeometry = this._tag.geometry instanceof Component_1.RectGeometry;
24836             if (isRectGeometry &&
24837                 ((this._tag.icon != null && i === this._tag.iconIndex) ||
24838                     (this._tag.icon == null && this._tag.text != null && i === 3))) {
24839                 continue;
24840             }
24841             var vertexCameraSpace = this._convertToCameraSpace(vertices3d[i], matrixWorldInverse);
24842             if (vertexCameraSpace.z > 0) {
24843                 continue;
24844             }
24845             var interact = this._interact(Component_1.TagOperation.Vertex, i);
24846             var vertexCanvas = this._projectToCanvas(vertexCameraSpace, projectionMatrix);
24847             var vertexCss = vertexCanvas.map(function (coord) { return (100 * coord) + "%"; });
24848             var properties = {
24849                 onmousedown: interact,
24850                 style: {
24851                     background: lineColor,
24852                     left: vertexCss[0],
24853                     position: "absolute",
24854                     top: vertexCss[1],
24855                 },
24856             };
24857             if (isRectGeometry) {
24858                 properties.style.cursor = i % 2 === 0 ? "nesw-resize" : "nwse-resize";
24859             }
24860             vNodes.push(vd.h("div.TagResizer", properties, []));
24861             if (!this._tag.indicateVertices) {
24862                 continue;
24863             }
24864             var pointProperties = {
24865                 style: {
24866                     background: lineColor,
24867                     left: vertexCss[0],
24868                     position: "absolute",
24869                     top: vertexCss[1],
24870                 },
24871             };
24872             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
24873         }
24874         return vNodes;
24875     };
24876     OutlineRenderTag.prototype._createFill = function () {
24877         var triangles = this._tag.geometry.getTriangles3d(this._transform);
24878         var positions = new Float32Array(triangles);
24879         var geometry = new THREE.BufferGeometry();
24880         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
24881         geometry.computeBoundingSphere();
24882         var material = new THREE.MeshBasicMaterial({
24883             color: this._tag.fillColor,
24884             opacity: this._tag.fillOpacity,
24885             side: THREE.DoubleSide,
24886             transparent: true,
24887         });
24888         return new THREE.Mesh(geometry, material);
24889     };
24890     OutlineRenderTag.prototype._createGLObjects = function () {
24891         var glObjects = [];
24892         if (this._fill != null) {
24893             glObjects.push(this._fill);
24894         }
24895         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
24896             var hole = _a[_i];
24897             glObjects.push(hole);
24898         }
24899         if (this._outline != null) {
24900             glObjects.push(this._outline);
24901         }
24902         return glObjects;
24903     };
24904     OutlineRenderTag.prototype._createHoles = function () {
24905         var holes = [];
24906         if (this._tag.geometry instanceof Component_1.PolygonGeometry) {
24907             var polygonGeometry = this._tag.geometry;
24908             var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
24909             for (var _i = 0, holes3d_1 = holes3d; _i < holes3d_1.length; _i++) {
24910                 var holePoints3d = holes3d_1[_i];
24911                 var hole = this._createLine(holePoints3d);
24912                 holes.push(hole);
24913             }
24914         }
24915         return holes;
24916     };
24917     OutlineRenderTag.prototype._createLine = function (points3d) {
24918         var positions = this._getLinePositions(points3d);
24919         var geometry = new THREE.BufferGeometry();
24920         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
24921         geometry.computeBoundingSphere();
24922         var material = new THREE.LineBasicMaterial({
24923             color: this._tag.lineColor,
24924             linewidth: this._tag.lineWidth,
24925         });
24926         return new THREE.Line(geometry, material);
24927     };
24928     OutlineRenderTag.prototype._createOutline = function () {
24929         var points3d = this._tag.geometry.getPoints3d(this._transform);
24930         return this._createLine(points3d);
24931     };
24932     OutlineRenderTag.prototype._disposeFill = function () {
24933         if (this._fill == null) {
24934             return;
24935         }
24936         this._fill.geometry.dispose();
24937         this._fill.material.dispose();
24938         this._fill = null;
24939     };
24940     OutlineRenderTag.prototype._disposeHoles = function () {
24941         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
24942             var hole = _a[_i];
24943             hole.geometry.dispose();
24944             hole.material.dispose();
24945         }
24946         this._holes = [];
24947     };
24948     OutlineRenderTag.prototype._disposeOutline = function () {
24949         if (this._outline == null) {
24950             return;
24951         }
24952         this._outline.geometry.dispose();
24953         this._outline.material.dispose();
24954         this._outline = null;
24955     };
24956     OutlineRenderTag.prototype._getLinePositions = function (points3d) {
24957         var length = points3d.length;
24958         var positions = new Float32Array(length * 3);
24959         for (var i = 0; i < length; ++i) {
24960             var index = 3 * i;
24961             var position = points3d[i];
24962             positions[index + 0] = position[0];
24963             positions[index + 1] = position[1];
24964             positions[index + 2] = position[2];
24965         }
24966         return positions;
24967     };
24968     OutlineRenderTag.prototype._getSpriteAlignment = function (index, alignment) {
24969         var horizontalAlignment = Viewer_1.SpriteAlignment.Center;
24970         var verticalAlignment = Viewer_1.SpriteAlignment.Center;
24971         if (alignment === Component_1.Alignment.Outer) {
24972             switch (index) {
24973                 case 0:
24974                     horizontalAlignment = Viewer_1.SpriteAlignment.End;
24975                     verticalAlignment = Viewer_1.SpriteAlignment.Start;
24976                     break;
24977                 case 1:
24978                     horizontalAlignment = Viewer_1.SpriteAlignment.End;
24979                     verticalAlignment = Viewer_1.SpriteAlignment.End;
24980                     break;
24981                 case 2:
24982                     horizontalAlignment = Viewer_1.SpriteAlignment.Start;
24983                     verticalAlignment = Viewer_1.SpriteAlignment.End;
24984                     break;
24985                 case 3:
24986                     horizontalAlignment = Viewer_1.SpriteAlignment.Start;
24987                     verticalAlignment = Viewer_1.SpriteAlignment.Start;
24988                     break;
24989                 default:
24990                     break;
24991             }
24992         }
24993         return [horizontalAlignment, verticalAlignment];
24994     };
24995     OutlineRenderTag.prototype._interact = function (operation, vertexIndex) {
24996         var _this = this;
24997         return function (e) {
24998             var offsetX = e.offsetX - e.target.offsetWidth / 2;
24999             var offsetY = e.offsetY - e.target.offsetHeight / 2;
25000             _this._interact$.next({
25001                 offsetX: offsetX,
25002                 offsetY: offsetY,
25003                 operation: operation,
25004                 tag: _this._tag,
25005                 vertexIndex: vertexIndex,
25006             });
25007         };
25008     };
25009     OutlineRenderTag.prototype._updateFillGeometry = function () {
25010         var triangles = this._tag.geometry.getTriangles3d(this._transform);
25011         var positions = new Float32Array(triangles);
25012         var geometry = this._fill.geometry;
25013         var attribute = geometry.getAttribute("position");
25014         if (attribute.array.length === positions.length) {
25015             attribute.set(positions);
25016             attribute.needsUpdate = true;
25017         }
25018         else {
25019             geometry.removeAttribute("position");
25020             geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
25021         }
25022         geometry.computeBoundingSphere();
25023     };
25024     OutlineRenderTag.prototype._updateFillMaterial = function () {
25025         var material = this._fill.material;
25026         material.color = new THREE.Color(this._tag.fillColor);
25027         material.opacity = this._tag.fillOpacity;
25028         material.needsUpdate = true;
25029     };
25030     OutlineRenderTag.prototype._updateHoleGeometries = function () {
25031         var polygonGeometry = this._tag.geometry;
25032         var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
25033         if (holes3d.length !== this._holes.length) {
25034             throw new Error("Changing the number of holes is not supported.");
25035         }
25036         for (var i = 0; i < this._holes.length; i++) {
25037             var holePoints3d = holes3d[i];
25038             var hole = this._holes[i];
25039             this._updateLine(hole, holePoints3d);
25040         }
25041     };
25042     OutlineRenderTag.prototype._updateHoleMaterials = function () {
25043         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
25044             var hole = _a[_i];
25045             var material = hole.material;
25046             this._updateLineBasicMaterial(material);
25047         }
25048     };
25049     OutlineRenderTag.prototype._updateLine = function (line, points3d) {
25050         var positions = this._getLinePositions(points3d);
25051         var geometry = line.geometry;
25052         var attribute = geometry.getAttribute("position");
25053         attribute.set(positions);
25054         attribute.needsUpdate = true;
25055         geometry.computeBoundingSphere();
25056     };
25057     OutlineRenderTag.prototype._updateOulineGeometry = function () {
25058         var points3d = this._tag.geometry.getPoints3d(this._transform);
25059         this._updateLine(this._outline, points3d);
25060     };
25061     OutlineRenderTag.prototype._updateOutlineMaterial = function () {
25062         var material = this._outline.material;
25063         this._updateLineBasicMaterial(material);
25064     };
25065     OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) {
25066         material.color = new THREE.Color(this._tag.lineColor);
25067         material.linewidth = Math.max(this._tag.lineWidth, 1);
25068         material.opacity = this._tag.lineWidth >= 1 ? 1 : 0;
25069         material.transparent = this._tag.lineWidth <= 0;
25070         material.needsUpdate = true;
25071     };
25072     return OutlineRenderTag;
25073 }(Component_1.RenderTag));
25074 exports.OutlineRenderTag = OutlineRenderTag;
25075
25076 },{"../../../Component":210,"../../../Viewer":219,"three":160,"virtual-dom":166}],268:[function(require,module,exports){
25077 "use strict";
25078 var __extends = (this && this.__extends) || function (d, b) {
25079     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25080     function __() { this.constructor = d; }
25081     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25082 };
25083 var Subject_1 = require("rxjs/Subject");
25084 var Component_1 = require("../../../Component");
25085 /**
25086  * @class OutlineTag
25087  * @classdesc Tag holding properties for visualizing a geometry outline.
25088  */
25089 var OutlineTag = (function (_super) {
25090     __extends(OutlineTag, _super);
25091     /**
25092      * Create an outline tag.
25093      *
25094      * @override
25095      * @constructor
25096      * @param {string} id
25097      * @param {Geometry} geometry
25098      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
25099      * behavior of the outline tag.
25100      */
25101     function OutlineTag(id, geometry, options) {
25102         var _this = this;
25103         _super.call(this, id, geometry);
25104         this._editable = options.editable == null ? false : options.editable;
25105         this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
25106         this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
25107         this._icon = options.icon === undefined ? null : options.icon;
25108         this._iconAlignment = options.iconAlignment == null ? Component_1.Alignment.Outer : options.iconAlignment;
25109         this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
25110         this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
25111         this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
25112         this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
25113         this._text = options.text === undefined ? null : options.text;
25114         this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
25115         this._click$ = new Subject_1.Subject();
25116         this._click$
25117             .subscribe(function (t) {
25118             _this.fire(OutlineTag.click, _this);
25119         });
25120     }
25121     Object.defineProperty(OutlineTag.prototype, "click$", {
25122         /**
25123          * Click observable.
25124          *
25125          * @description An observable emitting the tag when the icon of the
25126          * tag has been clicked.
25127          *
25128          * @returns {Observable<Tag>}
25129          */
25130         get: function () {
25131             return this._click$;
25132         },
25133         enumerable: true,
25134         configurable: true
25135     });
25136     Object.defineProperty(OutlineTag.prototype, "editable", {
25137         /**
25138          * Get editable property.
25139          * @returns {boolean} Value indicating if tag is editable.
25140          */
25141         get: function () {
25142             return this._editable;
25143         },
25144         /**
25145          * Set editable property.
25146          * @param {boolean}
25147          *
25148          * @fires Tag#changed
25149          */
25150         set: function (value) {
25151             this._editable = value;
25152             this._notifyChanged$.next(this);
25153         },
25154         enumerable: true,
25155         configurable: true
25156     });
25157     Object.defineProperty(OutlineTag.prototype, "fillColor", {
25158         /**
25159          * Get fill color property.
25160          * @returns {number}
25161          */
25162         get: function () {
25163             return this._fillColor;
25164         },
25165         /**
25166          * Set fill color property.
25167          * @param {number}
25168          *
25169          * @fires Tag#changed
25170          */
25171         set: function (value) {
25172             this._fillColor = value;
25173             this._notifyChanged$.next(this);
25174         },
25175         enumerable: true,
25176         configurable: true
25177     });
25178     Object.defineProperty(OutlineTag.prototype, "fillOpacity", {
25179         /**
25180          * Get fill opacity property.
25181          * @returns {number}
25182          */
25183         get: function () {
25184             return this._fillOpacity;
25185         },
25186         /**
25187          * Set fill opacity property.
25188          * @param {number}
25189          *
25190          * @fires Tag#changed
25191          */
25192         set: function (value) {
25193             this._fillOpacity = value;
25194             this._notifyChanged$.next(this);
25195         },
25196         enumerable: true,
25197         configurable: true
25198     });
25199     Object.defineProperty(OutlineTag.prototype, "geometry", {
25200         get: function () {
25201             return this._geometry;
25202         },
25203         enumerable: true,
25204         configurable: true
25205     });
25206     Object.defineProperty(OutlineTag.prototype, "icon", {
25207         /**
25208          * Get icon property.
25209          * @returns {string}
25210          */
25211         get: function () {
25212             return this._icon;
25213         },
25214         /**
25215          * Set icon property.
25216          * @param {string}
25217          *
25218          * @fires Tag#changed
25219          */
25220         set: function (value) {
25221             this._icon = value;
25222             this._notifyChanged$.next(this);
25223         },
25224         enumerable: true,
25225         configurable: true
25226     });
25227     Object.defineProperty(OutlineTag.prototype, "iconAlignment", {
25228         /**
25229          * Get icon alignment property.
25230          * @returns {Alignment}
25231          */
25232         get: function () {
25233             return this._iconAlignment;
25234         },
25235         /**
25236          * Set icon alignment property.
25237          * @param {Alignment}
25238          *
25239          * @fires Tag#changed
25240          */
25241         set: function (value) {
25242             this._iconAlignment = value;
25243             this._notifyChanged$.next(this);
25244         },
25245         enumerable: true,
25246         configurable: true
25247     });
25248     Object.defineProperty(OutlineTag.prototype, "iconIndex", {
25249         /**
25250          * Get icon index property.
25251          * @returns {number}
25252          */
25253         get: function () {
25254             return this._iconIndex;
25255         },
25256         /**
25257          * Set icon index property.
25258          * @param {number}
25259          *
25260          * @fires Tag#changed
25261          */
25262         set: function (value) {
25263             this._iconIndex = value;
25264             this._notifyChanged$.next(this);
25265         },
25266         enumerable: true,
25267         configurable: true
25268     });
25269     Object.defineProperty(OutlineTag.prototype, "indicateVertices", {
25270         /**
25271          * Get indicate vertices property.
25272          * @returns {boolean} Value indicating if vertices should be indicated
25273          * when tag is editable.
25274          */
25275         get: function () {
25276             return this._indicateVertices;
25277         },
25278         /**
25279          * Set indicate vertices property.
25280          * @param {boolean}
25281          *
25282          * @fires Tag#changed
25283          */
25284         set: function (value) {
25285             this._indicateVertices = value;
25286             this._notifyChanged$.next(this);
25287         },
25288         enumerable: true,
25289         configurable: true
25290     });
25291     Object.defineProperty(OutlineTag.prototype, "lineColor", {
25292         /**
25293          * Get line color property.
25294          * @returns {number}
25295          */
25296         get: function () {
25297             return this._lineColor;
25298         },
25299         /**
25300          * Set line color property.
25301          * @param {number}
25302          *
25303          * @fires Tag#changed
25304          */
25305         set: function (value) {
25306             this._lineColor = value;
25307             this._notifyChanged$.next(this);
25308         },
25309         enumerable: true,
25310         configurable: true
25311     });
25312     Object.defineProperty(OutlineTag.prototype, "lineWidth", {
25313         /**
25314          * Get line width property.
25315          * @returns {number}
25316          */
25317         get: function () {
25318             return this._lineWidth;
25319         },
25320         /**
25321          * Set line width property.
25322          * @param {number}
25323          *
25324          * @fires Tag#changed
25325          */
25326         set: function (value) {
25327             this._lineWidth = value;
25328             this._notifyChanged$.next(this);
25329         },
25330         enumerable: true,
25331         configurable: true
25332     });
25333     Object.defineProperty(OutlineTag.prototype, "text", {
25334         /**
25335          * Get text property.
25336          * @returns {string}
25337          */
25338         get: function () {
25339             return this._text;
25340         },
25341         /**
25342          * Set text property.
25343          * @param {string}
25344          *
25345          * @fires Tag#changed
25346          */
25347         set: function (value) {
25348             this._text = value;
25349             this._notifyChanged$.next(this);
25350         },
25351         enumerable: true,
25352         configurable: true
25353     });
25354     Object.defineProperty(OutlineTag.prototype, "textColor", {
25355         /**
25356          * Get text color property.
25357          * @returns {number}
25358          */
25359         get: function () {
25360             return this._textColor;
25361         },
25362         /**
25363          * Set text color property.
25364          * @param {number}
25365          *
25366          * @fires Tag#changed
25367          */
25368         set: function (value) {
25369             this._textColor = value;
25370             this._notifyChanged$.next(this);
25371         },
25372         enumerable: true,
25373         configurable: true
25374     });
25375     /**
25376      * Set options for tag.
25377      *
25378      * @description Sets all the option properties provided and keps
25379      * the rest of the values as is.
25380      *
25381      * @param {IOutlineTagOptions} options - Outline tag options
25382      *
25383      * @fires {Tag#changed}
25384      */
25385     OutlineTag.prototype.setOptions = function (options) {
25386         this._editable = options.editable == null ? this._editable : options.editable;
25387         this._icon = options.icon === undefined ? this._icon : options.icon;
25388         this._iconAlignment = options.iconAlignment == null ? this._iconAlignment : options.iconAlignment;
25389         this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
25390         this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
25391         this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
25392         this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
25393         this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
25394         this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
25395         this._text = options.text === undefined ? this._text : options.text;
25396         this._textColor = options.textColor == null ? this._textColor : options.textColor;
25397         this._notifyChanged$.next(this);
25398     };
25399     /**
25400      * Event fired when the icon of the outline tag is clicked.
25401      *
25402      * @event OutlineTag#click
25403      * @type {OutlineTag} The tag instance that was clicked.
25404      */
25405     OutlineTag.click = "click";
25406     return OutlineTag;
25407 }(Component_1.Tag));
25408 exports.OutlineTag = OutlineTag;
25409 Object.defineProperty(exports, "__esModule", { value: true });
25410 exports.default = OutlineTag;
25411
25412 },{"../../../Component":210,"rxjs/Subject":33}],269:[function(require,module,exports){
25413 /// <reference path="../../../../typings/index.d.ts" />
25414 "use strict";
25415 var THREE = require("three");
25416 var Subject_1 = require("rxjs/Subject");
25417 var RenderTag = (function () {
25418     function RenderTag(tag, transform) {
25419         this._tag = tag;
25420         this._transform = transform;
25421         this._glObjects = [];
25422         this._glObjectsChanged$ = new Subject_1.Subject();
25423         this._interact$ = new Subject_1.Subject();
25424     }
25425     Object.defineProperty(RenderTag.prototype, "glObjects", {
25426         /**
25427          * Get the GL objects for rendering of the tag.
25428          * @return {Array<Object3D>}
25429          */
25430         get: function () {
25431             return this._glObjects;
25432         },
25433         enumerable: true,
25434         configurable: true
25435     });
25436     Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", {
25437         get: function () {
25438             return this._glObjectsChanged$;
25439         },
25440         enumerable: true,
25441         configurable: true
25442     });
25443     Object.defineProperty(RenderTag.prototype, "interact$", {
25444         get: function () {
25445             return this._interact$;
25446         },
25447         enumerable: true,
25448         configurable: true
25449     });
25450     Object.defineProperty(RenderTag.prototype, "tag", {
25451         get: function () {
25452             return this._tag;
25453         },
25454         enumerable: true,
25455         configurable: true
25456     });
25457     RenderTag.prototype._projectToCanvas = function (point3d, projectionMatrix) {
25458         var projected = new THREE.Vector3(point3d.x, point3d.y, point3d.z)
25459             .applyProjection(projectionMatrix);
25460         return [(projected.x + 1) / 2, (-projected.y + 1) / 2];
25461     };
25462     RenderTag.prototype._convertToCameraSpace = function (point3d, matrixWorldInverse) {
25463         return new THREE.Vector3(point3d[0], point3d[1], point3d[2]).applyMatrix4(matrixWorldInverse);
25464     };
25465     return RenderTag;
25466 }());
25467 exports.RenderTag = RenderTag;
25468 Object.defineProperty(exports, "__esModule", { value: true });
25469 exports.default = RenderTag;
25470
25471 },{"rxjs/Subject":33,"three":160}],270:[function(require,module,exports){
25472 /// <reference path="../../../../typings/index.d.ts" />
25473 "use strict";
25474 var __extends = (this && this.__extends) || function (d, b) {
25475     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25476     function __() { this.constructor = d; }
25477     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25478 };
25479 var vd = require("virtual-dom");
25480 var Component_1 = require("../../../Component");
25481 var Viewer_1 = require("../../../Viewer");
25482 /**
25483  * @class SpotRenderTag
25484  * @classdesc Tag visualizing the properties of a SpotTag.
25485  */
25486 var SpotRenderTag = (function (_super) {
25487     __extends(SpotRenderTag, _super);
25488     function SpotRenderTag() {
25489         _super.apply(this, arguments);
25490     }
25491     SpotRenderTag.prototype.dispose = function () { return; };
25492     SpotRenderTag.prototype.getDOMObjects = function (atlas, matrixWorldInverse, projectionMatrix) {
25493         var _this = this;
25494         var vNodes = [];
25495         var centroid3d = this._tag.geometry.getCentroid3d(this._transform);
25496         var centroidCameraSpace = this._convertToCameraSpace(centroid3d, matrixWorldInverse);
25497         if (centroidCameraSpace.z < 0) {
25498             var centroidCanvas = this._projectToCanvas(centroidCameraSpace, projectionMatrix);
25499             var centroidCss = centroidCanvas.map(function (coord) { return (100 * coord) + "%"; });
25500             var interactNone = function (e) {
25501                 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
25502             };
25503             if (this._tag.icon != null) {
25504                 if (atlas.loaded) {
25505                     var sprite = atlas.getDOMSprite(this._tag.icon, Viewer_1.SpriteAlignment.Center, Viewer_1.SpriteAlignment.End);
25506                     var properties = {
25507                         onmousedown: interactNone,
25508                         style: {
25509                             bottom: 100 * (1 - centroidCanvas[1]) + "%",
25510                             left: centroidCss[0],
25511                             pointerEvents: "all",
25512                             position: "absolute",
25513                             transform: "translate(0px, -8px)",
25514                         },
25515                     };
25516                     vNodes.push(vd.h("div", properties, [sprite]));
25517                 }
25518             }
25519             else if (this._tag.text != null) {
25520                 var properties = {
25521                     onmousedown: interactNone,
25522                     style: {
25523                         bottom: 100 * (1 - centroidCanvas[1]) + "%",
25524                         color: "#" + ("000000" + this._tag.textColor.toString(16)).substr(-6),
25525                         left: centroidCss[0],
25526                         pointerEvents: "all",
25527                         position: "absolute",
25528                         transform: "translate(-50%, -7px)",
25529                     },
25530                     textContent: this._tag.text,
25531                 };
25532                 vNodes.push(vd.h("span.TagSymbol", properties, []));
25533             }
25534             var interact = this._interact(Component_1.TagOperation.Centroid);
25535             var background = "#" + ("000000" + this._tag.color.toString(16)).substr(-6);
25536             if (this._tag.editable) {
25537                 var interactorProperties = {
25538                     onmousedown: interact,
25539                     style: {
25540                         background: background,
25541                         left: centroidCss[0],
25542                         pointerEvents: "all",
25543                         position: "absolute",
25544                         top: centroidCss[1],
25545                     },
25546                 };
25547                 vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, []));
25548             }
25549             var pointProperties = {
25550                 style: {
25551                     background: background,
25552                     left: centroidCss[0],
25553                     position: "absolute",
25554                     top: centroidCss[1],
25555                 },
25556             };
25557             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
25558         }
25559         return vNodes;
25560     };
25561     SpotRenderTag.prototype._interact = function (operation, vertexIndex) {
25562         var _this = this;
25563         return function (e) {
25564             var offsetX = e.offsetX - e.target.offsetWidth / 2;
25565             var offsetY = e.offsetY - e.target.offsetHeight / 2;
25566             _this._interact$.next({
25567                 offsetX: offsetX,
25568                 offsetY: offsetY,
25569                 operation: operation,
25570                 tag: _this._tag,
25571                 vertexIndex: vertexIndex,
25572             });
25573         };
25574     };
25575     return SpotRenderTag;
25576 }(Component_1.RenderTag));
25577 exports.SpotRenderTag = SpotRenderTag;
25578
25579 },{"../../../Component":210,"../../../Viewer":219,"virtual-dom":166}],271:[function(require,module,exports){
25580 "use strict";
25581 var __extends = (this && this.__extends) || function (d, b) {
25582     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25583     function __() { this.constructor = d; }
25584     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25585 };
25586 var Component_1 = require("../../../Component");
25587 /**
25588  * @class SpotTag
25589  * @classdesc Tag holding properties for visualizing the centroid of a geometry.
25590  */
25591 var SpotTag = (function (_super) {
25592     __extends(SpotTag, _super);
25593     /**
25594      * Create a spot tag.
25595      *
25596      * @override
25597      * @constructor
25598      * @param {string} id
25599      * @param {Geometry} geometry
25600      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
25601      * behavior of the spot tag.
25602      */
25603     function SpotTag(id, geometry, options) {
25604         _super.call(this, id, geometry);
25605         this._color = options.color == null ? 0xFFFFFF : options.color;
25606         this._editable = options.editable == null ? false : options.editable;
25607         this._icon = options.icon === undefined ? null : options.icon;
25608         this._text = options.text === undefined ? null : options.text;
25609         this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
25610     }
25611     Object.defineProperty(SpotTag.prototype, "color", {
25612         /**
25613          * Get color property.
25614          * @returns {number} The color of the spot as a hexagonal number;
25615          */
25616         get: function () {
25617             return this._color;
25618         },
25619         /**
25620          * Set color property.
25621          * @param {number}
25622          *
25623          * @fires Tag#changed
25624          */
25625         set: function (value) {
25626             this._color = value;
25627             this._notifyChanged$.next(this);
25628         },
25629         enumerable: true,
25630         configurable: true
25631     });
25632     Object.defineProperty(SpotTag.prototype, "editable", {
25633         /**
25634          * Get editable property.
25635          * @returns {boolean} Value indicating if tag is editable.
25636          */
25637         get: function () {
25638             return this._editable;
25639         },
25640         /**
25641          * Set editable property.
25642          * @param {boolean}
25643          *
25644          * @fires Tag#changed
25645          */
25646         set: function (value) {
25647             this._editable = value;
25648             this._notifyChanged$.next(this);
25649         },
25650         enumerable: true,
25651         configurable: true
25652     });
25653     Object.defineProperty(SpotTag.prototype, "icon", {
25654         /**
25655          * Get icon property.
25656          * @returns {string}
25657          */
25658         get: function () {
25659             return this._icon;
25660         },
25661         /**
25662          * Set icon property.
25663          * @param {string}
25664          *
25665          * @fires Tag#changed
25666          */
25667         set: function (value) {
25668             this._icon = value;
25669             this._notifyChanged$.next(this);
25670         },
25671         enumerable: true,
25672         configurable: true
25673     });
25674     Object.defineProperty(SpotTag.prototype, "text", {
25675         /**
25676          * Get text property.
25677          * @returns {string}
25678          */
25679         get: function () {
25680             return this._text;
25681         },
25682         /**
25683          * Set text property.
25684          * @param {string}
25685          *
25686          * @fires Tag#changed
25687          */
25688         set: function (value) {
25689             this._text = value;
25690             this._notifyChanged$.next(this);
25691         },
25692         enumerable: true,
25693         configurable: true
25694     });
25695     Object.defineProperty(SpotTag.prototype, "textColor", {
25696         /**
25697          * Get text color property.
25698          * @returns {number}
25699          */
25700         get: function () {
25701             return this._textColor;
25702         },
25703         /**
25704          * Set text color property.
25705          * @param {number}
25706          *
25707          * @fires Tag#changed
25708          */
25709         set: function (value) {
25710             this._textColor = value;
25711             this._notifyChanged$.next(this);
25712         },
25713         enumerable: true,
25714         configurable: true
25715     });
25716     /**
25717      * Set options for tag.
25718      *
25719      * @description Sets all the option properties provided and keps
25720      * the rest of the values as is.
25721      *
25722      * @param {ISpotTagOptions} options - Spot tag options
25723      *
25724      * @fires {Tag#changed}
25725      */
25726     SpotTag.prototype.setOptions = function (options) {
25727         this._color = options.color == null ? this._color : options.color;
25728         this._editable = options.editable == null ? this._editable : options.editable;
25729         this._icon = options.icon === undefined ? this._icon : options.icon;
25730         this._text = options.text === undefined ? this._text : options.text;
25731         this._textColor = options.textColor == null ? this._textColor : options.textColor;
25732         this._notifyChanged$.next(this);
25733     };
25734     return SpotTag;
25735 }(Component_1.Tag));
25736 exports.SpotTag = SpotTag;
25737 Object.defineProperty(exports, "__esModule", { value: true });
25738 exports.default = SpotTag;
25739
25740 },{"../../../Component":210}],272:[function(require,module,exports){
25741 "use strict";
25742 var __extends = (this && this.__extends) || function (d, b) {
25743     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25744     function __() { this.constructor = d; }
25745     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25746 };
25747 var Subject_1 = require("rxjs/Subject");
25748 require("rxjs/add/operator/map");
25749 require("rxjs/add/operator/share");
25750 var Utils_1 = require("../../../Utils");
25751 /**
25752  * @class Tag
25753  * @abstract
25754  * @classdesc Abstract class representing the basic functionality of for a tag.
25755  */
25756 var Tag = (function (_super) {
25757     __extends(Tag, _super);
25758     /**
25759      * Create a tag.
25760      *
25761      * @constructor
25762      * @param {string} id
25763      * @param {Geometry} geometry
25764      */
25765     function Tag(id, geometry) {
25766         var _this = this;
25767         _super.call(this);
25768         this._id = id;
25769         this._geometry = geometry;
25770         this._notifyChanged$ = new Subject_1.Subject();
25771         this._notifyChanged$
25772             .subscribe(function (t) {
25773             _this.fire(Tag.changed, _this);
25774         });
25775         this._geometry.changed$
25776             .subscribe(function (g) {
25777             _this.fire(Tag.geometrychanged, _this);
25778         });
25779     }
25780     Object.defineProperty(Tag.prototype, "id", {
25781         /**
25782          * Get id property.
25783          * @returns {string}
25784          */
25785         get: function () {
25786             return this._id;
25787         },
25788         enumerable: true,
25789         configurable: true
25790     });
25791     Object.defineProperty(Tag.prototype, "geometry", {
25792         /**
25793          * Get geometry property.
25794          * @returns {Geometry}
25795          */
25796         get: function () {
25797             return this._geometry;
25798         },
25799         enumerable: true,
25800         configurable: true
25801     });
25802     Object.defineProperty(Tag.prototype, "changed$", {
25803         /**
25804          * Get changed observable.
25805          * @returns {Observable<Tag>}
25806          */
25807         get: function () {
25808             return this._notifyChanged$;
25809         },
25810         enumerable: true,
25811         configurable: true
25812     });
25813     Object.defineProperty(Tag.prototype, "geometryChanged$", {
25814         /**
25815          * Get geometry changed observable.
25816          * @returns {Observable<Tag>}
25817          */
25818         get: function () {
25819             var _this = this;
25820             return this._geometry.changed$
25821                 .map(function (geometry) {
25822                 return _this;
25823             })
25824                 .share();
25825         },
25826         enumerable: true,
25827         configurable: true
25828     });
25829     /**
25830      * Event fired when a property related to the visual appearance of the
25831      * tag has changed.
25832      *
25833      * @event Tag#changed
25834      * @type {Tag} The tag instance that has changed.
25835      */
25836     Tag.changed = "changed";
25837     /**
25838      * Event fired when the geometry of the tag has changed.
25839      *
25840      * @event Tag#geometrychanged
25841      * @type {Tag} The tag instance whose geometry has changed.
25842      */
25843     Tag.geometrychanged = "geometrychanged";
25844     return Tag;
25845 }(Utils_1.EventEmitter));
25846 exports.Tag = Tag;
25847 Object.defineProperty(exports, "__esModule", { value: true });
25848 exports.default = Tag;
25849
25850 },{"../../../Utils":218,"rxjs/Subject":33,"rxjs/add/operator/map":61,"rxjs/add/operator/share":70}],273:[function(require,module,exports){
25851 "use strict";
25852 var __extends = (this && this.__extends) || function (d, b) {
25853     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25854     function __() { this.constructor = d; }
25855     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25856 };
25857 var MapillaryError_1 = require("./MapillaryError");
25858 var ArgumentMapillaryError = (function (_super) {
25859     __extends(ArgumentMapillaryError, _super);
25860     function ArgumentMapillaryError(message) {
25861         _super.call(this, message != null ? message : "The argument is not valid.");
25862         this.name = "ArgumentMapillaryError";
25863     }
25864     return ArgumentMapillaryError;
25865 }(MapillaryError_1.MapillaryError));
25866 exports.ArgumentMapillaryError = ArgumentMapillaryError;
25867 Object.defineProperty(exports, "__esModule", { value: true });
25868 exports.default = ArgumentMapillaryError;
25869
25870 },{"./MapillaryError":275}],274:[function(require,module,exports){
25871 "use strict";
25872 var __extends = (this && this.__extends) || function (d, b) {
25873     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25874     function __() { this.constructor = d; }
25875     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25876 };
25877 var MapillaryError_1 = require("./MapillaryError");
25878 var GraphMapillaryError = (function (_super) {
25879     __extends(GraphMapillaryError, _super);
25880     function GraphMapillaryError(message) {
25881         _super.call(this, message);
25882         this.name = "GraphMapillaryError";
25883     }
25884     return GraphMapillaryError;
25885 }(MapillaryError_1.MapillaryError));
25886 exports.GraphMapillaryError = GraphMapillaryError;
25887 Object.defineProperty(exports, "__esModule", { value: true });
25888 exports.default = GraphMapillaryError;
25889
25890 },{"./MapillaryError":275}],275:[function(require,module,exports){
25891 "use strict";
25892 var __extends = (this && this.__extends) || function (d, b) {
25893     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
25894     function __() { this.constructor = d; }
25895     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25896 };
25897 var MapillaryError = (function (_super) {
25898     __extends(MapillaryError, _super);
25899     function MapillaryError(message) {
25900         _super.call(this);
25901         this.message = message;
25902         this.name = "MapillaryError";
25903         this.stack = new Error().stack;
25904     }
25905     return MapillaryError;
25906 }(Error));
25907 exports.MapillaryError = MapillaryError;
25908 Object.defineProperty(exports, "__esModule", { value: true });
25909 exports.default = MapillaryError;
25910
25911 },{}],276:[function(require,module,exports){
25912 /// <reference path="../../typings/index.d.ts" />
25913 "use strict";
25914 var THREE = require("three");
25915 /**
25916  * @class Camera
25917  *
25918  * @classdesc Holds information about a camera.
25919  */
25920 var Camera = (function () {
25921     /**
25922      * Create a new camera instance.
25923      * @param {Transform} [transform] - Optional transform instance.
25924      */
25925     function Camera(transform) {
25926         if (transform != null) {
25927             this._position = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0));
25928             this._lookat = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10));
25929             this._up = transform.upVector();
25930             this._focal = this._getFocal(transform);
25931         }
25932         else {
25933             this._position = new THREE.Vector3(0, 0, 0);
25934             this._lookat = new THREE.Vector3(0, 0, 1);
25935             this._up = new THREE.Vector3(0, -1, 0);
25936             this._focal = 1;
25937         }
25938     }
25939     Object.defineProperty(Camera.prototype, "position", {
25940         /**
25941          * Get position.
25942          * @returns {THREE.Vector3} The position vector.
25943          */
25944         get: function () {
25945             return this._position;
25946         },
25947         enumerable: true,
25948         configurable: true
25949     });
25950     Object.defineProperty(Camera.prototype, "lookat", {
25951         /**
25952          * Get lookat.
25953          * @returns {THREE.Vector3} The lookat vector.
25954          */
25955         get: function () {
25956             return this._lookat;
25957         },
25958         enumerable: true,
25959         configurable: true
25960     });
25961     Object.defineProperty(Camera.prototype, "up", {
25962         /**
25963          * Get up.
25964          * @returns {THREE.Vector3} The up vector.
25965          */
25966         get: function () {
25967             return this._up;
25968         },
25969         enumerable: true,
25970         configurable: true
25971     });
25972     Object.defineProperty(Camera.prototype, "focal", {
25973         /**
25974          * Get focal.
25975          * @returns {number} The focal length.
25976          */
25977         get: function () {
25978             return this._focal;
25979         },
25980         /**
25981          * Set focal.
25982          */
25983         set: function (value) {
25984             this._focal = value;
25985         },
25986         enumerable: true,
25987         configurable: true
25988     });
25989     /**
25990      * Update this camera to the linearly interpolated value of two other cameras.
25991      *
25992      * @param {Camera} a - First camera.
25993      * @param {Camera} b - Second camera.
25994      * @param {number} alpha - Interpolation value on the interval [0, 1].
25995      */
25996     Camera.prototype.lerpCameras = function (a, b, alpha) {
25997         this._position.subVectors(b.position, a.position).multiplyScalar(alpha).add(a.position);
25998         this._lookat.subVectors(b.lookat, a.lookat).multiplyScalar(alpha).add(a.lookat);
25999         this._up.subVectors(b.up, a.up).multiplyScalar(alpha).add(a.up);
26000         this._focal = (1 - alpha) * a.focal + alpha * b.focal;
26001     };
26002     /**
26003      * Copy the properties of another camera to this camera.
26004      *
26005      * @param {Camera} other - Another camera.
26006      */
26007     Camera.prototype.copy = function (other) {
26008         this._position.copy(other.position);
26009         this._lookat.copy(other.lookat);
26010         this._up.copy(other.up);
26011         this._focal = other.focal;
26012     };
26013     /**
26014      * Clone this camera.
26015      *
26016      * @returns {Camera} A camera with cloned properties equal to this camera.
26017      */
26018     Camera.prototype.clone = function () {
26019         var camera = new Camera();
26020         camera.position.copy(this._position);
26021         camera.lookat.copy(this._lookat);
26022         camera.up.copy(this._up);
26023         camera.focal = this._focal;
26024         return camera;
26025     };
26026     /**
26027      * Determine the distance between this camera and another camera.
26028      *
26029      * @param {Camera} other - Another camera.
26030      * @returns {number} The distance between the cameras.
26031      */
26032     Camera.prototype.diff = function (other) {
26033         var pd = this._position.distanceToSquared(other.position);
26034         var ld = this._lookat.distanceToSquared(other.lookat);
26035         var ud = this._up.distanceToSquared(other.up);
26036         var fd = 100 * Math.abs(this._focal - other.focal);
26037         return Math.max(pd, ld, ud, fd);
26038     };
26039     /**
26040      * Get the focal length based on the transform.
26041      *
26042      * @description Returns 0.5 focal length if transform has gpano
26043      * information.
26044      *
26045      * @returns {number} Focal length.
26046      */
26047     Camera.prototype._getFocal = function (transform) {
26048         return transform.gpano == null ? transform.focal : 0.5;
26049     };
26050     return Camera;
26051 }());
26052 exports.Camera = Camera;
26053
26054 },{"three":160}],277:[function(require,module,exports){
26055 "use strict";
26056 /**
26057  * @class GeoCoords
26058  *
26059  * @classdesc Converts coordinates between the geodetic (WGS84),
26060  * Earth-Centered, Earth-Fixed (ECEF) and local topocentric
26061  * East, North, Up (ENU) reference frames.
26062  *
26063  * The WGS84 has latitude (degrees), longitude (degrees) and
26064  * altitude (meters) values.
26065  *
26066  * The ECEF Z-axis pierces the north pole and the
26067  * XY-axis defines the equatorial plane. The X-axis extends
26068  * from the geocenter to the intersection of the Equator and
26069  * the Greenwich Meridian. All values in meters.
26070  *
26071  * The WGS84 parameters are:
26072  *
26073  * a = 6378137
26074  * b = a * (1 - f)
26075  * f = 1 / 298.257223563
26076  * e = Math.sqrt((a^2 - b^2) / a^2)
26077  * e' = Math.sqrt((a^2 - b^2) / b^2)
26078  *
26079  * The WGS84 to ECEF conversion is performed using the following:
26080  *
26081  * X = (N - h) * cos(phi) * cos(lambda)
26082  * Y = (N + h) * cos(phi) * sin(lambda)
26083  * Z = (b^2 * N / a^2 + h) * sin(phi)
26084  *
26085  * where
26086  *
26087  * phi = latitude
26088  * lambda = longitude
26089  * h = height above ellipsoid (altitude)
26090  * N = Radius of curvature (meters)
26091  *   = a / Math.sqrt(1 - e^2 * sin(phi)^2)
26092  *
26093  * The ECEF to WGS84 conversion is performed using the following:
26094  *
26095  * phi = arctan((Z + e'^2 * b * sin(theta)^3) / (p - e^2 * a * cos(theta)^3))
26096  * lambda = arctan(Y / X)
26097  * h = p / cos(phi) - N
26098  *
26099  * where
26100  *
26101  * p = Math.sqrt(X^2 + Y^2)
26102  * theta = arctan(Z * a / p * b)
26103  *
26104  * In the ENU reference frame the x-axis points to the
26105  * East, the y-axis to the North and the z-axis Up. All values
26106  * in meters.
26107  *
26108  * The ECEF to ENU conversion is performed using the following:
26109  *
26110  * | x |   |       -sin(lambda_r)                cos(lambda_r)             0      | | X - X_r |
26111  * | y | = | -sin(phi_r) * cos(lambda_r)  -sin(phi_r) * sin(lambda_r)  cos(phi_r) | | Y - Y_r |
26112  * | z |   |  cos(phi_r) * cos(lambda_r)   cos(phi_r) * sin(lambda_r)  sin(phi_r) | | Z - Z_r |
26113  *
26114  * where
26115  *
26116  * phi_r = latitude of reference
26117  * lambda_r = longitude of reference
26118  * X_r, Y_r, Z_r = ECEF coordinates of reference
26119  *
26120  * The ENU to ECEF conversion is performed by solving the above equation for X, Y, Z.
26121  *
26122  * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in
26123  * the first step for both conversions.
26124  */
26125 var GeoCoords = (function () {
26126     function GeoCoords() {
26127         this._wgs84a = 6378137.0;
26128         this._wgs84b = 6356752.31424518;
26129     }
26130     /**
26131      * Convert coordinates from geodetic (WGS84) reference to local topocentric
26132      * (ENU) reference.
26133      *
26134      * @param {number} lat Latitude in degrees.
26135      * @param {number} lon Longitude in degrees.
26136      * @param {number} alt Altitude in meters.
26137      * @param {number} refLat Reference latitude in degrees.
26138      * @param {number} refLon Reference longitude in degrees.
26139      * @param {number} refAlt Reference altitude in meters.
26140      * @returns {Array<number>} The x, y, z local topocentric ENU coordinates.
26141      */
26142     GeoCoords.prototype.geodeticToEnu = function (lat, lon, alt, refLat, refLon, refAlt) {
26143         var ecef = this.geodeticToEcef(lat, lon, alt);
26144         return this.ecefToEnu(ecef[0], ecef[1], ecef[2], refLat, refLon, refAlt);
26145     };
26146     /**
26147      * Convert coordinates from local topocentric (ENU) reference to
26148      * geodetic (WGS84) reference.
26149      *
26150      * @param {number} x Topocentric ENU coordinate in East direction.
26151      * @param {number} y Topocentric ENU coordinate in North direction.
26152      * @param {number} z Topocentric ENU coordinate in Up direction.
26153      * @param {number} refLat Reference latitude in degrees.
26154      * @param {number} refLon Reference longitude in degrees.
26155      * @param {number} refAlt Reference altitude in meters.
26156      * @returns {Array<number>} The latitude and longitude in degrees
26157      *                          as well as altitude in meters.
26158      */
26159     GeoCoords.prototype.enuToGeodetic = function (x, y, z, refLat, refLon, refAlt) {
26160         var ecef = this.enuToEcef(x, y, z, refLat, refLon, refAlt);
26161         return this.ecefToGeodetic(ecef[0], ecef[1], ecef[2]);
26162     };
26163     /**
26164      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
26165      * to local topocentric (ENU) reference.
26166      *
26167      * @param {number} X ECEF X-value.
26168      * @param {number} Y ECEF Y-value.
26169      * @param {number} Z ECEF Z-value.
26170      * @param {number} refLat Reference latitude in degrees.
26171      * @param {number} refLon Reference longitude in degrees.
26172      * @param {number} refAlt Reference altitude in meters.
26173      * @returns {Array<number>} The x, y, z topocentric ENU coordinates in East, North
26174      * and Up directions respectively.
26175      */
26176     GeoCoords.prototype.ecefToEnu = function (X, Y, Z, refLat, refLon, refAlt) {
26177         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
26178         var V = [X - refEcef[0], Y - refEcef[1], Z - refEcef[2]];
26179         refLat = refLat * Math.PI / 180.0;
26180         refLon = refLon * Math.PI / 180.0;
26181         var cosLat = Math.cos(refLat);
26182         var sinLat = Math.sin(refLat);
26183         var cosLon = Math.cos(refLon);
26184         var sinLon = Math.sin(refLon);
26185         var x = -sinLon * V[0] + cosLon * V[1];
26186         var y = -sinLat * cosLon * V[0] - sinLat * sinLon * V[1] + cosLat * V[2];
26187         var z = cosLat * cosLon * V[0] + cosLat * sinLon * V[1] + sinLat * V[2];
26188         return [x, y, z];
26189     };
26190     /**
26191      * Convert coordinates from local topocentric (ENU) reference
26192      * to Earth-Centered, Earth-Fixed (ECEF) reference.
26193      *
26194      * @param {number} x Topocentric ENU coordinate in East direction.
26195      * @param {number} y Topocentric ENU coordinate in North direction.
26196      * @param {number} z Topocentric ENU coordinate in Up direction.
26197      * @param {number} refLat Reference latitude in degrees.
26198      * @param {number} refLon Reference longitude in degrees.
26199      * @param {number} refAlt Reference altitude in meters.
26200      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
26201      */
26202     GeoCoords.prototype.enuToEcef = function (x, y, z, refLat, refLon, refAlt) {
26203         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
26204         refLat = refLat * Math.PI / 180.0;
26205         refLon = refLon * Math.PI / 180.0;
26206         var cosLat = Math.cos(refLat);
26207         var sinLat = Math.sin(refLat);
26208         var cosLon = Math.cos(refLon);
26209         var sinLon = Math.sin(refLon);
26210         var X = -sinLon * x - sinLat * cosLon * y + cosLat * cosLon * z + refEcef[0];
26211         var Y = cosLon * x - sinLat * sinLon * y + cosLat * sinLon * z + refEcef[1];
26212         var Z = cosLat * y + sinLat * z + refEcef[2];
26213         return [X, Y, Z];
26214     };
26215     /**
26216      * Convert coordinates from geodetic reference (WGS84) to Earth-Centered,
26217      * Earth-Fixed (ECEF) reference.
26218      *
26219      * @param {number} lat Latitude in degrees.
26220      * @param {number} lon Longitude in degrees.
26221      * @param {number} alt Altitude in meters.
26222      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
26223      */
26224     GeoCoords.prototype.geodeticToEcef = function (lat, lon, alt) {
26225         var a = this._wgs84a;
26226         var b = this._wgs84b;
26227         lat = lat * Math.PI / 180.0;
26228         lon = lon * Math.PI / 180.0;
26229         var cosLat = Math.cos(lat);
26230         var sinLat = Math.sin(lat);
26231         var cosLon = Math.cos(lon);
26232         var sinLon = Math.sin(lon);
26233         var a2 = a * a;
26234         var b2 = b * b;
26235         var L = 1.0 / Math.sqrt(a2 * cosLat * cosLat + b2 * sinLat * sinLat);
26236         var nhcl = (a2 * L + alt) * cosLat;
26237         var X = nhcl * cosLon;
26238         var Y = nhcl * sinLon;
26239         var Z = (b2 * L + alt) * sinLat;
26240         return [X, Y, Z];
26241     };
26242     /**
26243      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
26244      * to geodetic reference (WGS84).
26245      *
26246      * @param {number} X ECEF X-value.
26247      * @param {number} Y ECEF Y-value.
26248      * @param {number} Z ECEF Z-value.
26249      * @returns {Array<number>} The latitude and longitude in degrees
26250      *                          as well as altitude in meters.
26251      */
26252     GeoCoords.prototype.ecefToGeodetic = function (X, Y, Z) {
26253         var a = this._wgs84a;
26254         var b = this._wgs84b;
26255         var a2 = a * a;
26256         var b2 = b * b;
26257         var a2mb2 = a2 - b2;
26258         var ea = Math.sqrt(a2mb2 / a2);
26259         var eb = Math.sqrt(a2mb2 / b2);
26260         var p = Math.sqrt(X * X + Y * Y);
26261         var theta = Math.atan2(Z * a, p * b);
26262         var sinTheta = Math.sin(theta);
26263         var cosTheta = Math.cos(theta);
26264         var lon = Math.atan2(Y, X);
26265         var lat = Math.atan2(Z + eb * eb * b * sinTheta * sinTheta * sinTheta, p - ea * ea * a * cosTheta * cosTheta * cosTheta);
26266         var sinLat = Math.sin(lat);
26267         var cosLat = Math.cos(lat);
26268         var N = a / Math.sqrt(1 - ea * ea * sinLat * sinLat);
26269         var alt = p / cosLat - N;
26270         return [lat * 180.0 / Math.PI, lon * 180.0 / Math.PI, alt];
26271     };
26272     return GeoCoords;
26273 }());
26274 exports.GeoCoords = GeoCoords;
26275 Object.defineProperty(exports, "__esModule", { value: true });
26276 exports.default = GeoCoords;
26277
26278 },{}],278:[function(require,module,exports){
26279 /// <reference path="../../typings/index.d.ts" />
26280 "use strict";
26281 var THREE = require("three");
26282 /**
26283  * @class Spatial
26284  *
26285  * @classdesc Provides methods for scalar, vector and matrix calculations.
26286  */
26287 var Spatial = (function () {
26288     function Spatial() {
26289         this._epsilon = 1e-9;
26290     }
26291     /**
26292      * Converts degrees to radians.
26293      *
26294      * @param {number} deg Degrees.
26295      */
26296     Spatial.prototype.degToRad = function (deg) {
26297         return Math.PI * deg / 180;
26298     };
26299     /**
26300      * Converts radians to degrees.
26301      *
26302      * @param {number} rad Radians.
26303      */
26304     Spatial.prototype.radToDeg = function (rad) {
26305         return 180 * rad / Math.PI;
26306     };
26307     /**
26308      * Creates a rotation matrix from an angle-axis vector.
26309      *
26310      * @param {Array<number>} angleAxis Angle-axis representation of a rotation.
26311      */
26312     Spatial.prototype.rotationMatrix = function (angleAxis) {
26313         var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]);
26314         var angle = axis.length();
26315         axis.normalize();
26316         return new THREE.Matrix4().makeRotationAxis(axis, angle);
26317     };
26318     /**
26319      * Rotates a vector according to a angle-axis rotation vector.
26320      *
26321      * @param {Array<number>} vector Vector to rotate.
26322      * @param {Array<number>} angleAxis Angle-axis representation of a rotation.
26323      */
26324     Spatial.prototype.rotate = function (vector, angleAxis) {
26325         var v = new THREE.Vector3(vector[0], vector[1], vector[2]);
26326         var rotationMatrix = this.rotationMatrix(angleAxis);
26327         v.applyMatrix4(rotationMatrix);
26328         return v;
26329     };
26330     /**
26331      * Calculates the optical center from a rotation vector
26332      * on the angle-axis representation and a translation vector
26333      * according to C = -R^T t.
26334      *
26335      * @param {Array<number>} rotation Angle-axis representation of a rotation.
26336      * @param {Array<number>} translation Translation vector.
26337      */
26338     Spatial.prototype.opticalCenter = function (rotation, translation) {
26339         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
26340         var vector = [-translation[0], -translation[1], -translation[2]];
26341         return this.rotate(vector, angleAxis);
26342     };
26343     /**
26344      * Calculates the viewing direction from a rotation vector
26345      * on the angle-axis representation.
26346      *
26347      * @param {number[]} rotation Angle-axis representation of a rotation.
26348      */
26349     Spatial.prototype.viewingDirection = function (rotation) {
26350         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
26351         return this.rotate([0, 0, 1], angleAxis);
26352     };
26353     /**
26354      * Wrap a number on the interval [min, max].
26355      *
26356      * @param {number} value Value to wrap.
26357      * @param {number} min Lower endpoint of interval.
26358      * @param {number} max Upper endpoint of interval.
26359      *
26360      * @returs {number} The wrapped number.
26361      */
26362     Spatial.prototype.wrap = function (value, min, max) {
26363         if (max < min) {
26364             throw new Error("Invalid arguments: max must be larger than min.");
26365         }
26366         var interval = (max - min);
26367         while (value > max || value < min) {
26368             if (value > max) {
26369                 value = value - interval;
26370             }
26371             else if (value < min) {
26372                 value = value + interval;
26373             }
26374         }
26375         return value;
26376     };
26377     /**
26378      * Wrap an angle on the interval [-Pi, Pi].
26379      *
26380      * @param {number} angle Value to wrap.
26381      *
26382      * @returs {number} The wrapped angle.
26383      */
26384     Spatial.prototype.wrapAngle = function (angle) {
26385         return this.wrap(angle, -Math.PI, Math.PI);
26386     };
26387     /**
26388      * Limit the value to the interval [min, max] by changing the value to
26389      * the nearest available one when it is outside the interval.
26390      *
26391      * @param {number} value Value to clamp.
26392      * @param {number} min Minimum of the interval.
26393      * @param {number} max Maximum of the interval.
26394      *
26395      * @returns {number} The clamped value.
26396      */
26397     Spatial.prototype.clamp = function (value, min, max) {
26398         if (value < min) {
26399             return min;
26400         }
26401         if (value > max) {
26402             return max;
26403         }
26404         return value;
26405     };
26406     /**
26407      * Calculates the counter-clockwise angle from the first
26408      * vector (x1, y1)^T to the second (x2, y2)^T.
26409      *
26410      * @param {number} x1 X-value of first vector.
26411      * @param {number} y1 Y-value of first vector.
26412      * @param {number} x2 X-value of second vector.
26413      * @param {number} y2 Y-value of second vector.
26414      */
26415     Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) {
26416         var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1);
26417         return this.wrapAngle(angle);
26418     };
26419     /**
26420      * Calculates the minimum (absolute) angle change for rotation
26421      * from one angle to another on the [-Pi, Pi] interval.
26422      *
26423      * @param {number} angle1 The origin angle.
26424      * @param {number} angle2 The destination angle.
26425      */
26426     Spatial.prototype.angleDifference = function (angle1, angle2) {
26427         var angle = angle2 - angle1;
26428         return this.wrapAngle(angle);
26429     };
26430     /**
26431      * Calculates the relative rotation angle between two
26432      * angle-axis vectors.
26433      *
26434      * @param {number} rotation1 First angle-axis vector.
26435      * @param {number} rotation2 Second angle-axis vector.
26436      */
26437     Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) {
26438         var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]);
26439         var R2 = this.rotationMatrix(rotation2);
26440         var R = R1T.multiply(R2);
26441         var elements = R.elements;
26442         // from Tr(R) = 1 + 2*cos(theta)
26443         var theta = Math.acos((elements[0] + elements[5] + elements[10] - 1) / 2);
26444         return theta;
26445     };
26446     /**
26447      * Calculates the angle from a vector to a plane.
26448      *
26449      * @param {Array<number>} vector The vector.
26450      * @param {Array<number>} planeNormal Normal of the plane.
26451      */
26452     Spatial.prototype.angleToPlane = function (vector, planeNormal) {
26453         var v = new THREE.Vector3().fromArray(vector);
26454         var norm = v.length();
26455         if (norm < this._epsilon) {
26456             return 0;
26457         }
26458         var projection = v.dot(new THREE.Vector3().fromArray(planeNormal));
26459         return Math.asin(projection / norm);
26460     };
26461     /**
26462      * Calculates the distance between two coordinates
26463      * (latitude longitude pairs) in meters according to
26464      * the haversine formula.
26465      *
26466      * @param {number} lat1 The latitude of the first coordinate.
26467      * @param {number} lon1 The longitude of the first coordinate.
26468      * @param {number} lat2 The latitude of the second coordinate.
26469      * @param {number} lon2 The longitude of the second coordinate.
26470      */
26471     Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) {
26472         var r = 6371000;
26473         var dLat = this.degToRad(lat2 - lat1);
26474         var dLon = this.degToRad(lon2 - lon1);
26475         var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
26476             Math.cos(lat1) * Math.cos(lat2) *
26477                 Math.sin(dLon / 2) * Math.sin(dLon / 2);
26478         var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav));
26479         return d;
26480     };
26481     return Spatial;
26482 }());
26483 exports.Spatial = Spatial;
26484 Object.defineProperty(exports, "__esModule", { value: true });
26485 exports.default = Spatial;
26486
26487 },{"three":160}],279:[function(require,module,exports){
26488 /// <reference path="../../typings/index.d.ts" />
26489 "use strict";
26490 var THREE = require("three");
26491 /**
26492  * @class Transform
26493  *
26494  * @classdesc Class used for calculating coordinate transformations
26495  * and projections.
26496  */
26497 var Transform = (function () {
26498     /**
26499      * Create a new transform instance.
26500      * @param {Node} apiNavImIm - Node properties.
26501      * @param {HTMLImageElement} image - Node image.
26502      * @param {Array<number>} translation - Node translation vector in three dimensions.
26503      */
26504     function Transform(node, image, translation) {
26505         this._orientation = this._getValue(node.orientation, 1);
26506         var imageWidth = image != null ? image.width : 4;
26507         var imageHeight = image != null ? image.height : 3;
26508         var keepOrientation = this._orientation < 5;
26509         this._width = this._getValue(node.width, keepOrientation ? imageWidth : imageHeight);
26510         this._height = this._getValue(node.height, keepOrientation ? imageHeight : imageWidth);
26511         this._basicAspect = keepOrientation ?
26512             this._width / this._height :
26513             this._height / this._width;
26514         this._focal = this._getValue(node.focal, 1);
26515         this._scale = this._getValue(node.scale, 0);
26516         this._gpano = node.gpano != null ? node.gpano : null;
26517         this._rt = this._getRt(node.rotation, translation);
26518         this._srt = this._getSrt(this._rt, this._scale);
26519     }
26520     Object.defineProperty(Transform.prototype, "basicAspect", {
26521         /**
26522          * Get basic aspect.
26523          * @returns {number} The orientation adjusted aspect ratio.
26524          */
26525         get: function () {
26526             return this._basicAspect;
26527         },
26528         enumerable: true,
26529         configurable: true
26530     });
26531     Object.defineProperty(Transform.prototype, "focal", {
26532         /**
26533          * Get focal.
26534          * @returns {number} The node focal length.
26535          */
26536         get: function () {
26537             return this._focal;
26538         },
26539         enumerable: true,
26540         configurable: true
26541     });
26542     Object.defineProperty(Transform.prototype, "gpano", {
26543         /**
26544          * Get gpano.
26545          * @returns {number} The node gpano information.
26546          */
26547         get: function () {
26548             return this._gpano;
26549         },
26550         enumerable: true,
26551         configurable: true
26552     });
26553     Object.defineProperty(Transform.prototype, "height", {
26554         /**
26555          * Get height.
26556          * @returns {number} The orientation adjusted image height.
26557          */
26558         get: function () {
26559             return this._height;
26560         },
26561         enumerable: true,
26562         configurable: true
26563     });
26564     Object.defineProperty(Transform.prototype, "orientation", {
26565         /**
26566          * Get orientation.
26567          * @returns {number} The image orientation.
26568          */
26569         get: function () {
26570             return this._orientation;
26571         },
26572         enumerable: true,
26573         configurable: true
26574     });
26575     Object.defineProperty(Transform.prototype, "rt", {
26576         /**
26577          * Get rt.
26578          * @returns {THREE.Matrix4} The extrinsic camera matrix.
26579          */
26580         get: function () {
26581             return this._rt;
26582         },
26583         enumerable: true,
26584         configurable: true
26585     });
26586     Object.defineProperty(Transform.prototype, "srt", {
26587         /**
26588          * Get srt.
26589          * @returns {THREE.Matrix4} The scaled extrinsic camera matrix.
26590          */
26591         get: function () {
26592             return this._srt;
26593         },
26594         enumerable: true,
26595         configurable: true
26596     });
26597     Object.defineProperty(Transform.prototype, "scale", {
26598         /**
26599          * Get scale.
26600          * @returns {number} The node atomic reconstruction scale.
26601          */
26602         get: function () {
26603             return this._scale;
26604         },
26605         enumerable: true,
26606         configurable: true
26607     });
26608     Object.defineProperty(Transform.prototype, "width", {
26609         /**
26610          * Get width.
26611          * @returns {number} The orientation adjusted image width.
26612          */
26613         get: function () {
26614             return this._width;
26615         },
26616         enumerable: true,
26617         configurable: true
26618     });
26619     /**
26620      * Calculate the up vector for the node transform.
26621      *
26622      * @returns {THREE.Vector3} Normalized and orientation adjusted up vector.
26623      */
26624     Transform.prototype.upVector = function () {
26625         var rte = this._rt.elements;
26626         switch (this._orientation) {
26627             case 1:
26628                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
26629             case 3:
26630                 return new THREE.Vector3(rte[1], rte[5], rte[9]);
26631             case 6:
26632                 return new THREE.Vector3(-rte[0], -rte[4], -rte[8]);
26633             case 8:
26634                 return new THREE.Vector3(rte[0], rte[4], rte[8]);
26635             default:
26636                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
26637         }
26638     };
26639     /**
26640      * Calculate projector matrix for projecting 3D points to texture map
26641      * coordinates (u and v).
26642      *
26643      * @returns {THREE.Matrix4} Projection matrix for 3D point to texture
26644      * map coordinate calculations.
26645      */
26646     Transform.prototype.projectorMatrix = function () {
26647         var projector = this._normalizedToTextureMatrix();
26648         var f = this._focal;
26649         var projection = new THREE.Matrix4().set(f, 0, 0, 0, 0, f, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
26650         projector.multiply(projection);
26651         projector.multiply(this._rt);
26652         return projector;
26653     };
26654     /**
26655      * Project 3D world coordinates to basic coordinates.
26656      *
26657      * @param {Array<number>} point3d - 3D world coordinates.
26658      * @return {Array<number>} 2D basic coordinates.
26659      */
26660     Transform.prototype.projectBasic = function (point3d) {
26661         var sfm = this.projectSfM(point3d);
26662         return this._sfmToBasic(sfm);
26663     };
26664     /**
26665      * Unproject basic coordinates to 3D world coordinates.
26666      *
26667      * @param {Array<number>} basic - 2D basic coordinates.
26668      * @param {Array<number>} distance - Depth to unproject from camera center.
26669      * @returns {Array<number>} Unprojected 3D world coordinates.
26670      */
26671     Transform.prototype.unprojectBasic = function (basic, distance) {
26672         var sfm = this._basicToSfm(basic);
26673         return this.unprojectSfM(sfm, distance);
26674     };
26675     /**
26676      * Project 3D world coordinates to SfM coordinates.
26677      *
26678      * @param {Array<number>} point3d - 3D world coordinates.
26679      * @return {Array<number>} 2D SfM coordinates.
26680      */
26681     Transform.prototype.projectSfM = function (point3d) {
26682         var v = new THREE.Vector4(point3d[0], point3d[1], point3d[2], 1);
26683         v.applyMatrix4(this._rt);
26684         return this._bearingToSfm([v.x, v.y, v.z]);
26685     };
26686     /**
26687      * Unproject SfM coordinates to a 3D world coordinates.
26688      *
26689      * @param {Array<number>} sfm - 2D SfM coordinates.
26690      * @param {Array<number>} distance - Depth to unproject from camera center.
26691      * @returns {Array<number>} Unprojected 3D world coordinates.
26692      */
26693     Transform.prototype.unprojectSfM = function (sfm, distance) {
26694         var bearing = this._sfmToBearing(sfm);
26695         var v = new THREE.Vector4(distance * bearing[0], distance * bearing[1], distance * bearing[2], 1);
26696         v.applyMatrix4(new THREE.Matrix4().getInverse(this._rt));
26697         return [v.x / v.w, v.y / v.w, v.z / v.w];
26698     };
26699     /**
26700      * Transform SfM coordinates to bearing vector (3D cartesian
26701      * coordinates on the unit sphere).
26702      *
26703      * @param {Array<number>} sfm - 2D SfM coordinates.
26704      * @returns {Array<number>} Bearing vector (3D cartesian coordinates
26705      * on the unit sphere).
26706      */
26707     Transform.prototype._sfmToBearing = function (sfm) {
26708         if (this._fullPano()) {
26709             var lon = sfm[0] * 2 * Math.PI;
26710             var lat = -sfm[1] * 2 * Math.PI;
26711             var x = Math.cos(lat) * Math.sin(lon);
26712             var y = -Math.sin(lat);
26713             var z = Math.cos(lat) * Math.cos(lon);
26714             return [x, y, z];
26715         }
26716         else if (this._gpano) {
26717             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
26718             var fullPanoPixel = [
26719                 sfm[0] * size + this.gpano.CroppedAreaImageWidthPixels / 2 + this.gpano.CroppedAreaLeftPixels,
26720                 sfm[1] * size + this.gpano.CroppedAreaImageHeightPixels / 2 + this.gpano.CroppedAreaTopPixels,
26721             ];
26722             var lon = 2 * Math.PI * (fullPanoPixel[0] / this.gpano.FullPanoWidthPixels - 0.5);
26723             var lat = -Math.PI * (fullPanoPixel[1] / this.gpano.FullPanoHeightPixels - 0.5);
26724             var x = Math.cos(lat) * Math.sin(lon);
26725             var y = -Math.sin(lat);
26726             var z = Math.cos(lat) * Math.cos(lon);
26727             return [x, y, z];
26728         }
26729         else {
26730             var v = new THREE.Vector3(sfm[0], sfm[1], this._focal);
26731             v.normalize();
26732             return [v.x, v.y, v.z];
26733         }
26734     };
26735     /**
26736      * Transform bearing vector (3D cartesian coordiantes on the unit sphere) to
26737      * SfM coordinates.
26738      *
26739      * @param {Array<number>} bearing - Bearing vector (3D cartesian coordinates on the
26740      * unit sphere).
26741      * @returns {Array<number>} 2D SfM coordinates.
26742      */
26743     Transform.prototype._bearingToSfm = function (bearing) {
26744         if (this._fullPano()) {
26745             var x = bearing[0];
26746             var y = bearing[1];
26747             var z = bearing[2];
26748             var lon = Math.atan2(x, z);
26749             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
26750             return [lon / (2 * Math.PI), -lat / (2 * Math.PI)];
26751         }
26752         else if (this._gpano) {
26753             var x = bearing[0];
26754             var y = bearing[1];
26755             var z = bearing[2];
26756             var lon = Math.atan2(x, z);
26757             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
26758             var fullPanoPixel = [
26759                 (lon / (2 * Math.PI) + 0.5) * this.gpano.FullPanoWidthPixels,
26760                 (-lat / Math.PI + 0.5) * this.gpano.FullPanoHeightPixels,
26761             ];
26762             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
26763             return [
26764                 (fullPanoPixel[0] - this.gpano.CroppedAreaLeftPixels - this.gpano.CroppedAreaImageWidthPixels / 2) / size,
26765                 (fullPanoPixel[1] - this.gpano.CroppedAreaTopPixels - this.gpano.CroppedAreaImageHeightPixels / 2) / size,
26766             ];
26767         }
26768         else {
26769             return [
26770                 bearing[0] * this._focal / bearing[2],
26771                 bearing[1] * this._focal / bearing[2],
26772             ];
26773         }
26774     };
26775     /**
26776      * Convert basic coordinates to SfM coordinates.
26777      *
26778      * @param {Array<number>} basic - 2D basic coordinates.
26779      * @returns {Array<number>} 2D SfM coordinates.
26780      */
26781     Transform.prototype._basicToSfm = function (basic) {
26782         var rotatedX;
26783         var rotatedY;
26784         switch (this._orientation) {
26785             case 1:
26786                 rotatedX = basic[0];
26787                 rotatedY = basic[1];
26788                 break;
26789             case 3:
26790                 rotatedX = 1 - basic[0];
26791                 rotatedY = 1 - basic[1];
26792                 break;
26793             case 6:
26794                 rotatedX = basic[1];
26795                 rotatedY = 1 - basic[0];
26796                 break;
26797             case 8:
26798                 rotatedX = 1 - basic[1];
26799                 rotatedY = basic[0];
26800                 break;
26801             default:
26802                 rotatedX = basic[0];
26803                 rotatedY = basic[1];
26804                 break;
26805         }
26806         var w = this._width;
26807         var h = this._height;
26808         var s = Math.max(w, h);
26809         var sfmX = rotatedX * w / s - w / s / 2;
26810         var sfmY = rotatedY * h / s - h / s / 2;
26811         return [sfmX, sfmY];
26812     };
26813     /**
26814      * Convert SfM coordinates to basic coordinates.
26815      *
26816      * @param {Array<number>} sfm - 2D SfM coordinates.
26817      * @returns {Array<number>} 2D basic coordinates.
26818      */
26819     Transform.prototype._sfmToBasic = function (sfm) {
26820         var w = this._width;
26821         var h = this._height;
26822         var s = Math.max(w, h);
26823         var rotatedX = (sfm[0] + w / s / 2) / w * s;
26824         var rotatedY = (sfm[1] + h / s / 2) / h * s;
26825         var basicX;
26826         var basicY;
26827         switch (this._orientation) {
26828             case 1:
26829                 basicX = rotatedX;
26830                 basicY = rotatedY;
26831                 break;
26832             case 3:
26833                 basicX = 1 - rotatedX;
26834                 basicY = 1 - rotatedY;
26835                 break;
26836             case 6:
26837                 basicX = 1 - rotatedY;
26838                 basicY = rotatedX;
26839                 break;
26840             case 8:
26841                 basicX = rotatedY;
26842                 basicY = 1 - rotatedX;
26843                 break;
26844             default:
26845                 basicX = rotatedX;
26846                 basicY = rotatedY;
26847                 break;
26848         }
26849         return [basicX, basicY];
26850     };
26851     /**
26852      * Determines if the gpano information indicates a full panorama.
26853      *
26854      * @returns {boolean} Value determining if the gpano information indicates
26855      * a full panorama.
26856      */
26857     Transform.prototype._fullPano = function () {
26858         return this.gpano != null &&
26859             this.gpano.CroppedAreaLeftPixels === 0 &&
26860             this.gpano.CroppedAreaTopPixels === 0 &&
26861             this.gpano.CroppedAreaImageWidthPixels === this.gpano.FullPanoWidthPixels &&
26862             this.gpano.CroppedAreaImageHeightPixels === this.gpano.FullPanoHeightPixels;
26863     };
26864     /**
26865      * Checks a value and returns it if it exists and is larger than 0.
26866      * Fallbacks if it is null.
26867      *
26868      * @param {number} value - Value to check.
26869      * @param {number} fallback - Value to fall back to.
26870      * @returns {number} The value or its fallback value if it is not defined or negative.
26871      */
26872     Transform.prototype._getValue = function (value, fallback) {
26873         return value != null && value > 0 ? value : fallback;
26874     };
26875     /**
26876      * Creates the extrinsic camera matrix [ R | t ].
26877      *
26878      * @param {Array<number>} rotation - Rotation vector in angle axis representation.
26879      * @param {Array<number>} translation - Translation vector.
26880      * @returns {THREE.Matrix4} Extrisic camera matrix.
26881      */
26882     Transform.prototype._getRt = function (rotation, translation) {
26883         var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]);
26884         var angle = axis.length();
26885         axis.normalize();
26886         var rt = new THREE.Matrix4();
26887         rt.makeRotationAxis(axis, angle);
26888         rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2]));
26889         return rt;
26890     };
26891     /**
26892      * Calculates the scaled extrinsic camera matrix scale * [ R | t ].
26893      *
26894      * @param {THREE.Matrix4} rt - Extrisic camera matrix.
26895      * @param {number} scale - Scale factor.
26896      * @returns {THREE.Matrix4} Scaled extrisic camera matrix.
26897      */
26898     Transform.prototype._getSrt = function (rt, scale) {
26899         var srt = rt.clone();
26900         var elements = srt.elements;
26901         elements[12] = scale * elements[12];
26902         elements[13] = scale * elements[13];
26903         elements[14] = scale * elements[14];
26904         srt.scale(new THREE.Vector3(scale, scale, scale));
26905         return srt;
26906     };
26907     /**
26908      * Calculate a transformation matrix from normalized coordinates for
26909      * texture map coordinates.
26910      *
26911      * @returns {THREE.Matrix4} Normalized coordinates to texture map
26912      * coordinates transformation matrix.
26913      */
26914     Transform.prototype._normalizedToTextureMatrix = function () {
26915         var size = Math.max(this._width, this._height);
26916         var w = size / this._width;
26917         var h = size / this._height;
26918         switch (this._orientation) {
26919             case 1:
26920                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
26921             case 3:
26922                 return new THREE.Matrix4().set(-w, 0, 0, 0.5, 0, h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
26923             case 6:
26924                 return new THREE.Matrix4().set(0, -h, 0, 0.5, -w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
26925             case 8:
26926                 return new THREE.Matrix4().set(0, h, 0, 0.5, w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
26927             default:
26928                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
26929         }
26930     };
26931     return Transform;
26932 }());
26933 exports.Transform = Transform;
26934
26935 },{"three":160}],280:[function(require,module,exports){
26936 "use strict";
26937 /**
26938  * @class Filter
26939  *
26940  * @classdesc Represents a class for creating node filters. Implementation and
26941  * definitions based on https://github.com/mapbox/feature-filter.
26942  */
26943 var FilterCreator = (function () {
26944     function FilterCreator() {
26945     }
26946     /**
26947      * Create a filter from a filter expression.
26948      *
26949      * @description The following filters are supported:
26950      *
26951      * Comparison
26952      * `==`
26953      * `!=`
26954      * `<`
26955      * `<=`
26956      * `>`
26957      * `>=`
26958      *
26959      * Set membership
26960      * `in`
26961      * `!in`
26962      *
26963      * Combining
26964      * `all`
26965      *
26966      * @param {FilterExpression} filter - Comparison, set membership or combinding filter
26967      * expression.
26968      * @returns {FilterFunction} Function taking a node and returning a boolean that
26969      * indicates whether the node passed the test or not.
26970      */
26971     FilterCreator.prototype.createFilter = function (filter) {
26972         return new Function("node", "return " + this._compile(filter) + ";");
26973     };
26974     FilterCreator.prototype._compile = function (filter) {
26975         if (filter == null || filter.length <= 1) {
26976             return "true";
26977         }
26978         var operator = filter[0];
26979         var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) :
26980             operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) :
26981                 operator === ">" ||
26982                     operator === ">=" ||
26983                     operator === "<" ||
26984                     operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) :
26985                     operator === "in" ?
26986                         this._compileInOp(filter[1], filter.slice(2)) :
26987                         operator === "!in" ?
26988                             this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) :
26989                             operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") :
26990                                 "true";
26991         return "(" + operation + ")";
26992     };
26993     FilterCreator.prototype._compare = function (a, b) {
26994         return a < b ? -1 : a > b ? 1 : 0;
26995     };
26996     FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) {
26997         var left = this._compilePropertyReference(property);
26998         var right = JSON.stringify(value);
26999         return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right;
27000     };
27001     FilterCreator.prototype._compileInOp = function (property, values) {
27002         var compare = this._compare;
27003         var left = JSON.stringify(values.sort(compare));
27004         var right = this._compilePropertyReference(property);
27005         return left + ".indexOf(" + right + ")!==-1";
27006     };
27007     FilterCreator.prototype._compileLogicalOp = function (filters, operator) {
27008         var compile = this._compile.bind(this);
27009         return filters.map(compile).join(operator);
27010     };
27011     FilterCreator.prototype._compileNegation = function (expression) {
27012         return "!(" + expression + ")";
27013     };
27014     FilterCreator.prototype._compilePropertyReference = function (property) {
27015         return "node[" + JSON.stringify(property) + "]";
27016     };
27017     return FilterCreator;
27018 }());
27019 exports.FilterCreator = FilterCreator;
27020 Object.defineProperty(exports, "__esModule", { value: true });
27021 exports.default = FilterCreator;
27022
27023 },{}],281:[function(require,module,exports){
27024 /// <reference path="../../typings/index.d.ts" />
27025 "use strict";
27026 var Subject_1 = require("rxjs/Subject");
27027 require("rxjs/add/observable/from");
27028 require("rxjs/add/operator/catch");
27029 require("rxjs/add/operator/do");
27030 require("rxjs/add/operator/finally");
27031 require("rxjs/add/operator/map");
27032 require("rxjs/add/operator/publish");
27033 var rbush = require("rbush");
27034 var Edge_1 = require("../Edge");
27035 var Error_1 = require("../Error");
27036 var Graph_1 = require("../Graph");
27037 /**
27038  * @class Graph
27039  *
27040  * @classdesc Represents a graph of nodes with edges.
27041  */
27042 var Graph = (function () {
27043     /**
27044      * Create a new graph instance.
27045      *
27046      * @param {APIv3} [apiV3] - API instance for retrieving data.
27047      * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival.
27048      * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations.
27049      * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations.
27050      */
27051     function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator) {
27052         this._apiV3 = apiV3;
27053         this._cachedNodes = {};
27054         this._cachedNodeTiles = {};
27055         this._cachedSpatialEdges = {};
27056         this._cachedTiles = {};
27057         this._cachingFill$ = {};
27058         this._cachingFull$ = {};
27059         this._cachingSequences$ = {};
27060         this._cachingSpatialArea$ = {};
27061         this._cachingTiles$ = {};
27062         this._changed$ = new Subject_1.Subject();
27063         this._defaultAlt = 2;
27064         this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator();
27065         this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator();
27066         this._filter = this._filterCreator.createFilter(undefined);
27067         this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator();
27068         this._nodes = {};
27069         this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lon", ".lat", ".lon", ".lat"]);
27070         this._preStored = {};
27071         this._requiredNodeTiles = {};
27072         this._requiredSpatialArea = {};
27073         this._sequences = {};
27074         this._tilePrecision = 7;
27075         this._tileThreshold = 20;
27076     }
27077     Object.defineProperty(Graph.prototype, "changed$", {
27078         /**
27079          * Get changed$.
27080          *
27081          * @returns {Observable<Graph>} Observable emitting
27082          * the graph every time it has changed.
27083          */
27084         get: function () {
27085             return this._changed$;
27086         },
27087         enumerable: true,
27088         configurable: true
27089     });
27090     /**
27091      * Retrieve and cache node fill properties.
27092      *
27093      * @param {string} key - Key of node to fill.
27094      * @returns {Observable<Graph>} Observable emitting the graph
27095      * when the node has been updated.
27096      * @throws {GraphMapillaryError} When the operation is not valid on the
27097      * current graph.
27098      */
27099     Graph.prototype.cacheFill$ = function (key) {
27100         var _this = this;
27101         if (key in this._cachingFull$) {
27102             throw new Error_1.GraphMapillaryError("Cannot fill node while caching full (" + key + ").");
27103         }
27104         if (!this.hasNode(key)) {
27105             throw new Error_1.GraphMapillaryError("Cannot fill node that does not exist in graph (" + key + ").");
27106         }
27107         if (key in this._cachingFill$) {
27108             return this._cachingFill$[key];
27109         }
27110         var node = this.getNode(key);
27111         if (node.full) {
27112             throw new Error_1.GraphMapillaryError("Cannot fill node that is already full (" + key + ").");
27113         }
27114         this._cachingFill$[key] = this._apiV3.imageByKeyFill$([key])
27115             .do(function (imageByKeyFill) {
27116             if (!node.full) {
27117                 _this._makeFull(node, imageByKeyFill[key]);
27118             }
27119             delete _this._cachingFill$[key];
27120         })
27121             .map(function (imageByKeyFill) {
27122             return _this;
27123         })
27124             .finally(function () {
27125             if (key in _this._cachingFill$) {
27126                 delete _this._cachingFill$[key];
27127             }
27128             _this._changed$.next(_this);
27129         })
27130             .publish()
27131             .refCount();
27132         return this._cachingFill$[key];
27133     };
27134     /**
27135      * Retrieve and cache full node properties.
27136      *
27137      * @param {string} key - Key of node to fill.
27138      * @returns {Observable<Graph>} Observable emitting the graph
27139      * when the node has been updated.
27140      * @throws {GraphMapillaryError} When the operation is not valid on the
27141      * current graph.
27142      */
27143     Graph.prototype.cacheFull$ = function (key) {
27144         var _this = this;
27145         if (key in this._cachingFull$) {
27146             return this._cachingFull$[key];
27147         }
27148         if (this.hasNode(key)) {
27149             throw new Error_1.GraphMapillaryError("Cannot cache full node that already exist in graph (" + key + ").");
27150         }
27151         this._cachingFull$[key] = this._apiV3.imageByKeyFull$([key])
27152             .do(function (imageByKeyFull) {
27153             var fn = imageByKeyFull[key];
27154             if (_this.hasNode(key)) {
27155                 var node = _this.getNode(key);
27156                 if (!node.full) {
27157                     _this._makeFull(node, fn);
27158                 }
27159             }
27160             else {
27161                 if (fn.sequence == null || fn.sequence.key == null) {
27162                     throw new Error_1.GraphMapillaryError("Node has no sequence (" + key + ").");
27163                 }
27164                 var node = new Graph_1.Node(fn);
27165                 _this._makeFull(node, fn);
27166                 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
27167                 _this._preStore(h, node);
27168                 _this._setNode(node);
27169                 delete _this._cachingFull$[key];
27170             }
27171         })
27172             .map(function (imageByKeyFull) {
27173             return _this;
27174         })
27175             .finally(function () {
27176             if (key in _this._cachingFull$) {
27177                 delete _this._cachingFull$[key];
27178             }
27179             _this._changed$.next(_this);
27180         })
27181             .publish()
27182             .refCount();
27183         return this._cachingFull$[key];
27184     };
27185     /**
27186      * Retrieve and cache a node sequence.
27187      *
27188      * @param {string} key - Key of node for which to retrieve sequence.
27189      * @returns {Observable<Graph>} Observable emitting the graph
27190      * when the sequence has been retrieved.
27191      * @throws {GraphMapillaryError} When the operation is not valid on the
27192      * current graph.
27193      */
27194     Graph.prototype.cacheNodeSequence$ = function (key) {
27195         if (!this.hasNode(key)) {
27196             throw new Error_1.GraphMapillaryError("Cannot cache sequence edges of node that does not exist in graph (" + key + ").");
27197         }
27198         var node = this.getNode(key);
27199         if (node.sequenceKey in this._sequences) {
27200             throw new Error_1.GraphMapillaryError("Sequence already cached (" + key + "), (" + node.sequenceKey + ").");
27201         }
27202         return this._cacheSequence$(node.sequenceKey);
27203     };
27204     /**
27205      * Retrieve and cache a sequence.
27206      *
27207      * @param {string} sequenceKey - Key of sequence to cache.
27208      * @returns {Observable<Graph>} Observable emitting the graph
27209      * when the sequence has been retrieved.
27210      * @throws {GraphMapillaryError} When the operation is not valid on the
27211      * current graph.
27212      */
27213     Graph.prototype.cacheSequence$ = function (sequenceKey) {
27214         if (sequenceKey in this._sequences) {
27215             throw new Error_1.GraphMapillaryError("Sequence already cached (" + sequenceKey + ")");
27216         }
27217         return this._cacheSequence$(sequenceKey);
27218     };
27219     /**
27220      * Cache sequence edges for a node.
27221      *
27222      * @param {string} key - Key of node.
27223      * @throws {GraphMapillaryError} When the operation is not valid on the
27224      * current graph.
27225      */
27226     Graph.prototype.cacheSequenceEdges = function (key) {
27227         var node = this.getNode(key);
27228         if (!(node.sequenceKey in this._sequences)) {
27229             throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")");
27230         }
27231         var sequence = this._sequences[node.sequenceKey];
27232         var edges = this._edgeCalculator.computeSequenceEdges(node, sequence);
27233         node.cacheSequenceEdges(edges);
27234     };
27235     /**
27236      * Retrieve and cache full nodes for a node spatial area.
27237      *
27238      * @param {string} key - Key of node for which to retrieve sequence.
27239      * @returns {Observable<Graph>} Observable emitting the graph
27240      * when the nodes in the spatial area has been made full.
27241      * @throws {GraphMapillaryError} When the operation is not valid on the
27242      * current graph.
27243      */
27244     Graph.prototype.cacheSpatialArea$ = function (key) {
27245         var _this = this;
27246         if (!this.hasNode(key)) {
27247             throw new Error_1.GraphMapillaryError("Cannot cache spatial area of node that does not exist in graph (" + key + ").");
27248         }
27249         if (key in this._cachedSpatialEdges) {
27250             throw new Error_1.GraphMapillaryError("Node already spatially cached (" + key + ").");
27251         }
27252         if (!(key in this._requiredSpatialArea)) {
27253             throw new Error_1.GraphMapillaryError("Spatial area not determined (" + key + ").");
27254         }
27255         var spatialArea = this._requiredSpatialArea[key];
27256         if (Object.keys(spatialArea.cacheNodes).length === 0) {
27257             throw new Error_1.GraphMapillaryError("Spatial nodes already cached (" + key + ").");
27258         }
27259         if (key in this._cachingSpatialArea$) {
27260             return this._cachingSpatialArea$[key];
27261         }
27262         var batches = [];
27263         while (spatialArea.cacheKeys.length > 0) {
27264             batches.push(spatialArea.cacheKeys.splice(0, 200));
27265         }
27266         var batchesToCache = batches.length;
27267         var spatialNodes$ = [];
27268         var _loop_1 = function(batch) {
27269             var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch)
27270                 .do(function (imageByKeyFill) {
27271                 for (var fillKey in imageByKeyFill) {
27272                     if (!imageByKeyFill.hasOwnProperty(fillKey)) {
27273                         continue;
27274                     }
27275                     var spatialNode = spatialArea.cacheNodes[fillKey];
27276                     if (spatialNode.full) {
27277                         delete spatialArea.cacheNodes[fillKey];
27278                         continue;
27279                     }
27280                     var fillNode = imageByKeyFill[fillKey];
27281                     _this._makeFull(spatialNode, fillNode);
27282                     delete spatialArea.cacheNodes[fillKey];
27283                 }
27284                 if (--batchesToCache === 0) {
27285                     delete _this._cachingSpatialArea$[key];
27286                 }
27287             })
27288                 .map(function (imageByKeyFill) {
27289                 return _this;
27290             })
27291                 .catch(function (error) {
27292                 for (var _i = 0, batch_1 = batch; _i < batch_1.length; _i++) {
27293                     var batchKey = batch_1[_i];
27294                     if (batchKey in spatialArea.all) {
27295                         delete spatialArea.all[batchKey];
27296                     }
27297                     if (batchKey in spatialArea.cacheNodes) {
27298                         delete spatialArea.cacheNodes[batchKey];
27299                     }
27300                 }
27301                 if (--batchesToCache === 0) {
27302                     delete _this._cachingSpatialArea$[key];
27303                 }
27304                 throw error;
27305             })
27306                 .finally(function () {
27307                 if (Object.keys(spatialArea.cacheNodes).length === 0) {
27308                     _this._changed$.next(_this);
27309                 }
27310             })
27311                 .publish()
27312                 .refCount();
27313             spatialNodes$.push(spatialNodeBatch$);
27314         };
27315         var this_1 = this;
27316         for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {
27317             var batch = batches_1[_i];
27318             _loop_1(batch);
27319         }
27320         this._cachingSpatialArea$[key] = spatialNodes$;
27321         return spatialNodes$;
27322     };
27323     /**
27324      * Cache spatial edges for a node.
27325      *
27326      * @param {string} key - Key of node.
27327      * @throws {GraphMapillaryError} When the operation is not valid on the
27328      * current graph.
27329      */
27330     Graph.prototype.cacheSpatialEdges = function (key) {
27331         if (key in this._cachedSpatialEdges) {
27332             throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ").");
27333         }
27334         var node = this.getNode(key);
27335         var sequence = this._sequences[node.sequenceKey];
27336         var fallbackKeys = [];
27337         var prevKey = sequence.findPrevKey(node.key);
27338         if (prevKey != null) {
27339             fallbackKeys.push(prevKey);
27340         }
27341         var nextKey = sequence.findNextKey(node.key);
27342         if (nextKey != null) {
27343             fallbackKeys.push(nextKey);
27344         }
27345         var allSpatialNodes = this._requiredSpatialArea[key].all;
27346         var potentialNodes = [];
27347         var filter = this._filter;
27348         for (var spatialNodeKey in allSpatialNodes) {
27349             if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) {
27350                 continue;
27351             }
27352             var spatialNode = allSpatialNodes[spatialNodeKey];
27353             if (filter(spatialNode)) {
27354                 potentialNodes.push(allSpatialNodes[spatialNodeKey]);
27355             }
27356         }
27357         var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys);
27358         var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey);
27359         edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges));
27360         edges = edges.concat(this._edgeCalculator.computePanoEdges(node, potentialEdges));
27361         edges = edges.concat(this._edgeCalculator.computePerspectiveToPanoEdges(node, potentialEdges));
27362         edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges));
27363         node.cacheSpatialEdges(edges);
27364         this._cachedSpatialEdges[key] = node;
27365         delete this._requiredSpatialArea[key];
27366     };
27367     /**
27368      * Retrieve and cache geohash tiles for a node.
27369      *
27370      * @param {string} key - Key of node for which to retrieve tiles.
27371      * @returns {Observable<Graph>} Observable emitting the graph
27372      * when the tiles required for the node has been cached.
27373      * @throws {GraphMapillaryError} When the operation is not valid on the
27374      * current graph.
27375      */
27376     Graph.prototype.cacheTiles$ = function (key) {
27377         var _this = this;
27378         if (key in this._cachedNodeTiles) {
27379             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
27380         }
27381         if (!(key in this._requiredNodeTiles)) {
27382             throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ").");
27383         }
27384         var nodeTiles = this._requiredNodeTiles[key];
27385         if (nodeTiles.cache.length === 0 &&
27386             nodeTiles.caching.length === 0) {
27387             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
27388         }
27389         if (!this.hasNode(key)) {
27390             throw new Error_1.GraphMapillaryError("Cannot cache tiles of node that does not exist in graph (" + key + ").");
27391         }
27392         var hs = nodeTiles.cache.slice();
27393         nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs);
27394         nodeTiles.cache = [];
27395         var cacheTiles$ = [];
27396         var _loop_2 = function(h) {
27397             var cacheTile$ = null;
27398             if (h in this_2._cachingTiles$) {
27399                 cacheTile$ = this_2._cachingTiles$[h];
27400             }
27401             else {
27402                 cacheTile$ = this_2._apiV3.imagesByH$([h])
27403                     .do(function (imagesByH) {
27404                     var coreNodes = imagesByH[h];
27405                     if (h in _this._cachedTiles) {
27406                         return;
27407                     }
27408                     _this._cachedTiles[h] = [];
27409                     var hCache = _this._cachedTiles[h];
27410                     var preStored = _this._removeFromPreStore(h);
27411                     for (var index in coreNodes) {
27412                         if (!coreNodes.hasOwnProperty(index)) {
27413                             continue;
27414                         }
27415                         var coreNode = coreNodes[index];
27416                         if (coreNode == null) {
27417                             break;
27418                         }
27419                         if (coreNode.sequence == null ||
27420                             coreNode.sequence.key == null) {
27421                             console.warn("Sequence missing, discarding (" + coreNode.key + ")");
27422                             continue;
27423                         }
27424                         if (preStored != null && coreNode.key in preStored) {
27425                             var node_1 = preStored[coreNode.key];
27426                             delete preStored[coreNode.key];
27427                             hCache.push(node_1);
27428                             _this._nodeIndex.insert({ lat: node_1.latLon.lat, lon: node_1.latLon.lon, node: node_1 });
27429                             continue;
27430                         }
27431                         var node = new Graph_1.Node(coreNode);
27432                         hCache.push(node);
27433                         _this._nodeIndex.insert({ lat: node.latLon.lat, lon: node.latLon.lon, node: node });
27434                         _this._setNode(node);
27435                     }
27436                     delete _this._cachingTiles$[h];
27437                 })
27438                     .map(function (imagesByH) {
27439                     return _this;
27440                 })
27441                     .catch(function (error) {
27442                     delete _this._cachingTiles$[h];
27443                     throw error;
27444                 })
27445                     .publish()
27446                     .refCount();
27447                 this_2._cachingTiles$[h] = cacheTile$;
27448             }
27449             cacheTiles$.push(cacheTile$
27450                 .do(function (graph) {
27451                 var index = nodeTiles.caching.indexOf(h);
27452                 if (index > -1) {
27453                     nodeTiles.caching.splice(index, 1);
27454                 }
27455                 if (nodeTiles.caching.length === 0 &&
27456                     nodeTiles.cache.length === 0) {
27457                     delete _this._requiredNodeTiles[key];
27458                     _this._cachedNodeTiles[key] = true;
27459                 }
27460             })
27461                 .catch(function (error) {
27462                 var index = nodeTiles.caching.indexOf(h);
27463                 if (index > -1) {
27464                     nodeTiles.caching.splice(index, 1);
27465                 }
27466                 if (nodeTiles.caching.length === 0 &&
27467                     nodeTiles.cache.length === 0) {
27468                     delete _this._requiredNodeTiles[key];
27469                     _this._cachedNodeTiles[key] = true;
27470                 }
27471                 throw error;
27472             })
27473                 .finally(function () {
27474                 _this._changed$.next(_this);
27475             })
27476                 .publish()
27477                 .refCount());
27478         };
27479         var this_2 = this;
27480         for (var _i = 0, _a = nodeTiles.caching; _i < _a.length; _i++) {
27481             var h = _a[_i];
27482             _loop_2(h);
27483         }
27484         return cacheTiles$;
27485     };
27486     /**
27487      * Initialize the cache for a node.
27488      *
27489      * @param {string} key - Key of node.
27490      * @throws {GraphMapillaryError} When the operation is not valid on the
27491      * current graph.
27492      */
27493     Graph.prototype.initializeCache = function (key) {
27494         if (key in this._cachedNodes) {
27495             throw new Error_1.GraphMapillaryError("Node already in cache (" + key + ").");
27496         }
27497         var node = this.getNode(key);
27498         node.initializeCache(new Graph_1.NodeCache());
27499         this._cachedNodes[key] = node;
27500     };
27501     /**
27502      * Get a value indicating if the graph is fill caching a node.
27503      *
27504      * @param {string} key - Key of node.
27505      * @returns {boolean} Value indicating if the node is being fill cached.
27506      */
27507     Graph.prototype.isCachingFill = function (key) {
27508         return key in this._cachingFill$;
27509     };
27510     /**
27511      * Get a value indicating if the graph is fully caching a node.
27512      *
27513      * @param {string} key - Key of node.
27514      * @returns {boolean} Value indicating if the node is being fully cached.
27515      */
27516     Graph.prototype.isCachingFull = function (key) {
27517         return key in this._cachingFull$;
27518     };
27519     /**
27520      * Get a value indicating if the graph is caching a sequence of a node.
27521      *
27522      * @param {string} key - Key of node.
27523      * @returns {boolean} Value indicating if the sequence of a node is
27524      * being cached.
27525      */
27526     Graph.prototype.isCachingNodeSequence = function (key) {
27527         var node = this.getNode(key);
27528         return node.sequenceKey in this._cachingSequences$;
27529     };
27530     /**
27531      * Get a value indicating if the graph is caching a sequence.
27532      *
27533      * @param {string} sequenceKey - Key of sequence.
27534      * @returns {boolean} Value indicating if the sequence is
27535      * being cached.
27536      */
27537     Graph.prototype.isCachingSequence = function (sequenceKey) {
27538         return sequenceKey in this._cachingSequences$;
27539     };
27540     /**
27541      * Get a value indicating if the graph is caching the tiles
27542      * required for calculating spatial edges of a node.
27543      *
27544      * @param {string} key - Key of node.
27545      * @returns {boolean} Value indicating if the tiles of
27546      * a node are being cached.
27547      */
27548     Graph.prototype.isCachingTiles = function (key) {
27549         return key in this._requiredNodeTiles &&
27550             this._requiredNodeTiles[key].cache.length === 0 &&
27551             this._requiredNodeTiles[key].caching.length > 0;
27552     };
27553     /**
27554      * Get a value indicating if the cache has been initialized
27555      * for a node.
27556      *
27557      * @param {string} key - Key of node.
27558      * @returns {boolean} Value indicating if the cache has been
27559      * initialized for a node.
27560      */
27561     Graph.prototype.hasInitializedCache = function (key) {
27562         return key in this._cachedNodes;
27563     };
27564     /**
27565      * Get a value indicating if a node exist in the graph.
27566      *
27567      * @param {string} key - Key of node.
27568      * @returns {boolean} Value indicating if a node exist in the graph.
27569      */
27570     Graph.prototype.hasNode = function (key) {
27571         return key in this._nodes;
27572     };
27573     /**
27574      * Get a value indicating if a node sequence exist in the graph.
27575      *
27576      * @param {string} key - Key of node.
27577      * @returns {boolean} Value indicating if a node sequence exist
27578      * in the graph.
27579      */
27580     Graph.prototype.hasNodeSequence = function (key) {
27581         var node = this.getNode(key);
27582         return node.sequenceKey in this._sequences;
27583     };
27584     /**
27585      * Get a value indicating if a sequence exist in the graph.
27586      *
27587      * @param {string} sequenceKey - Key of sequence.
27588      * @returns {boolean} Value indicating if a sequence exist
27589      * in the graph.
27590      */
27591     Graph.prototype.hasSequence = function (sequenceKey) {
27592         return sequenceKey in this._sequences;
27593     };
27594     /**
27595      * Get a value indicating if the graph has fully cached
27596      * all nodes in the spatial area of a node.
27597      *
27598      * @param {string} key - Key of node.
27599      * @returns {boolean} Value indicating if the spatial area
27600      * of a node has been cached.
27601      */
27602     Graph.prototype.hasSpatialArea = function (key) {
27603         if (!this.hasNode(key)) {
27604             throw new Error_1.GraphMapillaryError("Spatial area nodes cannot be determined if node not in graph (" + key + ").");
27605         }
27606         if (key in this._cachedSpatialEdges) {
27607             return true;
27608         }
27609         if (key in this._requiredSpatialArea) {
27610             return Object.keys(this._requiredSpatialArea[key].cacheNodes).length === 0;
27611         }
27612         var node = this.getNode(key);
27613         var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold);
27614         var spatialItems = this._nodeIndex.search({
27615             maxX: bbox[1].lon,
27616             maxY: bbox[1].lat,
27617             minX: bbox[0].lon,
27618             minY: bbox[0].lat,
27619         });
27620         var spatialNodes = {
27621             all: {},
27622             cacheKeys: [],
27623             cacheNodes: {},
27624         };
27625         for (var _i = 0, spatialItems_1 = spatialItems; _i < spatialItems_1.length; _i++) {
27626             var spatialItem = spatialItems_1[_i];
27627             spatialNodes.all[spatialItem.node.key] = spatialItem.node;
27628             if (!spatialItem.node.full) {
27629                 spatialNodes.cacheKeys.push(spatialItem.node.key);
27630                 spatialNodes.cacheNodes[spatialItem.node.key] = spatialItem.node;
27631             }
27632         }
27633         this._requiredSpatialArea[key] = spatialNodes;
27634         return spatialNodes.cacheKeys.length === 0;
27635     };
27636     /**
27637      * Get a value indicating if the graph has a tiles required
27638      * for a node.
27639      *
27640      * @param {string} key - Key of node.
27641      * @returns {boolean} Value indicating if the the tiles required
27642      * by a node has been cached.
27643      */
27644     Graph.prototype.hasTiles = function (key) {
27645         var _this = this;
27646         if (key in this._cachedNodeTiles) {
27647             return true;
27648         }
27649         if (!this.hasNode(key)) {
27650             throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ").");
27651         }
27652         if (!(key in this._requiredNodeTiles)) {
27653             var node = this.getNode(key);
27654             var cache = this._graphCalculator
27655                 .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold)
27656                 .filter(function (h) {
27657                 return !(h in _this._cachedTiles);
27658             });
27659             this._requiredNodeTiles[key] = {
27660                 cache: cache,
27661                 caching: [],
27662             };
27663         }
27664         return this._requiredNodeTiles[key].cache.length === 0 &&
27665             this._requiredNodeTiles[key].caching.length === 0;
27666     };
27667     /**
27668      * Get a node.
27669      *
27670      * @param {string} key - Key of node.
27671      * @returns {Node} Retrieved node.
27672      */
27673     Graph.prototype.getNode = function (key) {
27674         return this._nodes[key];
27675     };
27676     /**
27677      * Get a sequence.
27678      *
27679      * @param {string} sequenceKey - Key of sequence.
27680      * @returns {Node} Retrieved sequence.
27681      */
27682     Graph.prototype.getSequence = function (sequenceKey) {
27683         return this._sequences[sequenceKey];
27684     };
27685     /**
27686      * Reset all spatial edges of the graph nodes.
27687      */
27688     Graph.prototype.resetSpatialEdges = function () {
27689         var cachedKeys = Object.keys(this._cachedSpatialEdges);
27690         for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) {
27691             var cachedKey = cachedKeys_1[_i];
27692             var node = this._cachedSpatialEdges[cachedKey];
27693             node.resetSpatialEdges();
27694             delete this._cachedSpatialEdges[cachedKey];
27695         }
27696     };
27697     /**
27698      * Reset the complete graph but keep the nodes corresponding
27699      * to the supplied keys. All other nodes will be disposed.
27700      *
27701      * @param {Array<string>} keepKeys - Keys for nodes to keep
27702      * in graph after reset.
27703      */
27704     Graph.prototype.reset = function (keepKeys) {
27705         var nodes = [];
27706         for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) {
27707             var key = keepKeys_1[_i];
27708             if (!this.hasNode(key)) {
27709                 throw new Error("Node does not exist " + key);
27710             }
27711             var node = this.getNode(key);
27712             node.resetSequenceEdges();
27713             node.resetSpatialEdges();
27714             nodes.push(node);
27715         }
27716         for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) {
27717             var cachedKey = _b[_a];
27718             if (keepKeys.indexOf(cachedKey) !== -1) {
27719                 continue;
27720             }
27721             this._cachedNodes[cachedKey].dispose();
27722             delete this._cachedNodes[cachedKey];
27723         }
27724         this._cachedNodeTiles = {};
27725         this._cachedSpatialEdges = {};
27726         this._cachedTiles = {};
27727         this._cachingFill$ = {};
27728         this._cachingFull$ = {};
27729         this._cachingSequences$ = {};
27730         this._cachingSpatialArea$ = {};
27731         this._cachingTiles$ = {};
27732         this._nodes = {};
27733         this._preStored = {};
27734         for (var _c = 0, nodes_1 = nodes; _c < nodes_1.length; _c++) {
27735             var node = nodes_1[_c];
27736             this._nodes[node.key] = node;
27737             var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision);
27738             this._preStore(h, node);
27739         }
27740         this._requiredNodeTiles = {};
27741         this._requiredSpatialArea = {};
27742         this._sequences = {};
27743         this._nodeIndex.clear();
27744     };
27745     /**
27746      * Set the spatial node filter.
27747      *
27748      * @param {FilterExpression} filter - Filter expression to be applied
27749      * when calculating spatial edges.
27750      */
27751     Graph.prototype.setFilter = function (filter) {
27752         this._filter = this._filterCreator.createFilter(filter);
27753     };
27754     Graph.prototype._cacheSequence$ = function (sequenceKey) {
27755         var _this = this;
27756         if (sequenceKey in this._cachingSequences$) {
27757             return this._cachingSequences$[sequenceKey];
27758         }
27759         this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey])
27760             .do(function (sequenceByKey) {
27761             if (!(sequenceKey in _this._sequences)) {
27762                 _this._sequences[sequenceKey] = new Graph_1.Sequence(sequenceByKey[sequenceKey]);
27763             }
27764             delete _this._cachingSequences$[sequenceKey];
27765         })
27766             .map(function (sequenceByKey) {
27767             return _this;
27768         })
27769             .finally(function () {
27770             if (sequenceKey in _this._cachingSequences$) {
27771                 delete _this._cachingSequences$[sequenceKey];
27772             }
27773             _this._changed$.next(_this);
27774         })
27775             .publish()
27776             .refCount();
27777         return this._cachingSequences$[sequenceKey];
27778     };
27779     Graph.prototype._makeFull = function (node, fillNode) {
27780         if (fillNode.calt == null) {
27781             fillNode.calt = this._defaultAlt;
27782         }
27783         if (fillNode.c_rotation == null) {
27784             fillNode.c_rotation = this._graphCalculator.rotationFromCompass(fillNode.ca, fillNode.orientation);
27785         }
27786         node.makeFull(fillNode);
27787     };
27788     Graph.prototype._preStore = function (h, node) {
27789         if (!(h in this._preStored)) {
27790             this._preStored[h] = {};
27791         }
27792         this._preStored[h][node.key] = node;
27793     };
27794     Graph.prototype._removeFromPreStore = function (h) {
27795         var preStored = null;
27796         if (h in this._preStored) {
27797             preStored = this._preStored[h];
27798             delete this._preStored[h];
27799         }
27800         return preStored;
27801     };
27802     Graph.prototype._setNode = function (node) {
27803         var key = node.key;
27804         if (this.hasNode(key)) {
27805             throw new Error_1.GraphMapillaryError("Node already exist (" + key + ").");
27806         }
27807         this._nodes[key] = node;
27808     };
27809     return Graph;
27810 }());
27811 exports.Graph = Graph;
27812 Object.defineProperty(exports, "__esModule", { value: true });
27813 exports.default = Graph;
27814
27815 },{"../Edge":211,"../Error":212,"../Graph":214,"rbush":24,"rxjs/Subject":33,"rxjs/add/observable/from":40,"rxjs/add/operator/catch":49,"rxjs/add/operator/do":55,"rxjs/add/operator/finally":58,"rxjs/add/operator/map":61,"rxjs/add/operator/publish":67}],282:[function(require,module,exports){
27816 /// <reference path="../../typings/index.d.ts" />
27817 "use strict";
27818 var geohash = require("latlon-geohash");
27819 var THREE = require("three");
27820 var Geo_1 = require("../Geo");
27821 var GeoHashDirections = (function () {
27822     function GeoHashDirections() {
27823     }
27824     GeoHashDirections.n = "n";
27825     GeoHashDirections.nw = "nw";
27826     GeoHashDirections.w = "w";
27827     GeoHashDirections.sw = "sw";
27828     GeoHashDirections.s = "s";
27829     GeoHashDirections.se = "se";
27830     GeoHashDirections.e = "e";
27831     GeoHashDirections.ne = "ne";
27832     return GeoHashDirections;
27833 }());
27834 var GraphCalculator = (function () {
27835     function GraphCalculator(geoCoords) {
27836         this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords();
27837     }
27838     GraphCalculator.prototype.encodeH = function (latLon, precision) {
27839         if (precision === void 0) { precision = 7; }
27840         return geohash.encode(latLon.lat, latLon.lon, precision);
27841     };
27842     GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) {
27843         if (precision === void 0) { precision = 7; }
27844         if (threshold === void 0) { threshold = 20; }
27845         var h = geohash.encode(latLon.lat, latLon.lon, precision);
27846         var bounds = geohash.bounds(h);
27847         var ne = bounds.ne;
27848         var sw = bounds.sw;
27849         var neighbours = geohash.neighbours(h);
27850         var bl = [0, 0, 0];
27851         var tr = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, sw.lat, sw.lon, 0);
27852         var position = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, sw.lat, sw.lon, 0);
27853         var left = position[0] - bl[0];
27854         var right = tr[0] - position[0];
27855         var bottom = position[1] - bl[1];
27856         var top = tr[1] - position[1];
27857         var l = left < threshold;
27858         var r = right < threshold;
27859         var b = bottom < threshold;
27860         var t = top < threshold;
27861         var hs = [h];
27862         if (t) {
27863             hs.push(neighbours[GeoHashDirections.n]);
27864         }
27865         if (t && l) {
27866             hs.push(neighbours[GeoHashDirections.nw]);
27867         }
27868         if (l) {
27869             hs.push(neighbours[GeoHashDirections.w]);
27870         }
27871         if (l && b) {
27872             hs.push(neighbours[GeoHashDirections.sw]);
27873         }
27874         if (b) {
27875             hs.push(neighbours[GeoHashDirections.s]);
27876         }
27877         if (b && r) {
27878             hs.push(neighbours[GeoHashDirections.se]);
27879         }
27880         if (r) {
27881             hs.push(neighbours[GeoHashDirections.e]);
27882         }
27883         if (r && t) {
27884             hs.push(neighbours[GeoHashDirections.ne]);
27885         }
27886         return hs;
27887     };
27888     GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) {
27889         var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0);
27890         var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0);
27891         return [
27892             { lat: bl[0], lon: bl[1] },
27893             { lat: tr[0], lon: tr[1] },
27894         ];
27895     };
27896     GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) {
27897         var x = 0;
27898         var y = 0;
27899         var z = 0;
27900         switch (orientation) {
27901             case 1:
27902                 x = Math.PI / 2;
27903                 break;
27904             case 3:
27905                 x = -Math.PI / 2;
27906                 z = Math.PI;
27907                 break;
27908             case 6:
27909                 y = -Math.PI / 2;
27910                 z = -Math.PI / 2;
27911                 break;
27912             case 8:
27913                 y = Math.PI / 2;
27914                 z = Math.PI / 2;
27915                 break;
27916             default:
27917                 break;
27918         }
27919         var rz = new THREE.Matrix4().makeRotationZ(z);
27920         var euler = new THREE.Euler(x, y, compassAngle * Math.PI / 180, "XYZ");
27921         var re = new THREE.Matrix4().makeRotationFromEuler(euler);
27922         var rotation = new THREE.Vector4().setAxisAngleFromRotationMatrix(re.multiply(rz));
27923         return rotation.multiplyScalar(rotation.w).toArray().slice(0, 3);
27924     };
27925     return GraphCalculator;
27926 }());
27927 exports.GraphCalculator = GraphCalculator;
27928 Object.defineProperty(exports, "__esModule", { value: true });
27929 exports.default = GraphCalculator;
27930
27931 },{"../Geo":213,"latlon-geohash":20,"three":160}],283:[function(require,module,exports){
27932 "use strict";
27933 var Observable_1 = require("rxjs/Observable");
27934 var Subject_1 = require("rxjs/Subject");
27935 require("rxjs/add/operator/catch");
27936 require("rxjs/add/operator/concat");
27937 require("rxjs/add/operator/do");
27938 require("rxjs/add/operator/expand");
27939 require("rxjs/add/operator/finally");
27940 require("rxjs/add/operator/first");
27941 require("rxjs/add/operator/last");
27942 require("rxjs/add/operator/map");
27943 require("rxjs/add/operator/mergeMap");
27944 require("rxjs/add/operator/publishReplay");
27945 /**
27946  * @class GraphService
27947  *
27948  * @classdesc Represents a service for graph operations.
27949  */
27950 var GraphService = (function () {
27951     /**
27952      * Create a new graph service instance.
27953      *
27954      * @param {Graph} graph - Graph instance to be operated on.
27955      */
27956     function GraphService(graph, imageLoadingService) {
27957         this._graph$ = Observable_1.Observable
27958             .of(graph)
27959             .concat(graph.changed$)
27960             .publishReplay(1)
27961             .refCount();
27962         this._graph$.subscribe();
27963         this._imageLoadingService = imageLoadingService;
27964         this._firstGraphSubjects$ = [];
27965         this._initializeCacheSubscriptions = [];
27966         this._sequenceSubscriptions = [];
27967         this._spatialSubscriptions = [];
27968     }
27969     /**
27970      * Cache a node in the graph and retrieve it.
27971      *
27972      * @description When called, the full properties of
27973      * the node are retrieved and the node cache is initialized.
27974      * After that the node assets are cached and the node
27975      * is emitted to the observable when.
27976      * In parallel to caching the node assets, the sequence and
27977      * spatial edges of the node are cached. For this, the sequence
27978      * of the node and the required tiles and spatial nodes are
27979      * retrieved. The sequence and spatial edges may be set before
27980      * or after the node is returned.
27981      *
27982      * @param {string} key - Key of the node to cache.
27983      * @return {Observable<Node>} Observable emitting a single item,
27984      * the node, when it has been retrieved and its assets are cached.
27985      * @throws {Error} Propagates any IO node caching errors to the caller.
27986      */
27987     GraphService.prototype.cacheNode$ = function (key) {
27988         var _this = this;
27989         var firstGraphSubject$ = new Subject_1.Subject();
27990         this._firstGraphSubjects$.push(firstGraphSubject$);
27991         var firstGraph$ = firstGraphSubject$
27992             .publishReplay(1)
27993             .refCount();
27994         var node$ = firstGraph$
27995             .map(function (graph) {
27996             return graph.getNode(key);
27997         })
27998             .mergeMap(function (node) {
27999             return node.assetsCached ?
28000                 Observable_1.Observable.of(node) :
28001                 node.cacheAssets$();
28002         })
28003             .publishReplay(1)
28004             .refCount();
28005         node$.subscribe(function (node) {
28006             _this._imageLoadingService.loadnode$.next(node);
28007         }, function (error) {
28008             console.error("Failed to cache node (" + key + ")", error);
28009         });
28010         var initializeCacheSubscription = this._graph$
28011             .first()
28012             .mergeMap(function (graph) {
28013             if (graph.isCachingFull(key) || !graph.hasNode(key)) {
28014                 return graph.cacheFull$(key);
28015             }
28016             if (graph.isCachingFill(key) || !graph.getNode(key).full) {
28017                 return graph.cacheFill$(key);
28018             }
28019             return Observable_1.Observable.of(graph);
28020         })
28021             .do(function (graph) {
28022             if (!graph.hasInitializedCache(key)) {
28023                 graph.initializeCache(key);
28024             }
28025         })
28026             .finally(function () {
28027             if (initializeCacheSubscription == null) {
28028                 return;
28029             }
28030             _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions);
28031             _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$);
28032         })
28033             .subscribe(function (graph) {
28034             firstGraphSubject$.next(graph);
28035             firstGraphSubject$.complete();
28036         }, function (error) {
28037             firstGraphSubject$.error(error);
28038         });
28039         if (!initializeCacheSubscription.closed) {
28040             this._initializeCacheSubscriptions.push(initializeCacheSubscription);
28041         }
28042         var sequenceSubscription = firstGraph$
28043             .mergeMap(function (graph) {
28044             if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) {
28045                 return graph.cacheNodeSequence$(key);
28046             }
28047             return Observable_1.Observable.of(graph);
28048         })
28049             .do(function (graph) {
28050             if (!graph.getNode(key).sequenceEdges.cached) {
28051                 graph.cacheSequenceEdges(key);
28052             }
28053         })
28054             .finally(function () {
28055             if (sequenceSubscription == null) {
28056                 return;
28057             }
28058             _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions);
28059         })
28060             .subscribe(function (graph) { return; }, function (error) {
28061             console.error("Failed to cache sequence edges (" + key + ").", error);
28062         });
28063         if (!sequenceSubscription.closed) {
28064             this._sequenceSubscriptions.push(sequenceSubscription);
28065         }
28066         var spatialSubscription = firstGraph$
28067             .expand(function (graph) {
28068             if (graph.hasTiles(key)) {
28069                 return Observable_1.Observable.empty();
28070             }
28071             return Observable_1.Observable
28072                 .from(graph.cacheTiles$(key))
28073                 .mergeMap(function (graph$) {
28074                 return graph$
28075                     .mergeMap(function (g) {
28076                     if (g.isCachingTiles(key)) {
28077                         return Observable_1.Observable.empty();
28078                     }
28079                     return Observable_1.Observable.of(g);
28080                 })
28081                     .catch(function (error, caught$) {
28082                     console.error("Failed to cache tile data (" + key + ").", error);
28083                     return Observable_1.Observable.empty();
28084                 });
28085             });
28086         })
28087             .last()
28088             .mergeMap(function (graph) {
28089             if (graph.hasSpatialArea(key)) {
28090                 return Observable_1.Observable.of(graph);
28091             }
28092             return Observable_1.Observable
28093                 .from(graph.cacheSpatialArea$(key))
28094                 .mergeMap(function (graph$) {
28095                 return graph$
28096                     .catch(function (error, caught$) {
28097                     console.error("Failed to cache spatial nodes (" + key + ").", error);
28098                     return Observable_1.Observable.empty();
28099                 });
28100             });
28101         })
28102             .last()
28103             .mergeMap(function (graph) {
28104             return graph.hasNodeSequence(key) ?
28105                 Observable_1.Observable.of(graph) :
28106                 graph.cacheNodeSequence$(key);
28107         })
28108             .do(function (graph) {
28109             if (!graph.getNode(key).spatialEdges.cached) {
28110                 graph.cacheSpatialEdges(key);
28111             }
28112         })
28113             .finally(function () {
28114             if (spatialSubscription == null) {
28115                 return;
28116             }
28117             _this._removeFromArray(spatialSubscription, _this._spatialSubscriptions);
28118         })
28119             .subscribe(function (graph) { return; }, function (error) {
28120             console.error("Failed to cache spatial edges (" + key + ").", error);
28121         });
28122         if (!spatialSubscription.closed) {
28123             this._spatialSubscriptions.push(spatialSubscription);
28124         }
28125         return node$
28126             .first(function (node) {
28127             return node.assetsCached;
28128         });
28129     };
28130     /**
28131      * Cache a sequence in the graph and retrieve it.
28132      *
28133      * @param {string} sequenceKey - Sequence key.
28134      * @returns {Observable<Sequence>} Observable emitting a single item,
28135      * the sequence, when it has been retrieved and its assets are cached.
28136      * @throws {Error} Propagates any IO node caching errors to the caller.
28137      */
28138     GraphService.prototype.cacheSequence$ = function (sequenceKey) {
28139         return this._graph$
28140             .first()
28141             .mergeMap(function (graph) {
28142             if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
28143                 return graph.cacheSequence$(sequenceKey);
28144             }
28145             return Observable_1.Observable.of(graph);
28146         })
28147             .map(function (graph) {
28148             return graph.getSequence(sequenceKey);
28149         });
28150     };
28151     /**
28152      * Set a spatial edge filter on the graph.
28153      *
28154      * @description Resets the spatial edges of all cached nodes.
28155      *
28156      * @param {FilterExpression} filter - Filter expression to be applied.
28157      * @return {Observable<Graph>} Observable emitting a single item,
28158      * the graph, when the spatial edges have been reset.
28159      */
28160     GraphService.prototype.setFilter$ = function (filter) {
28161         this._resetSubscriptions(this._spatialSubscriptions);
28162         return this._graph$
28163             .first()
28164             .do(function (graph) {
28165             graph.resetSpatialEdges();
28166             graph.setFilter(filter);
28167         });
28168     };
28169     /**
28170      * Reset the graph.
28171      *
28172      * @description Resets the graph but keeps the nodes of the
28173      * supplied keys.
28174      *
28175      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
28176      * @return {Observable<Node>} Observable emitting a single item,
28177      * the graph, when it has been reset.
28178      */
28179     GraphService.prototype.reset$ = function (keepKeys) {
28180         this._abortSubjects(this._firstGraphSubjects$);
28181         this._resetSubscriptions(this._initializeCacheSubscriptions);
28182         this._resetSubscriptions(this._sequenceSubscriptions);
28183         this._resetSubscriptions(this._spatialSubscriptions);
28184         return this._graph$
28185             .first()
28186             .do(function (graph) {
28187             graph.reset(keepKeys);
28188         });
28189     };
28190     GraphService.prototype._abortSubjects = function (subjects) {
28191         for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) {
28192             var subject = _a[_i];
28193             this._removeFromArray(subject, subjects);
28194             subject.error(new Error("Cache node request was aborted."));
28195         }
28196     };
28197     GraphService.prototype._removeFromArray = function (object, objects) {
28198         var index = objects.indexOf(object);
28199         if (index !== -1) {
28200             objects.splice(index, 1);
28201         }
28202     };
28203     GraphService.prototype._resetSubscriptions = function (subscriptions) {
28204         for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) {
28205             var subscription = _a[_i];
28206             this._removeFromArray(subscription, subscriptions);
28207             if (!subscription.closed) {
28208                 subscription.unsubscribe();
28209             }
28210         }
28211     };
28212     return GraphService;
28213 }());
28214 exports.GraphService = GraphService;
28215 Object.defineProperty(exports, "__esModule", { value: true });
28216 exports.default = GraphService;
28217
28218 },{"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/operator/catch":49,"rxjs/add/operator/concat":51,"rxjs/add/operator/do":55,"rxjs/add/operator/expand":56,"rxjs/add/operator/finally":58,"rxjs/add/operator/first":59,"rxjs/add/operator/last":60,"rxjs/add/operator/map":61,"rxjs/add/operator/mergeMap":64,"rxjs/add/operator/publishReplay":68}],284:[function(require,module,exports){
28219 "use strict";
28220 var Observable_1 = require("rxjs/Observable");
28221 var Utils_1 = require("../Utils");
28222 var ImageLoader = (function () {
28223     function ImageLoader() {
28224     }
28225     ImageLoader.loadThumbnail = function (key, imageSize) {
28226         return this._load(key, imageSize, Utils_1.Urls.thumbnail);
28227     };
28228     ImageLoader.loadDynamic = function (key, imageSize) {
28229         return this._load(key, imageSize, Utils_1.Urls.dynamicImage);
28230     };
28231     ImageLoader._load = function (key, size, getUrl) {
28232         return Observable_1.Observable.create(function (subscriber) {
28233             var image = new Image();
28234             image.crossOrigin = "Anonymous";
28235             var xmlHTTP = new XMLHttpRequest();
28236             xmlHTTP.open("GET", getUrl(key, size), true);
28237             xmlHTTP.responseType = "arraybuffer";
28238             xmlHTTP.onload = function (pe) {
28239                 if (xmlHTTP.status !== 200) {
28240                     subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
28241                     return;
28242                 }
28243                 image.onload = function (e) {
28244                     subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
28245                     subscriber.complete();
28246                 };
28247                 image.onerror = function (error) {
28248                     subscriber.error(new Error("Failed to load image (" + key + ")"));
28249                 };
28250                 var blob = new Blob([xmlHTTP.response]);
28251                 image.src = window.URL.createObjectURL(blob);
28252             };
28253             xmlHTTP.onprogress = function (pe) {
28254                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
28255             };
28256             xmlHTTP.onerror = function (error) {
28257                 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
28258             };
28259             xmlHTTP.send(null);
28260         });
28261     };
28262     return ImageLoader;
28263 }());
28264 exports.ImageLoader = ImageLoader;
28265 Object.defineProperty(exports, "__esModule", { value: true });
28266 exports.default = ImageLoader;
28267
28268 },{"../Utils":218,"rxjs/Observable":28}],285:[function(require,module,exports){
28269 /// <reference path="../../typings/index.d.ts" />
28270 "use strict";
28271 var Subject_1 = require("rxjs/Subject");
28272 var ImageLoadingService = (function () {
28273     function ImageLoadingService() {
28274         this._loadnode$ = new Subject_1.Subject();
28275         this._loadstatus$ = this._loadnode$
28276             .scan(function (nodes, node) {
28277             nodes[node.key] = node.loadStatus;
28278             return nodes;
28279         }, {})
28280             .publishReplay(1)
28281             .refCount();
28282         this._loadstatus$.subscribe();
28283     }
28284     Object.defineProperty(ImageLoadingService.prototype, "loadnode$", {
28285         get: function () {
28286             return this._loadnode$;
28287         },
28288         enumerable: true,
28289         configurable: true
28290     });
28291     Object.defineProperty(ImageLoadingService.prototype, "loadstatus$", {
28292         get: function () {
28293             return this._loadstatus$;
28294         },
28295         enumerable: true,
28296         configurable: true
28297     });
28298     return ImageLoadingService;
28299 }());
28300 exports.ImageLoadingService = ImageLoadingService;
28301
28302 },{"rxjs/Subject":33}],286:[function(require,module,exports){
28303 /// <reference path="../../typings/index.d.ts" />
28304 "use strict";
28305 var Pbf = require("pbf");
28306 var MeshReader = (function () {
28307     function MeshReader() {
28308     }
28309     MeshReader.read = function (buffer) {
28310         var pbf = new Pbf(buffer);
28311         return pbf.readFields(MeshReader._readMeshField, { faces: [], vertices: [] });
28312     };
28313     MeshReader._readMeshField = function (tag, mesh, pbf) {
28314         if (tag === 1) {
28315             mesh.vertices.push(pbf.readFloat());
28316         }
28317         else if (tag === 2) {
28318             mesh.faces.push(pbf.readVarint());
28319         }
28320     };
28321     return MeshReader;
28322 }());
28323 exports.MeshReader = MeshReader;
28324
28325 },{"pbf":22}],287:[function(require,module,exports){
28326 "use strict";
28327 require("rxjs/add/observable/combineLatest");
28328 require("rxjs/add/operator/map");
28329 /**
28330  * @class Node
28331  *
28332  * @classdesc Represents a node in the navigation graph.
28333  */
28334 var Node = (function () {
28335     /**
28336      * Create a new node instance.
28337      *
28338      * @param {ICoreNode} coreNode - Raw core node data.
28339      */
28340     function Node(core) {
28341         this._cache = null;
28342         this._core = core;
28343         this._fill = null;
28344     }
28345     Object.defineProperty(Node.prototype, "assetsCached", {
28346         /**
28347          * Get assets cached.
28348          *
28349          * @description The assets that need to be cached for this property
28350          * to report true are the following: fill properties, image and mesh.
28351          * The library ensures that the current node will always have the
28352          * assets cached.
28353          *
28354          * @returns {boolean} Value indicating whether all assets have been
28355          * cached.
28356          */
28357         get: function () {
28358             return this._core != null &&
28359                 this._fill != null &&
28360                 this._cache != null &&
28361                 this._cache.image != null &&
28362                 this._cache.mesh != null;
28363         },
28364         enumerable: true,
28365         configurable: true
28366     });
28367     Object.defineProperty(Node.prototype, "alt", {
28368         /**
28369          * Get alt.
28370          *
28371          * @description If SfM has not been run the computed altitude is
28372          * set to a default value of two meters.
28373          *
28374          * @returns {number} Altitude, in meters.
28375          */
28376         get: function () {
28377             return this._fill.calt;
28378         },
28379         enumerable: true,
28380         configurable: true
28381     });
28382     Object.defineProperty(Node.prototype, "ca", {
28383         /**
28384          * Get ca.
28385          *
28386          * @description If the SfM computed compass angle exists it will
28387          * be returned, otherwise the original EXIF compass angle.
28388          *
28389          * @returns {number} Compass angle, measured in degrees.
28390          */
28391         get: function () {
28392             return this._fill.cca != null ? this._fill.cca : this._fill.ca;
28393         },
28394         enumerable: true,
28395         configurable: true
28396     });
28397     Object.defineProperty(Node.prototype, "capturedAt", {
28398         /**
28399          * Get capturedAt.
28400          *
28401          * @returns {number} Timestamp when the image was captured.
28402          */
28403         get: function () {
28404             return this._fill.captured_at;
28405         },
28406         enumerable: true,
28407         configurable: true
28408     });
28409     Object.defineProperty(Node.prototype, "computedCA", {
28410         /**
28411          * Get computedCA.
28412          *
28413          * @description Will not be set if SfM has not been run.
28414          *
28415          * @returns {number} SfM computed compass angle, measured in degrees.
28416          */
28417         get: function () {
28418             return this._fill.cca;
28419         },
28420         enumerable: true,
28421         configurable: true
28422     });
28423     Object.defineProperty(Node.prototype, "computedLatLon", {
28424         /**
28425          * Get computedLatLon.
28426          *
28427          * @description Will not be set if SfM has not been run.
28428          *
28429          * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum,
28430          * measured in degrees.
28431          */
28432         get: function () {
28433             return this._core.cl;
28434         },
28435         enumerable: true,
28436         configurable: true
28437     });
28438     Object.defineProperty(Node.prototype, "focal", {
28439         /**
28440          * Get focal.
28441          *
28442          * @description Will not be set if SfM has not been run.
28443          *
28444          * @returns {number} SfM computed focal length.
28445          */
28446         get: function () {
28447             return this._fill.cfocal;
28448         },
28449         enumerable: true,
28450         configurable: true
28451     });
28452     Object.defineProperty(Node.prototype, "full", {
28453         /**
28454          * Get full.
28455          *
28456          * @description The library ensures that the current node will
28457          * always be full.
28458          *
28459          * @returns {boolean} Value indicating whether the node has all
28460          * properties filled.
28461          */
28462         get: function () {
28463             return this._fill != null;
28464         },
28465         enumerable: true,
28466         configurable: true
28467     });
28468     Object.defineProperty(Node.prototype, "fullPano", {
28469         /**
28470          * Get fullPano.
28471          *
28472          * @returns {boolean} Value indicating whether the node is a complete
28473          * 360 panorama.
28474          */
28475         get: function () {
28476             return this._fill.gpano != null &&
28477                 this._fill.gpano.CroppedAreaLeftPixels === 0 &&
28478                 this._fill.gpano.CroppedAreaTopPixels === 0 &&
28479                 this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels &&
28480                 this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels;
28481         },
28482         enumerable: true,
28483         configurable: true
28484     });
28485     Object.defineProperty(Node.prototype, "gpano", {
28486         /**
28487          * Get gpano.
28488          *
28489          * @description Will not be set for non panoramic images.
28490          *
28491          * @returns {IGPano} Panorama information for panorama images.
28492          */
28493         get: function () {
28494             return this._fill.gpano;
28495         },
28496         enumerable: true,
28497         configurable: true
28498     });
28499     Object.defineProperty(Node.prototype, "height", {
28500         /**
28501          * Get height.
28502          *
28503          * @returns {number} Height of original image, not adjusted
28504          * for orientation.
28505          */
28506         get: function () {
28507             return this._fill.height;
28508         },
28509         enumerable: true,
28510         configurable: true
28511     });
28512     Object.defineProperty(Node.prototype, "image", {
28513         /**
28514          * Get image.
28515          *
28516          * @description The image will always be set on the current node.
28517          *
28518          * @returns {HTMLImageElement} Cached image element of the node.
28519          */
28520         get: function () {
28521             return this._cache.image;
28522         },
28523         enumerable: true,
28524         configurable: true
28525     });
28526     Object.defineProperty(Node.prototype, "key", {
28527         /**
28528          * Get key.
28529          *
28530          * @returns {string} Unique key of the node.
28531          */
28532         get: function () {
28533             return this._core.key;
28534         },
28535         enumerable: true,
28536         configurable: true
28537     });
28538     Object.defineProperty(Node.prototype, "latLon", {
28539         /**
28540          * Get latLon.
28541          *
28542          * @description If the SfM computed latitude longitude exist
28543          * it will be returned, otherwise the original EXIF latitude
28544          * longitude.
28545          *
28546          * @returns {ILatLon} Latitude longitude in WGS84 datum,
28547          * measured in degrees.
28548          */
28549         get: function () {
28550             return this._core.cl != null ? this._core.cl : this._core.l;
28551         },
28552         enumerable: true,
28553         configurable: true
28554     });
28555     Object.defineProperty(Node.prototype, "loadStatus", {
28556         /**
28557          * Get loadStatus.
28558          *
28559          * @returns {ILoadStatus} Value indicating the load status
28560          * of the mesh and image.
28561          */
28562         get: function () {
28563             return this._cache.loadStatus;
28564         },
28565         enumerable: true,
28566         configurable: true
28567     });
28568     Object.defineProperty(Node.prototype, "merged", {
28569         /**
28570          * Get merged.
28571          *
28572          * @returns {boolean} Value indicating whether SfM has been
28573          * run on the node and the node has been merged into a
28574          * connected component.
28575          */
28576         get: function () {
28577             return this._fill != null &&
28578                 this._fill.merge_version != null &&
28579                 this._fill.merge_version > 0;
28580         },
28581         enumerable: true,
28582         configurable: true
28583     });
28584     Object.defineProperty(Node.prototype, "mergeCC", {
28585         /**
28586          * Get mergeCC.
28587          *
28588          * @description Will not be set if SfM has not yet been run on
28589          * node.
28590          *
28591          * @returns {number} SfM connected component key to which
28592          * image belongs.
28593          */
28594         get: function () {
28595             return this._fill.merge_cc;
28596         },
28597         enumerable: true,
28598         configurable: true
28599     });
28600     Object.defineProperty(Node.prototype, "mergeVersion", {
28601         /**
28602          * Get mergeVersion.
28603          *
28604          * @returns {number} Version for which SfM was run and image was merged.
28605          */
28606         get: function () {
28607             return this._fill.merge_version;
28608         },
28609         enumerable: true,
28610         configurable: true
28611     });
28612     Object.defineProperty(Node.prototype, "mesh", {
28613         /**
28614          * Get mesh.
28615          *
28616          * @description The mesh will always be set on the current node.
28617          *
28618          * @returns {IMesh} SfM triangulated mesh of reconstructed
28619          * atomic 3D points.
28620          */
28621         get: function () {
28622             return this._cache.mesh;
28623         },
28624         enumerable: true,
28625         configurable: true
28626     });
28627     Object.defineProperty(Node.prototype, "orientation", {
28628         /**
28629          * Get orientation.
28630          *
28631          * @returns {number} EXIF orientation of original image.
28632          */
28633         get: function () {
28634             return this._fill.orientation;
28635         },
28636         enumerable: true,
28637         configurable: true
28638     });
28639     Object.defineProperty(Node.prototype, "originalCA", {
28640         /**
28641          * Get originalCA.
28642          *
28643          * @returns {number} Original EXIF compass angle, measured in
28644          * degrees.
28645          */
28646         get: function () {
28647             return this._fill.ca;
28648         },
28649         enumerable: true,
28650         configurable: true
28651     });
28652     Object.defineProperty(Node.prototype, "originalLatLon", {
28653         /**
28654          * Get originalLatLon.
28655          *
28656          * @returns {ILatLon} Original EXIF latitude longitude in
28657          * WGS84 datum, measured in degrees.
28658          */
28659         get: function () {
28660             return this._core.l;
28661         },
28662         enumerable: true,
28663         configurable: true
28664     });
28665     Object.defineProperty(Node.prototype, "pano", {
28666         /**
28667          * Get pano.
28668          *
28669          * @returns {boolean} Value indicating whether the node is a panorama.
28670          * It could be a cropped or full panorama.
28671          */
28672         get: function () {
28673             return this._fill.gpano != null &&
28674                 this._fill.gpano.FullPanoWidthPixels != null;
28675         },
28676         enumerable: true,
28677         configurable: true
28678     });
28679     Object.defineProperty(Node.prototype, "projectKey", {
28680         /**
28681          * Get projectKey.
28682          *
28683          * @returns {string} Unique key of the project to which
28684          * the node belongs.
28685          */
28686         get: function () {
28687             return this._fill.project != null ?
28688                 this._fill.project.key :
28689                 null;
28690         },
28691         enumerable: true,
28692         configurable: true
28693     });
28694     Object.defineProperty(Node.prototype, "rotation", {
28695         /**
28696          * Get rotation.
28697          *
28698          * @description Will not be set if SfM has not been run.
28699          *
28700          * @returns {Array<number>} Rotation vector in angle axis representation.
28701          */
28702         get: function () {
28703             return this._fill.c_rotation;
28704         },
28705         enumerable: true,
28706         configurable: true
28707     });
28708     Object.defineProperty(Node.prototype, "scale", {
28709         /**
28710          * Get scale.
28711          *
28712          * @description Will not be set if SfM has not been run.
28713          *
28714          * @returns {number} Scale of atomic reconstruction.
28715          */
28716         get: function () {
28717             return this._fill.atomic_scale;
28718         },
28719         enumerable: true,
28720         configurable: true
28721     });
28722     Object.defineProperty(Node.prototype, "sequenceKey", {
28723         /**
28724          * Get sequenceKey.
28725          *
28726          * @returns {string} Unique key of the sequence to which
28727          * the node belongs.
28728          */
28729         get: function () {
28730             return this._core.sequence.key;
28731         },
28732         enumerable: true,
28733         configurable: true
28734     });
28735     Object.defineProperty(Node.prototype, "sequenceEdges", {
28736         /**
28737          * Get sequenceEdges.
28738          *
28739          * @returns {IEdgeStatus} Value describing the status of the
28740          * sequence edges.
28741          */
28742         get: function () {
28743             return this._cache.sequenceEdges;
28744         },
28745         enumerable: true,
28746         configurable: true
28747     });
28748     Object.defineProperty(Node.prototype, "sequenceEdges$", {
28749         /**
28750          * Get sequenceEdges$.
28751          *
28752          * @returns {Observable<IEdgeStatus>} Observable emitting
28753          * values describing the status of the sequence edges.
28754          */
28755         get: function () {
28756             return this._cache.sequenceEdges$;
28757         },
28758         enumerable: true,
28759         configurable: true
28760     });
28761     Object.defineProperty(Node.prototype, "spatialEdges", {
28762         /**
28763          * Get spatialEdges.
28764          *
28765          * @returns {IEdgeStatus} Value describing the status of the
28766          * spatial edges.
28767          */
28768         get: function () {
28769             return this._cache.spatialEdges;
28770         },
28771         enumerable: true,
28772         configurable: true
28773     });
28774     Object.defineProperty(Node.prototype, "spatialEdges$", {
28775         /**
28776          * Get spatialEdges$.
28777          *
28778          * @returns {Observable<IEdgeStatus>} Observable emitting
28779          * values describing the status of the spatial edges.
28780          */
28781         get: function () {
28782             return this._cache.spatialEdges$;
28783         },
28784         enumerable: true,
28785         configurable: true
28786     });
28787     Object.defineProperty(Node.prototype, "userKey", {
28788         /**
28789          * Get userKey.
28790          *
28791          * @returns {string} Unique key of the user who uploaded
28792          * the image.
28793          */
28794         get: function () {
28795             return this._fill.user.key;
28796         },
28797         enumerable: true,
28798         configurable: true
28799     });
28800     Object.defineProperty(Node.prototype, "username", {
28801         /**
28802          * Get username.
28803          *
28804          * @returns {string} Username of the user who uploaded
28805          * the image.
28806          */
28807         get: function () {
28808             return this._fill.user.username;
28809         },
28810         enumerable: true,
28811         configurable: true
28812     });
28813     Object.defineProperty(Node.prototype, "width", {
28814         /**
28815          * Get width.
28816          *
28817          * @returns {number} Width of original image, not
28818          * adjusted for orientation.
28819          */
28820         get: function () {
28821             return this._fill.width;
28822         },
28823         enumerable: true,
28824         configurable: true
28825     });
28826     /**
28827      * Cache the image and mesh assets.
28828      *
28829      * @description The assets are always cached internally by the
28830      * library prior to setting a node as the current node.
28831      *
28832      * @returns {Observable<Node>} Observable emitting this node whenever the
28833      * load status has changed and when the mesh or image has been fully loaded.
28834      */
28835     Node.prototype.cacheAssets$ = function () {
28836         var _this = this;
28837         return this._cache.cacheAssets$(this.key, this.pano, this.merged)
28838             .map(function (cache) {
28839             return _this;
28840         });
28841     };
28842     Node.prototype.cacheImage$ = function (imageSize) {
28843         var _this = this;
28844         return this._cache.cacheImage$(this.key, imageSize)
28845             .map(function (cache) {
28846             return _this;
28847         });
28848     };
28849     /**
28850      * Cache the sequence edges.
28851      *
28852      * @description The sequence edges are cached asynchronously
28853      * internally by the library.
28854      *
28855      * @param {Array<IEdge>} edges - Sequence edges to cache.
28856      */
28857     Node.prototype.cacheSequenceEdges = function (edges) {
28858         this._cache.cacheSequenceEdges(edges);
28859     };
28860     /**
28861      * Cache the spatial edges.
28862      *
28863      * @description The spatial edges are cached asynchronously
28864      * internally by the library.
28865      *
28866      * @param {Array<IEdge>} edges - Spatial edges to cache.
28867      */
28868     Node.prototype.cacheSpatialEdges = function (edges) {
28869         this._cache.cacheSpatialEdges(edges);
28870     };
28871     /**
28872      * Dispose the node.
28873      *
28874      * @description Disposes all cached assets.
28875      */
28876     Node.prototype.dispose = function () {
28877         if (this._cache != null) {
28878             this._cache.dispose();
28879             this._cache = null;
28880         }
28881         this._core = null;
28882         this._fill = null;
28883     };
28884     /**
28885      * Initialize the node cache.
28886      *
28887      * @description The node cache is initialized internally by
28888      * the library.
28889      *
28890      * @param {NodeCache} cache - The node cache to set as cache.
28891      */
28892     Node.prototype.initializeCache = function (cache) {
28893         if (this._cache != null) {
28894             throw new Error("Node cache already initialized (" + this.key + ").");
28895         }
28896         this._cache = cache;
28897     };
28898     /**
28899      * Fill the node with all properties.
28900      *
28901      * @description The node is filled internally by
28902      * the library.
28903      *
28904      * @param {IFillNode} fill - The fill node struct.
28905      */
28906     Node.prototype.makeFull = function (fill) {
28907         if (fill == null) {
28908             throw new Error("Fill can not be null.");
28909         }
28910         this._fill = fill;
28911     };
28912     /**
28913      * Reset the sequence edges.
28914      */
28915     Node.prototype.resetSequenceEdges = function () {
28916         this._cache.resetSequenceEdges();
28917     };
28918     /**
28919      * Reset the spatial edges.
28920      */
28921     Node.prototype.resetSpatialEdges = function () {
28922         this._cache.resetSpatialEdges();
28923     };
28924     return Node;
28925 }());
28926 exports.Node = Node;
28927 Object.defineProperty(exports, "__esModule", { value: true });
28928 exports.default = Node;
28929
28930 },{"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/map":61}],288:[function(require,module,exports){
28931 (function (Buffer){
28932 "use strict";
28933 var Subject_1 = require("rxjs/Subject");
28934 var Observable_1 = require("rxjs/Observable");
28935 require("rxjs/add/observable/combineLatest");
28936 require("rxjs/add/operator/publishReplay");
28937 var Graph_1 = require("../Graph");
28938 var Utils_1 = require("../Utils");
28939 /**
28940  * @class NodeCache
28941  *
28942  * @classdesc Represents the cached properties of a node.
28943  */
28944 var NodeCache = (function () {
28945     /**
28946      * Create a new node cache instance.
28947      */
28948     function NodeCache() {
28949         this._disposed = false;
28950         this._image = null;
28951         this._loadStatus = { loaded: 0, total: 0 };
28952         this._mesh = null;
28953         this._sequenceEdges = { cached: false, edges: [] };
28954         this._spatialEdges = { cached: false, edges: [] };
28955         this._sequenceEdgesChanged$ = new Subject_1.Subject();
28956         this._sequenceEdges$ = this._sequenceEdgesChanged$
28957             .startWith(this._sequenceEdges)
28958             .publishReplay(1)
28959             .refCount();
28960         this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe();
28961         this._spatialEdgesChanged$ = new Subject_1.Subject();
28962         this._spatialEdges$ = this._spatialEdgesChanged$
28963             .startWith(this._spatialEdges)
28964             .publishReplay(1)
28965             .refCount();
28966         this._spatialEdgesSubscription = this._spatialEdges$.subscribe();
28967         this._cachingAssets$ = null;
28968     }
28969     Object.defineProperty(NodeCache.prototype, "image", {
28970         /**
28971          * Get image.
28972          *
28973          * @description Will not be set when assets have not been cached
28974          * or when the object has been disposed.
28975          *
28976          * @returns {HTMLImageElement} Cached image element of the node.
28977          */
28978         get: function () {
28979             return this._image;
28980         },
28981         enumerable: true,
28982         configurable: true
28983     });
28984     Object.defineProperty(NodeCache.prototype, "loadStatus", {
28985         /**
28986          * Get loadStatus.
28987          *
28988          * @returns {ILoadStatus} Value indicating the load status
28989          * of the mesh and image.
28990          */
28991         get: function () {
28992             return this._loadStatus;
28993         },
28994         enumerable: true,
28995         configurable: true
28996     });
28997     Object.defineProperty(NodeCache.prototype, "mesh", {
28998         /**
28999          * Get mesh.
29000          *
29001          * @description Will not be set when assets have not been cached
29002          * or when the object has been disposed.
29003          *
29004          * @returns {IMesh} SfM triangulated mesh of reconstructed
29005          * atomic 3D points.
29006          */
29007         get: function () {
29008             return this._mesh;
29009         },
29010         enumerable: true,
29011         configurable: true
29012     });
29013     Object.defineProperty(NodeCache.prototype, "sequenceEdges", {
29014         /**
29015          * Get sequenceEdges.
29016          *
29017          * @returns {IEdgeStatus} Value describing the status of the
29018          * sequence edges.
29019          */
29020         get: function () {
29021             return this._sequenceEdges;
29022         },
29023         enumerable: true,
29024         configurable: true
29025     });
29026     Object.defineProperty(NodeCache.prototype, "sequenceEdges$", {
29027         /**
29028          * Get sequenceEdges$.
29029          *
29030          * @returns {Observable<IEdgeStatus>} Observable emitting
29031          * values describing the status of the sequence edges.
29032          */
29033         get: function () {
29034             return this._sequenceEdges$;
29035         },
29036         enumerable: true,
29037         configurable: true
29038     });
29039     Object.defineProperty(NodeCache.prototype, "spatialEdges", {
29040         /**
29041          * Get spatialEdges.
29042          *
29043          * @returns {IEdgeStatus} Value describing the status of the
29044          * spatial edges.
29045          */
29046         get: function () {
29047             return this._spatialEdges;
29048         },
29049         enumerable: true,
29050         configurable: true
29051     });
29052     Object.defineProperty(NodeCache.prototype, "spatialEdges$", {
29053         /**
29054          * Get spatialEdges$.
29055          *
29056          * @returns {Observable<IEdgeStatus>} Observable emitting
29057          * values describing the status of the spatial edges.
29058          */
29059         get: function () {
29060             return this._spatialEdges$;
29061         },
29062         enumerable: true,
29063         configurable: true
29064     });
29065     /**
29066      * Cache the image and mesh assets.
29067      *
29068      * @param {string} key - Key of the node to cache.
29069      * @param {boolean} pano - Value indicating whether node is a panorama.
29070      * @param {boolean} merged - Value indicating whether node is merged.
29071      * @returns {Observable<NodeCache>} Observable emitting this node
29072      * cache whenever the load status has changed and when the mesh or image
29073      * has been fully loaded.
29074      */
29075     NodeCache.prototype.cacheAssets$ = function (key, pano, merged) {
29076         var _this = this;
29077         if (this._cachingAssets$ != null) {
29078             return this._cachingAssets$;
29079         }
29080         var imageSize = pano ?
29081             Utils_1.Settings.basePanoramaSize :
29082             Utils_1.Settings.baseImageSize;
29083         this._cachingAssets$ = Observable_1.Observable
29084             .combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged), function (imageStatus, meshStatus) {
29085             _this._loadStatus.loaded = 0;
29086             _this._loadStatus.total = 0;
29087             if (meshStatus) {
29088                 _this._mesh = meshStatus.object;
29089                 _this._loadStatus.loaded += meshStatus.loaded.loaded;
29090                 _this._loadStatus.total += meshStatus.loaded.total;
29091             }
29092             if (imageStatus) {
29093                 _this._image = imageStatus.object;
29094                 _this._loadStatus.loaded += imageStatus.loaded.loaded;
29095                 _this._loadStatus.total += imageStatus.loaded.total;
29096             }
29097             return _this;
29098         })
29099             .finally(function () {
29100             _this._cachingAssets$ = null;
29101         })
29102             .publishReplay(1)
29103             .refCount();
29104         return this._cachingAssets$;
29105     };
29106     /**
29107      * Cache an image with a higher resolution than the current one.
29108      *
29109      * @param {string} key - Key of the node to cache.
29110      * @param {ImageSize} imageSize - The size to cache.
29111      * @returns {Observable<NodeCache>} Observable emitting a single item,
29112      * the node cache, when the image has been cached. If supplied image
29113      * size is not larger than the current image size the node cache is
29114      * returned immediately.
29115      */
29116     NodeCache.prototype.cacheImage$ = function (key, imageSize) {
29117         var _this = this;
29118         if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) {
29119             return Observable_1.Observable.of(this);
29120         }
29121         return this._cacheImage$(key, imageSize)
29122             .first(function (status) {
29123             return status.object != null;
29124         })
29125             .do(function (status) {
29126             _this._disposeImage();
29127             _this._image = status.object;
29128         })
29129             .map(function (imageStatus) {
29130             return _this;
29131         });
29132     };
29133     /**
29134      * Cache the sequence edges.
29135      *
29136      * @param {Array<IEdge>} edges - Sequence edges to cache.
29137      */
29138     NodeCache.prototype.cacheSequenceEdges = function (edges) {
29139         this._sequenceEdges = { cached: true, edges: edges };
29140         this._sequenceEdgesChanged$.next(this._sequenceEdges);
29141     };
29142     /**
29143      * Cache the spatial edges.
29144      *
29145      * @param {Array<IEdge>} edges - Spatial edges to cache.
29146      */
29147     NodeCache.prototype.cacheSpatialEdges = function (edges) {
29148         this._spatialEdges = { cached: true, edges: edges };
29149         this._spatialEdgesChanged$.next(this._spatialEdges);
29150     };
29151     /**
29152      * Dispose the node cache.
29153      *
29154      * @description Disposes all cached assets and unsubscribes to
29155      * all streams.
29156      */
29157     NodeCache.prototype.dispose = function () {
29158         this._sequenceEdgesSubscription.unsubscribe();
29159         this._spatialEdgesSubscription.unsubscribe();
29160         this._disposeImage();
29161         this._mesh = null;
29162         this._loadStatus.loaded = 0;
29163         this._loadStatus.total = 0;
29164         this._sequenceEdges = { cached: false, edges: [] };
29165         this._spatialEdges = { cached: false, edges: [] };
29166         this._sequenceEdgesChanged$.next(this._sequenceEdges);
29167         this._spatialEdgesChanged$.next(this._spatialEdges);
29168         this._disposed = true;
29169         if (this._imageRequest != null) {
29170             this._imageRequest.abort();
29171         }
29172         if (this._meshRequest != null) {
29173             this._meshRequest.abort();
29174         }
29175     };
29176     /**
29177      * Reset the sequence edges.
29178      */
29179     NodeCache.prototype.resetSequenceEdges = function () {
29180         this._sequenceEdges = { cached: false, edges: [] };
29181         this._sequenceEdgesChanged$.next(this._sequenceEdges);
29182     };
29183     /**
29184      * Reset the spatial edges.
29185      */
29186     NodeCache.prototype.resetSpatialEdges = function () {
29187         this._spatialEdges = { cached: false, edges: [] };
29188         this._spatialEdgesChanged$.next(this._spatialEdges);
29189     };
29190     /**
29191      * Cache the image.
29192      *
29193      * @param {string} key - Key of the node to cache.
29194      * @param {boolean} pano - Value indicating whether node is a panorama.
29195      * @returns {Observable<ILoadStatusObject<HTMLImageElement>>} Observable
29196      * emitting a load status object every time the load status changes
29197      * and completes when the image is fully loaded.
29198      */
29199     NodeCache.prototype._cacheImage$ = function (key, imageSize) {
29200         var _this = this;
29201         return Observable_1.Observable.create(function (subscriber) {
29202             var image = new Image();
29203             image.crossOrigin = "Anonymous";
29204             var xmlHTTP = new XMLHttpRequest();
29205             xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize), true);
29206             xmlHTTP.responseType = "arraybuffer";
29207             xmlHTTP.onload = function (pe) {
29208                 if (xmlHTTP.status !== 200) {
29209                     _this._imageRequest = null;
29210                     subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
29211                     return;
29212                 }
29213                 image.onload = function (e) {
29214                     _this._imageRequest = null;
29215                     if (_this._disposed) {
29216                         window.URL.revokeObjectURL(image.src);
29217                         subscriber.error(new Error("Image load was aborted (" + key + ")"));
29218                         return;
29219                     }
29220                     subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
29221                     subscriber.complete();
29222                 };
29223                 image.onerror = function (error) {
29224                     _this._imageRequest = null;
29225                     subscriber.error(new Error("Failed to load image (" + key + ")"));
29226                 };
29227                 var blob = new Blob([xmlHTTP.response]);
29228                 image.src = window.URL.createObjectURL(blob);
29229             };
29230             xmlHTTP.onprogress = function (pe) {
29231                 if (_this._disposed) {
29232                     return;
29233                 }
29234                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
29235             };
29236             xmlHTTP.onerror = function (error) {
29237                 _this._imageRequest = null;
29238                 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
29239             };
29240             xmlHTTP.onabort = function (event) {
29241                 _this._imageRequest = null;
29242                 subscriber.error(new Error("Image request was aborted (" + key + ")"));
29243             };
29244             _this._imageRequest = xmlHTTP;
29245             xmlHTTP.send(null);
29246         });
29247     };
29248     /**
29249      * Cache the mesh.
29250      *
29251      * @param {string} key - Key of the node to cache.
29252      * @param {boolean} merged - Value indicating whether node is merged.
29253      * @returns {Observable<ILoadStatusObject<IMesh>>} Observable emitting
29254      * a load status object every time the load status changes and completes
29255      * when the mesh is fully loaded.
29256      */
29257     NodeCache.prototype._cacheMesh$ = function (key, merged) {
29258         var _this = this;
29259         return Observable_1.Observable.create(function (subscriber) {
29260             if (!merged) {
29261                 subscriber.next(_this._createEmptyMeshLoadStatus());
29262                 subscriber.complete();
29263                 return;
29264             }
29265             var xmlHTTP = new XMLHttpRequest();
29266             xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true);
29267             xmlHTTP.responseType = "arraybuffer";
29268             xmlHTTP.onload = function (pe) {
29269                 _this._meshRequest = null;
29270                 if (_this._disposed) {
29271                     return;
29272                 }
29273                 var mesh = xmlHTTP.status === 200 ?
29274                     Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) :
29275                     { faces: [], vertices: [] };
29276                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: mesh });
29277                 subscriber.complete();
29278             };
29279             xmlHTTP.onprogress = function (pe) {
29280                 if (_this._disposed) {
29281                     return;
29282                 }
29283                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
29284             };
29285             xmlHTTP.onerror = function (e) {
29286                 _this._meshRequest = null;
29287                 console.error("Failed to cache mesh (" + key + ")");
29288                 subscriber.next(_this._createEmptyMeshLoadStatus());
29289                 subscriber.complete();
29290             };
29291             xmlHTTP.onabort = function (event) {
29292                 _this._meshRequest = null;
29293                 subscriber.error(new Error("Mesh request was aborted (" + key + ")"));
29294             };
29295             _this._meshRequest = xmlHTTP;
29296             xmlHTTP.send(null);
29297         });
29298     };
29299     /**
29300      * Create a load status object with an empty mesh.
29301      *
29302      * @returns {ILoadStatusObject<IMesh>} Load status object
29303      * with empty mesh.
29304      */
29305     NodeCache.prototype._createEmptyMeshLoadStatus = function () {
29306         return {
29307             loaded: { loaded: 0, total: 0 },
29308             object: { faces: [], vertices: [] },
29309         };
29310     };
29311     NodeCache.prototype._disposeImage = function () {
29312         if (this._image != null) {
29313             window.URL.revokeObjectURL(this._image.src);
29314         }
29315         this._image = null;
29316     };
29317     return NodeCache;
29318 }());
29319 exports.NodeCache = NodeCache;
29320 Object.defineProperty(exports, "__esModule", { value: true });
29321 exports.default = NodeCache;
29322
29323 }).call(this,require("buffer").Buffer)
29324
29325 },{"../Graph":214,"../Utils":218,"buffer":5,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/publishReplay":68}],289:[function(require,module,exports){
29326 /// <reference path="../../typings/index.d.ts" />
29327 "use strict";
29328 var _ = require("underscore");
29329 /**
29330  * @class Sequence
29331  *
29332  * @classdesc Represents a sequence of ordered nodes.
29333  */
29334 var Sequence = (function () {
29335     /**
29336      * Create a new sequene instance.
29337      *
29338      * @param {ISequence} sequence - Raw sequence data.
29339      */
29340     function Sequence(sequence) {
29341         this._key = sequence.key;
29342         this._keys = sequence.keys;
29343     }
29344     Object.defineProperty(Sequence.prototype, "key", {
29345         /**
29346          * Get key.
29347          *
29348          * @returns {string} Unique sequence key.
29349          */
29350         get: function () {
29351             return this._key;
29352         },
29353         enumerable: true,
29354         configurable: true
29355     });
29356     Object.defineProperty(Sequence.prototype, "keys", {
29357         /**
29358          * Get keys.
29359          *
29360          * @returns {Array<string>} Array of ordered node keys in the sequence.
29361          */
29362         get: function () {
29363             return this._keys;
29364         },
29365         enumerable: true,
29366         configurable: true
29367     });
29368     /**
29369      * Find the next node key in the sequence with respect to
29370      * the provided node key.
29371      *
29372      * @param {string} key - Reference node key.
29373      * @returns {string} Next key in sequence if it exists, null otherwise.
29374      */
29375     Sequence.prototype.findNextKey = function (key) {
29376         var i = _.indexOf(this._keys, key);
29377         if ((i + 1) >= this._keys.length || i === -1) {
29378             return null;
29379         }
29380         else {
29381             return this._keys[i + 1];
29382         }
29383     };
29384     /**
29385      * Find the previous node key in the sequence with respect to
29386      * the provided node key.
29387      *
29388      * @param {string} key - Reference node key.
29389      * @returns {string} Previous key in sequence if it exists, null otherwise.
29390      */
29391     Sequence.prototype.findPrevKey = function (key) {
29392         var i = _.indexOf(this._keys, key);
29393         if (i === 0 || i === -1) {
29394             return null;
29395         }
29396         else {
29397             return this._keys[i - 1];
29398         }
29399     };
29400     return Sequence;
29401 }());
29402 exports.Sequence = Sequence;
29403 Object.defineProperty(exports, "__esModule", { value: true });
29404 exports.default = Sequence;
29405
29406 },{"underscore":161}],290:[function(require,module,exports){
29407 /// <reference path="../../../typings/index.d.ts" />
29408 "use strict";
29409 var THREE = require("three");
29410 var Edge_1 = require("../../Edge");
29411 var Error_1 = require("../../Error");
29412 var Geo_1 = require("../../Geo");
29413 /**
29414  * @class EdgeCalculator
29415  *
29416  * @classdesc Represents a class for calculating node edges.
29417  */
29418 var EdgeCalculator = (function () {
29419     /**
29420      * Create a new edge calculator instance.
29421      *
29422      * @param {EdgeCalculatorSettings} settings - Settings struct.
29423      * @param {EdgeCalculatorDirections} directions - Directions struct.
29424      * @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
29425      */
29426     function EdgeCalculator(settings, directions, coefficients) {
29427         this._spatial = new Geo_1.Spatial();
29428         this._geoCoords = new Geo_1.GeoCoords();
29429         this._settings = settings != null ? settings : new Edge_1.EdgeCalculatorSettings();
29430         this._directions = directions != null ? directions : new Edge_1.EdgeCalculatorDirections();
29431         this._coefficients = coefficients != null ? coefficients : new Edge_1.EdgeCalculatorCoefficients();
29432     }
29433     /**
29434      * Returns the potential edges to destination nodes for a set
29435      * of nodes with respect to a source node.
29436      *
29437      * @param {Node} node - Source node.
29438      * @param {Array<Node>} nodes - Potential destination nodes.
29439      * @param {Array<string>} fallbackKeys - Keys for destination nodes that should
29440      * be returned even if they do not meet the criteria for a potential edge.
29441      * @throws {ArgumentMapillaryError} If node is not full.
29442      */
29443     EdgeCalculator.prototype.getPotentialEdges = function (node, potentialNodes, fallbackKeys) {
29444         if (!node.full) {
29445             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
29446         }
29447         if (!node.merged) {
29448             return [];
29449         }
29450         var currentDirection = this._spatial.viewingDirection(node.rotation);
29451         var currentVerticalDirection = this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
29452         var potentialEdges = [];
29453         for (var _i = 0, potentialNodes_1 = potentialNodes; _i < potentialNodes_1.length; _i++) {
29454             var potential = potentialNodes_1[_i];
29455             if (!potential.merged ||
29456                 potential.key === node.key) {
29457                 continue;
29458             }
29459             var enu = this._geoCoords.geodeticToEnu(potential.latLon.lat, potential.latLon.lon, potential.alt, node.latLon.lat, node.latLon.lon, node.alt);
29460             var motion = new THREE.Vector3(enu[0], enu[1], enu[2]);
29461             var distance = motion.length();
29462             if (distance > this._settings.maxDistance &&
29463                 fallbackKeys.indexOf(potential.key) < 0) {
29464                 continue;
29465             }
29466             var motionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, motion.x, motion.y);
29467             var verticalMotion = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
29468             var direction = this._spatial.viewingDirection(potential.rotation);
29469             var directionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
29470             var verticalDirection = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
29471             var verticalDirectionChange = verticalDirection - currentVerticalDirection;
29472             var rotation = this._spatial.relativeRotationAngle(node.rotation, potential.rotation);
29473             var worldMotionAzimuth = this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
29474             var sameSequence = potential.sequenceKey != null &&
29475                 node.sequenceKey != null &&
29476                 potential.sequenceKey === node.sequenceKey;
29477             var sameMergeCC = (potential.mergeCC == null && node.mergeCC == null) ||
29478                 potential.mergeCC === node.mergeCC;
29479             var sameUser = potential.userKey === node.userKey;
29480             var potentialEdge = {
29481                 capturedAt: potential.capturedAt,
29482                 directionChange: directionChange,
29483                 distance: distance,
29484                 fullPano: potential.fullPano,
29485                 key: potential.key,
29486                 motionChange: motionChange,
29487                 rotation: rotation,
29488                 sameMergeCC: sameMergeCC,
29489                 sameSequence: sameSequence,
29490                 sameUser: sameUser,
29491                 sequenceKey: potential.sequenceKey,
29492                 verticalDirectionChange: verticalDirectionChange,
29493                 verticalMotion: verticalMotion,
29494                 worldMotionAzimuth: worldMotionAzimuth,
29495             };
29496             potentialEdges.push(potentialEdge);
29497         }
29498         return potentialEdges;
29499     };
29500     /**
29501      * Computes the sequence edges for a node.
29502      *
29503      * @param {Node} node - Source node.
29504      * @throws {ArgumentMapillaryError} If node is not full.
29505      */
29506     EdgeCalculator.prototype.computeSequenceEdges = function (node, sequence) {
29507         if (!node.full) {
29508             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
29509         }
29510         if (node.sequenceKey !== sequence.key) {
29511             throw new Error_1.ArgumentMapillaryError("Node and sequence does not correspond.");
29512         }
29513         var edges = [];
29514         var nextKey = sequence.findNextKey(node.key);
29515         if (nextKey != null) {
29516             edges.push({
29517                 data: {
29518                     direction: Edge_1.EdgeDirection.Next,
29519                     worldMotionAzimuth: Number.NaN,
29520                 },
29521                 from: node.key,
29522                 to: nextKey,
29523             });
29524         }
29525         var prevKey = sequence.findPrevKey(node.key);
29526         if (prevKey != null) {
29527             edges.push({
29528                 data: {
29529                     direction: Edge_1.EdgeDirection.Prev,
29530                     worldMotionAzimuth: Number.NaN,
29531                 },
29532                 from: node.key,
29533                 to: prevKey,
29534             });
29535         }
29536         return edges;
29537     };
29538     /**
29539      * Computes the similar edges for a node.
29540      *
29541      * @description Similar edges for perspective images and cropped panoramas
29542      * look roughly in the same direction and are positioned closed to the node.
29543      * Similar edges for full panoramas only target other full panoramas.
29544      *
29545      * @param {Node} node - Source node.
29546      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
29547      * @throws {ArgumentMapillaryError} If node is not full.
29548      */
29549     EdgeCalculator.prototype.computeSimilarEdges = function (node, potentialEdges) {
29550         var _this = this;
29551         if (!node.full) {
29552             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
29553         }
29554         var nodeFullPano = node.fullPano;
29555         var sequenceGroups = {};
29556         for (var _i = 0, potentialEdges_1 = potentialEdges; _i < potentialEdges_1.length; _i++) {
29557             var potentialEdge = potentialEdges_1[_i];
29558             if (potentialEdge.sequenceKey == null) {
29559                 continue;
29560             }
29561             if (potentialEdge.sameSequence ||
29562                 !potentialEdge.sameMergeCC) {
29563                 continue;
29564             }
29565             if (nodeFullPano) {
29566                 if (!potentialEdge.fullPano) {
29567                     continue;
29568                 }
29569             }
29570             else {
29571                 if (!potentialEdge.fullPano &&
29572                     Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
29573                     continue;
29574                 }
29575             }
29576             if (potentialEdge.distance > this._settings.similarMaxDistance) {
29577                 continue;
29578             }
29579             if (potentialEdge.sameUser &&
29580                 Math.abs(potentialEdge.capturedAt - node.capturedAt) <
29581                     this._settings.similarMinTimeDifference) {
29582                 continue;
29583             }
29584             if (sequenceGroups[potentialEdge.sequenceKey] == null) {
29585                 sequenceGroups[potentialEdge.sequenceKey] = [];
29586             }
29587             sequenceGroups[potentialEdge.sequenceKey].push(potentialEdge);
29588         }
29589         var similarEdges = [];
29590         var calculateScore = node.fullPano ?
29591             function (potentialEdge) {
29592                 return potentialEdge.distance;
29593             } :
29594             function (potentialEdge) {
29595                 return _this._coefficients.similarDistance * potentialEdge.distance +
29596                     _this._coefficients.similarRotation * potentialEdge.rotation;
29597             };
29598         for (var sequenceKey in sequenceGroups) {
29599             if (!sequenceGroups.hasOwnProperty(sequenceKey)) {
29600                 continue;
29601             }
29602             var lowestScore = Number.MAX_VALUE;
29603             var similarEdge = null;
29604             for (var _a = 0, _b = sequenceGroups[sequenceKey]; _a < _b.length; _a++) {
29605                 var potentialEdge = _b[_a];
29606                 var score = calculateScore(potentialEdge);
29607                 if (score < lowestScore) {
29608                     lowestScore = score;
29609                     similarEdge = potentialEdge;
29610                 }
29611             }
29612             if (similarEdge == null) {
29613                 continue;
29614             }
29615             similarEdges.push(similarEdge);
29616         }
29617         return similarEdges
29618             .map(function (potentialEdge) {
29619             return {
29620                 data: {
29621                     direction: Edge_1.EdgeDirection.Similar,
29622                     worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
29623                 },
29624                 from: node.key,
29625                 to: potentialEdge.key,
29626             };
29627         });
29628     };
29629     /**
29630      * Computes the step edges for a perspective node.
29631      *
29632      * @param {Node} node - Source node.
29633      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
29634      * @param {string} prevKey - Key of previous node in sequence.
29635      * @param {string} prevKey - Key of next node in sequence.
29636      * @throws {ArgumentMapillaryError} If node is not full.
29637      */
29638     EdgeCalculator.prototype.computeStepEdges = function (node, potentialEdges, prevKey, nextKey) {
29639         if (!node.full) {
29640             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
29641         }
29642         var edges = [];
29643         if (node.fullPano) {
29644             return edges;
29645         }
29646         for (var k in this._directions.steps) {
29647             if (!this._directions.steps.hasOwnProperty(k)) {
29648                 continue;
29649             }
29650             var step = this._directions.steps[k];
29651             var lowestScore = Number.MAX_VALUE;
29652             var edge = null;
29653             var fallback = null;
29654             for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) {
29655                 var potential = potentialEdges_2[_i];
29656                 if (potential.fullPano) {
29657                     continue;
29658                 }
29659                 if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
29660                     continue;
29661                 }
29662                 var motionDifference = this._spatial.angleDifference(step.motionChange, potential.motionChange);
29663                 var directionMotionDifference = this._spatial.angleDifference(potential.directionChange, motionDifference);
29664                 var drift = Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
29665                 if (Math.abs(drift) > this._settings.stepMaxDrift) {
29666                     continue;
29667                 }
29668                 var potentialKey = potential.key;
29669                 if (step.useFallback && (potentialKey === prevKey || potentialKey === nextKey)) {
29670                     fallback = potential;
29671                 }
29672                 if (potential.distance > this._settings.stepMaxDistance) {
29673                     continue;
29674                 }
29675                 motionDifference = Math.sqrt(motionDifference * motionDifference +
29676                     potential.verticalMotion * potential.verticalMotion);
29677                 var score = this._coefficients.stepPreferredDistance *
29678                     Math.abs(potential.distance - this._settings.stepPreferredDistance) /
29679                     this._settings.stepMaxDistance +
29680                     this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
29681                     this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
29682                     this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
29683                     this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
29684                 if (score < lowestScore) {
29685                     lowestScore = score;
29686                     edge = potential;
29687                 }
29688             }
29689             edge = edge == null ? fallback : edge;
29690             if (edge != null) {
29691                 edges.push({
29692                     data: {
29693                         direction: step.direction,
29694                         worldMotionAzimuth: edge.worldMotionAzimuth,
29695                     },
29696                     from: node.key,
29697                     to: edge.key,
29698                 });
29699             }
29700         }
29701         return edges;
29702     };
29703     /**
29704      * Computes the turn edges for a perspective node.
29705      *
29706      * @param {Node} node - Source node.
29707      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
29708      * @throws {ArgumentMapillaryError} If node is not full.
29709      */
29710     EdgeCalculator.prototype.computeTurnEdges = function (node, potentialEdges) {
29711         if (!node.full) {
29712             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
29713         }
29714         var edges = [];
29715         if (node.fullPano) {
29716             return edges;
29717         }
29718         for (var k in this._directions.turns) {
29719             if (!this._directions.turns.hasOwnProperty(k)) {
29720                 continue;
29721             }
29722             var turn = this._directions.turns[k];
29723             var lowestScore = Number.MAX_VALUE;
29724             var edge = null;
29725             for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) {
29726                 var potential = potentialEdges_3[_i];
29727                 if (potential.fullPano) {
29728                     continue;
29729                 }
29730                 if (potential.distance > this._settings.turnMaxDistance) {
29731                     continue;
29732                 }
29733                 var rig = turn.direction !== Edge_1.EdgeDirection.TurnU &&
29734                     potential.distance < this._settings.turnMaxRigDistance &&
29735                     Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
29736                 var directionDifference = this._spatial.angleDifference(turn.directionChange, potential.directionChange);
29737                 var score = void 0;
29738                 if (rig &&
29739                     potential.directionChange * turn.directionChange > 0 &&
29740                     Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
29741                     score = -Math.PI / 2 + Math.abs(potential.directionChange);
29742                 }
29743                 else {
29744                     if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
29745                         continue;
29746                     }
29747                     var motionDifference = turn.motionChange ?
29748                         this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
29749                     motionDifference = Math.sqrt(motionDifference * motionDifference +
29750                         potential.verticalMotion * potential.verticalMotion);
29751                     score =
29752                         this._coefficients.turnDistance * potential.distance /
29753                             this._settings.turnMaxDistance +
29754                             this._coefficients.turnMotion * motionDifference / Math.PI +
29755                             this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
29756                             this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
29757                 }
29758                 if (score < lowestScore) {
29759                     lowestScore = score;
29760                     edge = potential;
29761                 }
29762             }
29763             if (edge != null) {
29764                 edges.push({
29765                     data: {
29766                         direction: turn.direction,
29767                         worldMotionAzimuth: edge.worldMotionAzimuth,
29768                     },
29769                     from: node.key,
29770                     to: edge.key,
29771                 });
29772             }
29773         }
29774         return edges;
29775     };
29776     /**
29777      * Computes the pano edges for a perspective node.
29778      *
29779      * @param {Node} node - Source node.
29780      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
29781      * @throws {ArgumentMapillaryError} If node is not full.
29782      */
29783     EdgeCalculator.prototype.computePerspectiveToPanoEdges = function (node, potentialEdges) {
29784         if (!node.full) {
29785             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
29786         }
29787         if (node.fullPano) {
29788             return [];
29789         }
29790         var lowestScore = Number.MAX_VALUE;
29791         var edge = null;
29792         for (var _i = 0, potentialEdges_4 = potentialEdges; _i < potentialEdges_4.length; _i++) {
29793             var potential = potentialEdges_4[_i];
29794             if (!potential.fullPano) {
29795                 continue;
29796             }
29797             var score = this._coefficients.panoPreferredDistance *
29798                 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
29799                 this._settings.panoMaxDistance +
29800                 this._coefficients.panoMotion * Math.abs(potential.motionChange) / Math.PI +
29801                 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
29802             if (score < lowestScore) {
29803                 lowestScore = score;
29804                 edge = potential;
29805             }
29806         }
29807         if (edge == null) {
29808             return [];
29809         }
29810         return [
29811             {
29812                 data: {
29813                     direction: Edge_1.EdgeDirection.Pano,
29814                     worldMotionAzimuth: edge.worldMotionAzimuth,
29815                 },
29816                 from: node.key,
29817                 to: edge.key,
29818             },
29819         ];
29820     };
29821     /**
29822      * Computes the pano and step edges for a pano node.
29823      *
29824      * @param {Node} node - Source node.
29825      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
29826      * @throws {ArgumentMapillaryError} If node is not full.
29827      */
29828     EdgeCalculator.prototype.computePanoEdges = function (node, potentialEdges) {
29829         if (!node.full) {
29830             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
29831         }
29832         if (!node.fullPano) {
29833             return [];
29834         }
29835         var panoEdges = [];
29836         var potentialPanos = [];
29837         var potentialSteps = [];
29838         for (var _i = 0, potentialEdges_5 = potentialEdges; _i < potentialEdges_5.length; _i++) {
29839             var potential = potentialEdges_5[_i];
29840             if (potential.distance > this._settings.panoMaxDistance) {
29841                 continue;
29842             }
29843             if (potential.fullPano) {
29844                 if (potential.distance < this._settings.panoMinDistance) {
29845                     continue;
29846                 }
29847                 potentialPanos.push(potential);
29848             }
29849             else {
29850                 for (var k in this._directions.panos) {
29851                     if (!this._directions.panos.hasOwnProperty(k)) {
29852                         continue;
29853                     }
29854                     var pano = this._directions.panos[k];
29855                     var turn = this._spatial.angleDifference(potential.directionChange, potential.motionChange);
29856                     var turnChange = this._spatial.angleDifference(pano.directionChange, turn);
29857                     if (Math.abs(turnChange) > this._settings.panoMaxStepTurnChange) {
29858                         continue;
29859                     }
29860                     potentialSteps.push([pano.direction, potential]);
29861                     // break if step direction found
29862                     break;
29863                 }
29864             }
29865         }
29866         var maxRotationDifference = Math.PI / this._settings.panoMaxItems;
29867         var occupiedAngles = [];
29868         var stepAngles = [];
29869         for (var index = 0; index < this._settings.panoMaxItems; index++) {
29870             var rotation = index / this._settings.panoMaxItems * 2 * Math.PI;
29871             var lowestScore = Number.MAX_VALUE;
29872             var edge = null;
29873             for (var _a = 0, potentialPanos_1 = potentialPanos; _a < potentialPanos_1.length; _a++) {
29874                 var potential = potentialPanos_1[_a];
29875                 var motionDifference = this._spatial.angleDifference(rotation, potential.motionChange);
29876                 if (Math.abs(motionDifference) > maxRotationDifference) {
29877                     continue;
29878                 }
29879                 var occupiedDifference = Number.MAX_VALUE;
29880                 for (var _b = 0, occupiedAngles_1 = occupiedAngles; _b < occupiedAngles_1.length; _b++) {
29881                     var occupiedAngle = occupiedAngles_1[_b];
29882                     var difference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
29883                     if (difference < occupiedDifference) {
29884                         occupiedDifference = difference;
29885                     }
29886                 }
29887                 if (occupiedDifference <= maxRotationDifference) {
29888                     continue;
29889                 }
29890                 var score = this._coefficients.panoPreferredDistance *
29891                     Math.abs(potential.distance - this._settings.panoPreferredDistance) /
29892                     this._settings.panoMaxDistance +
29893                     this._coefficients.panoMotion * Math.abs(motionDifference) / maxRotationDifference +
29894                     this._coefficients.panoSequencePenalty * (potential.sameSequence ? 0 : 1) +
29895                     this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
29896                 if (score < lowestScore) {
29897                     lowestScore = score;
29898                     edge = potential;
29899                 }
29900             }
29901             if (edge != null) {
29902                 occupiedAngles.push(edge.motionChange);
29903                 panoEdges.push({
29904                     data: {
29905                         direction: Edge_1.EdgeDirection.Pano,
29906                         worldMotionAzimuth: edge.worldMotionAzimuth,
29907                     },
29908                     from: node.key,
29909                     to: edge.key,
29910                 });
29911             }
29912             else {
29913                 stepAngles.push(rotation);
29914             }
29915         }
29916         var occupiedStepAngles = {};
29917         occupiedStepAngles[Edge_1.EdgeDirection.Pano] = occupiedAngles;
29918         occupiedStepAngles[Edge_1.EdgeDirection.StepForward] = [];
29919         occupiedStepAngles[Edge_1.EdgeDirection.StepLeft] = [];
29920         occupiedStepAngles[Edge_1.EdgeDirection.StepBackward] = [];
29921         occupiedStepAngles[Edge_1.EdgeDirection.StepRight] = [];
29922         for (var _c = 0, stepAngles_1 = stepAngles; _c < stepAngles_1.length; _c++) {
29923             var stepAngle = stepAngles_1[_c];
29924             var occupations = [];
29925             for (var k in this._directions.panos) {
29926                 if (!this._directions.panos.hasOwnProperty(k)) {
29927                     continue;
29928                 }
29929                 var pano = this._directions.panos[k];
29930                 var allOccupiedAngles = occupiedStepAngles[Edge_1.EdgeDirection.Pano]
29931                     .concat(occupiedStepAngles[pano.direction])
29932                     .concat(occupiedStepAngles[pano.prev])
29933                     .concat(occupiedStepAngles[pano.next]);
29934                 var lowestScore = Number.MAX_VALUE;
29935                 var edge = null;
29936                 for (var _d = 0, potentialSteps_1 = potentialSteps; _d < potentialSteps_1.length; _d++) {
29937                     var potential = potentialSteps_1[_d];
29938                     if (potential[0] !== pano.direction) {
29939                         continue;
29940                     }
29941                     var motionChange = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
29942                     if (Math.abs(motionChange) > maxRotationDifference) {
29943                         continue;
29944                     }
29945                     var minOccupiedDifference = Number.MAX_VALUE;
29946                     for (var _e = 0, allOccupiedAngles_1 = allOccupiedAngles; _e < allOccupiedAngles_1.length; _e++) {
29947                         var occupiedAngle = allOccupiedAngles_1[_e];
29948                         var occupiedDifference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
29949                         if (occupiedDifference < minOccupiedDifference) {
29950                             minOccupiedDifference = occupiedDifference;
29951                         }
29952                     }
29953                     if (minOccupiedDifference <= maxRotationDifference) {
29954                         continue;
29955                     }
29956                     var score = this._coefficients.panoPreferredDistance *
29957                         Math.abs(potential[1].distance - this._settings.panoPreferredDistance) /
29958                         this._settings.panoMaxDistance +
29959                         this._coefficients.panoMotion * Math.abs(motionChange) / maxRotationDifference +
29960                         this._coefficients.panoMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
29961                     if (score < lowestScore) {
29962                         lowestScore = score;
29963                         edge = potential;
29964                     }
29965                 }
29966                 if (edge != null) {
29967                     occupations.push(edge);
29968                     panoEdges.push({
29969                         data: {
29970                             direction: edge[0],
29971                             worldMotionAzimuth: edge[1].worldMotionAzimuth,
29972                         },
29973                         from: node.key,
29974                         to: edge[1].key,
29975                     });
29976                 }
29977             }
29978             for (var _f = 0, occupations_1 = occupations; _f < occupations_1.length; _f++) {
29979                 var occupation = occupations_1[_f];
29980                 occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
29981             }
29982         }
29983         return panoEdges;
29984     };
29985     return EdgeCalculator;
29986 }());
29987 exports.EdgeCalculator = EdgeCalculator;
29988 Object.defineProperty(exports, "__esModule", { value: true });
29989 exports.default = EdgeCalculator;
29990
29991 },{"../../Edge":211,"../../Error":212,"../../Geo":213,"three":160}],291:[function(require,module,exports){
29992 "use strict";
29993 var EdgeCalculatorCoefficients = (function () {
29994     function EdgeCalculatorCoefficients() {
29995         this.panoPreferredDistance = 2;
29996         this.panoMotion = 2;
29997         this.panoSequencePenalty = 1;
29998         this.panoMergeCCPenalty = 4;
29999         this.stepPreferredDistance = 4;
30000         this.stepMotion = 3;
30001         this.stepRotation = 4;
30002         this.stepSequencePenalty = 2;
30003         this.stepMergeCCPenalty = 6;
30004         this.similarDistance = 2;
30005         this.similarRotation = 3;
30006         this.turnDistance = 4;
30007         this.turnMotion = 2;
30008         this.turnSequencePenalty = 1;
30009         this.turnMergeCCPenalty = 4;
30010     }
30011     return EdgeCalculatorCoefficients;
30012 }());
30013 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients;
30014 Object.defineProperty(exports, "__esModule", { value: true });
30015 exports.default = EdgeCalculatorCoefficients;
30016
30017 },{}],292:[function(require,module,exports){
30018 "use strict";
30019 var Edge_1 = require("../../Edge");
30020 var EdgeCalculatorDirections = (function () {
30021     function EdgeCalculatorDirections() {
30022         this.steps = {};
30023         this.turns = {};
30024         this.panos = {};
30025         this.steps[Edge_1.EdgeDirection.StepForward] = {
30026             direction: Edge_1.EdgeDirection.StepForward,
30027             motionChange: 0,
30028             useFallback: true,
30029         };
30030         this.steps[Edge_1.EdgeDirection.StepBackward] = {
30031             direction: Edge_1.EdgeDirection.StepBackward,
30032             motionChange: Math.PI,
30033             useFallback: true,
30034         };
30035         this.steps[Edge_1.EdgeDirection.StepLeft] = {
30036             direction: Edge_1.EdgeDirection.StepLeft,
30037             motionChange: Math.PI / 2,
30038             useFallback: false,
30039         };
30040         this.steps[Edge_1.EdgeDirection.StepRight] = {
30041             direction: Edge_1.EdgeDirection.StepRight,
30042             motionChange: -Math.PI / 2,
30043             useFallback: false,
30044         };
30045         this.turns[Edge_1.EdgeDirection.TurnLeft] = {
30046             direction: Edge_1.EdgeDirection.TurnLeft,
30047             directionChange: Math.PI / 2,
30048             motionChange: Math.PI / 4,
30049         };
30050         this.turns[Edge_1.EdgeDirection.TurnRight] = {
30051             direction: Edge_1.EdgeDirection.TurnRight,
30052             directionChange: -Math.PI / 2,
30053             motionChange: -Math.PI / 4,
30054         };
30055         this.turns[Edge_1.EdgeDirection.TurnU] = {
30056             direction: Edge_1.EdgeDirection.TurnU,
30057             directionChange: Math.PI,
30058             motionChange: null,
30059         };
30060         this.panos[Edge_1.EdgeDirection.StepForward] = {
30061             direction: Edge_1.EdgeDirection.StepForward,
30062             directionChange: 0,
30063             next: Edge_1.EdgeDirection.StepLeft,
30064             prev: Edge_1.EdgeDirection.StepRight,
30065         };
30066         this.panos[Edge_1.EdgeDirection.StepBackward] = {
30067             direction: Edge_1.EdgeDirection.StepBackward,
30068             directionChange: Math.PI,
30069             next: Edge_1.EdgeDirection.StepRight,
30070             prev: Edge_1.EdgeDirection.StepLeft,
30071         };
30072         this.panos[Edge_1.EdgeDirection.StepLeft] = {
30073             direction: Edge_1.EdgeDirection.StepLeft,
30074             directionChange: Math.PI / 2,
30075             next: Edge_1.EdgeDirection.StepBackward,
30076             prev: Edge_1.EdgeDirection.StepForward,
30077         };
30078         this.panos[Edge_1.EdgeDirection.StepRight] = {
30079             direction: Edge_1.EdgeDirection.StepRight,
30080             directionChange: -Math.PI / 2,
30081             next: Edge_1.EdgeDirection.StepForward,
30082             prev: Edge_1.EdgeDirection.StepBackward,
30083         };
30084     }
30085     return EdgeCalculatorDirections;
30086 }());
30087 exports.EdgeCalculatorDirections = EdgeCalculatorDirections;
30088
30089 },{"../../Edge":211}],293:[function(require,module,exports){
30090 "use strict";
30091 var EdgeCalculatorSettings = (function () {
30092     function EdgeCalculatorSettings() {
30093         this.panoMinDistance = 0.1;
30094         this.panoMaxDistance = 20;
30095         this.panoPreferredDistance = 5;
30096         this.panoMaxItems = 4;
30097         this.panoMaxStepTurnChange = Math.PI / 8;
30098         this.rotationMaxDistance = this.turnMaxRigDistance;
30099         this.rotationMaxDirectionChange = Math.PI / 6;
30100         this.rotationMaxVerticalDirectionChange = Math.PI / 8;
30101         this.similarMaxDirectionChange = Math.PI / 8;
30102         this.similarMaxDistance = 12;
30103         this.similarMinTimeDifference = 12 * 3600 * 1000;
30104         this.stepMaxDistance = 20;
30105         this.stepMaxDirectionChange = Math.PI / 6;
30106         this.stepMaxDrift = Math.PI / 6;
30107         this.stepPreferredDistance = 4;
30108         this.turnMaxDistance = 15;
30109         this.turnMaxDirectionChange = 2 * Math.PI / 9;
30110         this.turnMaxRigDistance = 0.65;
30111         this.turnMinRigDirectionChange = Math.PI / 6;
30112     }
30113     Object.defineProperty(EdgeCalculatorSettings.prototype, "maxDistance", {
30114         get: function () {
30115             return Math.max(this.panoMaxDistance, this.similarMaxDistance, this.stepMaxDistance, this.turnMaxDistance);
30116         },
30117         enumerable: true,
30118         configurable: true
30119     });
30120     return EdgeCalculatorSettings;
30121 }());
30122 exports.EdgeCalculatorSettings = EdgeCalculatorSettings;
30123 Object.defineProperty(exports, "__esModule", { value: true });
30124 exports.default = EdgeCalculatorSettings;
30125
30126 },{}],294:[function(require,module,exports){
30127 "use strict";
30128 /**
30129  * Enumeration for edge directions
30130  * @enum {number}
30131  * @readonly
30132  * @description Directions for edges in node graph describing
30133  * sequence, spatial and node type relations between nodes.
30134  */
30135 (function (EdgeDirection) {
30136     /**
30137      * Next node in the sequence.
30138      */
30139     EdgeDirection[EdgeDirection["Next"] = 0] = "Next";
30140     /**
30141      * Previous node in the sequence.
30142      */
30143     EdgeDirection[EdgeDirection["Prev"] = 1] = "Prev";
30144     /**
30145      * Step to the left keeping viewing direction.
30146      */
30147     EdgeDirection[EdgeDirection["StepLeft"] = 2] = "StepLeft";
30148     /**
30149      * Step to the right keeping viewing direction.
30150      */
30151     EdgeDirection[EdgeDirection["StepRight"] = 3] = "StepRight";
30152     /**
30153      * Step forward keeping viewing direction.
30154      */
30155     EdgeDirection[EdgeDirection["StepForward"] = 4] = "StepForward";
30156     /**
30157      * Step backward keeping viewing direction.
30158      */
30159     EdgeDirection[EdgeDirection["StepBackward"] = 5] = "StepBackward";
30160     /**
30161      * Turn 90 degrees counter clockwise.
30162      */
30163     EdgeDirection[EdgeDirection["TurnLeft"] = 6] = "TurnLeft";
30164     /**
30165      * Turn 90 degrees clockwise.
30166      */
30167     EdgeDirection[EdgeDirection["TurnRight"] = 7] = "TurnRight";
30168     /**
30169      * Turn 180 degrees.
30170      */
30171     EdgeDirection[EdgeDirection["TurnU"] = 8] = "TurnU";
30172     /**
30173      * Panorama in general direction.
30174      */
30175     EdgeDirection[EdgeDirection["Pano"] = 9] = "Pano";
30176     /**
30177      * Looking in roughly the same direction at rougly the same position.
30178      */
30179     EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar";
30180 })(exports.EdgeDirection || (exports.EdgeDirection = {}));
30181 var EdgeDirection = exports.EdgeDirection;
30182 ;
30183
30184 },{}],295:[function(require,module,exports){
30185 /// <reference path="../../typings/index.d.ts" />
30186 "use strict";
30187 var _ = require("underscore");
30188 var vd = require("virtual-dom");
30189 var Subject_1 = require("rxjs/Subject");
30190 require("rxjs/add/operator/combineLatest");
30191 require("rxjs/add/operator/distinctUntilChanged");
30192 require("rxjs/add/operator/filter");
30193 require("rxjs/add/operator/map");
30194 require("rxjs/add/operator/pluck");
30195 require("rxjs/add/operator/scan");
30196 var Render_1 = require("../Render");
30197 var DOMRenderer = (function () {
30198     function DOMRenderer(element, renderService, currentFrame$) {
30199         this._adaptiveOperation$ = new Subject_1.Subject();
30200         this._render$ = new Subject_1.Subject();
30201         this._renderAdaptive$ = new Subject_1.Subject();
30202         this._renderService = renderService;
30203         this._currentFrame$ = currentFrame$;
30204         var rootNode = vd.create(vd.h("div.domRenderer", []));
30205         element.appendChild(rootNode);
30206         this._offset$ = this._adaptiveOperation$
30207             .scan(function (adaptive, operation) {
30208             return operation(adaptive);
30209         }, {
30210             elementHeight: element.offsetHeight,
30211             elementWidth: element.offsetWidth,
30212             imageAspect: 0,
30213             renderMode: Render_1.RenderMode.Fill,
30214         })
30215             .filter(function (adaptive) {
30216             return adaptive.imageAspect > 0 && adaptive.elementWidth > 0 && adaptive.elementHeight > 0;
30217         })
30218             .map(function (adaptive) {
30219             var elementAspect = adaptive.elementWidth / adaptive.elementHeight;
30220             var ratio = adaptive.imageAspect / elementAspect;
30221             var verticalOffset = 0;
30222             var horizontalOffset = 0;
30223             if (adaptive.renderMode === Render_1.RenderMode.Letterbox) {
30224                 if (adaptive.imageAspect > elementAspect) {
30225                     verticalOffset = adaptive.elementHeight * (1 - 1 / ratio) / 2;
30226                 }
30227                 else {
30228                     horizontalOffset = adaptive.elementWidth * (1 - ratio) / 2;
30229                 }
30230             }
30231             else {
30232                 if (adaptive.imageAspect > elementAspect) {
30233                     horizontalOffset = -adaptive.elementWidth * (ratio - 1) / 2;
30234                 }
30235                 else {
30236                     verticalOffset = -adaptive.elementHeight * (1 / ratio - 1) / 2;
30237                 }
30238             }
30239             return {
30240                 bottom: verticalOffset,
30241                 left: horizontalOffset,
30242                 right: horizontalOffset,
30243                 top: verticalOffset,
30244             };
30245         });
30246         this._currentFrame$
30247             .filter(function (frame) {
30248             return frame.state.currentNode != null;
30249         })
30250             .distinctUntilChanged(function (k1, k2) {
30251             return k1 === k2;
30252         }, function (frame) {
30253             return frame.state.currentNode.key;
30254         })
30255             .map(function (frame) {
30256             return frame.state.currentTransform.basicAspect;
30257         })
30258             .map(function (aspect) {
30259             return function (adaptive) {
30260                 adaptive.imageAspect = aspect;
30261                 return adaptive;
30262             };
30263         })
30264             .subscribe(this._adaptiveOperation$);
30265         this._renderAdaptive$
30266             .scan(function (vNodeHashes, vNodeHash) {
30267             if (vNodeHash.vnode == null) {
30268                 delete vNodeHashes[vNodeHash.name];
30269             }
30270             else {
30271                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
30272             }
30273             return vNodeHashes;
30274         }, {})
30275             .combineLatest(this._offset$)
30276             .map(function (vo) {
30277             var vNodes = _.values(vo[0]);
30278             var offset = vo[1];
30279             var properties = {
30280                 style: {
30281                     bottom: offset.bottom + "px",
30282                     left: offset.left + "px",
30283                     position: "absolute",
30284                     right: offset.right + "px",
30285                     top: offset.top + "px",
30286                     zIndex: -1,
30287                 },
30288             };
30289             return {
30290                 name: "adaptiveDomRenderer",
30291                 vnode: vd.h("div.adaptiveDomRenderer", properties, vNodes),
30292             };
30293         })
30294             .subscribe(this._render$);
30295         this._vNode$ = this._render$
30296             .scan(function (vNodeHashes, vNodeHash) {
30297             if (vNodeHash.vnode == null) {
30298                 delete vNodeHashes[vNodeHash.name];
30299             }
30300             else {
30301                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
30302             }
30303             return vNodeHashes;
30304         }, {})
30305             .map(function (vNodeHashes) {
30306             var vNodes = _.values(vNodeHashes);
30307             return vd.h("div.domRenderer", vNodes);
30308         });
30309         this._vPatch$ = this._vNode$
30310             .scan(function (nodePatch, vNode) {
30311             nodePatch.vpatch = vd.diff(nodePatch.vnode, vNode);
30312             nodePatch.vnode = vNode;
30313             return nodePatch;
30314         }, { vnode: vd.h("div.domRenderer", []), vpatch: null })
30315             .pluck("vpatch");
30316         this._element$ = this._vPatch$
30317             .scan(function (oldElement, vPatch) {
30318             return vd.patch(oldElement, vPatch);
30319         }, rootNode)
30320             .publishReplay(1)
30321             .refCount();
30322         this._element$.subscribe();
30323         this._renderService.size$
30324             .map(function (size) {
30325             return function (adaptive) {
30326                 adaptive.elementWidth = size.width;
30327                 adaptive.elementHeight = size.height;
30328                 return adaptive;
30329             };
30330         })
30331             .subscribe(this._adaptiveOperation$);
30332         this._renderService.renderMode$
30333             .map(function (renderMode) {
30334             return function (adaptive) {
30335                 adaptive.renderMode = renderMode;
30336                 return adaptive;
30337             };
30338         })
30339             .subscribe(this._adaptiveOperation$);
30340     }
30341     Object.defineProperty(DOMRenderer.prototype, "element$", {
30342         get: function () {
30343             return this._element$;
30344         },
30345         enumerable: true,
30346         configurable: true
30347     });
30348     Object.defineProperty(DOMRenderer.prototype, "render$", {
30349         get: function () {
30350             return this._render$;
30351         },
30352         enumerable: true,
30353         configurable: true
30354     });
30355     Object.defineProperty(DOMRenderer.prototype, "renderAdaptive$", {
30356         get: function () {
30357             return this._renderAdaptive$;
30358         },
30359         enumerable: true,
30360         configurable: true
30361     });
30362     DOMRenderer.prototype.clear = function (name) {
30363         this._renderAdaptive$.next({ name: name, vnode: null });
30364         this._render$.next({ name: name, vnode: null });
30365     };
30366     return DOMRenderer;
30367 }());
30368 exports.DOMRenderer = DOMRenderer;
30369 Object.defineProperty(exports, "__esModule", { value: true });
30370 exports.default = DOMRenderer;
30371
30372 },{"../Render":216,"rxjs/Subject":33,"rxjs/add/operator/combineLatest":50,"rxjs/add/operator/distinctUntilChanged":54,"rxjs/add/operator/filter":57,"rxjs/add/operator/map":61,"rxjs/add/operator/pluck":66,"rxjs/add/operator/scan":69,"underscore":161,"virtual-dom":166}],296:[function(require,module,exports){
30373 "use strict";
30374 (function (GLRenderStage) {
30375     GLRenderStage[GLRenderStage["Background"] = 0] = "Background";
30376     GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground";
30377 })(exports.GLRenderStage || (exports.GLRenderStage = {}));
30378 var GLRenderStage = exports.GLRenderStage;
30379 Object.defineProperty(exports, "__esModule", { value: true });
30380 exports.default = GLRenderStage;
30381
30382 },{}],297:[function(require,module,exports){
30383 /// <reference path="../../typings/index.d.ts" />
30384 "use strict";
30385 var THREE = require("three");
30386 var Observable_1 = require("rxjs/Observable");
30387 var Subject_1 = require("rxjs/Subject");
30388 require("rxjs/add/observable/combineLatest");
30389 require("rxjs/add/operator/distinctUntilChanged");
30390 require("rxjs/add/operator/filter");
30391 require("rxjs/add/operator/first");
30392 require("rxjs/add/operator/map");
30393 require("rxjs/add/operator/merge");
30394 require("rxjs/add/operator/mergeMap");
30395 require("rxjs/add/operator/scan");
30396 require("rxjs/add/operator/share");
30397 require("rxjs/add/operator/startWith");
30398 var Render_1 = require("../Render");
30399 var GLRenderer = (function () {
30400     function GLRenderer(renderService) {
30401         var _this = this;
30402         this._renderFrame$ = new Subject_1.Subject();
30403         this._renderCameraOperation$ = new Subject_1.Subject();
30404         this._render$ = new Subject_1.Subject();
30405         this._clear$ = new Subject_1.Subject();
30406         this._renderOperation$ = new Subject_1.Subject();
30407         this._rendererOperation$ = new Subject_1.Subject();
30408         this._eraserOperation$ = new Subject_1.Subject();
30409         this._renderService = renderService;
30410         this._renderer$ = this._rendererOperation$
30411             .scan(function (renderer, operation) {
30412             return operation(renderer);
30413         }, { needsRender: false, renderer: null });
30414         this._renderCollection$ = this._renderOperation$
30415             .scan(function (hashes, operation) {
30416             return operation(hashes);
30417         }, {})
30418             .share();
30419         this._renderCamera$ = this._renderCameraOperation$
30420             .scan(function (rc, operation) {
30421             return operation(rc);
30422         }, { frameId: -1, needsRender: false, perspective: null });
30423         this._eraser$ = this._eraserOperation$
30424             .startWith(function (eraser) {
30425             return eraser;
30426         })
30427             .scan(function (eraser, operation) {
30428             return operation(eraser);
30429         }, { needsRender: false });
30430         Observable_1.Observable
30431             .combineLatest([this._renderer$, this._renderCollection$, this._renderCamera$, this._eraser$], function (renderer, hashes, rc, eraser) {
30432             var renders = Object.keys(hashes)
30433                 .map(function (key) {
30434                 return hashes[key];
30435             });
30436             return { camera: rc, eraser: eraser, renderer: renderer, renders: renders };
30437         })
30438             .filter(function (co) {
30439             var needsRender = co.renderer.needsRender ||
30440                 co.camera.needsRender ||
30441                 co.eraser.needsRender;
30442             var frameId = co.camera.frameId;
30443             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
30444                 var render = _a[_i];
30445                 if (render.frameId !== frameId) {
30446                     return false;
30447                 }
30448                 needsRender = needsRender || render.needsRender;
30449             }
30450             return needsRender;
30451         })
30452             .distinctUntilChanged(function (n1, n2) {
30453             return n1 === n2;
30454         }, function (co) {
30455             return co.eraser.needsRender ? -1 : co.camera.frameId;
30456         })
30457             .subscribe(function (co) {
30458             co.renderer.needsRender = false;
30459             co.camera.needsRender = false;
30460             co.eraser.needsRender = false;
30461             var perspectiveCamera = co.camera.perspective;
30462             var backgroundRenders = [];
30463             var foregroundRenders = [];
30464             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
30465                 var render = _a[_i];
30466                 if (render.stage === Render_1.GLRenderStage.Background) {
30467                     backgroundRenders.push(render.render);
30468                 }
30469                 else if (render.stage === Render_1.GLRenderStage.Foreground) {
30470                     foregroundRenders.push(render.render);
30471                 }
30472             }
30473             var renderer = co.renderer.renderer;
30474             renderer.autoClear = false;
30475             renderer.clear();
30476             for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) {
30477                 var render = backgroundRenders_1[_b];
30478                 render(perspectiveCamera, renderer);
30479             }
30480             renderer.clearDepth();
30481             for (var _c = 0, foregroundRenders_1 = foregroundRenders; _c < foregroundRenders_1.length; _c++) {
30482                 var render = foregroundRenders_1[_c];
30483                 render(perspectiveCamera, renderer);
30484             }
30485         });
30486         this._renderFrame$
30487             .map(function (rc) {
30488             return function (irc) {
30489                 irc.frameId = rc.frameId;
30490                 irc.perspective = rc.perspective;
30491                 if (rc.changed === true) {
30492                     irc.needsRender = true;
30493                 }
30494                 return irc;
30495             };
30496         })
30497             .subscribe(this._renderCameraOperation$);
30498         this._renderFrameSubscribe();
30499         var renderHash$ = this._render$
30500             .map(function (hash) {
30501             return function (hashes) {
30502                 hashes[hash.name] = hash.render;
30503                 return hashes;
30504             };
30505         });
30506         var clearHash$ = this._clear$
30507             .map(function (name) {
30508             return function (hashes) {
30509                 delete hashes[name];
30510                 return hashes;
30511             };
30512         });
30513         Observable_1.Observable
30514             .merge(renderHash$, clearHash$)
30515             .subscribe(this._renderOperation$);
30516         var createRenderer$ = this._render$
30517             .first()
30518             .map(function (hash) {
30519             return function (renderer) {
30520                 var webGLRenderer = new THREE.WebGLRenderer();
30521                 var element = renderService.element;
30522                 webGLRenderer.setSize(element.offsetWidth, element.offsetHeight);
30523                 webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0);
30524                 webGLRenderer.sortObjects = false;
30525                 webGLRenderer.domElement.style.width = "100%";
30526                 webGLRenderer.domElement.style.height = "100%";
30527                 element.appendChild(webGLRenderer.domElement);
30528                 renderer.needsRender = true;
30529                 renderer.renderer = webGLRenderer;
30530                 return renderer;
30531             };
30532         });
30533         var resizeRenderer$ = this._renderService.size$
30534             .map(function (size) {
30535             return function (renderer) {
30536                 if (renderer.renderer == null) {
30537                     return renderer;
30538                 }
30539                 renderer.renderer.setSize(size.width, size.height);
30540                 renderer.needsRender = true;
30541                 return renderer;
30542             };
30543         });
30544         var clearRenderer$ = this._clear$
30545             .map(function (name) {
30546             return function (renderer) {
30547                 if (renderer.renderer == null) {
30548                     return renderer;
30549                 }
30550                 renderer.needsRender = true;
30551                 return renderer;
30552             };
30553         });
30554         Observable_1.Observable
30555             .merge(createRenderer$, resizeRenderer$, clearRenderer$)
30556             .subscribe(this._rendererOperation$);
30557         var renderCollectionEmpty$ = this._renderCollection$
30558             .filter(function (hashes) {
30559             return Object.keys(hashes).length === 0;
30560         })
30561             .share();
30562         renderCollectionEmpty$
30563             .subscribe(function (hashes) {
30564             if (_this._renderFrameSubscription == null) {
30565                 return;
30566             }
30567             _this._renderFrameSubscription.unsubscribe();
30568             _this._renderFrameSubscription = null;
30569             _this._renderFrameSubscribe();
30570         });
30571         renderCollectionEmpty$
30572             .map(function (hashes) {
30573             return function (eraser) {
30574                 eraser.needsRender = true;
30575                 return eraser;
30576             };
30577         })
30578             .subscribe(this._eraserOperation$);
30579     }
30580     Object.defineProperty(GLRenderer.prototype, "render$", {
30581         get: function () {
30582             return this._render$;
30583         },
30584         enumerable: true,
30585         configurable: true
30586     });
30587     GLRenderer.prototype.clear = function (name) {
30588         this._clear$.next(name);
30589     };
30590     GLRenderer.prototype._renderFrameSubscribe = function () {
30591         var _this = this;
30592         this._render$
30593             .first()
30594             .map(function (renderHash) {
30595             return function (irc) {
30596                 irc.needsRender = true;
30597                 return irc;
30598             };
30599         })
30600             .subscribe(function (operation) {
30601             _this._renderCameraOperation$.next(operation);
30602         });
30603         this._renderFrameSubscription = this._render$
30604             .first()
30605             .mergeMap(function (hash) {
30606             return _this._renderService.renderCameraFrame$;
30607         })
30608             .subscribe(this._renderFrame$);
30609     };
30610     return GLRenderer;
30611 }());
30612 exports.GLRenderer = GLRenderer;
30613 Object.defineProperty(exports, "__esModule", { value: true });
30614 exports.default = GLRenderer;
30615
30616 },{"../Render":216,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":54,"rxjs/add/operator/filter":57,"rxjs/add/operator/first":59,"rxjs/add/operator/map":61,"rxjs/add/operator/merge":62,"rxjs/add/operator/mergeMap":64,"rxjs/add/operator/scan":69,"rxjs/add/operator/share":70,"rxjs/add/operator/startWith":73,"three":160}],298:[function(require,module,exports){
30617 /// <reference path="../../typings/index.d.ts" />
30618 "use strict";
30619 var THREE = require("three");
30620 var Geo_1 = require("../Geo");
30621 var Render_1 = require("../Render");
30622 var RenderCamera = (function () {
30623     function RenderCamera(perspectiveCameraAspect, renderMode) {
30624         this.alpha = -1;
30625         this.zoom = 0;
30626         this._frameId = -1;
30627         this._changed = false;
30628         this._changedForFrame = -1;
30629         this.currentAspect = 1;
30630         this.currentPano = false;
30631         this.previousAspect = 1;
30632         this.previousPano = false;
30633         this.renderMode = renderMode;
30634         this._camera = new Geo_1.Camera();
30635         this._perspective = new THREE.PerspectiveCamera(50, perspectiveCameraAspect, 0.4, 10000);
30636     }
30637     Object.defineProperty(RenderCamera.prototype, "perspective", {
30638         get: function () {
30639             return this._perspective;
30640         },
30641         enumerable: true,
30642         configurable: true
30643     });
30644     Object.defineProperty(RenderCamera.prototype, "camera", {
30645         get: function () {
30646             return this._camera;
30647         },
30648         enumerable: true,
30649         configurable: true
30650     });
30651     Object.defineProperty(RenderCamera.prototype, "changed", {
30652         get: function () {
30653             return this.frameId === this._changedForFrame;
30654         },
30655         enumerable: true,
30656         configurable: true
30657     });
30658     Object.defineProperty(RenderCamera.prototype, "frameId", {
30659         get: function () {
30660             return this._frameId;
30661         },
30662         set: function (value) {
30663             this._frameId = value;
30664             if (this._changed) {
30665                 this._changed = false;
30666                 this._changedForFrame = value;
30667             }
30668         },
30669         enumerable: true,
30670         configurable: true
30671     });
30672     RenderCamera.prototype.updateProjection = function () {
30673         var currentAspect = this._getAspect(this.currentAspect, this.currentPano, this.perspective.aspect);
30674         var previousAspect = this._getAspect(this.previousAspect, this.previousPano, this.perspective.aspect);
30675         var aspect = (1 - this.alpha) * previousAspect + this.alpha * currentAspect;
30676         var verticalFov = this._getVerticalFov(aspect, this._camera.focal, this.zoom);
30677         this._perspective.fov = verticalFov;
30678         this._perspective.updateProjectionMatrix();
30679         this._changed = true;
30680     };
30681     RenderCamera.prototype.updatePerspective = function (camera) {
30682         this._perspective.up.copy(camera.up);
30683         this._perspective.position.copy(camera.position);
30684         this._perspective.lookAt(camera.lookat);
30685         this._changed = true;
30686     };
30687     RenderCamera.prototype._getVerticalFov = function (aspect, focal, zoom) {
30688         return 2 * Math.atan(0.5 / (Math.pow(2, zoom) * aspect * focal)) * 180 / Math.PI;
30689     };
30690     RenderCamera.prototype._getAspect = function (nodeAspect, pano, perspectiveCameraAspect) {
30691         if (pano) {
30692             return 1;
30693         }
30694         var coeff = Math.max(1, 1 / nodeAspect);
30695         var usePerspective = this.renderMode === Render_1.RenderMode.Letterbox ?
30696             nodeAspect > perspectiveCameraAspect :
30697             nodeAspect < perspectiveCameraAspect;
30698         var aspect = usePerspective ?
30699             coeff * perspectiveCameraAspect :
30700             coeff * nodeAspect;
30701         return aspect;
30702     };
30703     return RenderCamera;
30704 }());
30705 exports.RenderCamera = RenderCamera;
30706 Object.defineProperty(exports, "__esModule", { value: true });
30707 exports.default = RenderCamera;
30708
30709 },{"../Geo":213,"../Render":216,"three":160}],299:[function(require,module,exports){
30710 "use strict";
30711 /**
30712  * Enumeration for render mode
30713  * @enum {number}
30714  * @readonly
30715  * @description Modes for specifying how rendering is done
30716  * in the viewer. All modes preserves the original aspect
30717  * ratio of the images.
30718  */
30719 (function (RenderMode) {
30720     /**
30721      * Displays all content within the viewer.
30722      *
30723      * @description Black bars shown on both
30724      * sides of the content. Bars are shown
30725      * either below and above or to the left
30726      * and right of the content depending on
30727      * the aspect ratio relation between the
30728      * image and the viewer.
30729      */
30730     RenderMode[RenderMode["Letterbox"] = 0] = "Letterbox";
30731     /**
30732      * Fills the viewer by cropping content.
30733      *
30734      * @description Cropping is done either
30735      * in horizontal or vertical direction
30736      * depending on the aspect ratio relation
30737      * between the image and the viewer.
30738      */
30739     RenderMode[RenderMode["Fill"] = 1] = "Fill";
30740 })(exports.RenderMode || (exports.RenderMode = {}));
30741 var RenderMode = exports.RenderMode;
30742 Object.defineProperty(exports, "__esModule", { value: true });
30743 exports.default = RenderMode;
30744
30745 },{}],300:[function(require,module,exports){
30746 /// <reference path="../../typings/index.d.ts" />
30747 "use strict";
30748 var Subject_1 = require("rxjs/Subject");
30749 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
30750 require("rxjs/add/observable/combineLatest");
30751 require("rxjs/add/operator/do");
30752 require("rxjs/add/operator/filter");
30753 require("rxjs/add/operator/map");
30754 require("rxjs/add/operator/publishReplay");
30755 require("rxjs/add/operator/scan");
30756 require("rxjs/add/operator/skip");
30757 require("rxjs/add/operator/startWith");
30758 require("rxjs/add/operator/withLatestFrom");
30759 var Render_1 = require("../Render");
30760 var RenderService = (function () {
30761     function RenderService(element, currentFrame$, renderMode) {
30762         var _this = this;
30763         this._element = element;
30764         this._currentFrame$ = currentFrame$;
30765         renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill;
30766         this._resize$ = new Subject_1.Subject();
30767         this._renderCameraOperation$ = new Subject_1.Subject();
30768         this._size$ =
30769             new BehaviorSubject_1.BehaviorSubject({
30770                 height: this._element.offsetHeight,
30771                 width: this._element.offsetWidth,
30772             });
30773         this._resize$
30774             .map(function () {
30775             return { height: _this._element.offsetHeight, width: _this._element.offsetWidth };
30776         })
30777             .subscribe(this._size$);
30778         this._renderMode$ = new BehaviorSubject_1.BehaviorSubject(renderMode);
30779         this._renderCameraHolder$ = this._renderCameraOperation$
30780             .startWith(function (rc) {
30781             return rc;
30782         })
30783             .scan(function (rc, operation) {
30784             return operation(rc);
30785         }, new Render_1.RenderCamera(this._element.offsetWidth / this._element.offsetHeight, renderMode))
30786             .publishReplay(1)
30787             .refCount();
30788         this._renderCameraFrame$ = this._currentFrame$
30789             .withLatestFrom(this._renderCameraHolder$, function (frame, renderCamera) {
30790             return [frame, renderCamera];
30791         })
30792             .do(function (args) {
30793             var frame = args[0];
30794             var rc = args[1];
30795             var camera = frame.state.camera;
30796             if (rc.alpha !== frame.state.alpha ||
30797                 rc.zoom !== frame.state.zoom ||
30798                 rc.camera.diff(camera) > 1e-5) {
30799                 var currentTransform = frame.state.currentTransform;
30800                 var previousTransform = frame.state.previousTransform != null ?
30801                     frame.state.previousTransform :
30802                     frame.state.currentTransform;
30803                 var previousNode = frame.state.previousNode != null ?
30804                     frame.state.previousNode :
30805                     frame.state.currentNode;
30806                 rc.currentAspect = currentTransform.basicAspect;
30807                 rc.currentPano = frame.state.currentNode.pano;
30808                 rc.previousAspect = previousTransform.basicAspect;
30809                 rc.previousPano = previousNode.pano;
30810                 rc.alpha = frame.state.alpha;
30811                 rc.zoom = frame.state.zoom;
30812                 rc.camera.copy(camera);
30813                 rc.updatePerspective(camera);
30814                 rc.updateProjection();
30815             }
30816             rc.frameId = frame.id;
30817         })
30818             .map(function (args) {
30819             return args[1];
30820         })
30821             .publishReplay(1)
30822             .refCount();
30823         this._renderCamera$ = this._renderCameraFrame$
30824             .filter(function (rc) {
30825             return rc.changed;
30826         })
30827             .publishReplay(1)
30828             .refCount();
30829         this._size$
30830             .skip(1)
30831             .map(function (size) {
30832             return function (rc) {
30833                 rc.perspective.aspect = size.width / size.height;
30834                 rc.updateProjection();
30835                 return rc;
30836             };
30837         })
30838             .subscribe(this._renderCameraOperation$);
30839         this._renderMode$
30840             .skip(1)
30841             .map(function (rm) {
30842             return function (rc) {
30843                 rc.renderMode = rm;
30844                 rc.updateProjection();
30845                 return rc;
30846             };
30847         })
30848             .subscribe(this._renderCameraOperation$);
30849         this._renderCameraHolder$.subscribe();
30850         this._size$.subscribe();
30851         this._renderMode$.subscribe();
30852     }
30853     Object.defineProperty(RenderService.prototype, "element", {
30854         get: function () {
30855             return this._element;
30856         },
30857         enumerable: true,
30858         configurable: true
30859     });
30860     Object.defineProperty(RenderService.prototype, "resize$", {
30861         get: function () {
30862             return this._resize$;
30863         },
30864         enumerable: true,
30865         configurable: true
30866     });
30867     Object.defineProperty(RenderService.prototype, "size$", {
30868         get: function () {
30869             return this._size$;
30870         },
30871         enumerable: true,
30872         configurable: true
30873     });
30874     Object.defineProperty(RenderService.prototype, "renderMode$", {
30875         get: function () {
30876             return this._renderMode$;
30877         },
30878         enumerable: true,
30879         configurable: true
30880     });
30881     Object.defineProperty(RenderService.prototype, "renderCameraFrame$", {
30882         get: function () {
30883             return this._renderCameraFrame$;
30884         },
30885         enumerable: true,
30886         configurable: true
30887     });
30888     Object.defineProperty(RenderService.prototype, "renderCamera$", {
30889         get: function () {
30890             return this._renderCamera$;
30891         },
30892         enumerable: true,
30893         configurable: true
30894     });
30895     return RenderService;
30896 }());
30897 exports.RenderService = RenderService;
30898 Object.defineProperty(exports, "__esModule", { value: true });
30899 exports.default = RenderService;
30900
30901 },{"../Render":216,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/do":55,"rxjs/add/operator/filter":57,"rxjs/add/operator/map":61,"rxjs/add/operator/publishReplay":68,"rxjs/add/operator/scan":69,"rxjs/add/operator/skip":71,"rxjs/add/operator/startWith":73,"rxjs/add/operator/withLatestFrom":77}],301:[function(require,module,exports){
30902 "use strict";
30903 (function (State) {
30904     State[State["Traversing"] = 0] = "Traversing";
30905     State[State["Waiting"] = 1] = "Waiting";
30906 })(exports.State || (exports.State = {}));
30907 var State = exports.State;
30908 Object.defineProperty(exports, "__esModule", { value: true });
30909 exports.default = State;
30910
30911 },{}],302:[function(require,module,exports){
30912 "use strict";
30913 var State_1 = require("../State");
30914 var Geo_1 = require("../Geo");
30915 var StateContext = (function () {
30916     function StateContext() {
30917         this._state = new State_1.TraversingState({
30918             alpha: 1,
30919             camera: new Geo_1.Camera(),
30920             currentIndex: -1,
30921             reference: { alt: 0, lat: 0, lon: 0 },
30922             trajectory: [],
30923             zoom: 0,
30924         });
30925     }
30926     StateContext.prototype.traverse = function () {
30927         this._state = this._state.traverse();
30928     };
30929     StateContext.prototype.wait = function () {
30930         this._state = this._state.wait();
30931     };
30932     Object.defineProperty(StateContext.prototype, "state", {
30933         get: function () {
30934             if (this._state instanceof State_1.TraversingState) {
30935                 return State_1.State.Traversing;
30936             }
30937             else if (this._state instanceof State_1.WaitingState) {
30938                 return State_1.State.Waiting;
30939             }
30940             throw new Error("Invalid state");
30941         },
30942         enumerable: true,
30943         configurable: true
30944     });
30945     Object.defineProperty(StateContext.prototype, "reference", {
30946         get: function () {
30947             return this._state.reference;
30948         },
30949         enumerable: true,
30950         configurable: true
30951     });
30952     Object.defineProperty(StateContext.prototype, "alpha", {
30953         get: function () {
30954             return this._state.alpha;
30955         },
30956         enumerable: true,
30957         configurable: true
30958     });
30959     Object.defineProperty(StateContext.prototype, "camera", {
30960         get: function () {
30961             return this._state.camera;
30962         },
30963         enumerable: true,
30964         configurable: true
30965     });
30966     Object.defineProperty(StateContext.prototype, "zoom", {
30967         get: function () {
30968             return this._state.zoom;
30969         },
30970         enumerable: true,
30971         configurable: true
30972     });
30973     Object.defineProperty(StateContext.prototype, "currentNode", {
30974         get: function () {
30975             return this._state.currentNode;
30976         },
30977         enumerable: true,
30978         configurable: true
30979     });
30980     Object.defineProperty(StateContext.prototype, "previousNode", {
30981         get: function () {
30982             return this._state.previousNode;
30983         },
30984         enumerable: true,
30985         configurable: true
30986     });
30987     Object.defineProperty(StateContext.prototype, "currentCamera", {
30988         get: function () {
30989             return this._state.currentCamera;
30990         },
30991         enumerable: true,
30992         configurable: true
30993     });
30994     Object.defineProperty(StateContext.prototype, "currentTransform", {
30995         get: function () {
30996             return this._state.currentTransform;
30997         },
30998         enumerable: true,
30999         configurable: true
31000     });
31001     Object.defineProperty(StateContext.prototype, "previousTransform", {
31002         get: function () {
31003             return this._state.previousTransform;
31004         },
31005         enumerable: true,
31006         configurable: true
31007     });
31008     Object.defineProperty(StateContext.prototype, "trajectory", {
31009         get: function () {
31010             return this._state.trajectory;
31011         },
31012         enumerable: true,
31013         configurable: true
31014     });
31015     Object.defineProperty(StateContext.prototype, "currentIndex", {
31016         get: function () {
31017             return this._state.currentIndex;
31018         },
31019         enumerable: true,
31020         configurable: true
31021     });
31022     Object.defineProperty(StateContext.prototype, "lastNode", {
31023         get: function () {
31024             return this._state.trajectory[this._state.trajectory.length - 1];
31025         },
31026         enumerable: true,
31027         configurable: true
31028     });
31029     Object.defineProperty(StateContext.prototype, "nodesAhead", {
31030         get: function () {
31031             return this._state.trajectory.length - 1 - this._state.currentIndex;
31032         },
31033         enumerable: true,
31034         configurable: true
31035     });
31036     Object.defineProperty(StateContext.prototype, "motionless", {
31037         get: function () {
31038             return this._state.motionless;
31039         },
31040         enumerable: true,
31041         configurable: true
31042     });
31043     StateContext.prototype.getCenter = function () {
31044         return this._state.getCenter();
31045     };
31046     StateContext.prototype.setCenter = function (center) {
31047         this._state.setCenter(center);
31048     };
31049     StateContext.prototype.setZoom = function (zoom) {
31050         this._state.setZoom(zoom);
31051     };
31052     StateContext.prototype.update = function (fps) {
31053         this._state.update(fps);
31054     };
31055     StateContext.prototype.append = function (nodes) {
31056         this._state.append(nodes);
31057     };
31058     StateContext.prototype.prepend = function (nodes) {
31059         this._state.prepend(nodes);
31060     };
31061     StateContext.prototype.remove = function (n) {
31062         this._state.remove(n);
31063     };
31064     StateContext.prototype.clear = function () {
31065         this._state.clear();
31066     };
31067     StateContext.prototype.cut = function () {
31068         this._state.cut();
31069     };
31070     StateContext.prototype.set = function (nodes) {
31071         this._state.set(nodes);
31072     };
31073     StateContext.prototype.rotate = function (delta) {
31074         this._state.rotate(delta);
31075     };
31076     StateContext.prototype.rotateBasic = function (basicRotation) {
31077         this._state.rotateBasic(basicRotation);
31078     };
31079     StateContext.prototype.rotateToBasic = function (basic) {
31080         this._state.rotateToBasic(basic);
31081     };
31082     StateContext.prototype.move = function (delta) {
31083         this._state.move(delta);
31084     };
31085     StateContext.prototype.moveTo = function (delta) {
31086         this._state.moveTo(delta);
31087     };
31088     StateContext.prototype.zoomIn = function (delta, reference) {
31089         this._state.zoomIn(delta, reference);
31090     };
31091     return StateContext;
31092 }());
31093 exports.StateContext = StateContext;
31094
31095 },{"../Geo":213,"../State":217}],303:[function(require,module,exports){
31096 "use strict";
31097 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
31098 var Subject_1 = require("rxjs/Subject");
31099 var AnimationFrame_1 = require("rxjs/util/AnimationFrame");
31100 require("rxjs/add/operator/bufferCount");
31101 require("rxjs/add/operator/distinctUntilChanged");
31102 require("rxjs/add/operator/do");
31103 require("rxjs/add/operator/filter");
31104 require("rxjs/add/operator/first");
31105 require("rxjs/add/operator/map");
31106 require("rxjs/add/operator/pairwise");
31107 require("rxjs/add/operator/publishReplay");
31108 require("rxjs/add/operator/scan");
31109 require("rxjs/add/operator/startWith");
31110 require("rxjs/add/operator/switchMap");
31111 require("rxjs/add/operator/withLatestFrom");
31112 var State_1 = require("../State");
31113 var StateService = (function () {
31114     function StateService() {
31115         var _this = this;
31116         this._appendNode$ = new Subject_1.Subject();
31117         this._start$ = new Subject_1.Subject();
31118         this._frame$ = new Subject_1.Subject();
31119         this._fpsSampleRate = 30;
31120         this._contextOperation$ = new BehaviorSubject_1.BehaviorSubject(function (context) {
31121             return context;
31122         });
31123         this._context$ = this._contextOperation$
31124             .scan(function (context, operation) {
31125             return operation(context);
31126         }, new State_1.StateContext())
31127             .publishReplay(1)
31128             .refCount();
31129         this._state$ = this._context$
31130             .map(function (context) {
31131             return context.state;
31132         })
31133             .distinctUntilChanged()
31134             .publishReplay(1)
31135             .refCount();
31136         this._fps$ = this._start$
31137             .switchMap(function () {
31138             return _this._frame$
31139                 .bufferCount(1, _this._fpsSampleRate)
31140                 .map(function (frameIds) {
31141                 return new Date().getTime();
31142             })
31143                 .pairwise()
31144                 .map(function (times) {
31145                 return Math.max(20, 1000 * _this._fpsSampleRate / (times[1] - times[0]));
31146             })
31147                 .startWith(60);
31148         })
31149             .share();
31150         this._currentState$ = this._frame$
31151             .withLatestFrom(this._fps$, this._context$, function (frameId, fps, context) {
31152             return [frameId, fps, context];
31153         })
31154             .filter(function (fc) {
31155             return fc[2].currentNode != null;
31156         })
31157             .do(function (fc) {
31158             fc[2].update(fc[1]);
31159         })
31160             .map(function (fc) {
31161             return { fps: fc[1], id: fc[0], state: fc[2] };
31162         })
31163             .share();
31164         this._lastState$ = this._currentState$
31165             .publishReplay(1)
31166             .refCount();
31167         var nodeChanged$ = this._currentState$
31168             .distinctUntilChanged(undefined, function (f) {
31169             return f.state.currentNode.key;
31170         })
31171             .publishReplay(1)
31172             .refCount();
31173         var nodeChangedSubject$ = new Subject_1.Subject();
31174         nodeChanged$.subscribe(nodeChangedSubject$);
31175         this._currentNode$ = nodeChangedSubject$
31176             .map(function (f) {
31177             return f.state.currentNode;
31178         })
31179             .publishReplay(1)
31180             .refCount();
31181         this._currentCamera$ = nodeChangedSubject$
31182             .map(function (f) {
31183             return f.state.currentCamera;
31184         })
31185             .publishReplay(1)
31186             .refCount();
31187         this._currentTransform$ = nodeChangedSubject$
31188             .map(function (f) {
31189             return f.state.currentTransform;
31190         })
31191             .publishReplay(1)
31192             .refCount();
31193         this._reference$ = nodeChangedSubject$
31194             .map(function (f) {
31195             return f.state.reference;
31196         })
31197             .distinctUntilChanged(function (r1, r2) {
31198             return r1.lat === r2.lat && r1.lon === r2.lon;
31199         }, function (reference) {
31200             return { lat: reference.lat, lon: reference.lon };
31201         })
31202             .publishReplay(1)
31203             .refCount();
31204         this._currentNodeExternal$ = nodeChanged$
31205             .map(function (f) {
31206             return f.state.currentNode;
31207         })
31208             .publishReplay(1)
31209             .refCount();
31210         this._appendNode$
31211             .map(function (node) {
31212             return function (context) {
31213                 context.append([node]);
31214                 return context;
31215             };
31216         })
31217             .subscribe(this._contextOperation$);
31218         this._movingOperation$ = new Subject_1.Subject();
31219         nodeChanged$
31220             .map(function (frame) {
31221             return true;
31222         })
31223             .subscribe(this._movingOperation$);
31224         this._movingOperation$
31225             .distinctUntilChanged()
31226             .filter(function (moving) {
31227             return moving;
31228         })
31229             .switchMap(function (moving) {
31230             return _this._currentState$
31231                 .filter(function (frame) {
31232                 return frame.state.nodesAhead === 0;
31233             })
31234                 .map(function (frame) {
31235                 return [frame.state.camera.clone(), frame.state.zoom];
31236             })
31237                 .pairwise()
31238                 .map(function (pair) {
31239                 var c1 = pair[0][0];
31240                 var c2 = pair[1][0];
31241                 var z1 = pair[0][1];
31242                 var z2 = pair[1][1];
31243                 return c1.diff(c2) > 1e-5 || Math.abs(z1 - z2) > 1e-5;
31244             })
31245                 .first(function (changed) {
31246                 return !changed;
31247             });
31248         })
31249             .subscribe(this._movingOperation$);
31250         this._moving$ = this._movingOperation$
31251             .distinctUntilChanged()
31252             .share();
31253         this._state$.subscribe();
31254         this._currentNode$.subscribe();
31255         this._currentCamera$.subscribe();
31256         this._currentTransform$.subscribe();
31257         this._reference$.subscribe();
31258         this._currentNodeExternal$.subscribe();
31259         this._lastState$.subscribe();
31260         this._frameId = null;
31261         this._frameGenerator = new AnimationFrame_1.RequestAnimationFrameDefinition(window);
31262     }
31263     Object.defineProperty(StateService.prototype, "currentState$", {
31264         get: function () {
31265             return this._currentState$;
31266         },
31267         enumerable: true,
31268         configurable: true
31269     });
31270     Object.defineProperty(StateService.prototype, "currentNode$", {
31271         get: function () {
31272             return this._currentNode$;
31273         },
31274         enumerable: true,
31275         configurable: true
31276     });
31277     Object.defineProperty(StateService.prototype, "currentNodeExternal$", {
31278         get: function () {
31279             return this._currentNodeExternal$;
31280         },
31281         enumerable: true,
31282         configurable: true
31283     });
31284     Object.defineProperty(StateService.prototype, "currentCamera$", {
31285         get: function () {
31286             return this._currentCamera$;
31287         },
31288         enumerable: true,
31289         configurable: true
31290     });
31291     Object.defineProperty(StateService.prototype, "currentTransform$", {
31292         get: function () {
31293             return this._currentTransform$;
31294         },
31295         enumerable: true,
31296         configurable: true
31297     });
31298     Object.defineProperty(StateService.prototype, "state$", {
31299         get: function () {
31300             return this._state$;
31301         },
31302         enumerable: true,
31303         configurable: true
31304     });
31305     Object.defineProperty(StateService.prototype, "reference$", {
31306         get: function () {
31307             return this._reference$;
31308         },
31309         enumerable: true,
31310         configurable: true
31311     });
31312     Object.defineProperty(StateService.prototype, "moving$", {
31313         get: function () {
31314             return this._moving$;
31315         },
31316         enumerable: true,
31317         configurable: true
31318     });
31319     Object.defineProperty(StateService.prototype, "appendNode$", {
31320         get: function () {
31321             return this._appendNode$;
31322         },
31323         enumerable: true,
31324         configurable: true
31325     });
31326     StateService.prototype.traverse = function () {
31327         this._movingOperation$.next(true);
31328         this._invokeContextOperation(function (context) { context.traverse(); });
31329     };
31330     StateService.prototype.wait = function () {
31331         this._invokeContextOperation(function (context) { context.wait(); });
31332     };
31333     StateService.prototype.appendNodes = function (nodes) {
31334         this._invokeContextOperation(function (context) { context.append(nodes); });
31335     };
31336     StateService.prototype.prependNodes = function (nodes) {
31337         this._invokeContextOperation(function (context) { context.prepend(nodes); });
31338     };
31339     StateService.prototype.removeNodes = function (n) {
31340         this._invokeContextOperation(function (context) { context.remove(n); });
31341     };
31342     StateService.prototype.clearNodes = function () {
31343         this._invokeContextOperation(function (context) { context.clear(); });
31344     };
31345     StateService.prototype.cutNodes = function () {
31346         this._invokeContextOperation(function (context) { context.cut(); });
31347     };
31348     StateService.prototype.setNodes = function (nodes) {
31349         this._invokeContextOperation(function (context) { context.set(nodes); });
31350     };
31351     StateService.prototype.rotate = function (delta) {
31352         this._movingOperation$.next(true);
31353         this._invokeContextOperation(function (context) { context.rotate(delta); });
31354     };
31355     StateService.prototype.rotateBasic = function (basicRotation) {
31356         this._movingOperation$.next(true);
31357         this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); });
31358     };
31359     StateService.prototype.rotateToBasic = function (basic) {
31360         this._movingOperation$.next(true);
31361         this._invokeContextOperation(function (context) { context.rotateToBasic(basic); });
31362     };
31363     StateService.prototype.move = function (delta) {
31364         this._movingOperation$.next(true);
31365         this._invokeContextOperation(function (context) { context.move(delta); });
31366     };
31367     StateService.prototype.moveTo = function (position) {
31368         this._movingOperation$.next(true);
31369         this._invokeContextOperation(function (context) { context.moveTo(position); });
31370     };
31371     /**
31372      * Change zoom level while keeping the reference point position approximately static.
31373      *
31374      * @parameter {number} delta - Change in zoom level.
31375      * @parameter {Array<number>} reference - Reference point in basic coordinates.
31376      */
31377     StateService.prototype.zoomIn = function (delta, reference) {
31378         this._movingOperation$.next(true);
31379         this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); });
31380     };
31381     StateService.prototype.getCenter = function () {
31382         return this._lastState$
31383             .first()
31384             .map(function (frame) {
31385             return frame.state.getCenter();
31386         });
31387     };
31388     StateService.prototype.getZoom = function () {
31389         return this._lastState$
31390             .first()
31391             .map(function (frame) {
31392             return frame.state.zoom;
31393         });
31394     };
31395     StateService.prototype.setCenter = function (center) {
31396         this._movingOperation$.next(true);
31397         this._invokeContextOperation(function (context) { context.setCenter(center); });
31398     };
31399     StateService.prototype.setZoom = function (zoom) {
31400         this._movingOperation$.next(true);
31401         this._invokeContextOperation(function (context) { context.setZoom(zoom); });
31402     };
31403     StateService.prototype.start = function () {
31404         if (this._frameId == null) {
31405             this._start$.next(null);
31406             this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
31407             this._frame$.next(this._frameId);
31408         }
31409     };
31410     StateService.prototype.stop = function () {
31411         if (this._frameId != null) {
31412             this._frameGenerator.cancelAnimationFrame(this._frameId);
31413             this._frameId = null;
31414         }
31415     };
31416     StateService.prototype._invokeContextOperation = function (action) {
31417         this._contextOperation$
31418             .next(function (context) {
31419             action(context);
31420             return context;
31421         });
31422     };
31423     StateService.prototype._frame = function (time) {
31424         this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
31425         this._frame$.next(this._frameId);
31426     };
31427     return StateService;
31428 }());
31429 exports.StateService = StateService;
31430
31431 },{"../State":217,"rxjs/BehaviorSubject":25,"rxjs/Subject":33,"rxjs/add/operator/bufferCount":48,"rxjs/add/operator/distinctUntilChanged":54,"rxjs/add/operator/do":55,"rxjs/add/operator/filter":57,"rxjs/add/operator/first":59,"rxjs/add/operator/map":61,"rxjs/add/operator/pairwise":65,"rxjs/add/operator/publishReplay":68,"rxjs/add/operator/scan":69,"rxjs/add/operator/startWith":73,"rxjs/add/operator/switchMap":74,"rxjs/add/operator/withLatestFrom":77,"rxjs/util/AnimationFrame":145}],304:[function(require,module,exports){
31432 /// <reference path="../../../typings/index.d.ts" />
31433 "use strict";
31434 var Error_1 = require("../../Error");
31435 var Geo_1 = require("../../Geo");
31436 var StateBase = (function () {
31437     function StateBase(state) {
31438         this._spatial = new Geo_1.Spatial();
31439         this._geoCoords = new Geo_1.GeoCoords();
31440         this._referenceThreshold = 0.01;
31441         this._reference = state.reference;
31442         this._alpha = state.alpha;
31443         this._camera = state.camera.clone();
31444         this._zoom = state.zoom;
31445         this._currentIndex = state.currentIndex;
31446         this._trajectory = state.trajectory.slice();
31447         this._trajectoryTransforms = [];
31448         this._trajectoryCameras = [];
31449         for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) {
31450             var node = _a[_i];
31451             var translation = this._nodeToTranslation(node);
31452             var transform = new Geo_1.Transform(node, node.image, translation);
31453             this._trajectoryTransforms.push(transform);
31454             this._trajectoryCameras.push(new Geo_1.Camera(transform));
31455         }
31456         this._currentNode = this._trajectory.length > 0 ?
31457             this._trajectory[this._currentIndex] :
31458             null;
31459         this._previousNode = this._trajectory.length > 1 && this.currentIndex > 0 ?
31460             this._trajectory[this._currentIndex - 1] :
31461             null;
31462         this._currentCamera = this._trajectoryCameras.length > 0 ?
31463             this._trajectoryCameras[this._currentIndex].clone() :
31464             new Geo_1.Camera();
31465         this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
31466             this._trajectoryCameras[this._currentIndex - 1].clone() :
31467             this._currentCamera.clone();
31468     }
31469     Object.defineProperty(StateBase.prototype, "reference", {
31470         get: function () {
31471             return this._reference;
31472         },
31473         enumerable: true,
31474         configurable: true
31475     });
31476     Object.defineProperty(StateBase.prototype, "alpha", {
31477         get: function () {
31478             return this._getAlpha();
31479         },
31480         enumerable: true,
31481         configurable: true
31482     });
31483     Object.defineProperty(StateBase.prototype, "camera", {
31484         get: function () {
31485             return this._camera;
31486         },
31487         enumerable: true,
31488         configurable: true
31489     });
31490     Object.defineProperty(StateBase.prototype, "zoom", {
31491         get: function () {
31492             return this._zoom;
31493         },
31494         enumerable: true,
31495         configurable: true
31496     });
31497     Object.defineProperty(StateBase.prototype, "trajectory", {
31498         get: function () {
31499             return this._trajectory;
31500         },
31501         enumerable: true,
31502         configurable: true
31503     });
31504     Object.defineProperty(StateBase.prototype, "currentIndex", {
31505         get: function () {
31506             return this._currentIndex;
31507         },
31508         enumerable: true,
31509         configurable: true
31510     });
31511     Object.defineProperty(StateBase.prototype, "currentNode", {
31512         get: function () {
31513             return this._currentNode;
31514         },
31515         enumerable: true,
31516         configurable: true
31517     });
31518     Object.defineProperty(StateBase.prototype, "previousNode", {
31519         get: function () {
31520             return this._previousNode;
31521         },
31522         enumerable: true,
31523         configurable: true
31524     });
31525     Object.defineProperty(StateBase.prototype, "currentCamera", {
31526         get: function () {
31527             return this._currentCamera;
31528         },
31529         enumerable: true,
31530         configurable: true
31531     });
31532     Object.defineProperty(StateBase.prototype, "currentTransform", {
31533         get: function () {
31534             return this._trajectoryTransforms.length > 0 ?
31535                 this._trajectoryTransforms[this.currentIndex] : null;
31536         },
31537         enumerable: true,
31538         configurable: true
31539     });
31540     Object.defineProperty(StateBase.prototype, "previousTransform", {
31541         get: function () {
31542             return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
31543                 this._trajectoryTransforms[this.currentIndex - 1] : null;
31544         },
31545         enumerable: true,
31546         configurable: true
31547     });
31548     Object.defineProperty(StateBase.prototype, "motionless", {
31549         get: function () {
31550             return this._motionless;
31551         },
31552         enumerable: true,
31553         configurable: true
31554     });
31555     StateBase.prototype.append = function (nodes) {
31556         if (nodes.length < 1) {
31557             throw Error("Trajectory can not be empty");
31558         }
31559         if (this._currentIndex < 0) {
31560             this.set(nodes);
31561         }
31562         else {
31563             this._trajectory = this._trajectory.concat(nodes);
31564             this._appendToTrajectories(nodes);
31565         }
31566     };
31567     StateBase.prototype.prepend = function (nodes) {
31568         if (nodes.length < 1) {
31569             throw Error("Trajectory can not be empty");
31570         }
31571         this._trajectory = nodes.slice().concat(this._trajectory);
31572         this._currentIndex += nodes.length;
31573         this._setCurrentNode();
31574         var referenceReset = this._setReference(this._currentNode);
31575         if (referenceReset) {
31576             this._setTrajectories();
31577         }
31578         else {
31579             this._prependToTrajectories(nodes);
31580         }
31581         this._setCurrentCamera();
31582     };
31583     StateBase.prototype.remove = function (n) {
31584         if (n < 0) {
31585             throw Error("n must be a positive integer");
31586         }
31587         if (this._currentIndex - 1 < n) {
31588             throw Error("Current and previous nodes can not be removed");
31589         }
31590         for (var i = 0; i < n; i++) {
31591             this._trajectory.shift();
31592             this._trajectoryTransforms.shift();
31593             this._trajectoryCameras.shift();
31594             this._currentIndex--;
31595         }
31596         this._setCurrentNode();
31597     };
31598     StateBase.prototype.clear = function () {
31599         this.cut();
31600         if (this._currentIndex > 0) {
31601             this.remove(this._currentIndex - 1);
31602         }
31603     };
31604     StateBase.prototype.cut = function () {
31605         while (this._trajectory.length - 1 > this._currentIndex) {
31606             this._trajectory.pop();
31607             this._trajectoryTransforms.pop();
31608             this._trajectoryCameras.pop();
31609         }
31610     };
31611     StateBase.prototype.set = function (nodes) {
31612         this._setTrajectory(nodes);
31613         this._setCurrentNode();
31614         this._setReference(this._currentNode);
31615         this._setTrajectories();
31616         this._setCurrentCamera();
31617     };
31618     StateBase.prototype.getCenter = function () {
31619         return this._currentNode != null ?
31620             this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
31621             [0.5, 0.5];
31622     };
31623     StateBase.prototype._setCurrent = function () {
31624         this._setCurrentNode();
31625         var referenceReset = this._setReference(this._currentNode);
31626         if (referenceReset) {
31627             this._setTrajectories();
31628         }
31629         this._setCurrentCamera();
31630     };
31631     StateBase.prototype._setCurrentCamera = function () {
31632         this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
31633         this._previousCamera = this._currentIndex > 0 ?
31634             this._trajectoryCameras[this._currentIndex - 1].clone() :
31635             this._currentCamera.clone();
31636     };
31637     StateBase.prototype._motionlessTransition = function () {
31638         var nodesSet = this._currentNode != null && this._previousNode != null;
31639         return nodesSet && !(this._currentNode.merged &&
31640             this._previousNode.merged &&
31641             this._withinOriginalDistance() &&
31642             this._sameConnectedComponent());
31643     };
31644     StateBase.prototype._setReference = function (node) {
31645         // do not reset reference if node is within threshold distance
31646         if (Math.abs(node.latLon.lat - this.reference.lat) < this._referenceThreshold &&
31647             Math.abs(node.latLon.lon - this.reference.lon) < this._referenceThreshold) {
31648             return false;
31649         }
31650         // do not reset reference if previous node exist and transition is with motion
31651         if (this._previousNode != null && !this._motionlessTransition()) {
31652             return false;
31653         }
31654         this._reference.lat = node.latLon.lat;
31655         this._reference.lon = node.latLon.lon;
31656         this._reference.alt = node.alt;
31657         return true;
31658     };
31659     StateBase.prototype._setCurrentNode = function () {
31660         this._currentNode = this._trajectory.length > 0 ?
31661             this._trajectory[this._currentIndex] :
31662             null;
31663         this._previousNode = this._currentIndex > 0 ?
31664             this._trajectory[this._currentIndex - 1] :
31665             null;
31666     };
31667     StateBase.prototype._setTrajectory = function (nodes) {
31668         if (nodes.length < 1) {
31669             throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty");
31670         }
31671         if (this._currentNode != null) {
31672             this._trajectory = [this._currentNode].concat(nodes);
31673             this._currentIndex = 1;
31674         }
31675         else {
31676             this._trajectory = nodes.slice();
31677             this._currentIndex = 0;
31678         }
31679     };
31680     StateBase.prototype._setTrajectories = function () {
31681         this._trajectoryTransforms.length = 0;
31682         this._trajectoryCameras.length = 0;
31683         this._appendToTrajectories(this._trajectory);
31684     };
31685     StateBase.prototype._appendToTrajectories = function (nodes) {
31686         for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
31687             var node = nodes_1[_i];
31688             if (!node.assetsCached) {
31689                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory");
31690             }
31691             var translation = this._nodeToTranslation(node);
31692             var transform = new Geo_1.Transform(node, node.image, translation);
31693             this._trajectoryTransforms.push(transform);
31694             this._trajectoryCameras.push(new Geo_1.Camera(transform));
31695         }
31696     };
31697     StateBase.prototype._prependToTrajectories = function (nodes) {
31698         for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) {
31699             var node = _a[_i];
31700             if (!node.assetsCached) {
31701                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory");
31702             }
31703             var translation = this._nodeToTranslation(node);
31704             var transform = new Geo_1.Transform(node, node.image, translation);
31705             this._trajectoryTransforms.unshift(transform);
31706             this._trajectoryCameras.unshift(new Geo_1.Camera(transform));
31707         }
31708     };
31709     StateBase.prototype._nodeToTranslation = function (node) {
31710         var C = this._geoCoords.geodeticToEnu(node.latLon.lat, node.latLon.lon, node.alt, this._reference.lat, this._reference.lon, this._reference.alt);
31711         var RC = this._spatial.rotate(C, node.rotation);
31712         return [-RC.x, -RC.y, -RC.z];
31713     };
31714     StateBase.prototype._sameConnectedComponent = function () {
31715         var current = this._currentNode;
31716         var previous = this._previousNode;
31717         if (!current ||
31718             !current.mergeCC ||
31719             !previous ||
31720             !previous.mergeCC) {
31721             return true;
31722         }
31723         return current.mergeCC === previous.mergeCC;
31724     };
31725     StateBase.prototype._withinOriginalDistance = function () {
31726         var current = this._currentNode;
31727         var previous = this._previousNode;
31728         if (!current || !previous) {
31729             return true;
31730         }
31731         // 50 km/h moves 28m in 2s
31732         var distance = this._spatial.distanceFromLatLon(current.originalLatLon.lat, current.originalLatLon.lon, previous.originalLatLon.lat, previous.originalLatLon.lon);
31733         return distance < 25;
31734     };
31735     return StateBase;
31736 }());
31737 exports.StateBase = StateBase;
31738
31739 },{"../../Error":212,"../../Geo":213}],305:[function(require,module,exports){
31740 /// <reference path="../../../typings/index.d.ts" />
31741 "use strict";
31742 var __extends = (this && this.__extends) || function (d, b) {
31743     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
31744     function __() { this.constructor = d; }
31745     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31746 };
31747 var THREE = require("three");
31748 var UnitBezier = require("unitbezier");
31749 var State_1 = require("../../State");
31750 var RotationDelta = (function () {
31751     function RotationDelta(phi, theta) {
31752         this._phi = phi;
31753         this._theta = theta;
31754     }
31755     Object.defineProperty(RotationDelta.prototype, "phi", {
31756         get: function () {
31757             return this._phi;
31758         },
31759         set: function (value) {
31760             this._phi = value;
31761         },
31762         enumerable: true,
31763         configurable: true
31764     });
31765     Object.defineProperty(RotationDelta.prototype, "theta", {
31766         get: function () {
31767             return this._theta;
31768         },
31769         set: function (value) {
31770             this._theta = value;
31771         },
31772         enumerable: true,
31773         configurable: true
31774     });
31775     Object.defineProperty(RotationDelta.prototype, "isZero", {
31776         get: function () {
31777             return this._phi === 0 && this._theta === 0;
31778         },
31779         enumerable: true,
31780         configurable: true
31781     });
31782     RotationDelta.prototype.copy = function (delta) {
31783         this._phi = delta.phi;
31784         this._theta = delta.theta;
31785     };
31786     RotationDelta.prototype.lerp = function (other, alpha) {
31787         this._phi = (1 - alpha) * this._phi + alpha * other.phi;
31788         this._theta = (1 - alpha) * this._theta + alpha * other.theta;
31789     };
31790     RotationDelta.prototype.multiply = function (value) {
31791         this._phi *= value;
31792         this._theta *= value;
31793     };
31794     RotationDelta.prototype.threshold = function (value) {
31795         this._phi = Math.abs(this._phi) > value ? this._phi : 0;
31796         this._theta = Math.abs(this._theta) > value ? this._theta : 0;
31797     };
31798     RotationDelta.prototype.lengthSquared = function () {
31799         return this._phi * this._phi + this._theta * this._theta;
31800     };
31801     RotationDelta.prototype.reset = function () {
31802         this._phi = 0;
31803         this._theta = 0;
31804     };
31805     return RotationDelta;
31806 }());
31807 var TraversingState = (function (_super) {
31808     __extends(TraversingState, _super);
31809     function TraversingState(state) {
31810         _super.call(this, state);
31811         this._adjustCameras();
31812         this._motionless = this._motionlessTransition();
31813         this._baseAlpha = this._alpha;
31814         this._animationSpeed = 0.025;
31815         this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
31816         this._useBezier = false;
31817         this._rotationDelta = new RotationDelta(0, 0);
31818         this._requestedRotationDelta = null;
31819         this._basicRotation = [0, 0];
31820         this._requestedBasicRotation = null;
31821         this._rotationAcceleration = 0.86;
31822         this._rotationIncreaseAlpha = 0.97;
31823         this._rotationDecreaseAlpha = 0.9;
31824         this._rotationThreshold = 0.001;
31825         this._desiredZoom = state.zoom;
31826         this._minZoom = 0;
31827         this._maxZoom = 3;
31828         this._lookatDepth = 10;
31829         this._desiredLookat = null;
31830         this._desiredCenter = null;
31831     }
31832     TraversingState.prototype.traverse = function () {
31833         throw new Error("Not implemented");
31834     };
31835     TraversingState.prototype.wait = function () {
31836         return new State_1.WaitingState(this);
31837     };
31838     TraversingState.prototype.append = function (nodes) {
31839         var emptyTrajectory = this._trajectory.length === 0;
31840         if (emptyTrajectory) {
31841             this._resetTransition();
31842         }
31843         _super.prototype.append.call(this, nodes);
31844         if (emptyTrajectory) {
31845             this._setDesiredCenter();
31846             this._setDesiredZoom();
31847         }
31848     };
31849     TraversingState.prototype.prepend = function (nodes) {
31850         var emptyTrajectory = this._trajectory.length === 0;
31851         if (emptyTrajectory) {
31852             this._resetTransition();
31853         }
31854         _super.prototype.prepend.call(this, nodes);
31855         if (emptyTrajectory) {
31856             this._setDesiredCenter();
31857             this._setDesiredZoom();
31858         }
31859     };
31860     TraversingState.prototype.set = function (nodes) {
31861         _super.prototype.set.call(this, nodes);
31862         this._desiredLookat = null;
31863         this._resetTransition();
31864         this._clearRotation();
31865         this._setDesiredCenter();
31866         this._setDesiredZoom();
31867         if (this._trajectory.length < 3) {
31868             this._useBezier = true;
31869         }
31870     };
31871     TraversingState.prototype.move = function (delta) {
31872         throw new Error("Not implemented");
31873     };
31874     TraversingState.prototype.moveTo = function (delta) {
31875         throw new Error("Not implemented");
31876     };
31877     TraversingState.prototype.rotate = function (rotationDelta) {
31878         if (this._currentNode == null) {
31879             return;
31880         }
31881         this._desiredZoom = this._zoom;
31882         this._desiredLookat = null;
31883         this._requestedBasicRotation = null;
31884         if (this._requestedRotationDelta != null) {
31885             this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi;
31886             this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta;
31887         }
31888         else {
31889             this._requestedRotationDelta = new RotationDelta(rotationDelta.phi, rotationDelta.theta);
31890         }
31891     };
31892     TraversingState.prototype.rotateBasic = function (basicRotation) {
31893         if (this._currentNode == null) {
31894             return;
31895         }
31896         this._desiredZoom = this._zoom;
31897         this._desiredLookat = null;
31898         this._requestedRotationDelta = null;
31899         if (this._requestedBasicRotation != null) {
31900             this._requestedBasicRotation[0] += basicRotation[0];
31901             this._requestedBasicRotation[1] += basicRotation[1];
31902         }
31903         else {
31904             this._requestedBasicRotation = basicRotation.slice();
31905         }
31906     };
31907     TraversingState.prototype.rotateToBasic = function (basic) {
31908         if (this._currentNode == null) {
31909             return;
31910         }
31911         this._desiredZoom = this._zoom;
31912         this._desiredLookat = null;
31913         basic[0] = this._spatial.clamp(basic[0], 0, 1);
31914         basic[1] = this._spatial.clamp(basic[1], 0, 1);
31915         var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth);
31916         this._currentCamera.lookat.fromArray(lookat);
31917     };
31918     TraversingState.prototype.zoomIn = function (delta, reference) {
31919         if (this._currentNode == null) {
31920             return;
31921         }
31922         this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta));
31923         var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray());
31924         var currentCenterX = currentCenter[0];
31925         var currentCenterY = currentCenter[1];
31926         var zoom0 = Math.pow(2, this._zoom);
31927         var zoom1 = Math.pow(2, this._desiredZoom);
31928         var refX = reference[0];
31929         var refY = reference[1];
31930         if (this.currentTransform.gpano != null &&
31931             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
31932             if (refX - currentCenterX > 0.5) {
31933                 refX = refX - 1;
31934             }
31935             else if (currentCenterX - refX > 0.5) {
31936                 refX = 1 + refX;
31937             }
31938         }
31939         var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX);
31940         var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY);
31941         var gpano = this.currentTransform.gpano;
31942         if (this._currentNode.fullPano) {
31943             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
31944             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95);
31945         }
31946         else if (gpano != null &&
31947             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
31948             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
31949             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1);
31950         }
31951         else {
31952             newCenterX = this._spatial.clamp(newCenterX, 0, 1);
31953             newCenterY = this._spatial.clamp(newCenterY, 0, 1);
31954         }
31955         this._desiredLookat = new THREE.Vector3()
31956             .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth));
31957     };
31958     TraversingState.prototype.setCenter = function (center) {
31959         this._desiredLookat = null;
31960         this._requestedRotationDelta = null;
31961         this._requestedBasicRotation = null;
31962         this._desiredZoom = this._zoom;
31963         var clamped = [
31964             this._spatial.clamp(center[0], 0, 1),
31965             this._spatial.clamp(center[1], 0, 1),
31966         ];
31967         if (this._currentNode == null) {
31968             this._desiredCenter = clamped;
31969             return;
31970         }
31971         this._desiredCenter = null;
31972         var currentLookat = new THREE.Vector3()
31973             .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth));
31974         var previousTransform = this.previousTransform != null ?
31975             this.previousTransform :
31976             this.currentTransform;
31977         var previousLookat = new THREE.Vector3()
31978             .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth));
31979         this._currentCamera.lookat.copy(currentLookat);
31980         this._previousCamera.lookat.copy(previousLookat);
31981     };
31982     TraversingState.prototype.setZoom = function (zoom) {
31983         this._desiredLookat = null;
31984         this._requestedRotationDelta = null;
31985         this._requestedBasicRotation = null;
31986         this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom);
31987         this._desiredZoom = this._zoom;
31988     };
31989     TraversingState.prototype.update = function (fps) {
31990         if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) {
31991             this._currentIndex += 1;
31992             this._useBezier = this._trajectory.length < 3 &&
31993                 this._currentIndex + 1 === this._trajectory.length;
31994             this._setCurrent();
31995             this._resetTransition();
31996             this._clearRotation();
31997             this._desiredZoom = this._currentNode.fullPano ? this._zoom : 0;
31998             this._desiredLookat = null;
31999         }
32000         var animationSpeed = this._animationSpeed * (60 / fps);
32001         this._baseAlpha = Math.min(1, this._baseAlpha + animationSpeed);
32002         if (this._useBezier) {
32003             this._alpha = this._unitBezier.solve(this._baseAlpha);
32004         }
32005         else {
32006             this._alpha = this._baseAlpha;
32007         }
32008         this._updateRotation();
32009         if (!this._rotationDelta.isZero) {
32010             this._applyRotation(this._previousCamera);
32011             this._applyRotation(this._currentCamera);
32012         }
32013         this._updateRotationBasic();
32014         if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
32015             this._applyRotationBasic();
32016         }
32017         this._updateZoom(animationSpeed);
32018         this._updateLookat(animationSpeed);
32019         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
32020     };
32021     TraversingState.prototype._getAlpha = function () {
32022         return this._motionless ? Math.ceil(this._alpha) : this._alpha;
32023     };
32024     TraversingState.prototype._setCurrentCamera = function () {
32025         _super.prototype._setCurrentCamera.call(this);
32026         this._adjustCameras();
32027     };
32028     TraversingState.prototype._adjustCameras = function () {
32029         if (this._previousNode == null) {
32030             return;
32031         }
32032         var lookat = this._camera.lookat.clone().sub(this._camera.position);
32033         this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
32034         if (this._currentNode.fullPano) {
32035             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
32036         }
32037     };
32038     TraversingState.prototype._resetTransition = function () {
32039         this._alpha = 0;
32040         this._baseAlpha = 0;
32041         this._motionless = this._motionlessTransition();
32042     };
32043     TraversingState.prototype._applyRotation = function (camera) {
32044         if (camera == null) {
32045             return;
32046         }
32047         var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
32048         var qInverse = q.clone().inverse();
32049         var offset = new THREE.Vector3();
32050         offset.copy(camera.lookat).sub(camera.position);
32051         offset.applyQuaternion(q);
32052         var length = offset.length();
32053         var phi = Math.atan2(offset.y, offset.x);
32054         phi += this._rotationDelta.phi;
32055         var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
32056         theta += this._rotationDelta.theta;
32057         theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
32058         offset.x = Math.sin(theta) * Math.cos(phi);
32059         offset.y = Math.sin(theta) * Math.sin(phi);
32060         offset.z = Math.cos(theta);
32061         offset.applyQuaternion(qInverse);
32062         camera.lookat.copy(camera.position).add(offset.multiplyScalar(length));
32063     };
32064     TraversingState.prototype._applyRotationBasic = function () {
32065         var currentNode = this._currentNode;
32066         var previousNode = this._previousNode != null ?
32067             this.previousNode :
32068             this.currentNode;
32069         var currentCamera = this._currentCamera;
32070         var previousCamera = this._previousCamera;
32071         var currentTransform = this.currentTransform;
32072         var previousTransform = this.previousTransform != null ?
32073             this.previousTransform :
32074             this.currentTransform;
32075         var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray());
32076         var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray());
32077         var currentGPano = currentTransform.gpano;
32078         var previousGPano = previousTransform.gpano;
32079         if (currentNode.fullPano) {
32080             currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1);
32081             currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0.05, 0.95);
32082         }
32083         else if (currentGPano != null &&
32084             currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) {
32085             currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1);
32086             currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
32087         }
32088         else {
32089             currentBasic[0] = this._spatial.clamp(currentBasic[0] + this._basicRotation[0], 0, 1);
32090             currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
32091         }
32092         if (previousNode.fullPano) {
32093             previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1);
32094             previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0.05, 0.95);
32095         }
32096         else if (previousGPano != null &&
32097             previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) {
32098             previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1);
32099             previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0, 1);
32100         }
32101         else {
32102             previousBasic[0] = this._spatial.clamp(previousBasic[0] + this._basicRotation[0], 0, 1);
32103             previousBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
32104         }
32105         var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth);
32106         currentCamera.lookat.fromArray(currentLookat);
32107         var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth);
32108         previousCamera.lookat.fromArray(previousLookat);
32109     };
32110     TraversingState.prototype._updateZoom = function (animationSpeed) {
32111         var diff = this._desiredZoom - this._zoom;
32112         if (diff === 0) {
32113             return;
32114         }
32115         else if (Math.abs(diff) < 0.0001) {
32116             this._zoom = this._desiredZoom;
32117         }
32118         else {
32119             this._zoom += 5 * animationSpeed * diff;
32120         }
32121     };
32122     TraversingState.prototype._updateLookat = function (animationSpeed) {
32123         if (this._desiredLookat === null) {
32124             return;
32125         }
32126         var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat);
32127         if (Math.abs(diff) < 0.00001) {
32128             this._currentCamera.lookat.copy(this._desiredLookat);
32129             this._desiredLookat = null;
32130         }
32131         else {
32132             this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed);
32133         }
32134     };
32135     TraversingState.prototype._updateRotation = function () {
32136         if (this._requestedRotationDelta != null) {
32137             var length_1 = this._rotationDelta.lengthSquared();
32138             var requestedLength = this._requestedRotationDelta.lengthSquared();
32139             if (requestedLength > length_1) {
32140                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha);
32141             }
32142             else {
32143                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha);
32144             }
32145             this._requestedRotationDelta = null;
32146             return;
32147         }
32148         if (this._rotationDelta.isZero) {
32149             return;
32150         }
32151         this._rotationDelta.multiply(this._rotationAcceleration);
32152         this._rotationDelta.threshold(this._rotationThreshold);
32153     };
32154     TraversingState.prototype._updateRotationBasic = function () {
32155         if (this._requestedBasicRotation != null) {
32156             var x = this._basicRotation[0];
32157             var y = this._basicRotation[1];
32158             var lengthSquared = x * x + y * y;
32159             var reqX = this._requestedBasicRotation[0];
32160             var reqY = this._requestedBasicRotation[1];
32161             var reqLengthSquared = reqX * reqX + reqY * reqY;
32162             if (reqLengthSquared > lengthSquared) {
32163                 this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX;
32164                 this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY;
32165             }
32166             else {
32167                 this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX;
32168                 this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY;
32169             }
32170             this._requestedBasicRotation = null;
32171             return;
32172         }
32173         if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) {
32174             return;
32175         }
32176         this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0];
32177         this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1];
32178         if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) &&
32179             Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) {
32180             this._basicRotation = [0, 0];
32181         }
32182     };
32183     TraversingState.prototype._clearRotation = function () {
32184         if (this._currentNode.fullPano) {
32185             return;
32186         }
32187         if (this._requestedRotationDelta != null) {
32188             this._requestedRotationDelta = null;
32189         }
32190         if (!this._rotationDelta.isZero) {
32191             this._rotationDelta.reset();
32192         }
32193         if (this._requestedBasicRotation != null) {
32194             this._requestedBasicRotation = null;
32195         }
32196         if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) {
32197             this._basicRotation = [0, 0];
32198         }
32199     };
32200     TraversingState.prototype._setDesiredCenter = function () {
32201         if (this._desiredCenter == null) {
32202             return;
32203         }
32204         var lookatDirection = new THREE.Vector3()
32205             .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth))
32206             .sub(this._currentCamera.position);
32207         this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection));
32208         this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection));
32209         this._desiredCenter = null;
32210     };
32211     TraversingState.prototype._setDesiredZoom = function () {
32212         this._desiredZoom =
32213             this._currentNode.fullPano || this._previousNode == null ?
32214                 this._zoom : 0;
32215     };
32216     return TraversingState;
32217 }(State_1.StateBase));
32218 exports.TraversingState = TraversingState;
32219
32220 },{"../../State":217,"three":160,"unitbezier":162}],306:[function(require,module,exports){
32221 "use strict";
32222 var __extends = (this && this.__extends) || function (d, b) {
32223     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
32224     function __() { this.constructor = d; }
32225     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32226 };
32227 var State_1 = require("../../State");
32228 var WaitingState = (function (_super) {
32229     __extends(WaitingState, _super);
32230     function WaitingState(state) {
32231         _super.call(this, state);
32232         this._adjustCameras();
32233         this._motionless = this._motionlessTransition();
32234     }
32235     WaitingState.prototype.traverse = function () {
32236         return new State_1.TraversingState(this);
32237     };
32238     WaitingState.prototype.wait = function () {
32239         throw new Error("Not implemented");
32240     };
32241     WaitingState.prototype.prepend = function (nodes) {
32242         _super.prototype.prepend.call(this, nodes);
32243         this._motionless = this._motionlessTransition();
32244     };
32245     WaitingState.prototype.set = function (nodes) {
32246         _super.prototype.set.call(this, nodes);
32247         this._motionless = this._motionlessTransition();
32248     };
32249     WaitingState.prototype.rotate = function (delta) { return; };
32250     WaitingState.prototype.rotateBasic = function (basicRotation) { return; };
32251     WaitingState.prototype.rotateToBasic = function (basic) { return; };
32252     WaitingState.prototype.zoomIn = function (delta, reference) { return; };
32253     WaitingState.prototype.move = function (delta) {
32254         this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
32255     };
32256     WaitingState.prototype.moveTo = function (position) {
32257         this._alpha = Math.max(0, Math.min(1, position));
32258     };
32259     WaitingState.prototype.update = function (fps) {
32260         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
32261     };
32262     WaitingState.prototype.setCenter = function (center) { return; };
32263     WaitingState.prototype.setZoom = function (zoom) { return; };
32264     WaitingState.prototype._getAlpha = function () {
32265         return this._motionless ? Math.round(this._alpha) : this._alpha;
32266     };
32267     ;
32268     WaitingState.prototype._setCurrentCamera = function () {
32269         _super.prototype._setCurrentCamera.call(this);
32270         this._adjustCameras();
32271     };
32272     WaitingState.prototype._adjustCameras = function () {
32273         if (this._previousNode == null) {
32274             return;
32275         }
32276         if (this._currentNode.fullPano) {
32277             var lookat = this._camera.lookat.clone().sub(this._camera.position);
32278             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
32279         }
32280         if (this._previousNode.fullPano) {
32281             var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
32282             this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
32283         }
32284     };
32285     return WaitingState;
32286 }(State_1.StateBase));
32287 exports.WaitingState = WaitingState;
32288
32289 },{"../../State":217}],307:[function(require,module,exports){
32290 "use strict";
32291 var EventEmitter = (function () {
32292     function EventEmitter() {
32293         this._events = {};
32294     }
32295     /**
32296      * Subscribe to an event by its name.
32297      * @param {string }eventType - The name of the event to subscribe to.
32298      * @param {any} fn - The handler called when the event occurs.
32299      */
32300     EventEmitter.prototype.on = function (eventType, fn) {
32301         this._events[eventType] = this._events[eventType] || [];
32302         this._events[eventType].push(fn);
32303         return;
32304     };
32305     /**
32306      * Unsubscribe from an event by its name.
32307      * @param {string} eventType - The name of the event to subscribe to.
32308      * @param {any} fn - The handler to remove.
32309      */
32310     EventEmitter.prototype.off = function (eventType, fn) {
32311         if (!eventType) {
32312             this._events = {};
32313             return;
32314         }
32315         if (!this._listens(eventType)) {
32316             var idx = this._events[eventType].indexOf(fn);
32317             if (idx >= 0) {
32318                 this._events[eventType].splice(idx, 1);
32319             }
32320             if (this._events[eventType].length) {
32321                 delete this._events[eventType];
32322             }
32323         }
32324         else {
32325             delete this._events[eventType];
32326         }
32327         return;
32328     };
32329     EventEmitter.prototype.fire = function (eventType, data) {
32330         if (!this._listens(eventType)) {
32331             return;
32332         }
32333         for (var _i = 0, _a = this._events[eventType]; _i < _a.length; _i++) {
32334             var fn = _a[_i];
32335             fn.call(this, data);
32336         }
32337         return;
32338     };
32339     EventEmitter.prototype._listens = function (eventType) {
32340         return !!(this._events && this._events[eventType]);
32341     };
32342     return EventEmitter;
32343 }());
32344 exports.EventEmitter = EventEmitter;
32345 Object.defineProperty(exports, "__esModule", { value: true });
32346 exports.default = EventEmitter;
32347
32348 },{}],308:[function(require,module,exports){
32349 "use strict";
32350 var Viewer_1 = require("../Viewer");
32351 var Settings = (function () {
32352     function Settings() {
32353     }
32354     Settings.setOptions = function (options) {
32355         Settings._baseImageSize = options.baseImageSize != null ?
32356             options.baseImageSize :
32357             Viewer_1.ImageSize.Size640;
32358         Settings._basePanoramaSize = options.basePanoramaSize != null ?
32359             options.basePanoramaSize :
32360             Viewer_1.ImageSize.Size2048;
32361         Settings._maxImageSize = options.maxImageSize != null ?
32362             options.maxImageSize :
32363             Viewer_1.ImageSize.Size2048;
32364     };
32365     Object.defineProperty(Settings, "baseImageSize", {
32366         get: function () {
32367             return Settings._baseImageSize;
32368         },
32369         enumerable: true,
32370         configurable: true
32371     });
32372     Object.defineProperty(Settings, "basePanoramaSize", {
32373         get: function () {
32374             return Settings._basePanoramaSize;
32375         },
32376         enumerable: true,
32377         configurable: true
32378     });
32379     Object.defineProperty(Settings, "maxImageSize", {
32380         get: function () {
32381             return Settings._maxImageSize;
32382         },
32383         enumerable: true,
32384         configurable: true
32385     });
32386     return Settings;
32387 }());
32388 exports.Settings = Settings;
32389 Object.defineProperty(exports, "__esModule", { value: true });
32390 exports.default = Settings;
32391
32392 },{"../Viewer":219}],309:[function(require,module,exports){
32393 "use strict";
32394 var Urls = (function () {
32395     function Urls() {
32396     }
32397     Urls.dynamicImage = function (key, size) {
32398         return "https://d2qb1440i7l50o.cloudfront.net/" + key + "/full/!" + size + "," + size + "/0/default.jpg?origin=mapillary.webgl";
32399     };
32400     Urls.thumbnail = function (key, size) {
32401         return "https://d1cuyjsrcm0gby.cloudfront.net/" + key + "/thumb-" + size + ".jpg?origin=mapillary.webgl";
32402     };
32403     Urls.falcorModel = function (clientId) {
32404         return "https://a.mapillary.com/v3/model.json?client_id=" + clientId;
32405     };
32406     Urls.protoMesh = function (key) {
32407         return "https://d1brzeo354iq2l.cloudfront.net/v2/mesh/" + key;
32408     };
32409     return Urls;
32410 }());
32411 exports.Urls = Urls;
32412 Object.defineProperty(exports, "__esModule", { value: true });
32413 exports.default = Urls;
32414
32415 },{}],310:[function(require,module,exports){
32416 "use strict";
32417 var Component_1 = require("../Component");
32418 var ComponentController = (function () {
32419     function ComponentController(container, navigator, key, options) {
32420         var _this = this;
32421         this._container = container;
32422         this._navigator = navigator;
32423         this._options = options != null ? options : {};
32424         this._key = key;
32425         this._componentService = new Component_1.ComponentService(this._container, this._navigator);
32426         this._coverComponent = this._componentService.getCover();
32427         this._initializeComponents();
32428         if (key) {
32429             this._initilizeCoverComponent();
32430             this._subscribeCoverComponent();
32431         }
32432         else {
32433             this._navigator.movedToKey$
32434                 .first(function (k) {
32435                 return k != null;
32436             })
32437                 .subscribe(function (movedToKey) {
32438                 _this._key = movedToKey;
32439                 _this._componentService.deactivateCover();
32440                 _this._coverComponent.configure({ key: _this._key, loading: false, visible: false });
32441                 _this._subscribeCoverComponent();
32442                 _this._navigator.stateService.start();
32443             });
32444         }
32445     }
32446     ComponentController.prototype.get = function (name) {
32447         return this._componentService.get(name);
32448     };
32449     ComponentController.prototype.activate = function (name) {
32450         this._componentService.activate(name);
32451     };
32452     ComponentController.prototype.activateCover = function () {
32453         this._coverComponent.configure({ loading: false, visible: true });
32454     };
32455     ComponentController.prototype.deactivate = function (name) {
32456         this._componentService.deactivate(name);
32457     };
32458     ComponentController.prototype.deactivateCover = function () {
32459         this._coverComponent.configure({ loading: true, visible: true });
32460     };
32461     ComponentController.prototype.resize = function () {
32462         this._componentService.resize();
32463     };
32464     ComponentController.prototype._initializeComponents = function () {
32465         var options = this._options;
32466         this._uFalse(options.background, "background");
32467         this._uFalse(options.debug, "debug");
32468         this._uFalse(options.image, "image");
32469         this._uFalse(options.marker, "marker");
32470         this._uFalse(options.navigation, "navigation");
32471         this._uFalse(options.route, "route");
32472         this._uFalse(options.slider, "slider");
32473         this._uFalse(options.stats, "stats");
32474         this._uFalse(options.tag, "tag");
32475         this._uTrue(options.attribution, "attribution");
32476         this._uTrue(options.bearing, "bearing");
32477         this._uTrue(options.cache, "cache");
32478         this._uTrue(options.direction, "direction");
32479         this._uTrue(options.imagePlane, "imagePlane");
32480         this._uTrue(options.keyboard, "keyboard");
32481         this._uTrue(options.loading, "loading");
32482         this._uTrue(options.mouse, "mouse");
32483         this._uTrue(options.sequence, "sequence");
32484     };
32485     ComponentController.prototype._initilizeCoverComponent = function () {
32486         var options = this._options;
32487         this._coverComponent.configure({ key: this._key });
32488         if (options.cover === undefined || options.cover) {
32489             this.activateCover();
32490         }
32491         else {
32492             this.deactivateCover();
32493         }
32494     };
32495     ComponentController.prototype._subscribeCoverComponent = function () {
32496         var _this = this;
32497         this._coverComponent.configuration$.subscribe(function (conf) {
32498             if (conf.loading) {
32499                 _this._navigator.moveToKey$(conf.key)
32500                     .subscribe(function (node) {
32501                     _this._navigator.stateService.start();
32502                     _this._coverComponent.configure({ loading: false, visible: false });
32503                     _this._componentService.deactivateCover();
32504                 }, function (error) {
32505                     console.error("Failed to deactivate cover.", error);
32506                     _this._coverComponent.configure({ loading: false, visible: true });
32507                 });
32508             }
32509             else if (conf.visible) {
32510                 _this._navigator.stateService.stop();
32511                 _this._componentService.activateCover();
32512             }
32513         });
32514     };
32515     ComponentController.prototype._uFalse = function (option, name) {
32516         if (option === undefined) {
32517             this._componentService.deactivate(name);
32518             return;
32519         }
32520         if (typeof option === "boolean") {
32521             if (option) {
32522                 this._componentService.activate(name);
32523             }
32524             else {
32525                 this._componentService.deactivate(name);
32526             }
32527             return;
32528         }
32529         this._componentService.configure(name, option);
32530         this._componentService.activate(name);
32531     };
32532     ComponentController.prototype._uTrue = function (option, name) {
32533         if (option === undefined) {
32534             this._componentService.activate(name);
32535             return;
32536         }
32537         if (typeof option === "boolean") {
32538             if (option) {
32539                 this._componentService.activate(name);
32540             }
32541             else {
32542                 this._componentService.deactivate(name);
32543             }
32544             return;
32545         }
32546         this._componentService.configure(name, option);
32547         this._componentService.activate(name);
32548     };
32549     return ComponentController;
32550 }());
32551 exports.ComponentController = ComponentController;
32552
32553 },{"../Component":210}],311:[function(require,module,exports){
32554 "use strict";
32555 var Render_1 = require("../Render");
32556 var Viewer_1 = require("../Viewer");
32557 var Container = (function () {
32558     function Container(id, stateService, options) {
32559         this.id = id;
32560         this.element = document.getElementById(id);
32561         this.element.classList.add("mapillary-js");
32562         this.renderService = new Render_1.RenderService(this.element, stateService.currentState$, options.renderMode);
32563         this.glRenderer = new Render_1.GLRenderer(this.renderService);
32564         this.domRenderer = new Render_1.DOMRenderer(this.element, this.renderService, stateService.currentState$);
32565         this.mouseService = new Viewer_1.MouseService(this.element);
32566         this.touchService = new Viewer_1.TouchService(this.element);
32567         this.spriteService = new Viewer_1.SpriteService(options.sprite);
32568     }
32569     return Container;
32570 }());
32571 exports.Container = Container;
32572 Object.defineProperty(exports, "__esModule", { value: true });
32573 exports.default = Container;
32574
32575 },{"../Render":216,"../Viewer":219}],312:[function(require,module,exports){
32576 "use strict";
32577 var Observable_1 = require("rxjs/Observable");
32578 require("rxjs/add/observable/combineLatest");
32579 require("rxjs/add/operator/distinctUntilChanged");
32580 require("rxjs/add/operator/map");
32581 var Viewer_1 = require("../Viewer");
32582 var EventLauncher = (function () {
32583     function EventLauncher(eventEmitter, navigator, container) {
32584         var _this = this;
32585         this._container = container;
32586         this._eventEmitter = eventEmitter;
32587         this._navigator = navigator;
32588         this._loadingSubscription = this._navigator.loadingService.loading$
32589             .subscribe(function (loading) {
32590             _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading);
32591         });
32592         this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$
32593             .subscribe(function (node) {
32594             _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node);
32595         });
32596         this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$
32597             .switchMap(function (node) {
32598             return node.sequenceEdges$;
32599         })
32600             .subscribe(function (status) {
32601             _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status);
32602         });
32603         this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$
32604             .switchMap(function (node) {
32605             return node.spatialEdges$;
32606         })
32607             .subscribe(function (status) {
32608             _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status);
32609         });
32610         Observable_1.Observable
32611             .combineLatest(this._navigator.stateService.moving$, this._container.mouseService.active$)
32612             .map(function (values) {
32613             return values[0] || values[1];
32614         })
32615             .distinctUntilChanged()
32616             .subscribe(function (started) {
32617             if (started) {
32618                 _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null);
32619             }
32620             else {
32621                 _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null);
32622             }
32623         });
32624     }
32625     EventLauncher.prototype.dispose = function () {
32626         this._loadingSubscription.unsubscribe();
32627         this._currentNodeSubscription.unsubscribe();
32628     };
32629     return EventLauncher;
32630 }());
32631 exports.EventLauncher = EventLauncher;
32632 Object.defineProperty(exports, "__esModule", { value: true });
32633 exports.default = EventLauncher;
32634
32635 },{"../Viewer":219,"rxjs/Observable":28,"rxjs/add/observable/combineLatest":37,"rxjs/add/operator/distinctUntilChanged":54,"rxjs/add/operator/map":61}],313:[function(require,module,exports){
32636 "use strict";
32637 /**
32638  * Enumeration for image sizes
32639  * @enum {number}
32640  * @readonly
32641  * @description Image sizes in pixels for the long side of the image.
32642  */
32643 (function (ImageSize) {
32644     /**
32645      * 320 pixels image size
32646      */
32647     ImageSize[ImageSize["Size320"] = 320] = "Size320";
32648     /**
32649      * 640 pixels image size
32650      */
32651     ImageSize[ImageSize["Size640"] = 640] = "Size640";
32652     /**
32653      * 1024 pixels image size
32654      */
32655     ImageSize[ImageSize["Size1024"] = 1024] = "Size1024";
32656     /**
32657      * 2048 pixels image size
32658      */
32659     ImageSize[ImageSize["Size2048"] = 2048] = "Size2048";
32660 })(exports.ImageSize || (exports.ImageSize = {}));
32661 var ImageSize = exports.ImageSize;
32662
32663 },{}],314:[function(require,module,exports){
32664 /// <reference path="../../typings/index.d.ts" />
32665 "use strict";
32666 var _ = require("underscore");
32667 var Subject_1 = require("rxjs/Subject");
32668 require("rxjs/add/operator/debounceTime");
32669 require("rxjs/add/operator/distinctUntilChanged");
32670 require("rxjs/add/operator/map");
32671 require("rxjs/add/operator/publishReplay");
32672 require("rxjs/add/operator/scan");
32673 require("rxjs/add/operator/startWith");
32674 var LoadingService = (function () {
32675     function LoadingService() {
32676         this._loadersSubject$ = new Subject_1.Subject();
32677         this._loaders$ = this._loadersSubject$
32678             .scan(function (loaders, loader) {
32679             if (loader.task !== undefined) {
32680                 loaders[loader.task] = loader.loading;
32681             }
32682             return loaders;
32683         }, {})
32684             .startWith({})
32685             .publishReplay(1)
32686             .refCount();
32687     }
32688     Object.defineProperty(LoadingService.prototype, "loading$", {
32689         get: function () {
32690             return this._loaders$
32691                 .map(function (loaders) {
32692                 return _.reduce(loaders, function (loader, acc) {
32693                     return (loader || acc);
32694                 }, false);
32695             })
32696                 .debounceTime(100)
32697                 .distinctUntilChanged();
32698         },
32699         enumerable: true,
32700         configurable: true
32701     });
32702     LoadingService.prototype.taskLoading$ = function (task) {
32703         return this._loaders$
32704             .map(function (loaders) {
32705             return !!loaders[task];
32706         })
32707             .debounceTime(100)
32708             .distinctUntilChanged();
32709     };
32710     LoadingService.prototype.startLoading = function (task) {
32711         this._loadersSubject$.next({ loading: true, task: task });
32712     };
32713     LoadingService.prototype.stopLoading = function (task) {
32714         this._loadersSubject$.next({ loading: false, task: task });
32715     };
32716     return LoadingService;
32717 }());
32718 exports.LoadingService = LoadingService;
32719 Object.defineProperty(exports, "__esModule", { value: true });
32720 exports.default = LoadingService;
32721
32722 },{"rxjs/Subject":33,"rxjs/add/operator/debounceTime":52,"rxjs/add/operator/distinctUntilChanged":54,"rxjs/add/operator/map":61,"rxjs/add/operator/publishReplay":68,"rxjs/add/operator/scan":69,"rxjs/add/operator/startWith":73,"underscore":161}],315:[function(require,module,exports){
32723 /// <reference path="../../typings/index.d.ts" />
32724 "use strict";
32725 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
32726 var Observable_1 = require("rxjs/Observable");
32727 var Subject_1 = require("rxjs/Subject");
32728 require("rxjs/add/observable/fromEvent");
32729 require("rxjs/add/operator/distinctUntilChanged");
32730 require("rxjs/add/operator/filter");
32731 require("rxjs/add/operator/map");
32732 require("rxjs/add/operator/merge");
32733 require("rxjs/add/operator/mergeMap");
32734 require("rxjs/add/operator/publishReplay");
32735 require("rxjs/add/operator/scan");
32736 require("rxjs/add/operator/switchMap");
32737 require("rxjs/add/operator/withLatestFrom");
32738 var MouseService = (function () {
32739     function MouseService(element) {
32740         var _this = this;
32741         this._element = element;
32742         this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
32743         this._active$ = this._activeSubject$
32744             .distinctUntilChanged()
32745             .publishReplay(1)
32746             .refCount();
32747         this._preventMouseDownOperation$ = new Subject_1.Subject();
32748         this._preventMouseDown$ = new Subject_1.Subject();
32749         this._mouseMoveOperation$ = new Subject_1.Subject();
32750         this._claimMouse$ = new Subject_1.Subject();
32751         this._mouseDown$ = Observable_1.Observable.fromEvent(element, "mousedown");
32752         this._mouseLeave$ = Observable_1.Observable.fromEvent(element, "mouseleave");
32753         this._mouseUp$ = Observable_1.Observable.fromEvent(element, "mouseup");
32754         this._mouseOver$ = Observable_1.Observable.fromEvent(element, "mouseover");
32755         this._click$ = Observable_1.Observable.fromEvent(element, "click");
32756         this._mouseWheel$ = Observable_1.Observable.fromEvent(element, "wheel");
32757         this._mouseWheel$
32758             .subscribe(function (event) {
32759             event.preventDefault();
32760         });
32761         this._preventMouseDownOperation$
32762             .scan(function (prevent, operation) {
32763             return operation(prevent);
32764         }, true)
32765             .subscribe();
32766         this._preventMouseDown$
32767             .map(function (prevent) {
32768             return function (previous) {
32769                 return prevent;
32770             };
32771         })
32772             .subscribe(this._preventMouseDownOperation$);
32773         this._mouseDown$
32774             .map(function (e) {
32775             return function (prevent) {
32776                 if (prevent) {
32777                     e.preventDefault();
32778                 }
32779                 return prevent;
32780             };
32781         })
32782             .subscribe(this._preventMouseDownOperation$);
32783         this._mouseMove$ = this._mouseMoveOperation$
32784             .scan(function (e, operation) {
32785             return operation(e);
32786         }, null);
32787         Observable_1.Observable
32788             .fromEvent(element, "mousemove")
32789             .map(function (e) {
32790             return function (previous) {
32791                 if (previous == null) {
32792                     previous = e;
32793                 }
32794                 if (e.movementX == null) {
32795                     Object.defineProperty(e, "movementX", {
32796                         configurable: false,
32797                         enumerable: false,
32798                         value: e.clientX - previous.clientX,
32799                         writable: false,
32800                     });
32801                 }
32802                 if (e.movementY == null) {
32803                     Object.defineProperty(e, "movementY", {
32804                         configurable: false,
32805                         enumerable: false,
32806                         value: e.clientY - previous.clientY,
32807                         writable: false,
32808                     });
32809                 }
32810                 return e;
32811             };
32812         })
32813             .subscribe(this._mouseMoveOperation$);
32814         var dragStop$ = Observable_1.Observable
32815             .merge(this._mouseLeave$, this._mouseUp$);
32816         this._mouseDragStart$ = this._mouseDown$
32817             .mergeMap(function (e) {
32818             return _this._mouseMove$
32819                 .takeUntil(dragStop$)
32820                 .take(1);
32821         });
32822         this._mouseDrag$ = this._mouseDown$
32823             .mergeMap(function (e) {
32824             return _this._mouseMove$
32825                 .skip(1)
32826                 .takeUntil(dragStop$);
32827         });
32828         this._mouseDragEnd$ = this._mouseDragStart$
32829             .mergeMap(function (e) {
32830             return dragStop$.first();
32831         });
32832         this._staticClick$ = this._mouseDown$
32833             .switchMap(function (e) {
32834             return _this._click$
32835                 .takeUntil(_this._mouseMove$)
32836                 .take(1);
32837         });
32838         this._mouseOwner$ = this._claimMouse$
32839             .scan(function (claims, mouseClaim) {
32840             if (mouseClaim.zindex == null) {
32841                 delete claims[mouseClaim.name];
32842             }
32843             else {
32844                 claims[mouseClaim.name] = mouseClaim.zindex;
32845             }
32846             return claims;
32847         }, {})
32848             .map(function (claims) {
32849             var owner = null;
32850             var curZ = -1;
32851             for (var name_1 in claims) {
32852                 if (claims.hasOwnProperty(name_1)) {
32853                     if (claims[name_1] > curZ) {
32854                         curZ = claims[name_1];
32855                         owner = name_1;
32856                     }
32857                 }
32858             }
32859             return owner;
32860         })
32861             .publishReplay(1)
32862             .refCount();
32863     }
32864     Object.defineProperty(MouseService.prototype, "active$", {
32865         get: function () {
32866             return this._active$;
32867         },
32868         enumerable: true,
32869         configurable: true
32870     });
32871     Object.defineProperty(MouseService.prototype, "activate$", {
32872         get: function () {
32873             return this._activeSubject$;
32874         },
32875         enumerable: true,
32876         configurable: true
32877     });
32878     Object.defineProperty(MouseService.prototype, "mouseOwner$", {
32879         get: function () {
32880             return this._mouseOwner$;
32881         },
32882         enumerable: true,
32883         configurable: true
32884     });
32885     Object.defineProperty(MouseService.prototype, "mouseDown$", {
32886         get: function () {
32887             return this._mouseDown$;
32888         },
32889         enumerable: true,
32890         configurable: true
32891     });
32892     Object.defineProperty(MouseService.prototype, "mouseMove$", {
32893         get: function () {
32894             return this._mouseMove$;
32895         },
32896         enumerable: true,
32897         configurable: true
32898     });
32899     Object.defineProperty(MouseService.prototype, "mouseLeave$", {
32900         get: function () {
32901             return this._mouseLeave$;
32902         },
32903         enumerable: true,
32904         configurable: true
32905     });
32906     Object.defineProperty(MouseService.prototype, "mouseUp$", {
32907         get: function () {
32908             return this._mouseUp$;
32909         },
32910         enumerable: true,
32911         configurable: true
32912     });
32913     Object.defineProperty(MouseService.prototype, "click$", {
32914         get: function () {
32915             return this._click$;
32916         },
32917         enumerable: true,
32918         configurable: true
32919     });
32920     Object.defineProperty(MouseService.prototype, "mouseWheel$", {
32921         get: function () {
32922             return this._mouseWheel$;
32923         },
32924         enumerable: true,
32925         configurable: true
32926     });
32927     Object.defineProperty(MouseService.prototype, "mouseDragStart$", {
32928         get: function () {
32929             return this._mouseDragStart$;
32930         },
32931         enumerable: true,
32932         configurable: true
32933     });
32934     Object.defineProperty(MouseService.prototype, "mouseDrag$", {
32935         get: function () {
32936             return this._mouseDrag$;
32937         },
32938         enumerable: true,
32939         configurable: true
32940     });
32941     Object.defineProperty(MouseService.prototype, "mouseDragEnd$", {
32942         get: function () {
32943             return this._mouseDragEnd$;
32944         },
32945         enumerable: true,
32946         configurable: true
32947     });
32948     Object.defineProperty(MouseService.prototype, "staticClick$", {
32949         get: function () {
32950             return this._staticClick$;
32951         },
32952         enumerable: true,
32953         configurable: true
32954     });
32955     Object.defineProperty(MouseService.prototype, "preventDefaultMouseDown$", {
32956         get: function () {
32957             return this._preventMouseDown$;
32958         },
32959         enumerable: true,
32960         configurable: true
32961     });
32962     MouseService.prototype.claimMouse = function (name, zindex) {
32963         this._claimMouse$.next({ name: name, zindex: zindex });
32964     };
32965     MouseService.prototype.unclaimMouse = function (name) {
32966         this._claimMouse$.next({ name: name, zindex: null });
32967     };
32968     MouseService.prototype.filtered$ = function (name, observable$) {
32969         return observable$
32970             .withLatestFrom(this.mouseOwner$, function (event, owner) {
32971             return [event, owner];
32972         })
32973             .filter(function (eo) {
32974             return eo[1] === name;
32975         })
32976             .map(function (eo) {
32977             return eo[0];
32978         });
32979     };
32980     return MouseService;
32981 }());
32982 exports.MouseService = MouseService;
32983 Object.defineProperty(exports, "__esModule", { value: true });
32984 exports.default = MouseService;
32985
32986 },{"rxjs/BehaviorSubject":25,"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/observable/fromEvent":41,"rxjs/add/operator/distinctUntilChanged":54,"rxjs/add/operator/filter":57,"rxjs/add/operator/map":61,"rxjs/add/operator/merge":62,"rxjs/add/operator/mergeMap":64,"rxjs/add/operator/publishReplay":68,"rxjs/add/operator/scan":69,"rxjs/add/operator/switchMap":74,"rxjs/add/operator/withLatestFrom":77}],316:[function(require,module,exports){
32987 /// <reference path="../../typings/index.d.ts" />
32988 "use strict";
32989 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
32990 var Observable_1 = require("rxjs/Observable");
32991 require("rxjs/add/observable/throw");
32992 require("rxjs/add/operator/do");
32993 require("rxjs/add/operator/finally");
32994 require("rxjs/add/operator/first");
32995 require("rxjs/add/operator/map");
32996 require("rxjs/add/operator/mergeMap");
32997 var API_1 = require("../API");
32998 var Graph_1 = require("../Graph");
32999 var Edge_1 = require("../Edge");
33000 var State_1 = require("../State");
33001 var Viewer_1 = require("../Viewer");
33002 var Navigator = (function () {
33003     function Navigator(clientId, token, apiV3, graphService, imageLoadingService, loadingService, stateService) {
33004         this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token);
33005         this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService();
33006         this._graphService = graphService != null ?
33007             graphService :
33008             new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService);
33009         this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService();
33010         this._loadingName = "navigator";
33011         this._stateService = stateService != null ? stateService : new State_1.StateService();
33012         this._keyRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
33013         this._movedToKey$ = new BehaviorSubject_1.BehaviorSubject(null);
33014         this._dirRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
33015         this._latLonRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
33016     }
33017     Object.defineProperty(Navigator.prototype, "apiV3", {
33018         get: function () {
33019             return this._apiV3;
33020         },
33021         enumerable: true,
33022         configurable: true
33023     });
33024     Object.defineProperty(Navigator.prototype, "graphService", {
33025         get: function () {
33026             return this._graphService;
33027         },
33028         enumerable: true,
33029         configurable: true
33030     });
33031     Object.defineProperty(Navigator.prototype, "imageLoadingService", {
33032         get: function () {
33033             return this._imageLoadingService;
33034         },
33035         enumerable: true,
33036         configurable: true
33037     });
33038     Object.defineProperty(Navigator.prototype, "keyRequested$", {
33039         get: function () {
33040             return this._keyRequested$;
33041         },
33042         enumerable: true,
33043         configurable: true
33044     });
33045     Object.defineProperty(Navigator.prototype, "loadingService", {
33046         get: function () {
33047             return this._loadingService;
33048         },
33049         enumerable: true,
33050         configurable: true
33051     });
33052     Object.defineProperty(Navigator.prototype, "movedToKey$", {
33053         get: function () {
33054             return this._movedToKey$;
33055         },
33056         enumerable: true,
33057         configurable: true
33058     });
33059     Object.defineProperty(Navigator.prototype, "stateService", {
33060         get: function () {
33061             return this._stateService;
33062         },
33063         enumerable: true,
33064         configurable: true
33065     });
33066     Navigator.prototype.moveToKey$ = function (key) {
33067         var _this = this;
33068         this.loadingService.startLoading(this._loadingName);
33069         this._keyRequested$.next(key);
33070         return this._graphService.cacheNode$(key)
33071             .do(function (node) {
33072             _this.stateService.setNodes([node]);
33073             _this._movedToKey$.next(node.key);
33074         })
33075             .finally(function () {
33076             _this.loadingService.stopLoading(_this._loadingName);
33077         });
33078     };
33079     Navigator.prototype.moveDir$ = function (direction) {
33080         var _this = this;
33081         this.loadingService.startLoading(this._loadingName);
33082         this._dirRequested$.next(direction);
33083         return this.stateService.currentNode$
33084             .first()
33085             .mergeMap(function (node) {
33086             return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
33087                 node.sequenceEdges$ :
33088                 node.spatialEdges$)
33089                 .first()
33090                 .map(function (status) {
33091                 for (var _i = 0, _a = status.edges; _i < _a.length; _i++) {
33092                     var edge = _a[_i];
33093                     if (edge.data.direction === direction) {
33094                         return edge.to;
33095                     }
33096                 }
33097                 return null;
33098             });
33099         })
33100             .mergeMap(function (directionKey) {
33101             if (directionKey == null) {
33102                 _this.loadingService.stopLoading(_this._loadingName);
33103                 return Observable_1.Observable
33104                     .throw(new Error("Direction (" + direction + ") does not exist for current node."));
33105             }
33106             return _this.moveToKey$(directionKey);
33107         });
33108     };
33109     Navigator.prototype.moveCloseTo$ = function (lat, lon) {
33110         var _this = this;
33111         this.loadingService.startLoading(this._loadingName);
33112         this._latLonRequested$.next({ lat: lat, lon: lon });
33113         return this.apiV3.imageCloseTo$(lat, lon)
33114             .mergeMap(function (fullNode) {
33115             if (fullNode == null) {
33116                 _this.loadingService.stopLoading(_this._loadingName);
33117                 return Observable_1.Observable
33118                     .throw(new Error("No image found close to lat " + lat + ", lon " + lon + "."));
33119             }
33120             return _this.moveToKey$(fullNode.key);
33121         });
33122     };
33123     Navigator.prototype.setFilter$ = function (filter) {
33124         var _this = this;
33125         this._stateService.clearNodes();
33126         return this._movedToKey$
33127             .first()
33128             .mergeMap(function (key) {
33129             if (key != null) {
33130                 return _this._trajectoryKeys$()
33131                     .mergeMap(function (keys) {
33132                     return _this._graphService.setFilter$(filter)
33133                         .mergeMap(function (graph) {
33134                         return _this._cacheKeys$(keys);
33135                     });
33136                 })
33137                     .last();
33138             }
33139             return _this._keyRequested$
33140                 .mergeMap(function (requestedKey) {
33141                 if (requestedKey != null) {
33142                     return _this._graphService.setFilter$(filter)
33143                         .mergeMap(function (graph) {
33144                         return _this._graphService.cacheNode$(requestedKey);
33145                     });
33146                 }
33147                 return _this._graphService.setFilter$(filter)
33148                     .map(function (graph) {
33149                     return undefined;
33150                 });
33151             });
33152         })
33153             .map(function (node) {
33154             return undefined;
33155         });
33156     };
33157     Navigator.prototype.setToken$ = function (token) {
33158         var _this = this;
33159         this._stateService.clearNodes();
33160         return this._movedToKey$
33161             .first()
33162             .do(function (key) {
33163             _this._apiV3.setToken(token);
33164         })
33165             .mergeMap(function (key) {
33166             return key == null ?
33167                 _this._graphService.reset$([])
33168                     .map(function (graph) {
33169                     return undefined;
33170                 }) :
33171                 _this._trajectoryKeys$()
33172                     .mergeMap(function (keys) {
33173                     return _this._graphService.reset$(keys)
33174                         .mergeMap(function (graph) {
33175                         return _this._cacheKeys$(keys);
33176                     });
33177                 })
33178                     .last()
33179                     .map(function (node) {
33180                     return undefined;
33181                 });
33182         });
33183     };
33184     Navigator.prototype._cacheKeys$ = function (keys) {
33185         var _this = this;
33186         var cacheNodes$ = keys
33187             .map(function (key) {
33188             return _this._graphService.cacheNode$(key);
33189         });
33190         return Observable_1.Observable
33191             .from(cacheNodes$)
33192             .mergeAll();
33193     };
33194     Navigator.prototype._trajectoryKeys$ = function () {
33195         return this._stateService.currentState$
33196             .first()
33197             .map(function (frame) {
33198             return frame.state.trajectory
33199                 .map(function (node) {
33200                 return node.key;
33201             });
33202         });
33203     };
33204     return Navigator;
33205 }());
33206 exports.Navigator = Navigator;
33207 Object.defineProperty(exports, "__esModule", { value: true });
33208 exports.default = Navigator;
33209
33210 },{"../API":209,"../Edge":211,"../Graph":214,"../State":217,"../Viewer":219,"rxjs/BehaviorSubject":25,"rxjs/Observable":28,"rxjs/add/observable/throw":45,"rxjs/add/operator/do":55,"rxjs/add/operator/finally":58,"rxjs/add/operator/first":59,"rxjs/add/operator/map":61,"rxjs/add/operator/mergeMap":64}],317:[function(require,module,exports){
33211 "use strict";
33212 (function (SpriteAlignment) {
33213     SpriteAlignment[SpriteAlignment["Center"] = 0] = "Center";
33214     SpriteAlignment[SpriteAlignment["Start"] = 1] = "Start";
33215     SpriteAlignment[SpriteAlignment["End"] = 2] = "End";
33216 })(exports.SpriteAlignment || (exports.SpriteAlignment = {}));
33217 var SpriteAlignment = exports.SpriteAlignment;
33218 Object.defineProperty(exports, "__esModule", { value: true });
33219 exports.default = SpriteAlignment;
33220
33221 },{}],318:[function(require,module,exports){
33222 /// <reference path="../../typings/index.d.ts" />
33223 "use strict";
33224 var THREE = require("three");
33225 var vd = require("virtual-dom");
33226 var Subject_1 = require("rxjs/Subject");
33227 require("rxjs/add/operator/publishReplay");
33228 require("rxjs/add/operator/scan");
33229 require("rxjs/add/operator/startWith");
33230 var Viewer_1 = require("../Viewer");
33231 var SpriteAtlas = (function () {
33232     function SpriteAtlas() {
33233     }
33234     Object.defineProperty(SpriteAtlas.prototype, "json", {
33235         set: function (value) {
33236             this._json = value;
33237         },
33238         enumerable: true,
33239         configurable: true
33240     });
33241     Object.defineProperty(SpriteAtlas.prototype, "image", {
33242         set: function (value) {
33243             this._image = value;
33244             this._texture = new THREE.Texture(this._image);
33245             this._texture.minFilter = THREE.NearestFilter;
33246         },
33247         enumerable: true,
33248         configurable: true
33249     });
33250     Object.defineProperty(SpriteAtlas.prototype, "loaded", {
33251         get: function () {
33252             return !!(this._image && this._json);
33253         },
33254         enumerable: true,
33255         configurable: true
33256     });
33257     SpriteAtlas.prototype.getGLSprite = function (name) {
33258         if (!this.loaded) {
33259             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
33260         }
33261         var definition = this._json[name];
33262         if (!definition) {
33263             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
33264             return new THREE.Object3D();
33265         }
33266         var texture = this._texture.clone();
33267         texture.needsUpdate = true;
33268         var width = this._image.width;
33269         var height = this._image.height;
33270         texture.offset.x = definition.x / width;
33271         texture.offset.y = (height - definition.y - definition.height) / height;
33272         texture.repeat.x = definition.width / width;
33273         texture.repeat.y = definition.height / height;
33274         var material = new THREE.SpriteMaterial({ map: texture });
33275         return new THREE.Sprite(material);
33276     };
33277     SpriteAtlas.prototype.getDOMSprite = function (name, horizontalAlign, verticalAlign) {
33278         if (!this.loaded) {
33279             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
33280         }
33281         if (horizontalAlign == null) {
33282             horizontalAlign = Viewer_1.SpriteAlignment.Start;
33283         }
33284         if (verticalAlign == null) {
33285             verticalAlign = Viewer_1.SpriteAlignment.Start;
33286         }
33287         var definition = this._json[name];
33288         if (!definition) {
33289             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
33290             return vd.h("div", {}, []);
33291         }
33292         var clipTop = definition.y;
33293         var clipRigth = definition.x + definition.width;
33294         var clipBottom = definition.y + definition.height;
33295         var clipLeft = definition.x;
33296         var left = -definition.x;
33297         var top = -definition.y;
33298         var height = this._image.height;
33299         var width = this._image.width;
33300         switch (horizontalAlign) {
33301             case Viewer_1.SpriteAlignment.Center:
33302                 left -= definition.width / 2;
33303                 break;
33304             case Viewer_1.SpriteAlignment.End:
33305                 left -= definition.width;
33306                 break;
33307             case Viewer_1.SpriteAlignment.Start:
33308                 break;
33309             default:
33310                 break;
33311         }
33312         switch (verticalAlign) {
33313             case Viewer_1.SpriteAlignment.Center:
33314                 top -= definition.height / 2;
33315                 break;
33316             case Viewer_1.SpriteAlignment.End:
33317                 top -= definition.height;
33318                 break;
33319             case Viewer_1.SpriteAlignment.Start:
33320                 break;
33321             default:
33322                 break;
33323         }
33324         var pixelRatioInverse = 1 / definition.pixelRatio;
33325         clipTop *= pixelRatioInverse;
33326         clipRigth *= pixelRatioInverse;
33327         clipBottom *= pixelRatioInverse;
33328         clipLeft *= pixelRatioInverse;
33329         left *= pixelRatioInverse;
33330         top *= pixelRatioInverse;
33331         height *= pixelRatioInverse;
33332         width *= pixelRatioInverse;
33333         var properties = {
33334             src: this._image.src,
33335             style: {
33336                 clip: "rect(" + clipTop + "px, " + clipRigth + "px, " + clipBottom + "px, " + clipLeft + "px)",
33337                 height: height + "px",
33338                 left: left + "px",
33339                 position: "absolute",
33340                 top: top + "px",
33341                 width: width + "px",
33342             },
33343         };
33344         return vd.h("img", properties, []);
33345     };
33346     return SpriteAtlas;
33347 }());
33348 var SpriteService = (function () {
33349     function SpriteService(sprite) {
33350         var _this = this;
33351         this._retina = window.devicePixelRatio > 1;
33352         this._spriteAtlasOperation$ = new Subject_1.Subject();
33353         this._spriteAtlas$ = this._spriteAtlasOperation$
33354             .startWith(function (atlas) {
33355             return atlas;
33356         })
33357             .scan(function (atlas, operation) {
33358             return operation(atlas);
33359         }, new SpriteAtlas())
33360             .publishReplay(1)
33361             .refCount();
33362         this._spriteAtlas$.subscribe();
33363         if (sprite == null) {
33364             return;
33365         }
33366         var format = this._retina ? "@2x" : "";
33367         var imageXmlHTTP = new XMLHttpRequest();
33368         imageXmlHTTP.open("GET", sprite + format + ".png", true);
33369         imageXmlHTTP.responseType = "arraybuffer";
33370         imageXmlHTTP.onload = function () {
33371             var image = new Image();
33372             image.onload = function () {
33373                 _this._spriteAtlasOperation$.next(function (atlas) {
33374                     atlas.image = image;
33375                     return atlas;
33376                 });
33377             };
33378             var blob = new Blob([imageXmlHTTP.response]);
33379             image.src = window.URL.createObjectURL(blob);
33380         };
33381         imageXmlHTTP.onerror = function (error) {
33382             console.error(new Error("Failed to fetch sprite sheet (" + sprite + format + ".png)"));
33383         };
33384         imageXmlHTTP.send();
33385         var jsonXmlHTTP = new XMLHttpRequest();
33386         jsonXmlHTTP.open("GET", sprite + format + ".json", true);
33387         jsonXmlHTTP.responseType = "text";
33388         jsonXmlHTTP.onload = function () {
33389             var json = JSON.parse(jsonXmlHTTP.response);
33390             _this._spriteAtlasOperation$.next(function (atlas) {
33391                 atlas.json = json;
33392                 return atlas;
33393             });
33394         };
33395         jsonXmlHTTP.onerror = function (error) {
33396             console.error(new Error("Failed to fetch sheet (" + sprite + format + ".json)"));
33397         };
33398         jsonXmlHTTP.send();
33399     }
33400     Object.defineProperty(SpriteService.prototype, "spriteAtlas$", {
33401         get: function () {
33402             return this._spriteAtlas$;
33403         },
33404         enumerable: true,
33405         configurable: true
33406     });
33407     return SpriteService;
33408 }());
33409 exports.SpriteService = SpriteService;
33410 Object.defineProperty(exports, "__esModule", { value: true });
33411 exports.default = SpriteService;
33412
33413 },{"../Viewer":219,"rxjs/Subject":33,"rxjs/add/operator/publishReplay":68,"rxjs/add/operator/scan":69,"rxjs/add/operator/startWith":73,"three":160,"virtual-dom":166}],319:[function(require,module,exports){
33414 /// <reference path="../../typings/index.d.ts" />
33415 "use strict";
33416 var Observable_1 = require("rxjs/Observable");
33417 var Subject_1 = require("rxjs/Subject");
33418 require("rxjs/add/operator/filter");
33419 require("rxjs/add/operator/map");
33420 require("rxjs/add/operator/merge");
33421 require("rxjs/add/operator/scan");
33422 require("rxjs/add/operator/switchMap");
33423 var TouchMove = (function () {
33424     function TouchMove(touch) {
33425         this.movementX = 0;
33426         this.movementY = 0;
33427         if (touch == null) {
33428             return;
33429         }
33430         this.identifier = touch.identifier;
33431         this.clientX = touch.clientX;
33432         this.clientY = touch.clientY;
33433         this.pageX = touch.pageX;
33434         this.pageY = touch.pageY;
33435         this.screenX = touch.screenX;
33436         this.screenY = touch.screenY;
33437         this.target = touch.target;
33438     }
33439     return TouchMove;
33440 }());
33441 exports.TouchMove = TouchMove;
33442 var TouchService = (function () {
33443     function TouchService(element) {
33444         var _this = this;
33445         this._element = element;
33446         this._touchStart$ = Observable_1.Observable.fromEvent(element, "touchstart");
33447         this._touchMove$ = Observable_1.Observable.fromEvent(element, "touchmove");
33448         this._touchEnd$ = Observable_1.Observable.fromEvent(element, "touchend");
33449         this._touchCancel$ = Observable_1.Observable.fromEvent(element, "touchcancel");
33450         this._preventTouchMoveOperation$ = new Subject_1.Subject();
33451         this._preventTouchMove$ = new Subject_1.Subject();
33452         this._preventTouchMoveOperation$
33453             .scan(function (prevent, operation) {
33454             return operation(prevent);
33455         }, true)
33456             .subscribe();
33457         this._preventTouchMove$
33458             .map(function (prevent) {
33459             return function (previous) {
33460                 return prevent;
33461             };
33462         })
33463             .subscribe(this._preventTouchMoveOperation$);
33464         this._touchMove$
33465             .map(function (te) {
33466             return function (prevent) {
33467                 if (prevent) {
33468                     te.preventDefault();
33469                 }
33470                 return prevent;
33471             };
33472         })
33473             .subscribe(this._preventTouchMoveOperation$);
33474         this._singleTouchMoveOperation$ = new Subject_1.Subject();
33475         this._singleTouchMove$ = this._singleTouchMoveOperation$
33476             .scan(function (touch, operation) {
33477             return operation(touch);
33478         }, new TouchMove());
33479         this._touchMove$
33480             .filter(function (te) {
33481             return te.touches.length === 1 && te.targetTouches.length === 1;
33482         })
33483             .map(function (te) {
33484             return function (previous) {
33485                 var touch = te.touches[0];
33486                 var current = new TouchMove(touch);
33487                 current.movementX = touch.pageX - previous.pageX;
33488                 current.movementY = touch.pageY - previous.pageY;
33489                 return current;
33490             };
33491         })
33492             .subscribe(this._singleTouchMoveOperation$);
33493         var singleTouchStart$ = Observable_1.Observable
33494             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
33495             .filter(function (te) {
33496             return te.touches.length === 1 && te.targetTouches.length === 1;
33497         });
33498         var multipleTouchStart$ = Observable_1.Observable
33499             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
33500             .filter(function (te) {
33501             return te.touches.length >= 1;
33502         });
33503         var touchStop$ = Observable_1.Observable
33504             .merge(this._touchEnd$, this._touchCancel$)
33505             .filter(function (te) {
33506             return te.touches.length === 0;
33507         });
33508         this._singleTouch$ = singleTouchStart$
33509             .switchMap(function (te) {
33510             return _this._singleTouchMove$
33511                 .skip(1)
33512                 .takeUntil(Observable_1.Observable
33513                 .merge(multipleTouchStart$, touchStop$));
33514         });
33515         var touchesChanged$ = Observable_1.Observable
33516             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$);
33517         var pinchStart$ = touchesChanged$
33518             .filter(function (te) {
33519             return te.touches.length === 2 && te.targetTouches.length === 2;
33520         });
33521         var pinchStop$ = touchesChanged$
33522             .filter(function (te) {
33523             return te.touches.length !== 2 || te.targetTouches.length !== 2;
33524         });
33525         this._pinchOperation$ = new Subject_1.Subject();
33526         this._pinch$ = this._pinchOperation$
33527             .scan(function (pinch, operation) {
33528             return operation(pinch);
33529         }, {
33530             centerClientX: 0,
33531             centerClientY: 0,
33532             centerPageX: 0,
33533             centerPageY: 0,
33534             centerScreenX: 0,
33535             centerScreenY: 0,
33536             changeX: 0,
33537             changeY: 0,
33538             distance: 0,
33539             distanceChange: 0,
33540             distanceX: 0,
33541             distanceY: 0,
33542             touch1: null,
33543             touch2: null,
33544         });
33545         this._touchMove$
33546             .filter(function (te) {
33547             return te.touches.length === 2 && te.targetTouches.length === 2;
33548         })
33549             .map(function (te) {
33550             return function (previous) {
33551                 var touch1 = te.touches[0];
33552                 var touch2 = te.touches[1];
33553                 var minX = Math.min(touch1.clientX, touch2.clientX);
33554                 var maxX = Math.max(touch1.clientX, touch2.clientX);
33555                 var minY = Math.min(touch1.clientY, touch2.clientY);
33556                 var maxY = Math.max(touch1.clientY, touch2.clientY);
33557                 var centerClientX = minX + (maxX - minX) / 2;
33558                 var centerClientY = minY + (maxY - minY) / 2;
33559                 var centerPageX = centerClientX + touch1.pageX - touch1.clientX;
33560                 var centerPageY = centerClientY + touch1.pageY - touch1.clientY;
33561                 var centerScreenX = centerClientX + touch1.screenX - touch1.clientX;
33562                 var centerScreenY = centerClientY + touch1.screenY - touch1.clientY;
33563                 var distanceX = Math.abs(touch1.clientX - touch2.clientX);
33564                 var distanceY = Math.abs(touch1.clientY - touch2.clientY);
33565                 var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
33566                 var distanceChange = distance - previous.distance;
33567                 var changeX = distanceX - previous.distanceX;
33568                 var changeY = distanceY - previous.distanceY;
33569                 var current = {
33570                     centerClientX: centerClientX,
33571                     centerClientY: centerClientY,
33572                     centerPageX: centerPageX,
33573                     centerPageY: centerPageY,
33574                     centerScreenX: centerScreenX,
33575                     centerScreenY: centerScreenY,
33576                     changeX: changeX,
33577                     changeY: changeY,
33578                     distance: distance,
33579                     distanceChange: distanceChange,
33580                     distanceX: distanceX,
33581                     distanceY: distanceY,
33582                     touch1: touch1,
33583                     touch2: touch2,
33584                 };
33585                 return current;
33586             };
33587         })
33588             .subscribe(this._pinchOperation$);
33589         this._pinchChange$ = pinchStart$
33590             .switchMap(function (te) {
33591             return _this._pinch$
33592                 .skip(1)
33593                 .takeUntil(pinchStop$);
33594         });
33595     }
33596     Object.defineProperty(TouchService.prototype, "touchStart$", {
33597         get: function () {
33598             return this._touchStart$;
33599         },
33600         enumerable: true,
33601         configurable: true
33602     });
33603     Object.defineProperty(TouchService.prototype, "touchMove$", {
33604         get: function () {
33605             return this._touchMove$;
33606         },
33607         enumerable: true,
33608         configurable: true
33609     });
33610     Object.defineProperty(TouchService.prototype, "touchEnd$", {
33611         get: function () {
33612             return this._touchEnd$;
33613         },
33614         enumerable: true,
33615         configurable: true
33616     });
33617     Object.defineProperty(TouchService.prototype, "touchCancel$", {
33618         get: function () {
33619             return this._touchCancel$;
33620         },
33621         enumerable: true,
33622         configurable: true
33623     });
33624     Object.defineProperty(TouchService.prototype, "singleTouchMove$", {
33625         get: function () {
33626             return this._singleTouch$;
33627         },
33628         enumerable: true,
33629         configurable: true
33630     });
33631     Object.defineProperty(TouchService.prototype, "pinch$", {
33632         get: function () {
33633             return this._pinchChange$;
33634         },
33635         enumerable: true,
33636         configurable: true
33637     });
33638     Object.defineProperty(TouchService.prototype, "preventDefaultTouchMove$", {
33639         get: function () {
33640             return this._preventTouchMove$;
33641         },
33642         enumerable: true,
33643         configurable: true
33644     });
33645     return TouchService;
33646 }());
33647 exports.TouchService = TouchService;
33648
33649 },{"rxjs/Observable":28,"rxjs/Subject":33,"rxjs/add/operator/filter":57,"rxjs/add/operator/map":61,"rxjs/add/operator/merge":62,"rxjs/add/operator/scan":69,"rxjs/add/operator/switchMap":74}],320:[function(require,module,exports){
33650 /// <reference path="../../typings/index.d.ts" />
33651 "use strict";
33652 var __extends = (this && this.__extends) || function (d, b) {
33653     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
33654     function __() { this.constructor = d; }
33655     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33656 };
33657 var when = require("when");
33658 var Viewer_1 = require("../Viewer");
33659 var Utils_1 = require("../Utils");
33660 /**
33661  * @class Viewer
33662  *
33663  * @classdesc The Viewer object represents the navigable photo viewer.
33664  * Create a Viewer by specifying a container, client ID, photo key and
33665  * other options. The viewer exposes methods and events for programmatic
33666  * interaction.
33667  */
33668 var Viewer = (function (_super) {
33669     __extends(Viewer, _super);
33670     /**
33671      * Create a new viewer instance.
33672      *
33673      * @param {string} id - Required `id` of a DOM element which will
33674      * be transformed into the viewer.
33675      * @param {string} clientId - Required `Mapillary API ClientID`. Can
33676      * be obtained from https://www.mapillary.com/app/settings/developers.
33677      * @param {string} [key] - Optional `photoId` to start from, can be any
33678      * Mapillary photo, if null no image is loaded.
33679      * @param {IViewerOptions} [options] - Optional configuration object
33680      * specifing Viewer's initial setup.
33681      * @param {string} [token] - Optional bearer token for API requests of
33682      * protected resources.
33683      */
33684     function Viewer(id, clientId, key, options, token) {
33685         _super.call(this);
33686         options = options != null ? options : {};
33687         Utils_1.Settings.setOptions(options);
33688         this._navigator = new Viewer_1.Navigator(clientId, token);
33689         this._container = new Viewer_1.Container(id, this._navigator.stateService, options);
33690         this._eventLauncher = new Viewer_1.EventLauncher(this, this._navigator, this._container);
33691         this._componentController = new Viewer_1.ComponentController(this._container, this._navigator, key, options.component);
33692     }
33693     /**
33694      * Activate a component.
33695      *
33696      * @param {string} name - Name of the component which will become active.
33697      */
33698     Viewer.prototype.activateComponent = function (name) {
33699         this._componentController.activate(name);
33700     };
33701     /**
33702      * Activate the cover (deactivates all other components).
33703      */
33704     Viewer.prototype.activateCover = function () {
33705         this._componentController.activateCover();
33706     };
33707     /**
33708      * Deactivate a component.
33709      *
33710      * @param {string} name - Name of component which become inactive.
33711      */
33712     Viewer.prototype.deactivateComponent = function (name) {
33713         this._componentController.deactivate(name);
33714     };
33715     /**
33716      * Deactivate the cover (activates all components marked as active).
33717      */
33718     Viewer.prototype.deactivateCover = function () {
33719         this._componentController.deactivateCover();
33720     };
33721     /**
33722      * Get the basic coordinates of the current photo that is
33723      * at the center of the viewport.
33724      *
33725      * @description Basic coordinates are on the [0, 1] interval and
33726      * has the origin point, [0, 0], at the top left corner and the
33727      * maximum value, [1, 1], at the bottom right corner of the original
33728      * photo.
33729      *
33730      * @returns {Promise<number[]>} Promise to the basic coordinates
33731      * of the current photo at the center for the viewport.
33732      */
33733     Viewer.prototype.getCenter = function () {
33734         var _this = this;
33735         return when.promise(function (resolve, reject) {
33736             _this._navigator.stateService.getCenter()
33737                 .subscribe(function (center) {
33738                 resolve(center);
33739             }, function (error) {
33740                 reject(error);
33741             });
33742         });
33743     };
33744     /**
33745      * Get a component.
33746      *
33747      * @param {string} name - Name of component.
33748      * @returns {Component} The requested component.
33749      */
33750     Viewer.prototype.getComponent = function (name) {
33751         return this._componentController.get(name);
33752     };
33753     /**
33754      * Get the photo's current zoom level.
33755      *
33756      * @returns {Promise<number>} Promise to the viewers's current
33757      * zoom level.
33758      */
33759     Viewer.prototype.getZoom = function () {
33760         var _this = this;
33761         return when.promise(function (resolve, reject) {
33762             _this._navigator.stateService.getZoom()
33763                 .subscribe(function (zoom) {
33764                 resolve(zoom);
33765             }, function (error) {
33766                 reject(error);
33767             });
33768         });
33769     };
33770     /**
33771      * Move close to given latitude and longitude.
33772      *
33773      * @param {Number} lat - Latitude, in degrees.
33774      * @param {Number} lon - Longitude, in degrees.
33775      * @returns {Promise<Node>} Promise to the node that was navigated to.
33776      * @throws {Error} If no nodes exist close to provided latitude
33777      * longitude.
33778      * @throws {Error} Propagates any IO errors to the caller.
33779      */
33780     Viewer.prototype.moveCloseTo = function (lat, lon) {
33781         var _this = this;
33782         return when.promise(function (resolve, reject) {
33783             _this._navigator.moveCloseTo$(lat, lon).subscribe(function (node) {
33784                 resolve(node);
33785             }, function (error) {
33786                 reject(error);
33787             });
33788         });
33789     };
33790     /**
33791      * Navigate in a given direction.
33792      *
33793      * @description This method has to be called through EdgeDirection enumeration as in the example.
33794      *
33795      * @param {EdgeDirection} dir - Direction in which which to move.
33796      * @returns {Promise<Node>} Promise to the node that was navigated to.
33797      * @throws {Error} If the current node does not have the edge direction
33798      * or the edges has not yet been cached.
33799      * @throws {Error} Propagates any IO errors to the caller.
33800      *
33801      * @example `viewer.moveDir(Mapillary.EdgeDirection.Next);`
33802      */
33803     Viewer.prototype.moveDir = function (dir) {
33804         var _this = this;
33805         return when.promise(function (resolve, reject) {
33806             _this._navigator.moveDir$(dir).subscribe(function (node) {
33807                 resolve(node);
33808             }, function (error) {
33809                 reject(error);
33810             });
33811         });
33812     };
33813     /**
33814      * Navigate to a given photo key.
33815      *
33816      * @param {string} key - A valid Mapillary photo key.
33817      * @returns {Promise<Node>} Promise to the node that was navigated to.
33818      * @throws {Error} Propagates any IO errors to the caller.
33819      */
33820     Viewer.prototype.moveToKey = function (key) {
33821         var _this = this;
33822         return when.promise(function (resolve, reject) {
33823             _this._navigator.moveToKey$(key).subscribe(function (node) {
33824                 resolve(node);
33825             }, function (error) {
33826                 reject(error);
33827             });
33828         });
33829     };
33830     /**
33831      * Detect the viewer's new width and height and resize it.
33832      *
33833      * @description The components will also detect the viewer's
33834      * new size and resize their rendered elements if needed.
33835      */
33836     Viewer.prototype.resize = function () {
33837         this._container.renderService.resize$.next(null);
33838         this._componentController.resize();
33839     };
33840     /**
33841      * Set a bearer token for API requests of protected resources.
33842      *
33843      * @description When the supplied token is an empty string
33844      * or null, any previously set access token will be cleared.
33845      *
33846      * Calling setAuthToken aborts all outstanding move requests.
33847      * The promises of those move requests will be rejected and
33848      * the rejections need to be caught.
33849      *
33850      * @param {string} [token] token - Bearer token.
33851      * @returns {Promise<void>} Promise that resolves after token
33852      * is set.
33853      */
33854     Viewer.prototype.setAuthToken = function (token) {
33855         var _this = this;
33856         return when.promise(function (resolve, reject) {
33857             _this._navigator.setToken$(token)
33858                 .subscribe(function () {
33859                 resolve(undefined);
33860             }, function (error) {
33861                 reject(error);
33862             });
33863         });
33864     };
33865     /**
33866      * Set the basic coordinates of the current photo to be in the
33867      * center of the viewport.
33868      *
33869      * @description Basic coordinates are on the [0, 1] interval and
33870      * has the origin point, [0, 0], at the top left corner and the
33871      * maximum value, [1, 1], at the bottom right corner of the original
33872      * photo.
33873      *
33874      * @param {number[]} The basic coordinates of the current
33875      * photo to be at the center for the viewport.
33876      */
33877     Viewer.prototype.setCenter = function (center) {
33878         this._navigator.stateService.setCenter(center);
33879     };
33880     /**
33881      * Set the filter selecting nodes to use when calculating
33882      * the spatial edges.
33883      *
33884      * @description The following filter types are supported:
33885      *
33886      * Comparison
33887      *
33888      * `["==", key, value]` equality: `node[key] = value`
33889      *
33890      * `["!=", key, value]` inequality: `node[key] ≠ value`
33891      *
33892      * `["<", key, value]` less than: `node[key] < value`
33893      *
33894      * `["<=", key, value]` less than or equal: `node[key] ≤ value`
33895      *
33896      * `[">", key, value]` greater than: `node[key] > value`
33897      *
33898      * `[">=", key, value]` greater than or equal: `node[key] ≥ value`
33899      *
33900      * Set membership
33901      *
33902      * `["in", key, v0, ..., vn]` set inclusion: `node[key] ∈ {v0, ..., vn}`
33903      *
33904      * `["!in", key, v0, ..., vn]` set exclusion: `node[key] ∉ {v0, ..., vn}`
33905      *
33906      * Combining
33907      *
33908      * `["all", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`
33909      *
33910      * A key must be a string that identifies a node property name. A value must be
33911      * a string, number, or boolean. Strictly-typed comparisons are used. The values
33912      * `f0, ..., fn` of the combining filter must be filter expressions.
33913      *
33914      * Clear the filter by setting it to null or empty array.
33915      *
33916      * @param {FilterExpression} filter - The filter expression.
33917      * @returns {Promise<void>} Promise that resolves after filter is applied.
33918      *
33919      * @example `viewer.setFilter(["==", "sequenceKey", "<my sequence key>"]);`
33920      */
33921     Viewer.prototype.setFilter = function (filter) {
33922         var _this = this;
33923         return when.promise(function (resolve, reject) {
33924             _this._navigator.setFilter$(filter)
33925                 .subscribe(function () {
33926                 resolve(undefined);
33927             }, function (error) {
33928                 reject(error);
33929             });
33930         });
33931     };
33932     /**
33933      * Set the viewer's render mode.
33934      *
33935      * @param {RenderMode} renderMode - Render mode.
33936      *
33937      * @example `viewer.setRenderMode(Mapillary.RenderMode.Letterbox);`
33938      */
33939     Viewer.prototype.setRenderMode = function (renderMode) {
33940         this._container.renderService.renderMode$.next(renderMode);
33941     };
33942     /**
33943      * Set the photo's current zoom level.
33944      *
33945      * @description Possible zoom level values are on the [0, 3] interval.
33946      * Zero means zooming out to fit the photo to the view whereas three
33947      * shows the highest level of detail.
33948      *
33949      * @param {number} The photo's current zoom level.
33950      */
33951     Viewer.prototype.setZoom = function (zoom) {
33952         this._navigator.stateService.setZoom(zoom);
33953     };
33954     /**
33955      * Fired when the viewer is loading more data.
33956      * @event
33957      * @type {boolean} loading - Value indicating whether the viewer is loading.
33958      */
33959     Viewer.loadingchanged = "loadingchanged";
33960     /**
33961      * Fired when the viewer finishes transitioning and is in a fixed
33962      * position with a fixed point of view.
33963      * @event
33964      */
33965     Viewer.moveend = "moveend";
33966     /**
33967      * Fired when the viewer starts transitioning from one view to another,
33968      * either by changing the node or by interaction such as pan and zoom.
33969      * @event
33970      */
33971     Viewer.movestart = "movestart";
33972     /**
33973      * Fired every time the viewer navigates to a new node.
33974      * @event
33975      * @type {Node} node - Current node.
33976      */
33977     Viewer.nodechanged = "nodechanged";
33978     /**
33979      * Fired every time the sequence edges of the current node changes.
33980      * @event
33981      * @type {IEdgeStatus} status - The edge status object.
33982      */
33983     Viewer.sequenceedgeschanged = "sequenceedgeschanged";
33984     /**
33985      * Fired every time the spatial edges of the current node changes.
33986      * @event
33987      * @type {IEdgeStatus} status - The edge status object.
33988      */
33989     Viewer.spatialedgeschanged = "spatialedgeschanged";
33990     return Viewer;
33991 }(Utils_1.EventEmitter));
33992 exports.Viewer = Viewer;
33993
33994 },{"../Utils":218,"../Viewer":219,"when":207}]},{},[215])(215)
33995 });
33996 //# sourceMappingURL=mapillary.js.map